text
stringlengths
54
60.6k
<commit_before>#include "benchmark/BenchmarkKernel.h" #include <iostream> using namespace std; BenchmarkKernel::~BenchmarkKernel() { } int main(int argc, const char* argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " <input files>... <output file>" << endl; return 1; } vector<string> inputs(argv + 1, argv + argc - 1); string output(argv[argc - 1]); auto kernel = createKernel(); if (inputs.size() < kernel->requiredInputs()) { cerr << argv[0] << " requires " << kernel->requiredInputs() << " input files..." << endl; return 1; } kernel->startup(inputs); kernel->run(); kernel->shutdown(output); } <commit_msg>now measuring time of Kernel::run() in µs and printing results onto std::out<commit_after>#include "benchmark/BenchmarkKernel.h" #include <iostream> #include <chrono> #include <functional> #include <map> using namespace std; BenchmarkKernel::~BenchmarkKernel() { } map<string, float> benchmark(function<void()> func, size_t iterations = 1) { typedef chrono::high_resolution_clock clock; typedef chrono::microseconds microseconds; clock::time_point before = clock::now(); for(size_t i=0; i<iterations; i++) { func(); } clock::time_point after = clock::now(); microseconds total_ms = (after - before); return map<string,float>{{"time (µs)", total_ms.count()}}; } int main(int argc, const char* argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " <input files>... <output file>" << endl; return 1; } // split args into first as inputs and the last as output vector<string> inputs(argv + 1, argv + argc - 1); string output(argv[argc - 1]); auto kernel = createKernel(); // check for required number of input arguments if (inputs.size() < kernel->requiredInputs()) { cerr << argv[0] << " requires " << kernel->requiredInputs() << " input files..." << endl; return 1; } // execute kernel kernel->startup(inputs); auto stats = benchmark([&](){kernel->run();}); kernel->shutdown(output); // print statistics for (auto& kv : stats) { cout << kv.first << ": " << kv.second << std::endl; } } <|endoftext|>
<commit_before>/* libvisio * Version: MPL 1.1 / GPLv2+ / LGPLv2+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch> * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com> * * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPLv2+"), or * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"), * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable * instead of those above. */ #include "libvisio_utils.h" #define VSD_NUM_ELEMENTS(array) sizeof(array)/sizeof(array[0]) uint8_t libvisio::readU8(WPXInputStream *input) { if (!input || input->atEOS()) throw EndOfStreamException(); unsigned long numBytesRead; uint8_t const * p = input->read(sizeof(uint8_t), numBytesRead); if (p && numBytesRead == sizeof(uint8_t)) return *(uint8_t const *)(p); throw EndOfStreamException(); } uint16_t libvisio::readU16(WPXInputStream *input) { uint16_t p0 = (uint16_t)readU8(input); uint16_t p1 = (uint16_t)readU8(input); return (uint16_t)(p0|(p1<<8)); } uint32_t libvisio::readU32(WPXInputStream *input) { uint32_t p0 = (uint32_t)readU8(input); uint32_t p1 = (uint32_t)readU8(input); uint32_t p2 = (uint32_t)readU8(input); uint32_t p3 = (uint32_t)readU8(input); return (uint32_t)(p0|(p1<<8)|(p2<<16)|(p3<<24)); } uint64_t libvisio::readU64(WPXInputStream *input) { uint64_t p0 = (uint64_t)readU8(input); uint64_t p1 = (uint64_t)readU8(input); uint64_t p2 = (uint64_t)readU8(input); uint64_t p3 = (uint64_t)readU8(input); uint64_t p4 = (uint64_t)readU8(input); uint64_t p5 = (uint64_t)readU8(input); uint64_t p6 = (uint64_t)readU8(input); uint64_t p7 = (uint64_t)readU8(input); return (uint64_t)(p0|(p1<<8)|(p2<<16)|(p3<<24)|(p4<<32)|(p5<<40)|(p6<<48)|(p7<<56)); } double libvisio::readDouble(WPXInputStream *input) { uint64_t value = readU64(input); double *doublePointer = reinterpret_cast<double *>(&value); return *doublePointer; } <commit_msg>Fix warning that dereferencing type-punned pointer will break strict-aliasing rules<commit_after>/* libvisio * Version: MPL 1.1 / GPLv2+ / LGPLv2+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch> * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com> * * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPLv2+"), or * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"), * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable * instead of those above. */ #include "libvisio_utils.h" #define VSD_NUM_ELEMENTS(array) sizeof(array)/sizeof(array[0]) uint8_t libvisio::readU8(WPXInputStream *input) { if (!input || input->atEOS()) throw EndOfStreamException(); unsigned long numBytesRead; uint8_t const * p = input->read(sizeof(uint8_t), numBytesRead); if (p && numBytesRead == sizeof(uint8_t)) return *(uint8_t const *)(p); throw EndOfStreamException(); } uint16_t libvisio::readU16(WPXInputStream *input) { uint16_t p0 = (uint16_t)readU8(input); uint16_t p1 = (uint16_t)readU8(input); return (uint16_t)(p0|(p1<<8)); } uint32_t libvisio::readU32(WPXInputStream *input) { uint32_t p0 = (uint32_t)readU8(input); uint32_t p1 = (uint32_t)readU8(input); uint32_t p2 = (uint32_t)readU8(input); uint32_t p3 = (uint32_t)readU8(input); return (uint32_t)(p0|(p1<<8)|(p2<<16)|(p3<<24)); } uint64_t libvisio::readU64(WPXInputStream *input) { uint64_t p0 = (uint64_t)readU8(input); uint64_t p1 = (uint64_t)readU8(input); uint64_t p2 = (uint64_t)readU8(input); uint64_t p3 = (uint64_t)readU8(input); uint64_t p4 = (uint64_t)readU8(input); uint64_t p5 = (uint64_t)readU8(input); uint64_t p6 = (uint64_t)readU8(input); uint64_t p7 = (uint64_t)readU8(input); return (uint64_t)(p0|(p1<<8)|(p2<<16)|(p3<<24)|(p4<<32)|(p5<<40)|(p6<<48)|(p7<<56)); } double libvisio::readDouble(WPXInputStream *input) { union { uint64_t u; double d; } tmpUnion; tmpUnion.u = readU64(input); return tmpUnion.d; } <|endoftext|>
<commit_before>#include "contextpanewidgetimage.h" #include "ui_contextpanewidgetimage.h" #include <qmljs/qmljspropertyreader.h> #include <QFile> #include <QPixmap> #include <QPainter> namespace QmlDesigner { ContextPaneWidgetImage::ContextPaneWidgetImage(QWidget *parent) : QWidget(parent), ui(new Ui::ContextPaneWidgetImage) { ui->setupUi(this); ui->fileWidget->setShowComboBox(true); ui->fileWidget->setFilter("*.png *.gif *.jpg"); connect(ui->stretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->tileRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->horizontalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->verticalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->preserveAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->cropAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->fileWidget, SIGNAL(fileNameChanged(QUrl)), this, SLOT(onFileNameChanged())); } ContextPaneWidgetImage::~ContextPaneWidgetImage() { delete ui; } void ContextPaneWidgetImage::setProperties(QmlJS::PropertyReader *propertyReader) { if (propertyReader->hasProperty(QLatin1String("fillMode"))) { QString fillMode = propertyReader->readProperty(QLatin1String("fillMode")).toString(); if (fillMode.contains("Image.")) fillMode.remove("Image."); ui->stretchRadioButton->setChecked(true); if (fillMode == "Tile") ui->tileRadioButton->setChecked(true); if (fillMode == "TileVertically") ui->horizontalStretchRadioButton->setChecked(true); if (fillMode == "TileHorizontally") ui->verticalStretchRadioButton->setChecked(true); if (fillMode == "PreserveAspectFit") ui->preserveAspectFitRadioButton->setChecked(true); if (fillMode == "PreserveAspectCrop") ui->cropAspectFitRadioButton->setChecked(true); } else { ui->stretchRadioButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("source"))) { QString source = propertyReader->readProperty(QLatin1String("source")).toString(); ui->fileWidget->setFileName(source); setPixmap(m_path + '/' + source); } } void ContextPaneWidgetImage::setPath(const QString& path) { m_path = path; ui->fileWidget->setPath(QUrl::fromLocalFile(m_path)); } void ContextPaneWidgetImage::onStretchChanged() { QString stretch; if (ui->stretchRadioButton->isChecked()) stretch = QLatin1String("Stretch"); else if (ui->tileRadioButton->isChecked()) stretch = QLatin1String("Tile"); else if (ui->horizontalStretchRadioButton->isChecked()) stretch = QLatin1String("TileVertically"); else if (ui->verticalStretchRadioButton->isChecked()) stretch = QLatin1String("TileHorizontally"); else if (ui->preserveAspectFitRadioButton->isChecked()) stretch = QLatin1String("PreserveAspectFit"); else if (ui->cropAspectFitRadioButton->isChecked()) stretch = QLatin1String("PreserveAspectCrop"); if (stretch == QLatin1String("Stretch")) emit removeProperty(QLatin1String("fillMode")); else emit propertyChanged(QLatin1String("fillMode"), stretch); } void ContextPaneWidgetImage::onFileNameChanged() { if (ui->fileWidget->fileName().isNull()) emit removeProperty(QLatin1String("source")); else emit propertyChanged(QLatin1String("source"), QString(QLatin1Char('\"') + ui->fileWidget->fileName() + QLatin1Char('\"'))); } void ContextPaneWidgetImage::setPixmap(const QString &fileName) { QPixmap pix(76,76); pix.fill(Qt::black); if (QFile(fileName).exists()) { QPixmap source(fileName); QPainter p(&pix); if (ui->stretchRadioButton->isChecked()) { p.drawPixmap(0,0,76,76, source); } else if (ui->tileRadioButton->isChecked()) { QPixmap small = source.scaled(38,38); p.drawTiledPixmap(0,0,76,76, small); } else if (ui->horizontalStretchRadioButton->isChecked()) { QPixmap small = source.scaled(38,38); QPixmap half = pix.scaled(38, 76); QPainter p2(&half); p2.drawTiledPixmap(0,0,38,76, small); p.drawPixmap(0,0,76,76, half); } else if (ui->verticalStretchRadioButton->isChecked()) { QPixmap small = source.scaled(38,38); QPixmap half = pix.scaled(76, 38); QPainter p2(&half); p2.drawTiledPixmap(0,0,76,38, small); p.drawPixmap(0,0,76,76, half); } else if (ui->preserveAspectFitRadioButton->isChecked()) { QPixmap preserved = source.scaledToWidth(76); int offset = (76 - preserved.height()) / 2; p.drawPixmap(0, offset, 76, preserved.height(), source); } else if (ui->cropAspectFitRadioButton->isChecked()) { QPixmap cropped = source.scaledToHeight(76); int offset = (76 - cropped.width()) / 2; p.drawPixmap(offset, 0, cropped.width(), 76, source); } } ui->label->setPixmap(pix); } void ContextPaneWidgetImage::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } } //QmlDesigner <commit_msg>QmlDesigner: property pane adding label for image size<commit_after>#include "contextpanewidgetimage.h" #include "ui_contextpanewidgetimage.h" #include <qmljs/qmljspropertyreader.h> #include <QFile> #include <QPixmap> #include <QPainter> namespace QmlDesigner { ContextPaneWidgetImage::ContextPaneWidgetImage(QWidget *parent) : QWidget(parent), ui(new Ui::ContextPaneWidgetImage) { ui->setupUi(this); ui->fileWidget->setShowComboBox(true); ui->fileWidget->setFilter("*.png *.gif *.jpg"); connect(ui->stretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->tileRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->horizontalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->verticalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->preserveAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->cropAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged())); connect(ui->fileWidget, SIGNAL(fileNameChanged(QUrl)), this, SLOT(onFileNameChanged())); } ContextPaneWidgetImage::~ContextPaneWidgetImage() { delete ui; } void ContextPaneWidgetImage::setProperties(QmlJS::PropertyReader *propertyReader) { if (propertyReader->hasProperty(QLatin1String("fillMode"))) { QString fillMode = propertyReader->readProperty(QLatin1String("fillMode")).toString(); if (fillMode.contains("Image.")) fillMode.remove("Image."); ui->stretchRadioButton->setChecked(true); if (fillMode == "Tile") ui->tileRadioButton->setChecked(true); if (fillMode == "TileVertically") ui->horizontalStretchRadioButton->setChecked(true); if (fillMode == "TileHorizontally") ui->verticalStretchRadioButton->setChecked(true); if (fillMode == "PreserveAspectFit") ui->preserveAspectFitRadioButton->setChecked(true); if (fillMode == "PreserveAspectCrop") ui->cropAspectFitRadioButton->setChecked(true); } else { ui->stretchRadioButton->setChecked(true); } if (propertyReader->hasProperty(QLatin1String("source"))) { QString source = propertyReader->readProperty(QLatin1String("source")).toString(); ui->fileWidget->setFileName(source); if (QFile::exists(m_path + '/' + source)) setPixmap(m_path + '/' + source); else setPixmap(source); } else { ui->sizeLabel->setText(""); } } void ContextPaneWidgetImage::setPath(const QString& path) { m_path = path; ui->fileWidget->setPath(QUrl::fromLocalFile(m_path)); } void ContextPaneWidgetImage::onStretchChanged() { QString stretch; if (ui->stretchRadioButton->isChecked()) stretch = QLatin1String("Stretch"); else if (ui->tileRadioButton->isChecked()) stretch = QLatin1String("Tile"); else if (ui->horizontalStretchRadioButton->isChecked()) stretch = QLatin1String("TileVertically"); else if (ui->verticalStretchRadioButton->isChecked()) stretch = QLatin1String("TileHorizontally"); else if (ui->preserveAspectFitRadioButton->isChecked()) stretch = QLatin1String("PreserveAspectFit"); else if (ui->cropAspectFitRadioButton->isChecked()) stretch = QLatin1String("PreserveAspectCrop"); if (stretch == QLatin1String("Stretch")) emit removeProperty(QLatin1String("fillMode")); else emit propertyChanged(QLatin1String("fillMode"), stretch); } void ContextPaneWidgetImage::onFileNameChanged() { if (ui->fileWidget->fileName().isNull()) emit removeProperty(QLatin1String("source")); else emit propertyChanged(QLatin1String("source"), QString(QLatin1Char('\"') + ui->fileWidget->fileName() + QLatin1Char('\"'))); } void ContextPaneWidgetImage::setPixmap(const QString &fileName) { QPixmap pix(76,76); pix.fill(Qt::black); if (QFile(fileName).exists()) { QPixmap source(fileName); ui->sizeLabel->setText(QString::number(source.width()) + 'x' + QString::number(source.height())); QPainter p(&pix); if (ui->stretchRadioButton->isChecked()) { p.drawPixmap(0,0,76,76, source); } else if (ui->tileRadioButton->isChecked()) { QPixmap small = source.scaled(38,38); p.drawTiledPixmap(0,0,76,76, small); } else if (ui->horizontalStretchRadioButton->isChecked()) { QPixmap small = source.scaled(38,38); QPixmap half = pix.scaled(38, 76); QPainter p2(&half); p2.drawTiledPixmap(0,0,38,76, small); p.drawPixmap(0,0,76,76, half); } else if (ui->verticalStretchRadioButton->isChecked()) { QPixmap small = source.scaled(38,38); QPixmap half = pix.scaled(76, 38); QPainter p2(&half); p2.drawTiledPixmap(0,0,76,38, small); p.drawPixmap(0,0,76,76, half); } else if (ui->preserveAspectFitRadioButton->isChecked()) { QPixmap preserved = source.scaledToWidth(76); int offset = (76 - preserved.height()) / 2; p.drawPixmap(0, offset, 76, preserved.height(), source); } else if (ui->cropAspectFitRadioButton->isChecked()) { QPixmap cropped = source.scaledToHeight(76); int offset = (76 - cropped.width()) / 2; p.drawPixmap(offset, 0, cropped.width(), 76, source); } } else { ui->sizeLabel->setText(""); } ui->label->setPixmap(pix); } void ContextPaneWidgetImage::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } } //QmlDesigner <|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; _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(); } } <commit_msg>Minor optimization to the 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.resize(0); // keep allocated buffer 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.reserve(_length); 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 <fstream> #include <iostream> #include <string> #include <cstring> #include <vector> #include "mugen_item_content.h" #include "mugen_section.h" #include "mugen_reader.h" // Check for Clsn static bool checkClsn( const std::string &clsn ){ return ( clsn.find("Clsn") != std::string::npos ); } MugenReader::MugenReader( const char * file ){ ifile.open( file ); myfile = string( file ); } MugenReader::MugenReader( const string & file ){ ifile.open( file.c_str() ); myfile = file; } MugenReader::~MugenReader(){ for( std::vector< MugenSection * >::iterator i = collection.begin() ; i != collection.end() ; ++i ){ delete (*i); } } const std::vector< MugenSection * > & MugenReader::getCollection() throw(MugenException){ if ( !ifile ){ throw MugenException( std::string("Could not open ") + myfile ); } std::string line; const char openbracket = '['; const char closebracket = ']'; const char openparen = '('; const char closeparen = ')'; const char comment = ';'; const char seperator = ','; const char colon = ':'; const char equal = '='; const char notequal = '!'; const char quote = '"'; const char orcondition = '|'; const char andcondition = '&'; const char greater = '>'; const char less = '<'; const char add = '+'; const char multiply = '*'; SearchState state = Section; // Our section and items MugenSection * sectionHolder = 0; // Marker for areas bool beginSection = false; bool inQuote = false; while( !ifile.eof() ){ getline( ifile, line ); // Use to hold section or content in the options std::string contentHolder = ""; // Place holder to put back all the grabbed content MugenItemContent *itemHolder = new MugenItemContent(); // Needed to kill loop bool breakLoop = false; for( unsigned int i = 0; i < line.size(); ++i ){ // Go to work switch( state ){ case Section:{ // Done with this if( line[i] == comment ){ breakLoop = true; break; } else if ( line[i] == ' ' && !beginSection )continue; //Start grabbing our section else if( line[i] == openbracket){ beginSection = true; } //End of our section store and go to ContentGet else if( line[i] == closebracket){ sectionHolder = new MugenSection(); sectionHolder->setHeader( contentHolder ); state = ContentGet; beginSection = false; breakLoop = true; break; } else if( beginSection )contentHolder += line[i]; } break; case ContentGet: default:{ // Done with this if( line[i] == comment ){ if( itemHolder->hasItems() ){ if( !contentHolder.empty() ){ *itemHolder << contentHolder; } *sectionHolder << itemHolder; } breakLoop = true; break; } // Check if we are near the end to kill it if( i+1 == line.size() && !contentHolder.empty() ){ if ( line[i] != ' ' ) contentHolder += line[i]; *itemHolder << contentHolder; *sectionHolder << itemHolder; breakLoop = true; break; } // Buh bye spaces if ( line[i] == ' ' && !inQuote ){ continue; } // Check if this section is done, push it on the stack and reset everything if( line[i] == openbracket && !checkClsn( contentHolder ) && !itemHolder->hasItems() ){ if( sectionHolder->hasItems() )addSection( sectionHolder ); beginSection = true; state = Section; contentHolder = ""; break; } // It's peanut butter bracket time else if( line[i] == openbracket && !checkClsn( contentHolder ) && !inQuote ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = openbracket; *itemHolder << contentHolder; contentHolder = ""; } else if( line[i] == closebracket && !checkClsn( contentHolder ) && !inQuote ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = closebracket; *itemHolder << contentHolder; contentHolder = ""; } // We got one push back the other and reset the holder to get the next else if( line[i] == colon || line[i] == seperator ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = ""; } // Conditional or else if( line[i] == orcondition && !inQuote ){ // Check to see if the next line is another | if( i+1 != line.size() ){ if( line[i+1] == orcondition ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = orcondition; } else { contentHolder += orcondition; *itemHolder << contentHolder; contentHolder = ""; } } } // Conditional and else if( line[i] == andcondition && !inQuote ){ // Check to see if the next line is another & if( i+1 != line.size() ){ if( line[i+1] == andcondition ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = andcondition; } else { contentHolder += andcondition; *itemHolder << contentHolder; contentHolder = ""; } } } // Parenthesis open else if(line[i] == openparen && !inQuote ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = openparen; *itemHolder << contentHolder; contentHolder = ""; } // Parenthesis closed else if(line[i] == closeparen && !inQuote ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = closeparen; *itemHolder << contentHolder; contentHolder = ""; } // Equal else if(line[i] == equal && !inQuote ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = equal; *itemHolder << contentHolder; contentHolder = ""; } // Not Equal else if( line[i] == notequal && !inQuote ){ // Check to see if the next line is = if( i+1 != line.size() ){ if( line[i+1] == equal ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = "!="; *itemHolder << contentHolder; contentHolder = ""; i++; } } } // Greater than else if(line[i] == greater && !inQuote ){ // Check to see if the next line is = if( i+1 != line.size() ){ if( line[i+1] == equal ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = ">="; *itemHolder << contentHolder; contentHolder = ""; i++; } else{ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = greater; *itemHolder << contentHolder; contentHolder = ""; } } } // Less than else if(line[i] == less && !inQuote ){ // Check to see if the next line is = if( i+1 != line.size() ){ if( line[i+1] == equal ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = "<="; *itemHolder << contentHolder; contentHolder = ""; i++; } else{ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = less; *itemHolder << contentHolder; contentHolder = ""; } } } // Add else if(line[i] == add && !inQuote ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = add; *itemHolder << contentHolder; contentHolder = ""; } // Multiply else if(line[i] == multiply && !inQuote ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = multiply; *itemHolder << contentHolder; contentHolder = ""; } // We has a quote begin or end it else if( line[i] == quote ){ inQuote = !inQuote; } //Start grabbing our item else contentHolder += line[i]; } break; } if( breakLoop )break; } } // Add in last section if( sectionHolder->hasItems() )addSection( sectionHolder ); return collection; } void MugenReader::addSection( MugenSection * section ){ collection.push_back ( section ); } <commit_msg>Removed code to parse expressions in order to pass to lex/yacc handler<commit_after>#include <fstream> #include <iostream> #include <string> #include <cstring> #include <vector> #include "mugen_item_content.h" #include "mugen_section.h" #include "mugen_reader.h" // Check for Clsn static bool checkClsn( const std::string &clsn ){ return ( clsn.find("Clsn") != std::string::npos ); } MugenReader::MugenReader( const char * file ){ ifile.open( file ); myfile = string( file ); } MugenReader::MugenReader( const string & file ){ ifile.open( file.c_str() ); myfile = file; } MugenReader::~MugenReader(){ for( std::vector< MugenSection * >::iterator i = collection.begin() ; i != collection.end() ; ++i ){ delete (*i); } } const std::vector< MugenSection * > & MugenReader::getCollection() throw(MugenException){ if ( !ifile ){ throw MugenException( std::string("Could not open ") + myfile ); } std::string line; const char openbracket = '['; const char closebracket = ']'; const char comment = ';'; const char seperator = ','; const char colon = ':'; const char equal = '='; const char quote = '"'; SearchState state = Section; // Our section and items MugenSection * sectionHolder = 0; // Marker for areas bool beginSection = false; while( !ifile.eof() ){ getline( ifile, line ); // Use to hold section or content in the options std::string contentHolder = ""; // Place holder to put back all the grabbed content MugenItemContent *itemHolder = new MugenItemContent(); // Needed to kill loop bool breakLoop = false; bool inQuote = false; bool getExpression = false; for( unsigned int i = 0; i < line.size(); ++i ){ // Go to work switch( state ){ case Section:{ // Done with this if( line[i] == comment ){ breakLoop = true; break; } else if ( line[i] == ' ' && !beginSection )continue; //Start grabbing our section else if( line[i] == openbracket){ beginSection = true; } //End of our section store and go to ContentGet else if( line[i] == closebracket){ sectionHolder = new MugenSection(); sectionHolder->setHeader( contentHolder ); state = ContentGet; beginSection = false; breakLoop = true; break; } else if( beginSection )contentHolder += line[i]; } break; case ContentGet: default:{ // Done with this if( line[i] == comment ){ if( itemHolder->hasItems() ){ if( !contentHolder.empty() ){ *itemHolder << contentHolder; } *sectionHolder << itemHolder; } breakLoop = true; break; } // Check if we are near the end to kill it if( i+1 == line.size() && !contentHolder.empty() ){ if ( line[i] != ' ' ) contentHolder += line[i]; *itemHolder << contentHolder; *sectionHolder << itemHolder; breakLoop = true; break; } // Buh bye spaces if( line[i] == ' ' && !inQuote ){ continue; } // Start getting expression if( line[i] != ' ' && getExpression ){ inQuote = true; } // Check if this section is done, push it on the stack and reset everything if( line[i] == openbracket && !checkClsn( contentHolder ) && !itemHolder->hasItems() ){ if( sectionHolder->hasItems() )addSection( sectionHolder ); beginSection = true; state = Section; contentHolder = ""; break; } // We got one push back the other and reset the holder to get the next else if( line[i] == colon || line[i] == seperator ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; contentHolder = ""; } // Equal else if(line[i] == equal && !inQuote ){ if( !contentHolder.empty() ) *itemHolder << contentHolder; getExpression = true; contentHolder = ""; } // We has a quote begin or end it else if( line[i] == quote ){ inQuote = !inQuote; } //Start grabbing our item else contentHolder += line[i]; } break; } if( breakLoop )break; } } // Add in last section if( sectionHolder->hasItems() )addSection( sectionHolder ); return collection; } void MugenReader::addSection( MugenSection * section ){ collection.push_back ( section ); } <|endoftext|>
<commit_before>#pragma once #include "helix/nasdaq/nordic_itch_messages.h" #include "helix/order_book.hh" #include "helix/helix.hh" #include "helix/net.hh" #include <unordered_map> #include <vector> #include <memory> #include <set> namespace helix { namespace nasdaq { // NASDAQ OXM Nordic ITCH feed. // // This is a feed handler for Nordic ITCH. The handler assumes that transport // protocol framing such as SoapTCP or MoldUDP has already been parsed and // works directly on ITCH messages. // // The feed handler reconstructs a full depth order book from a ITCH message // flow using an algorithm that is specified in Appendix A of the protocol // specification. As not all messages include an order book ID, the handler // keeps mapping from every order ID it encounters to the order book the order // is part of. // // The ITCH variant processed by this feed handler is specified by NASDAQ OMX // in: // // Nordic Equity TotalView-ITCH // Version 1.90.2 // April 7, 2014 // class itch_session : public net::message_parser { private: //! Seconds since midnight in CET (Central European Time). uint64_t time_sec; //! Milliseconds since @time_sec. uint64_t time_msec; //! Callback function for processing order book events. core::ob_callback _process_ob; //! Callback function for processing trade events. core::trade_callback _process_trade; //! A map of order books by order book ID. std::unordered_map<uint64_t, helix::core::order_book> order_book_id_map; //! A map of order books by order ID. std::unordered_map<uint64_t, helix::core::order_book&> order_id_map; //! A set of symbols that we are interested in. std::set<std::string> _symbols; public: class unknown_message_type : public std::logic_error { public: unknown_message_type(std::string cause) : logic_error(cause) { } }; public: itch_session(const std::vector<std::string>& symbols) { for (auto sym : symbols) { auto padding = ITCH_SYMBOL_LEN - sym.size(); if (padding > 0) { sym.insert(sym.size(), padding, ' '); } _symbols.insert(sym); } } void register_callback(core::ob_callback process_ob) { _process_ob = process_ob; } void register_callback(core::trade_callback process_trade) { _process_trade = process_trade; } virtual size_t parse(const net::packet_view& packet) override; private: template<typename T> size_t process_msg(const net::packet_view& packet); void process_msg(const itch_seconds* m); void process_msg(const itch_milliseconds* m); void process_msg(const itch_market_segment_state* m); void process_msg(const itch_system_event* m); void process_msg(const itch_order_book_directory* m); void process_msg(const itch_order_book_trading_action* m); void process_msg(const itch_add_order* m); void process_msg(const itch_add_order_mpid* m); void process_msg(const itch_order_executed* m); void process_msg(const itch_order_executed_with_price* m); void process_msg(const itch_order_cancel* m); void process_msg(const itch_order_delete* m); void process_msg(const itch_trade* m); void process_msg(const itch_cross_trade* m); void process_msg(const itch_broken_trade* m); void process_msg(const itch_noii* m); //! Timestamp in milliseconds inline uint64_t timestamp() const { return time_sec * 1000 + time_msec; } }; } } <commit_msg>Fix typo<commit_after>#pragma once #include "helix/nasdaq/nordic_itch_messages.h" #include "helix/order_book.hh" #include "helix/helix.hh" #include "helix/net.hh" #include <unordered_map> #include <vector> #include <memory> #include <set> namespace helix { namespace nasdaq { // NASDAQ OXM Nordic ITCH feed. // // This is a feed handler for Nordic ITCH. The handler assumes that transport // protocol framing such as SoupTCP or MoldUDP has already been parsed and // works directly on ITCH messages. // // The feed handler reconstructs a full depth order book from a ITCH message // flow using an algorithm that is specified in Appendix A of the protocol // specification. As not all messages include an order book ID, the handler // keeps mapping from every order ID it encounters to the order book the order // is part of. // // The ITCH variant processed by this feed handler is specified by NASDAQ OMX // in: // // Nordic Equity TotalView-ITCH // Version 1.90.2 // April 7, 2014 // class itch_session : public net::message_parser { private: //! Seconds since midnight in CET (Central European Time). uint64_t time_sec; //! Milliseconds since @time_sec. uint64_t time_msec; //! Callback function for processing order book events. core::ob_callback _process_ob; //! Callback function for processing trade events. core::trade_callback _process_trade; //! A map of order books by order book ID. std::unordered_map<uint64_t, helix::core::order_book> order_book_id_map; //! A map of order books by order ID. std::unordered_map<uint64_t, helix::core::order_book&> order_id_map; //! A set of symbols that we are interested in. std::set<std::string> _symbols; public: class unknown_message_type : public std::logic_error { public: unknown_message_type(std::string cause) : logic_error(cause) { } }; public: itch_session(const std::vector<std::string>& symbols) { for (auto sym : symbols) { auto padding = ITCH_SYMBOL_LEN - sym.size(); if (padding > 0) { sym.insert(sym.size(), padding, ' '); } _symbols.insert(sym); } } void register_callback(core::ob_callback process_ob) { _process_ob = process_ob; } void register_callback(core::trade_callback process_trade) { _process_trade = process_trade; } virtual size_t parse(const net::packet_view& packet) override; private: template<typename T> size_t process_msg(const net::packet_view& packet); void process_msg(const itch_seconds* m); void process_msg(const itch_milliseconds* m); void process_msg(const itch_market_segment_state* m); void process_msg(const itch_system_event* m); void process_msg(const itch_order_book_directory* m); void process_msg(const itch_order_book_trading_action* m); void process_msg(const itch_add_order* m); void process_msg(const itch_add_order_mpid* m); void process_msg(const itch_order_executed* m); void process_msg(const itch_order_executed_with_price* m); void process_msg(const itch_order_cancel* m); void process_msg(const itch_order_delete* m); void process_msg(const itch_trade* m); void process_msg(const itch_cross_trade* m); void process_msg(const itch_broken_trade* m); void process_msg(const itch_noii* m); //! Timestamp in milliseconds inline uint64_t timestamp() const { return time_sec * 1000 + time_msec; } }; } } <|endoftext|>
<commit_before>#include <nimble/common.h> #include <nimble/utils/utils.h> uint8_t na::HexToByte(char c) { c = (char)tolower(c); if (c >= '0' && c <= '9') { return (uint8_t)(c - '0'); } if (c >= 'a' && c <= 'f') { return (uint8_t)(0xA + (c - 'a')); } return 0; } na::Bounds na::ParseBounds(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return Bounds(atoi(parse[0])); } else if (parse.len() == 2) { return Bounds(atoi(parse[0]), atoi(parse[1])); } else if (parse.len() == 4) { return Bounds(atoi(parse[0]), atoi(parse[1]), atoi(parse[2]), atoi(parse[3])); } else { printf("Unknown amount of parameters for bounds: %d\n", (int)parse.len()); } return Bounds(0); } glm::ivec2 na::ParseIvec2(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::ivec2(atoi(parse[0])); } else if (parse.len() == 2) { return glm::ivec2(atoi(parse[0]), atoi(parse[1])); } else { printf("Unknown amount of parameters for ivec2: %d\n", (int)parse.len()); } return glm::ivec2(); } glm::vec2 na::ParseVec2(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::vec2(atof(parse[0])); } else if (parse.len() == 2) { return glm::vec2(atof(parse[0]), atof(parse[1])); } else { printf("Unknown amount of parameters for vec2: %d\n", (int)parse.len()); } return glm::vec2(); } glm::vec3 na::ParseVec3(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::vec3(atof(parse[0])); } else if (parse.len() == 3) { return glm::vec3(atof(parse[0]), atof(parse[1]), atof(parse[2])); } else { printf("Unknown amount of parameters for vec3: %d\n", (int)parse.len()); } return glm::vec3(); } glm::vec4 na::ParseVec4(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::vec4(atof(parse[0])); } else if (parse.len() == 4) { return glm::vec4(atof(parse[0]), atof(parse[1]), atof(parse[2]), atof(parse[3])); } else { printf("Unknown amount of parameters for vec4: %d\n", (int)parse.len()); } return glm::vec4(); } glm::vec4 na::ParseColor(const char* sz) { if (*sz == '#') { size_t len = strlen(sz); uint8_t r, g, b, a; r = g = b = a = 0; if (len == 4) { // '#f00' r = HexToByte(sz[1]); r |= (r << 4); g = HexToByte(sz[2]); g |= (g << 4); b = HexToByte(sz[3]); b |= (b << 4); a = 255; } else if (len == 5) { // '#f00f' r = HexToByte(sz[1]); r |= (r << 4); g = HexToByte(sz[2]); g |= (g << 4); b = HexToByte(sz[3]); b |= (b << 4); a = HexToByte(sz[4]); a |= (a << 4); } else if (len == 7) { // '#ff0000' r = (HexToByte(sz[1]) << 4 | HexToByte(sz[2])); g = (HexToByte(sz[3]) << 4 | HexToByte(sz[4])); b = (HexToByte(sz[5]) << 4 | HexToByte(sz[6])); a = 255; } else if (len == 9) { // '#ff0000ff' r = (HexToByte(sz[1]) << 4 | HexToByte(sz[2])); g = (HexToByte(sz[3]) << 4 | HexToByte(sz[4])); b = (HexToByte(sz[5]) << 4 | HexToByte(sz[6])); a = (HexToByte(sz[7]) << 4 | HexToByte(sz[8])); } return glm::vec4( r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f ); } else { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::vec4(atof(parse[0])); } else if (parse.len() == 4) { return glm::vec4(atof(parse[0]), atof(parse[1]), atof(parse[2]), atof(parse[3])); } else { printf("Unknown amount of parameters for color: %d\n", (int)parse.len()); } } return glm::vec4(); } <commit_msg>Fix warnings<commit_after>#include <nimble/common.h> #include <nimble/utils/utils.h> uint8_t na::HexToByte(char c) { c = (char)tolower(c); if (c >= '0' && c <= '9') { return (uint8_t)(c - '0'); } if (c >= 'a' && c <= 'f') { return (uint8_t)(0xA + (c - 'a')); } return 0; } na::Bounds na::ParseBounds(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return Bounds(atoi(parse[0])); } else if (parse.len() == 2) { return Bounds(atoi(parse[0]), atoi(parse[1])); } else if (parse.len() == 4) { return Bounds(atoi(parse[0]), atoi(parse[1]), atoi(parse[2]), atoi(parse[3])); } else { printf("Unknown amount of parameters for bounds: %d\n", (int)parse.len()); } return Bounds(0); } glm::ivec2 na::ParseIvec2(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::ivec2(atoi(parse[0])); } else if (parse.len() == 2) { return glm::ivec2(atoi(parse[0]), atoi(parse[1])); } else { printf("Unknown amount of parameters for ivec2: %d\n", (int)parse.len()); } return glm::ivec2(); } glm::vec2 na::ParseVec2(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::vec2((float)atof(parse[0])); } else if (parse.len() == 2) { return glm::vec2((float)atof(parse[0]), (float)atof(parse[1])); } else { printf("Unknown amount of parameters for vec2: %d\n", (int)parse.len()); } return glm::vec2(); } glm::vec3 na::ParseVec3(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::vec3((float)atof(parse[0])); } else if (parse.len() == 3) { return glm::vec3((float)atof(parse[0]), (float)atof(parse[1]), (float)atof(parse[2])); } else { printf("Unknown amount of parameters for vec3: %d\n", (int)parse.len()); } return glm::vec3(); } glm::vec4 na::ParseVec4(const char* sz) { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::vec4((float)atof(parse[0])); } else if (parse.len() == 4) { return glm::vec4((float)atof(parse[0]), (float)atof(parse[1]), (float)atof(parse[2]), (float)atof(parse[3])); } else { printf("Unknown amount of parameters for vec4: %d\n", (int)parse.len()); } return glm::vec4(); } glm::vec4 na::ParseColor(const char* sz) { if (*sz == '#') { size_t len = strlen(sz); uint8_t r, g, b, a; r = g = b = a = 0; if (len == 4) { // '#f00' r = HexToByte(sz[1]); r |= (r << 4); g = HexToByte(sz[2]); g |= (g << 4); b = HexToByte(sz[3]); b |= (b << 4); a = 255; } else if (len == 5) { // '#f00f' r = HexToByte(sz[1]); r |= (r << 4); g = HexToByte(sz[2]); g |= (g << 4); b = HexToByte(sz[3]); b |= (b << 4); a = HexToByte(sz[4]); a |= (a << 4); } else if (len == 7) { // '#ff0000' r = (HexToByte(sz[1]) << 4 | HexToByte(sz[2])); g = (HexToByte(sz[3]) << 4 | HexToByte(sz[4])); b = (HexToByte(sz[5]) << 4 | HexToByte(sz[6])); a = 255; } else if (len == 9) { // '#ff0000ff' r = (HexToByte(sz[1]) << 4 | HexToByte(sz[2])); g = (HexToByte(sz[3]) << 4 | HexToByte(sz[4])); b = (HexToByte(sz[5]) << 4 | HexToByte(sz[6])); a = (HexToByte(sz[7]) << 4 | HexToByte(sz[8])); } return glm::vec4( r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f ); } else { s2::stringsplit parse(sz, " "); if (parse.len() == 1) { return glm::vec4((float)atof(parse[0])); } else if (parse.len() == 4) { return glm::vec4((float)atof(parse[0]), (float)atof(parse[1]), (float)atof(parse[2]), (float)atof(parse[3])); } else { printf("Unknown amount of parameters for color: %d\n", (int)parse.len()); } } return glm::vec4(); } <|endoftext|>
<commit_before>// nnet/nnet-component.cc // Copyright 2011-2013 Brno University of Technology (Author: Karel Vesely) // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "nnet/nnet-component.h" #include "nnet/nnet-nnet.h" #include "nnet/nnet-activation.h" #include "nnet/nnet-affine-transform.h" #include "nnet/nnet-various.h" #include "nnet/nnet-lstm.h" #include "nnet/nnet-bilstm.h" #include "nnet/nnet-bilstm-parallel.h" #include <sstream> namespace kaldi { namespace nnet1 { const struct Component::key_value Component::kMarkerMap[] = { { Component::kAffineTransform,"<AffineTransform>" }, { Component::kLstm,"<Lstm>"}, { Component::kBiLstm,"<BiLstm>"}, { Component::kBiLstmParallel,"<BiLstmParallel>"}, { Component::kSoftmax,"<Softmax>" }, }; const char* Component::TypeToMarker(ComponentType t) { int32 N=sizeof(kMarkerMap)/sizeof(kMarkerMap[0]); for(int i=0; i<N; i++) { if (kMarkerMap[i].key == t) return kMarkerMap[i].value; } KALDI_ERR << "Unknown type" << t; return NULL; } Component::ComponentType Component::MarkerToType(const std::string &s) { std::string s_lowercase(s); std::transform(s.begin(), s.end(), s_lowercase.begin(), ::tolower); // lc int32 N=sizeof(kMarkerMap)/sizeof(kMarkerMap[0]); for(int i=0; i<N; i++) { std::string m(kMarkerMap[i].value); std::string m_lowercase(m); std::transform(m.begin(), m.end(), m_lowercase.begin(), ::tolower); if (s_lowercase == m_lowercase) return kMarkerMap[i].key; } KALDI_ERR << "Unknown marker : '" << s << "'"; return kUnknown; } Component* Component::NewComponentOfType(ComponentType comp_type, int32 input_dim, int32 output_dim) { Component *ans = NULL; switch (comp_type) { case Component::kAffineTransform : ans = new AffineTransform(input_dim, output_dim); break; case Component::kLstm : ans = new Lstm(input_dim, output_dim); break; case Component::kBiLstm : ans = new BiLstm(input_dim, output_dim); break; case Component::kBiLstmParallel : ans = new BiLstmParallel(input_dim, output_dim); break; case Component::kSoftmax : ans = new Softmax(input_dim, output_dim); break; case Component::kUnknown : default : KALDI_ERR << "Missing type: " << TypeToMarker(comp_type); } return ans; } Component* Component::Init(const std::string &conf_line) { std::istringstream is(conf_line); std::string component_type_string; int32 input_dim, output_dim; // initialize component w/o internal data ReadToken(is, false, &component_type_string); ComponentType component_type = MarkerToType(component_type_string); ExpectToken(is, false, "<InputDim>"); ReadBasicType(is, false, &input_dim); ExpectToken(is, false, "<OutputDim>"); ReadBasicType(is, false, &output_dim); Component *ans = NewComponentOfType(component_type, input_dim, output_dim); // initialize internal data with the remaining part of config line ans->InitData(is); return ans; } Component* Component::Read(std::istream &is, bool binary) { int32 dim_out, dim_in; std::string token; int first_char = Peek(is, binary); if (first_char == EOF) return NULL; ReadToken(is, binary, &token); // Skip optional initial token if(token == "<Nnet>") { ReadToken(is, binary, &token); // Next token is a Component } // Finish reading when optional terminal token appears if(token == "</Nnet>") { return NULL; } ReadBasicType(is, binary, &dim_out); ReadBasicType(is, binary, &dim_in); Component *ans = NewComponentOfType(MarkerToType(token), dim_in, dim_out); ans->ReadData(is, binary); return ans; } void Component::Write(std::ostream &os, bool binary) const { WriteToken(os, binary, Component::TypeToMarker(GetType())); WriteBasicType(os, binary, OutputDim()); WriteBasicType(os, binary, InputDim()); if(!binary) os << "\n"; this->WriteData(os, binary); } void Component::WriteNonParal(std::ostream &os, bool binary) const { WriteToken(os, binary, Component::TypeToMarker(GetTypeNonParal())); WriteBasicType(os, binary, OutputDim()); WriteBasicType(os, binary, InputDim()); if(!binary) os << "\n"; this->WriteData(os, binary); } } // namespace nnet1 } // namespace kaldi <commit_msg>Update nnet-component.cc<commit_after>// nnet/nnet-component.cc // Copyright 2011-2013 Brno University of Technology (Author: Karel Vesely) // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "nnet/nnet-component.h" #include "nnet/nnet-nnet.h" #include "nnet/nnet-activation.h" #include "nnet/nnet-affine-transform.h" #include "nnet/nnet-various.h" #include "nnet/nnet-bilstm.h" #include "nnet/nnet-bilstm-parallel.h" #include <sstream> namespace kaldi { namespace nnet1 { const struct Component::key_value Component::kMarkerMap[] = { { Component::kAffineTransform,"<AffineTransform>" }, { Component::kLstm,"<Lstm>"}, { Component::kBiLstm,"<BiLstm>"}, { Component::kBiLstmParallel,"<BiLstmParallel>"}, { Component::kSoftmax,"<Softmax>" }, }; const char* Component::TypeToMarker(ComponentType t) { int32 N=sizeof(kMarkerMap)/sizeof(kMarkerMap[0]); for(int i=0; i<N; i++) { if (kMarkerMap[i].key == t) return kMarkerMap[i].value; } KALDI_ERR << "Unknown type" << t; return NULL; } Component::ComponentType Component::MarkerToType(const std::string &s) { std::string s_lowercase(s); std::transform(s.begin(), s.end(), s_lowercase.begin(), ::tolower); // lc int32 N=sizeof(kMarkerMap)/sizeof(kMarkerMap[0]); for(int i=0; i<N; i++) { std::string m(kMarkerMap[i].value); std::string m_lowercase(m); std::transform(m.begin(), m.end(), m_lowercase.begin(), ::tolower); if (s_lowercase == m_lowercase) return kMarkerMap[i].key; } KALDI_ERR << "Unknown marker : '" << s << "'"; return kUnknown; } Component* Component::NewComponentOfType(ComponentType comp_type, int32 input_dim, int32 output_dim) { Component *ans = NULL; switch (comp_type) { case Component::kAffineTransform : ans = new AffineTransform(input_dim, output_dim); break; case Component::kLstm : ans = new Lstm(input_dim, output_dim); break; case Component::kBiLstm : ans = new BiLstm(input_dim, output_dim); break; case Component::kBiLstmParallel : ans = new BiLstmParallel(input_dim, output_dim); break; case Component::kSoftmax : ans = new Softmax(input_dim, output_dim); break; case Component::kUnknown : default : KALDI_ERR << "Missing type: " << TypeToMarker(comp_type); } return ans; } Component* Component::Init(const std::string &conf_line) { std::istringstream is(conf_line); std::string component_type_string; int32 input_dim, output_dim; // initialize component w/o internal data ReadToken(is, false, &component_type_string); ComponentType component_type = MarkerToType(component_type_string); ExpectToken(is, false, "<InputDim>"); ReadBasicType(is, false, &input_dim); ExpectToken(is, false, "<OutputDim>"); ReadBasicType(is, false, &output_dim); Component *ans = NewComponentOfType(component_type, input_dim, output_dim); // initialize internal data with the remaining part of config line ans->InitData(is); return ans; } Component* Component::Read(std::istream &is, bool binary) { int32 dim_out, dim_in; std::string token; int first_char = Peek(is, binary); if (first_char == EOF) return NULL; ReadToken(is, binary, &token); // Skip optional initial token if(token == "<Nnet>") { ReadToken(is, binary, &token); // Next token is a Component } // Finish reading when optional terminal token appears if(token == "</Nnet>") { return NULL; } ReadBasicType(is, binary, &dim_out); ReadBasicType(is, binary, &dim_in); Component *ans = NewComponentOfType(MarkerToType(token), dim_in, dim_out); ans->ReadData(is, binary); return ans; } void Component::Write(std::ostream &os, bool binary) const { WriteToken(os, binary, Component::TypeToMarker(GetType())); WriteBasicType(os, binary, OutputDim()); WriteBasicType(os, binary, InputDim()); if(!binary) os << "\n"; this->WriteData(os, binary); } void Component::WriteNonParal(std::ostream &os, bool binary) const { WriteToken(os, binary, Component::TypeToMarker(GetTypeNonParal())); WriteBasicType(os, binary, OutputDim()); WriteBasicType(os, binary, InputDim()); if(!binary) os << "\n"; this->WriteData(os, binary); } } // namespace nnet1 } // namespace kaldi <|endoftext|>
<commit_before>#include <mlopen/convolution.hpp> #include <mlopen/mlo_internal.hpp> namespace mlopen { mlopenStatus_t ConvolutionDescriptor::FindConvFwdAlgorithm(mlopen::Handle& handle, const mlopen::TensorDescriptor& xDesc, const cl_mem x, const mlopen::TensorDescriptor& wDesc, const cl_mem w, const mlopen::TensorDescriptor& yDesc, const cl_mem y, const int requestAlgoCount, int *returnedAlgoCount, mlopenConvAlgoPerf_t *perfResults, mlopenConvPreference_t preference, void *workSpace, size_t workSpaceSize, bool exhaustiveSearch) const { if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } #if 0 if(returnedAlgoCount == nullptr || perfResults == nullptr) { return mlopenStatusBadParm; } if(requestAlgoCount < 1) { return mlopenStatusBadParm; } #endif // Generate kernels if OpenCL // Compile, cache kernels, etc. // Launch all kernels and store the perf, workspace limits, etc. mlo_construct_direct2D construct_params(1); // forward { construct_params.setTimerIter(100); construct_params.doSearch(exhaustiveSearch); construct_params.saveSearchRequest(true); // TO DO WHERE IS THE PATH ? std::string kernel_path = "../src/Kernels/"; construct_params.setKernelPath(kernel_path); construct_params.setGeneralCompOptions(""); construct_params.setStream(handle.GetStream()); construct_params.setOutputDescFromMLDesc(yDesc); construct_params.setInputDescFromMLDesc(xDesc); construct_params.setWeightDescFromMLDesc(wDesc); construct_params.setConvDescr(pad_h, pad_w, u, v, upscalex, upscaley); construct_params.mloConstructDirect2D(); } std::string program_name = std::string("../src/Kernels/") + construct_params.getKernelFile(); //"../src/Hello.cl"; // CL kernel filename std::string kernel_name = construct_params.getKernelName(); // "hello_world_kernel"; // kernel name std::string parms = construct_params.getCompilerOptions(); // kernel parameters std::string network_config; construct_params.mloBuildConf_Key(network_config); const std::vector<size_t> & vld = construct_params.getLocalWkSize(); const std::vector<size_t> & vgd = construct_params.getGlobalWkSize(); float padding_val = 0; handle.GetKernel("mlopenConvolutionFwdAlgoDirect", network_config, program_name, kernel_name, vld, vgd, parms)(x, w, y, padding_val); handle.Finish(); return mlopenStatusSuccess; } mlopenStatus_t ConvolutionDescriptor::ConvolutionForward(mlopen::Handle& handle, const void *alpha, const mlopen::TensorDescriptor& xDesc, const cl_mem x, const mlopen::TensorDescriptor& wDesc, const cl_mem w, mlopenConvFwdAlgorithm_t algo, const void *beta, const mlopen::TensorDescriptor& yDesc, cl_mem y, void *workSpace, size_t workSpaceSize) const { if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize()) { return mlopenStatusBadParm; } if(xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType()) { return mlopenStatusBadParm; } if(xDesc.GetLengths()[1] != wDesc.GetLengths()[1]) { return mlopenStatusBadParm; } if(xDesc.GetSize() < 3) { return mlopenStatusBadParm; } // TODO: Replicating code for now. mlo_construct_direct2D construct_params(1); // forward { construct_params.setOutputDescFromMLDesc(yDesc); construct_params.setInputDescFromMLDesc(xDesc); construct_params.setWeightDescFromMLDesc(wDesc); } std::string network_config; construct_params.mloBuildConf_Key(network_config); std::string algorithm_name; switch(algo) { case mlopenConvolutionFwdAlgoDirect: algorithm_name = "mlopenConvolutionFwdAlgoDirect"; break; case mlopenConvolutionFwdAlgoGEMM: algorithm_name = "mlopenConvolutionFwdAlgoGEMM"; break; case mlopenConvolutionFwdAlgoFFT: algorithm_name = "mlopenConvolutionFwdAlgoFFT"; break; case mlopenConvolutionFwdAlgoWinograd: algorithm_name = "mlopenConvolutionFwdAlgoWinograd"; break; } float padding_val = 0; handle.GetKernel(algorithm_name, network_config)(x, w, y, padding_val); handle.Finish(); return mlopenStatusSuccess; } // FindBackwardDataAlgorithm() // mlopenStatus_t ConvolutionDescriptor::FindConvBwdDataAlgorithm(mlopen::Handle& handle, const mlopen::TensorDescriptor& dyDesc, const cl_mem dy, const mlopen::TensorDescriptor& wDesc, const cl_mem w, const mlopen::TensorDescriptor& dxDesc, const cl_mem dx, const int requestAlgoCount, int *returnedAlgoCount, mlopenConvAlgoPerf_t *perfResults, mlopenConvPreference_t preference, void *workSpace, size_t workSpaceSize, bool exhaustiveSearch) const { if(dx == nullptr || w == nullptr || dy == nullptr) { return mlopenStatusBadParm; } #if 0 if(returnedAlgoCount == nullptr || perfResults == nullptr) { return mlopenStatusBadParm; } if(requestAlgoCount < 1) { return mlopenStatusBadParm; } #endif // Generate kernels if OpenCL // Compile, cache kernels, etc. // Launch all kernels and store the perf, workspace limits, etc. mlo_construct_direct2D construct_params(0); // backward { construct_params.setTimerIter(100); construct_params.doSearch(exhaustiveSearch); construct_params.saveSearchRequest(true); // TO DO WHERE IS THE PATH ? std::string kernel_path = "../src/Kernels/"; construct_params.setKernelPath(kernel_path); construct_params.setGeneralCompOptions(""); construct_params.setStream(handle.GetStream()); construct_params.setOutputDescFromMLDesc(dxDesc); construct_params.setInputDescFromMLDesc(dyDesc); construct_params.setWeightDescFromMLDesc(wDesc); construct_params.setConvDescr(pad_h, pad_w, u, v, upscalex, upscaley); construct_params.mloConstructDirect2D(); } std::string program_name = std::string("../src/Kernels/") + construct_params.getKernelFile(); std::string kernel_name = construct_params.getKernelName(); // kernel name std::string parms = construct_params.getCompilerOptions(); // kernel parameters std::string network_config; construct_params.mloBuildConf_Key(network_config); const std::vector<size_t> & vld = construct_params.getLocalWkSize(); const std::vector<size_t> & vgd = construct_params.getGlobalWkSize(); float padding_val = 0; handle.GetKernel("mlopenConvolutionBwdDataAlgo_0", network_config, program_name, kernel_name, vld, vgd, parms)(dy, w, dx, padding_val); handle.Finish(); return mlopenStatusSuccess; } // BackwardDataAlgorithm() mlopenStatus_t ConvolutionDescriptor::ConvolutionBackwardData(mlopen::Handle& handle, const void *alpha, const mlopen::TensorDescriptor& dyDesc, const cl_mem dy, const mlopen::TensorDescriptor& wDesc, const cl_mem w, mlopenConvBwdDataAlgorithm_t algo, const void *beta, const mlopen::TensorDescriptor& dxDesc, cl_mem dx, void *workSpace, size_t workSpaceSize) const { if(dx == nullptr || w == nullptr || dy == nullptr) { return mlopenStatusBadParm; } if(dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize()) { return mlopenStatusBadParm; } if(dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType()) { return mlopenStatusBadParm; } if(dyDesc.GetLengths()[1] != wDesc.GetLengths()[1]) { return mlopenStatusBadParm; } if(dyDesc.GetSize() < 3) { return mlopenStatusBadParm; } // TODO: Replicating code for now. mlo_construct_direct2D construct_params(0); // backward { construct_params.setOutputDescFromMLDesc(dxDesc); construct_params.setInputDescFromMLDesc(dyDesc); construct_params.setWeightDescFromMLDesc(wDesc); } std::string network_config; construct_params.mloBuildConf_Key(network_config); std::string algorithm_name; switch(algo) { case mlopenConvolutionBwdDataAlgo_0: algorithm_name = "mlopenConvolutionBwdDataAlgo_0"; break; default: printf("Algorithm not found\n"); break; } float padding_val = 0; handle.GetKernel(algorithm_name, network_config)(dy, w, dx, padding_val); handle.Finish(); return mlopenStatusSuccess; } } <commit_msg>Remove kernel path<commit_after>#include <mlopen/convolution.hpp> #include <mlopen/mlo_internal.hpp> namespace mlopen { mlopenStatus_t ConvolutionDescriptor::FindConvFwdAlgorithm(mlopen::Handle& handle, const mlopen::TensorDescriptor& xDesc, const cl_mem x, const mlopen::TensorDescriptor& wDesc, const cl_mem w, const mlopen::TensorDescriptor& yDesc, const cl_mem y, const int requestAlgoCount, int *returnedAlgoCount, mlopenConvAlgoPerf_t *perfResults, mlopenConvPreference_t preference, void *workSpace, size_t workSpaceSize, bool exhaustiveSearch) const { if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } #if 0 if(returnedAlgoCount == nullptr || perfResults == nullptr) { return mlopenStatusBadParm; } if(requestAlgoCount < 1) { return mlopenStatusBadParm; } #endif // Generate kernels if OpenCL // Compile, cache kernels, etc. // Launch all kernels and store the perf, workspace limits, etc. mlo_construct_direct2D construct_params(1); // forward { construct_params.setTimerIter(100); construct_params.doSearch(exhaustiveSearch); construct_params.saveSearchRequest(true); construct_params.setGeneralCompOptions(""); construct_params.setStream(handle.GetStream()); construct_params.setOutputDescFromMLDesc(yDesc); construct_params.setInputDescFromMLDesc(xDesc); construct_params.setWeightDescFromMLDesc(wDesc); construct_params.setConvDescr(pad_h, pad_w, u, v, upscalex, upscaley); construct_params.mloConstructDirect2D(); } std::string program_name = construct_params.getKernelFile(); //"../src/Hello.cl"; // CL kernel filename std::string kernel_name = construct_params.getKernelName(); // "hello_world_kernel"; // kernel name std::string parms = construct_params.getCompilerOptions(); // kernel parameters std::string network_config; construct_params.mloBuildConf_Key(network_config); const std::vector<size_t> & vld = construct_params.getLocalWkSize(); const std::vector<size_t> & vgd = construct_params.getGlobalWkSize(); float padding_val = 0; handle.GetKernel("mlopenConvolutionFwdAlgoDirect", network_config, program_name, kernel_name, vld, vgd, parms)(x, w, y, padding_val); handle.Finish(); return mlopenStatusSuccess; } mlopenStatus_t ConvolutionDescriptor::ConvolutionForward(mlopen::Handle& handle, const void *alpha, const mlopen::TensorDescriptor& xDesc, const cl_mem x, const mlopen::TensorDescriptor& wDesc, const cl_mem w, mlopenConvFwdAlgorithm_t algo, const void *beta, const mlopen::TensorDescriptor& yDesc, cl_mem y, void *workSpace, size_t workSpaceSize) const { if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize()) { return mlopenStatusBadParm; } if(xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType()) { return mlopenStatusBadParm; } if(xDesc.GetLengths()[1] != wDesc.GetLengths()[1]) { return mlopenStatusBadParm; } if(xDesc.GetSize() < 3) { return mlopenStatusBadParm; } // TODO: Replicating code for now. mlo_construct_direct2D construct_params(1); // forward { construct_params.setOutputDescFromMLDesc(yDesc); construct_params.setInputDescFromMLDesc(xDesc); construct_params.setWeightDescFromMLDesc(wDesc); } std::string network_config; construct_params.mloBuildConf_Key(network_config); std::string algorithm_name; switch(algo) { case mlopenConvolutionFwdAlgoDirect: algorithm_name = "mlopenConvolutionFwdAlgoDirect"; break; case mlopenConvolutionFwdAlgoGEMM: algorithm_name = "mlopenConvolutionFwdAlgoGEMM"; break; case mlopenConvolutionFwdAlgoFFT: algorithm_name = "mlopenConvolutionFwdAlgoFFT"; break; case mlopenConvolutionFwdAlgoWinograd: algorithm_name = "mlopenConvolutionFwdAlgoWinograd"; break; } float padding_val = 0; handle.GetKernel(algorithm_name, network_config)(x, w, y, padding_val); handle.Finish(); return mlopenStatusSuccess; } // FindBackwardDataAlgorithm() // mlopenStatus_t ConvolutionDescriptor::FindConvBwdDataAlgorithm(mlopen::Handle& handle, const mlopen::TensorDescriptor& dyDesc, const cl_mem dy, const mlopen::TensorDescriptor& wDesc, const cl_mem w, const mlopen::TensorDescriptor& dxDesc, const cl_mem dx, const int requestAlgoCount, int *returnedAlgoCount, mlopenConvAlgoPerf_t *perfResults, mlopenConvPreference_t preference, void *workSpace, size_t workSpaceSize, bool exhaustiveSearch) const { if(dx == nullptr || w == nullptr || dy == nullptr) { return mlopenStatusBadParm; } #if 0 if(returnedAlgoCount == nullptr || perfResults == nullptr) { return mlopenStatusBadParm; } if(requestAlgoCount < 1) { return mlopenStatusBadParm; } #endif // Generate kernels if OpenCL // Compile, cache kernels, etc. // Launch all kernels and store the perf, workspace limits, etc. mlo_construct_direct2D construct_params(0); // backward { construct_params.setTimerIter(100); construct_params.doSearch(exhaustiveSearch); construct_params.saveSearchRequest(true); construct_params.setGeneralCompOptions(""); construct_params.setStream(handle.GetStream()); construct_params.setOutputDescFromMLDesc(dxDesc); construct_params.setInputDescFromMLDesc(dyDesc); construct_params.setWeightDescFromMLDesc(wDesc); construct_params.setConvDescr(pad_h, pad_w, u, v, upscalex, upscaley); construct_params.mloConstructDirect2D(); } std::string program_name = construct_params.getKernelFile(); std::string kernel_name = construct_params.getKernelName(); // kernel name std::string parms = construct_params.getCompilerOptions(); // kernel parameters std::string network_config; construct_params.mloBuildConf_Key(network_config); const std::vector<size_t> & vld = construct_params.getLocalWkSize(); const std::vector<size_t> & vgd = construct_params.getGlobalWkSize(); float padding_val = 0; handle.GetKernel("mlopenConvolutionBwdDataAlgo_0", network_config, program_name, kernel_name, vld, vgd, parms)(dy, w, dx, padding_val); handle.Finish(); return mlopenStatusSuccess; } // BackwardDataAlgorithm() mlopenStatus_t ConvolutionDescriptor::ConvolutionBackwardData(mlopen::Handle& handle, const void *alpha, const mlopen::TensorDescriptor& dyDesc, const cl_mem dy, const mlopen::TensorDescriptor& wDesc, const cl_mem w, mlopenConvBwdDataAlgorithm_t algo, const void *beta, const mlopen::TensorDescriptor& dxDesc, cl_mem dx, void *workSpace, size_t workSpaceSize) const { if(dx == nullptr || w == nullptr || dy == nullptr) { return mlopenStatusBadParm; } if(dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize()) { return mlopenStatusBadParm; } if(dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType()) { return mlopenStatusBadParm; } if(dyDesc.GetLengths()[1] != wDesc.GetLengths()[1]) { return mlopenStatusBadParm; } if(dyDesc.GetSize() < 3) { return mlopenStatusBadParm; } // TODO: Replicating code for now. mlo_construct_direct2D construct_params(0); // backward { construct_params.setOutputDescFromMLDesc(dxDesc); construct_params.setInputDescFromMLDesc(dyDesc); construct_params.setWeightDescFromMLDesc(wDesc); } std::string network_config; construct_params.mloBuildConf_Key(network_config); std::string algorithm_name; switch(algo) { case mlopenConvolutionBwdDataAlgo_0: algorithm_name = "mlopenConvolutionBwdDataAlgo_0"; break; default: printf("Algorithm not found\n"); break; } float padding_val = 0; handle.GetKernel(algorithm_name, network_config)(dy, w, dx, padding_val); handle.Finish(); return mlopenStatusSuccess; } } <|endoftext|>
<commit_before>#ifndef TOKEN_PARSER_HPP #define TOKEN_PARSER_HPP #include <string> #include <vector> #include "baseParser.hpp" #include "ast.hpp" #include "token.hpp" #include "operator.hpp" /* EBNF-ish format of a program: program = block ; block = [ statement, ";", { statement, ";" } ] ; statement = declaration | ( "define", function ) | for_loop | while_loop | block | if_statement | try_catch | throw_statement | expression ; declaration = "define" | type_list, ident, [ "=", expression ] ; for_loop = "for", expression, ";", expression, ";", expression, "do", block, "end" ; while_loop = "while", expression, "do", block, "end" ; if_statement = "if", expression, "do", block, [ "else", block | if_statement ] | "end" ; type_definition = "define", "type", ident, [ "inherits", type_list ], "do", [ contructor_definition ], [ { method_definition | member_definition } ], "end" ; constructor_definition = "define", "constructor", [ argument, {",", argument } ], "do", block, "end" ; method_definition = "define", [ visibility_specifier ], [ "static" ], function ; member_definition = "define", [ visibility_specifier ], [ "static" ], ident, [ "=", expression ] ; try_catch = "try", block, "catch", type_list, ident, "do", block, "end" ; throw_statement = "throw", expression ; function = "function", ident, [ argument, {",", argument } ], [ "=>", type_list ], "do", block, "end" ; visibility_specifier = "public" | "private" | "protected" ; type_list = ident, {",", ident} ; argument = ( "[", type_list, ident, "]" ) | ( "[", ident, ":", type_list, "]" ) ; expression = ? any expr ? ; function_call = ident, "(", expression, { ",", expression }, ")" ; ident = ? any valid identifier ? ; */ class TokenParser: public BaseParser { private: std::vector<Token> input; uint64 pos = 0; enum BlockType { ROOT_BLOCK, CODE_BLOCK, IF_BLOCK }; inline Token current() { return input[pos]; } // Skip a number of tokens, usually just advances to the next one inline void skip(int by = 1) { pos += by; } inline bool accept(TokenType tok) { return tok == current().type; } inline bool accept(std::string operatorName) { if (!current().isOperator()) return false; if (current().hasOperatorName(operatorName)) return true; return false; } inline bool accept(Fixity fixity) { return current().isOperator() && current().hasFixity(fixity); } inline bool acceptTerminal() { return current().isTerminal(); } bool expect(TokenType tok, std::string errorMessage = "Unexpected symbol") { if (accept(tok)) { return true; } else { auto currentData = current().isOperator() ? current().getOperator().getName() : current().data; throw Error("SyntaxError", errorMessage + " (found: " + currentData + ")", current().line); } } inline bool isEndOfExpression() { return accept(C_SEMI) || accept(C_PAREN_RIGHT) || accept(FILE_END) || accept(K_DO); } inline Node<ExpressionNode>::Link exprFromCurrent() { auto e = Node<ExpressionNode>::make(current()); e->setLineNumber(current().line); return e; } Node<ExpressionNode>::Link expression(bool throwIfEmpty = true) { auto primary = parseExpressionPrimary(); if (primary == nullptr) { if (throwIfEmpty) throw InternalError("Empty expression", {METADATA_PAIRS}); else return nullptr; } return expressionImpl(primary, 0); } Node<ExpressionNode>::Link parseExpressionPrimary() { if (accept(C_SEMI)) return nullptr; // Semicolon is a no-op Node<ExpressionNode>::Link expr; if (accept(C_PAREN_LEFT)) { skip(); expr = expression(); expect(C_PAREN_RIGHT, "Mismatched parenthesis"); skip(); return expr; } else if (acceptTerminal()) { expr = exprFromCurrent(); skip(); // Check if there are any postfix operators around if (accept(POSTFIX)) { expr->addChild(exprFromCurrent()); skip(); } return expr; // Prefix operators } else if (accept(PREFIX)) { auto lastNode = expr = exprFromCurrent(); skip(); while (accept(PREFIX)) { lastNode->addChild(exprFromCurrent()); lastNode = lastNode->at(-1); skip(); } lastNode->addChild(parseExpressionPrimary()); return expr; } else { throw InternalError("Unimplemented primary expression", { METADATA_PAIRS, {"token", current().toString()}, {"token pos", std::to_string(pos)} }); } } Node<ExpressionNode>::Link expressionImpl(Node<ExpressionNode>::Link lhs, int minPrecedence) { Node<ExpressionNode>::Link base = nullptr; Node<ExpressionNode>::Link lastExpr = nullptr; Token tok = current(); if (isEndOfExpression()) return lhs; while (tok.hasArity(BINARY) && tok.getPrecedence() >= minPrecedence) { auto tokExpr = Node<ExpressionNode>::make(tok); tokExpr->setLineNumber(tok.line); tokExpr->addChild(lhs); skip(); auto rhs = parseExpressionPrimary(); tok = current(); while (tok.isOperator() && tok.hasArity(BINARY) && ( tok.getPrecedence() <= tokExpr->getToken().getPrecedence() || (tok.getPrecedence() == tokExpr->getToken().getPrecedence() && tok.hasAssociativity(ASSOCIATE_FROM_RIGHT)) ) ) { tokExpr->addChild(rhs); tokExpr = expressionImpl(tokExpr, tok.getPrecedence()); rhs = nullptr; tok = current(); } lhs = rhs; if (base == nullptr) { base = lastExpr = tokExpr; } else { lastExpr->addChild(tokExpr); lastExpr = tokExpr; } if (isEndOfExpression()) break; } if (base == nullptr) { base = lhs; } else if (lhs != nullptr) { lastExpr->addChild(lhs); } return base; } void initialize(Node<DeclarationNode>::Link decl) { // Do initialization only if it exists if (accept("=")) { skip(); decl->addChild(expression()); } } inline void expectSemi() { expect(C_SEMI, "Expected semicolon"); skip(); } // This function assumes K_IF has been skipped Node<BranchNode>::Link parseIfStatement() { auto branch = Node<BranchNode>::make(); branch->setLineNumber(current().line); branch->setCondition(expression()); branch->setSuccessBlock(block(IF_BLOCK)); skip(-1); // Go back to the block termination token if (accept(K_ELSE)) { skip(); // Else-if structure if (accept(K_IF)) { skip(); branch->setFailiureBlock(parseIfStatement()); // Simple else block } else if (accept(K_DO)) { branch->setFailiureBlock(block(CODE_BLOCK)); } else { throw Error("SyntaxError", "Else must be followed by a block or an if statement", current().line); } } return branch; } Node<DeclarationNode>::Link declarationFromTypes(TypeList typeList) { auto name = current().data; auto line = current().line; skip(); Node<DeclarationNode>::Link decl; if (typeList.size() == 0) decl = Node<DeclarationNode>::make(name); else decl = Node<DeclarationNode>::make(name, typeList); decl->setLineNumber(line); initialize(decl); return decl; } Node<DeclarationNode>::Link declaration() { if (accept(K_DEFINE)) { skip(); // Dynamic variable declaration if (accept(IDENTIFIER)) { return declarationFromTypes({}); // Function declaration } else if (accept(K_FUNCTION)) { skip(); // TODO throw InternalError("Unimplemented", {METADATA_PAIRS, {"token", "function def"}}); } else { throw Error("SyntaxError", "Unexpected token after define keyword", current().line); } } else if (accept(IDENTIFIER)) { auto ident = current().data; skip(); // Single-type declaration if (accept(IDENTIFIER)) { return declarationFromTypes({ident}); } // Multi-type declaration if (accept(",")) { TypeList types = {ident}; do { skip(); expect(IDENTIFIER, "Expected identifier in type list"); types.insert(current().data); skip(); } while (accept(",")); expect(IDENTIFIER); return declarationFromTypes(types); } } throw InternalError("Invalid declaration", {METADATA_PAIRS}); } ASTNode::Link statement() { if (accept(K_IF)) { skip(); return parseIfStatement(); } else if (accept(K_FOR)) { auto loop = Node<LoopNode>::make(); loop->setLineNumber(current().line); skip(); // Skip "for" loop->setInit(declaration()); expectSemi(); loop->setCondition(expression(false)); expectSemi(); loop->setUpdate(expression(false)); expectSemi(); loop->setCode(block(CODE_BLOCK)); return loop; } if (accept(K_WHILE)) { skip(); // TODO throw InternalError("Unimplemented", {METADATA_PAIRS, {"token", "while loop"}}); } else if (accept(K_DO)) { return block(CODE_BLOCK); } else if (accept(K_DEFINE)) { auto decl = declaration(); expectSemi(); return decl; } else if (accept(IDENTIFIER)) { skip(); if (accept(IDENTIFIER) || accept(",")) { skip(-1); // Go back to the prev identifier auto decl = declaration(); expectSemi(); return decl; } else { auto e = expression(); expectSemi(); return e; } } else { auto e = expression(); expectSemi(); return e; } } Node<BlockNode>::Link block(BlockType type) { if (type != ROOT_BLOCK) { expect(K_DO, "Expected code block"); skip(); } Node<BlockNode>::Link block = Node<BlockNode>::make(); block->setLineNumber(current().line); while (!accept(K_END)) { if (type == IF_BLOCK && accept(K_ELSE)) break; if (type == ROOT_BLOCK && accept(FILE_END)) break; block->addChild(statement()); } skip(); // Skip block end return block; } public: TokenParser() {} void parse(std::vector<Token> input) { this->input = input; pos = 0; tree = AST(); tree.setRoot(*block(ROOT_BLOCK)); } }; #endif <commit_msg>Fixed loop logic in token parser<commit_after>#ifndef TOKEN_PARSER_HPP #define TOKEN_PARSER_HPP #include <string> #include <vector> #include "baseParser.hpp" #include "ast.hpp" #include "token.hpp" #include "operator.hpp" /* EBNF-ish format of a program: program = block ; block = [ statement, ";", { statement, ";" } ] ; statement = declaration | ( "define", function ) | for_loop | while_loop | block | if_statement | try_catch | throw_statement | expression ; declaration = "define" | type_list, ident, [ "=", expression ] ; for_loop = "for", expression, ";", expression, ";", expression, "do", block, "end" ; while_loop = "while", expression, "do", block, "end" ; if_statement = "if", expression, "do", block, [ "else", block | if_statement ] | "end" ; type_definition = "define", "type", ident, [ "inherits", type_list ], "do", [ contructor_definition ], [ { method_definition | member_definition } ], "end" ; constructor_definition = "define", "constructor", [ argument, {",", argument } ], "do", block, "end" ; method_definition = "define", [ visibility_specifier ], [ "static" ], function ; member_definition = "define", [ visibility_specifier ], [ "static" ], ident, [ "=", expression ] ; try_catch = "try", block, "catch", type_list, ident, "do", block, "end" ; throw_statement = "throw", expression ; function = "function", ident, [ argument, {",", argument } ], [ "=>", type_list ], "do", block, "end" ; visibility_specifier = "public" | "private" | "protected" ; type_list = ident, {",", ident} ; argument = ( "[", type_list, ident, "]" ) | ( "[", ident, ":", type_list, "]" ) ; expression = ? any expr ? ; function_call = ident, "(", expression, { ",", expression }, ")" ; ident = ? any valid identifier ? ; */ class TokenParser: public BaseParser { private: std::vector<Token> input; uint64 pos = 0; enum BlockType { ROOT_BLOCK, CODE_BLOCK, IF_BLOCK }; inline Token current() { return input[pos]; } // Skip a number of tokens, usually just advances to the next one inline void skip(int by = 1) { pos += by; } inline bool accept(TokenType tok) { return tok == current().type; } inline bool accept(std::string operatorName) { if (!current().isOperator()) return false; if (current().hasOperatorName(operatorName)) return true; return false; } inline bool accept(Fixity fixity) { return current().isOperator() && current().hasFixity(fixity); } inline bool acceptTerminal() { return current().isTerminal(); } bool expect(TokenType tok, std::string errorMessage = "Unexpected symbol") { if (accept(tok)) { return true; } else { auto currentData = current().isOperator() ? current().getOperator().getName() : current().data; throw Error("SyntaxError", errorMessage + " (found: " + currentData + ")", current().line); } } inline bool isEndOfExpression() { return accept(C_SEMI) || accept(C_PAREN_RIGHT) || accept(FILE_END) || accept(K_DO); } inline Node<ExpressionNode>::Link exprFromCurrent() { auto e = Node<ExpressionNode>::make(current()); e->setLineNumber(current().line); return e; } Node<ExpressionNode>::Link expression(bool throwIfEmpty = true) { auto primary = parseExpressionPrimary(); if (primary == nullptr) { if (throwIfEmpty) throw InternalError("Empty expression", {METADATA_PAIRS}); else return nullptr; } return expressionImpl(primary, 0); } Node<ExpressionNode>::Link parseExpressionPrimary() { if (accept(C_SEMI) || accept(K_DO)) return nullptr; // Empty expression Node<ExpressionNode>::Link expr; if (accept(C_PAREN_LEFT)) { skip(); expr = expression(); expect(C_PAREN_RIGHT, "Mismatched parenthesis"); skip(); return expr; } else if (acceptTerminal()) { expr = exprFromCurrent(); skip(); // Check if there are any postfix operators around if (accept(POSTFIX)) { expr->addChild(exprFromCurrent()); skip(); } return expr; // Prefix operators } else if (accept(PREFIX)) { auto lastNode = expr = exprFromCurrent(); skip(); while (accept(PREFIX)) { lastNode->addChild(exprFromCurrent()); lastNode = lastNode->at(-1); skip(); } lastNode->addChild(parseExpressionPrimary()); return expr; } else { throw InternalError("Unimplemented primary expression", { METADATA_PAIRS, {"token", current().toString()}, {"token pos", std::to_string(pos)} }); } } Node<ExpressionNode>::Link expressionImpl(Node<ExpressionNode>::Link lhs, int minPrecedence) { Node<ExpressionNode>::Link base = nullptr; Node<ExpressionNode>::Link lastExpr = nullptr; Token tok = current(); if (isEndOfExpression()) return lhs; while (tok.hasArity(BINARY) && tok.getPrecedence() >= minPrecedence) { auto tokExpr = Node<ExpressionNode>::make(tok); tokExpr->setLineNumber(tok.line); tokExpr->addChild(lhs); skip(); auto rhs = parseExpressionPrimary(); tok = current(); while (tok.isOperator() && tok.hasArity(BINARY) && ( tok.getPrecedence() <= tokExpr->getToken().getPrecedence() || (tok.getPrecedence() == tokExpr->getToken().getPrecedence() && tok.hasAssociativity(ASSOCIATE_FROM_RIGHT)) ) ) { tokExpr->addChild(rhs); tokExpr = expressionImpl(tokExpr, tok.getPrecedence()); rhs = nullptr; tok = current(); } lhs = rhs; if (base == nullptr) { base = lastExpr = tokExpr; } else { lastExpr->addChild(tokExpr); lastExpr = tokExpr; } if (isEndOfExpression()) break; } if (base == nullptr) { base = lhs; } else if (lhs != nullptr) { lastExpr->addChild(lhs); } return base; } void initialize(Node<DeclarationNode>::Link decl) { // Do initialization only if it exists if (accept("=")) { skip(); decl->addChild(expression()); } } inline void expectSemi() { expect(C_SEMI, "Expected semicolon"); skip(); } // This function assumes K_IF has been skipped Node<BranchNode>::Link parseIfStatement() { auto branch = Node<BranchNode>::make(); branch->setLineNumber(current().line); branch->setCondition(expression()); branch->setSuccessBlock(block(IF_BLOCK)); skip(-1); // Go back to the block termination token if (accept(K_ELSE)) { skip(); // Else-if structure if (accept(K_IF)) { skip(); branch->setFailiureBlock(parseIfStatement()); // Simple else block } else if (accept(K_DO)) { branch->setFailiureBlock(block(CODE_BLOCK)); } else { throw Error("SyntaxError", "Else must be followed by a block or an if statement", current().line); } } return branch; } Node<DeclarationNode>::Link declarationFromTypes(TypeList typeList) { auto name = current().data; auto line = current().line; skip(); Node<DeclarationNode>::Link decl; if (typeList.size() == 0) decl = Node<DeclarationNode>::make(name); else decl = Node<DeclarationNode>::make(name, typeList); decl->setLineNumber(line); initialize(decl); return decl; } Node<DeclarationNode>::Link declaration(bool throwIfEmpty = true) { if (accept(C_SEMI)) { if (throwIfEmpty) throw InternalError("Empty declaration", {METADATA_PAIRS}); else return nullptr; } if (accept(K_DEFINE)) { skip(); // Dynamic variable declaration if (accept(IDENTIFIER)) { return declarationFromTypes({}); // Function declaration } else if (accept(K_FUNCTION)) { skip(); // TODO throw InternalError("Unimplemented", {METADATA_PAIRS, {"token", "function def"}}); } else { throw Error("SyntaxError", "Unexpected token after define keyword", current().line); } } else if (accept(IDENTIFIER)) { auto ident = current().data; skip(); // Single-type declaration if (accept(IDENTIFIER)) { return declarationFromTypes({ident}); } // Multi-type declaration if (accept(",")) { TypeList types = {ident}; do { skip(); expect(IDENTIFIER, "Expected identifier in type list"); types.insert(current().data); skip(); } while (accept(",")); expect(IDENTIFIER); return declarationFromTypes(types); } } throw InternalError("Invalid declaration", {METADATA_PAIRS}); } ASTNode::Link statement() { if (accept(K_IF)) { skip(); return parseIfStatement(); } else if (accept(K_FOR)) { auto loop = Node<LoopNode>::make(); loop->setLineNumber(current().line); skip(); // Skip "for" loop->setInit(declaration(false)); expectSemi(); loop->setCondition(expression(false)); expectSemi(); loop->setUpdate(expression(false)); loop->setCode(block(CODE_BLOCK)); return loop; } if (accept(K_WHILE)) { skip(); // TODO throw InternalError("Unimplemented", {METADATA_PAIRS, {"token", "while loop"}}); } else if (accept(K_DO)) { return block(CODE_BLOCK); } else if (accept(K_DEFINE)) { auto decl = declaration(); expectSemi(); return decl; } else if (accept(IDENTIFIER)) { skip(); if (accept(IDENTIFIER) || accept(",")) { skip(-1); // Go back to the prev identifier auto decl = declaration(); expectSemi(); return decl; } else { auto e = expression(); expectSemi(); return e; } } else { auto e = expression(); expectSemi(); return e; } } Node<BlockNode>::Link block(BlockType type) { if (type != ROOT_BLOCK) { expect(K_DO, "Expected code block"); skip(); } Node<BlockNode>::Link block = Node<BlockNode>::make(); block->setLineNumber(current().line); while (!accept(K_END)) { if (type == IF_BLOCK && accept(K_ELSE)) break; if (type == ROOT_BLOCK && accept(FILE_END)) break; block->addChild(statement()); } skip(); // Skip block end return block; } public: TokenParser() {} void parse(std::vector<Token> input) { this->input = input; pos = 0; tree = AST(); tree.setRoot(*block(ROOT_BLOCK)); } }; #endif <|endoftext|>
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Ethan Coon Default base with a few methods implemented in standard ways. ------------------------------------------------------------------------- */ #ifndef AMANZI_PK_DEFAULT_BASE_HH_ #define AMANZI_PK_DEFAULT_BASE_HH_ #include "Teuchos_ParameterList.hpp" #include "VerboseObject.hh" #include "PK.hh" namespace Amanzi { class PKDefaultBase : public PK { public: PKDefaultBase(const Teuchos::RCP<Teuchos::ParameterList>& plist, Teuchos::ParameterList& FElist, const Teuchos::RCP<TreeVector>& solution) : plist_(plist), solution_(solution) {} // Virtual destructor virtual ~PKDefaultBase() {} virtual void setup(const Teuchos::Ptr<State>& S); virtual void set_states(const Teuchos::RCP<const State>& S, const Teuchos::RCP<State>& S_inter, const Teuchos::RCP<State>& S_next); // -- ensure a solution is valid virtual bool valid_step() { return true; } virtual void solution_to_state(TreeVector& soln, const Teuchos::RCP<State>& S) = 0; // this is here to pass the buck virtually virtual void solution_to_state(const TreeVector& soln, const Teuchos::RCP<State>& S); virtual std::string name() { return name_; } protected: Teuchos::RCP<Teuchos::ParameterList> plist_; Teuchos::RCP<TreeVector> solution_; std::string name_; // states Teuchos::RCP<const State> S_; Teuchos::RCP<State> S_inter_; Teuchos::RCP<State> S_next_; // fancy OS Teuchos::RCP<VerboseObject> vo_; }; } // namespace #endif <commit_msg>test push<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Ethan Coon Default base with a few methods implemented in standard ways. ------------------------------------------------------------------------- */ #ifndef AMANZI_PK_DEFAULT_BASE_HH_ #define AMANZI_PK_DEFAULT_BASE_HH_ #include "Teuchos_ParameterList.hpp" #include "VerboseObject.hh" #include "PK.hh" namespace Amanzi { class PKDefaultBase : public PK { public: PKDefaultBase(const Teuchos::RCP<Teuchos::ParameterList>& plist, Teuchos::ParameterList& FElist, const Teuchos::RCP<TreeVector>& solution) : plist_(plist), solution_(solution) {} // Virtual destructor virtual ~PKDefaultBase() {} virtual void setup(const Teuchos::Ptr<State>& S); virtual void set_states(const Teuchos::RCP<const State>& S, const Teuchos::RCP<State>& S_inter, const Teuchos::RCP<State>& S_next); // -- ensure a solution is valid virtual bool valid_step() { return true; } virtual void solution_to_state(TreeVector& soln, const Teuchos::RCP<State>& S) = 0; // this is here to pass the buck virtually virtual void solution_to_state(const TreeVector& soln, const Teuchos::RCP<State>& S); virtual std::string name() { return name_; } protected: Teuchos::RCP<Teuchos::ParameterList> plist_; Teuchos::RCP<TreeVector> solution_; std::string name_; // states Teuchos::RCP<const State> S_; Teuchos::RCP<State> S_inter_; Teuchos::RCP<State> S_next_; // fancy OS Teuchos::RCP<VerboseObject> vo_; }; } // namespace #endif <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "PolygonNode.h" #include "NodeDefinition.h" #include "../graphics/VertexArray.h" #include "../base/Exception.h" #include "../base/GeomHelper.h" #include "../base/triangulate/Triangulate.h" #include "../glm/gtx/norm.hpp" #include <iostream> #include <sstream> using namespace std; namespace avg { NodeDefinition PolygonNode::createDefinition() { VectorVec2Vector cv; vector<glm::vec2> v; vector<float> vd; return NodeDefinition("polygon", Node::buildNode<PolygonNode>) .extendDefinition(FilledVectorNode::createDefinition()) .addArg(Arg<string>("linejoin", "bevel")) .addArg(Arg<vector<glm::vec2> >("pos", v, false, offsetof(PolygonNode, m_Pts))) .addArg(Arg<vector<float> >("texcoords", vd, false, offsetof(PolygonNode, m_TexCoords))) .addArg(Arg<VectorVec2Vector>("holes", cv, false, offsetof(PolygonNode, m_Holes))) ; } PolygonNode::PolygonNode(const ArgList& args) : FilledVectorNode(args) { args.setMembers(this); if (m_TexCoords.size() > m_Pts.size()+1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, "Too many texture coordinates in polygon")); } if (m_Pts.size() != 0 && m_Pts.size() < 3) { throw(Exception(AVG_ERR_UNSUPPORTED, "A polygon must have min. tree points.")); } if (m_Holes.size() > 0) { for (unsigned int i = 0; i < m_Holes.size(); i++) { if (m_Holes[i].size() < 3) { throw(Exception(AVG_ERR_UNSUPPORTED, "A hole of a polygon must have min. tree points.")); } } } setLineJoin(args.getArgVal<string>("linejoin")); calcPolyLineCumulDist(m_CumulDist, m_Pts, true); } PolygonNode::~PolygonNode() { } const vector<glm::vec2>& PolygonNode::getPos() const { return m_Pts; } void PolygonNode::setPos(const vector<glm::vec2>& pts) { m_Pts.clear(); m_Pts = pts; m_TexCoords.clear(); m_EffTexCoords.clear(); calcPolyLineCumulDist(m_CumulDist, m_Pts, true); setDrawNeeded(); } const vector<float>& PolygonNode::getTexCoords() const { return m_TexCoords; } const VectorVec2Vector& PolygonNode::getHoles() const { return m_Holes; } void PolygonNode::setHoles(const VectorVec2Vector& holes) { m_Holes = holes; m_TexCoords.clear(); m_EffTexCoords.clear(); setDrawNeeded(); } void PolygonNode::setTexCoords(const vector<float>& coords) { if (coords.size() > m_Pts.size()+1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, "Too many texture coordinates in polygon")); } m_EffTexCoords.clear(); m_TexCoords = coords; setDrawNeeded(); } string PolygonNode::getLineJoin() const { return lineJoin2String(m_LineJoin); } void PolygonNode::setLineJoin(const string& s) { m_LineJoin = string2LineJoin(s); setDrawNeeded(); } void PolygonNode::getElementsByPos(const glm::vec2& pos, vector<NodeWeakPtr>& pElements) { if (reactsToMouseEvents() && pointInPolygon(pos, m_Pts)) { pElements.push_back(shared_from_this()); } } void PolygonNode::calcVertexes(VertexArrayPtr& pVertexArray, Pixel32 color) { if (getNumDifferentPts(m_Pts) < 3) { return; } if (m_EffTexCoords.empty()) { calcEffPolyLineTexCoords(m_EffTexCoords, m_TexCoords, m_CumulDist); } calcPolyLine(m_Pts, m_EffTexCoords, true, m_LineJoin, pVertexArray, color); } void PolygonNode::calcFillVertexes(VertexArrayPtr& pVertexArray, Pixel32 color) { if (getNumDifferentPts(m_Pts) < 3) { return; } // Remove duplicate points vector<glm::vec2> pts; vector<unsigned int> holeIndexes; pts.reserve(m_Pts.size()); pts.push_back(m_Pts[0]); for (unsigned i = 1; i < m_Pts.size(); ++i) { if (glm::distance2(m_Pts[i], m_Pts[i-1]) > 0.1) { pts.push_back(m_Pts[i]); } } if (m_Holes.size() > 0) { for (unsigned int i = 0; i < m_Holes.size(); i++) { //loop over collection holeIndexes.push_back(pts.size()); for (unsigned int j = 0; j < m_Holes[i].size(); j++) { //loop over vector pts.push_back(m_Holes[i][j]); } } } if (color.getA() > 0) { glm::vec2 minCoord = pts[0]; glm::vec2 maxCoord = pts[0]; for (unsigned i = 1; i < pts.size(); ++i) { if (pts[i].x < minCoord.x) { minCoord.x = pts[i].x; } if (pts[i].x > maxCoord.x) { maxCoord.x = pts[i].x; } if (pts[i].y < minCoord.y) { minCoord.y = pts[i].y; } if (pts[i].y > maxCoord.y) { maxCoord.y = pts[i].y; } } vector<unsigned int> triIndexes; triangulatePolygon(triIndexes, pts, holeIndexes); for (unsigned i = 0; i < pts.size(); ++i) { glm::vec2 texCoord = calcFillTexCoord(pts[i], minCoord, maxCoord); pVertexArray->appendPos(pts[i], texCoord, color); } for (unsigned i = 0; i < triIndexes.size(); i+=3) { pVertexArray->appendTriIndexes(triIndexes[i], triIndexes[i+1], triIndexes[i+2]); } } } } <commit_msg>Add hole support to only border view of a polygonNode.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "PolygonNode.h" #include "NodeDefinition.h" #include "../graphics/VertexArray.h" #include "../base/Exception.h" #include "../base/GeomHelper.h" #include "../base/triangulate/Triangulate.h" #include "../glm/gtx/norm.hpp" #include <iostream> #include <sstream> using namespace std; namespace avg { NodeDefinition PolygonNode::createDefinition() { VectorVec2Vector cv; vector<glm::vec2> v; vector<float> vd; return NodeDefinition("polygon", Node::buildNode<PolygonNode>) .extendDefinition(FilledVectorNode::createDefinition()) .addArg(Arg<string>("linejoin", "bevel")) .addArg(Arg<vector<glm::vec2> >("pos", v, false, offsetof(PolygonNode, m_Pts))) .addArg(Arg<vector<float> >("texcoords", vd, false, offsetof(PolygonNode, m_TexCoords))) .addArg(Arg<VectorVec2Vector>("holes", cv, false, offsetof(PolygonNode, m_Holes))) ; } PolygonNode::PolygonNode(const ArgList& args) : FilledVectorNode(args) { args.setMembers(this); if (m_TexCoords.size() > m_Pts.size()+1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, "Too many texture coordinates in polygon")); } if (m_Pts.size() != 0 && m_Pts.size() < 3) { throw(Exception(AVG_ERR_UNSUPPORTED, "A polygon must have min. tree points.")); } if (m_Holes.size() > 0) { for (unsigned int i = 0; i < m_Holes.size(); i++) { if (m_Holes[i].size() < 3) { throw(Exception(AVG_ERR_UNSUPPORTED, "A hole of a polygon must have min. tree points.")); } } } setLineJoin(args.getArgVal<string>("linejoin")); calcPolyLineCumulDist(m_CumulDist, m_Pts, true); } PolygonNode::~PolygonNode() { } const vector<glm::vec2>& PolygonNode::getPos() const { return m_Pts; } void PolygonNode::setPos(const vector<glm::vec2>& pts) { m_Pts.clear(); m_Pts = pts; m_TexCoords.clear(); m_EffTexCoords.clear(); calcPolyLineCumulDist(m_CumulDist, m_Pts, true); setDrawNeeded(); } const vector<float>& PolygonNode::getTexCoords() const { return m_TexCoords; } const VectorVec2Vector& PolygonNode::getHoles() const { return m_Holes; } void PolygonNode::setHoles(const VectorVec2Vector& holes) { m_Holes = holes; m_TexCoords.clear(); m_EffTexCoords.clear(); setDrawNeeded(); } void PolygonNode::setTexCoords(const vector<float>& coords) { if (coords.size() > m_Pts.size()+1) { throw(Exception(AVG_ERR_OUT_OF_RANGE, "Too many texture coordinates in polygon")); } m_EffTexCoords.clear(); m_TexCoords = coords; setDrawNeeded(); } string PolygonNode::getLineJoin() const { return lineJoin2String(m_LineJoin); } void PolygonNode::setLineJoin(const string& s) { m_LineJoin = string2LineJoin(s); setDrawNeeded(); } void PolygonNode::getElementsByPos(const glm::vec2& pos, vector<NodeWeakPtr>& pElements) { if (reactsToMouseEvents() && pointInPolygon(pos, m_Pts)) { pElements.push_back(shared_from_this()); } } void PolygonNode::calcVertexes(VertexArrayPtr& pVertexArray, Pixel32 color) { if (getNumDifferentPts(m_Pts) < 3) { return; } if (m_EffTexCoords.empty()) { calcEffPolyLineTexCoords(m_EffTexCoords, m_TexCoords, m_CumulDist); } calcPolyLine(m_Pts, m_EffTexCoords, true, m_LineJoin, pVertexArray, color); for (unsigned i = 0; i < m_Holes.size(); i++) { calcPolyLine(m_Holes[i], m_EffTexCoords, true, m_LineJoin, pVertexArray, color); } } void PolygonNode::calcFillVertexes(VertexArrayPtr& pVertexArray, Pixel32 color) { if (getNumDifferentPts(m_Pts) < 3) { return; } // Remove duplicate points vector<glm::vec2> pts; vector<unsigned int> holeIndexes; pts.reserve(m_Pts.size()); pts.push_back(m_Pts[0]); for (unsigned i = 1; i < m_Pts.size(); ++i) { if (glm::distance2(m_Pts[i], m_Pts[i-1]) > 0.1) { pts.push_back(m_Pts[i]); } } if (m_Holes.size() > 0) { for (unsigned int i = 0; i < m_Holes.size(); i++) { //loop over collection holeIndexes.push_back(pts.size()); for (unsigned int j = 0; j < m_Holes[i].size(); j++) { //loop over vector pts.push_back(m_Holes[i][j]); } } } if (color.getA() > 0) { glm::vec2 minCoord = pts[0]; glm::vec2 maxCoord = pts[0]; for (unsigned i = 1; i < pts.size(); ++i) { if (pts[i].x < minCoord.x) { minCoord.x = pts[i].x; } if (pts[i].x > maxCoord.x) { maxCoord.x = pts[i].x; } if (pts[i].y < minCoord.y) { minCoord.y = pts[i].y; } if (pts[i].y > maxCoord.y) { maxCoord.y = pts[i].y; } } vector<unsigned int> triIndexes; triangulatePolygon(triIndexes, pts, holeIndexes); for (unsigned i = 0; i < pts.size(); ++i) { glm::vec2 texCoord = calcFillTexCoord(pts[i], minCoord, maxCoord); pVertexArray->appendPos(pts[i], texCoord, color); } for (unsigned i = 0; i < triIndexes.size(); i+=3) { pVertexArray->appendTriIndexes(triIndexes[i], triIndexes[i+1], triIndexes[i+2]); } } } } <|endoftext|>
<commit_before>#include "transactionview.h" #include "transactionfilterproxy.h" #include "transactionrecord.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "bitcoinunits.h" #include "csvmodelwriter.h" #include "transactiondescdialog.h" #include "editaddressdialog.h" #include "optionsmodel.h" #include "guiutil.h" #include <QScrollBar> #include <QComboBox> #include <QDoubleValidator> #include <QHBoxLayout> #include <QVBoxLayout> #include <QLineEdit> #include <QTableView> #include <QHeaderView> #include <QPushButton> #include <QMessageBox> #include <QPoint> #include <QMenu> #include <QApplication> #include <QClipboard> #include <QLabel> #include <QDateTimeEdit> TransactionView::TransactionView(QWidget *parent) : QWidget(parent), model(0), transactionProxyModel(0), transactionView(0) { // Build filter row setContentsMargins(0,0,0,0); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->setContentsMargins(0,0,0,0); #ifdef Q_OS_MAC hlayout->setSpacing(5); hlayout->addSpacing(26); #else hlayout->setSpacing(0); hlayout->addSpacing(23); #endif dateWidget = new QComboBox(this); #ifdef Q_OS_MAC dateWidget->setFixedWidth(121); #else dateWidget->setFixedWidth(120); #endif dateWidget->addItem(tr("Today"), Today); dateWidget->addItem(tr("All"), All); dateWidget->addItem(tr("This week"), ThisWeek); dateWidget->addItem(tr("This month"), ThisMonth); dateWidget->addItem(tr("Last month"), LastMonth); dateWidget->addItem(tr("This year"), ThisYear); dateWidget->addItem(tr("Range..."), Range); hlayout->addWidget(dateWidget); typeWidget = new QComboBox(this); #ifdef Q_OS_MAC typeWidget->setFixedWidth(121); #else typeWidget->setFixedWidth(120); #endif typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES); typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) | TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther)); typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) | TransactionFilterProxy::TYPE(TransactionRecord::SendToOther)); typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf)); typeWidget->addItem(tr("Mined"), TransactionFilterProxy::TYPE(TransactionRecord::Generated)); typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other)); hlayout->addWidget(typeWidget); addressWidget = new QLineEdit(this); #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ addressWidget->setPlaceholderText(tr("Enter address or label to search")); #endif hlayout->addWidget(addressWidget); amountWidget = new QLineEdit(this); #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ amountWidget->setPlaceholderText(tr("Min amount")); #endif #ifdef Q_OS_MAC amountWidget->setFixedWidth(97); #else amountWidget->setFixedWidth(100); #endif amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this)); hlayout->addWidget(amountWidget); QVBoxLayout *vlayout = new QVBoxLayout(this); vlayout->setContentsMargins(0,0,0,0); vlayout->setSpacing(0); QTableView *view = new QTableView(this); vlayout->addLayout(hlayout); vlayout->addWidget(createDateRangeWidget()); vlayout->addWidget(view); vlayout->setSpacing(0); int width = view->verticalScrollBar()->sizeHint().width(); // Cover scroll bar width with spacing #ifdef Q_OS_MAC hlayout->addSpacing(width+2); #else hlayout->addSpacing(width); #endif // Always show scroll bar view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); view->setTabKeyNavigation(false); view->setContextMenuPolicy(Qt::CustomContextMenu); transactionView = view; // Actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); QAction *copyTxIDAction = new QAction(tr("Copy transaction ID"), this); QAction *editLabelAction = new QAction(tr("Edit label"), this); QAction *showDetailsAction = new QAction(tr("Show transaction details"), this); contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTxIDAction); contextMenu->addAction(editLabelAction); contextMenu->addAction(showDetailsAction); // Connect actions connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int))); connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int))); connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString))); connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString))); connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex))); connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID())); connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel())); connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails())); } void TransactionView::setModel(WalletModel *model) { this->model = model; if(model) { transactionProxyModel = new TransactionFilterProxy(this); transactionProxyModel->setSourceModel(model->getTransactionTableModel()); transactionProxyModel->setDynamicSortFilter(true); transactionProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); transactionProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); transactionProxyModel->setSortRole(Qt::EditRole); transactionView->setModel(transactionProxyModel); transactionView->setAlternatingRowColors(true); transactionView->setSelectionBehavior(QAbstractItemView::SelectRows); transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection); transactionView->setSortingEnabled(true); transactionView->sortByColumn(TransactionTableModel::Date, Qt::DescendingOrder); transactionView->verticalHeader()->hide(); transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Status, 23); transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Date, 120); transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Type, 120); transactionView->horizontalHeader()->setResizeMode( TransactionTableModel::ToAddress, QHeaderView::Stretch); transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Amount, 100); } } void TransactionView::chooseDate(int idx) { if(!transactionProxyModel) return; QDate current = QDate::currentDate(); dateRangeWidget->setVisible(false); switch(dateWidget->itemData(idx).toInt()) { case All: transactionProxyModel->setDateRange( TransactionFilterProxy::MIN_DATE, TransactionFilterProxy::MAX_DATE); break; case Today: transactionProxyModel->setDateRange( QDateTime(current), TransactionFilterProxy::MAX_DATE); break; case ThisWeek: { // Find last Monday QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1)); transactionProxyModel->setDateRange( QDateTime(startOfWeek), TransactionFilterProxy::MAX_DATE); } break; case ThisMonth: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), current.month(), 1)), TransactionFilterProxy::MAX_DATE); break; case LastMonth: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), current.month()-1, 1)), QDateTime(QDate(current.year(), current.month(), 1))); break; case ThisYear: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), 1, 1)), TransactionFilterProxy::MAX_DATE); break; case Range: dateRangeWidget->setVisible(true); dateRangeChanged(); break; } } void TransactionView::chooseType(int idx) { if(!transactionProxyModel) return; transactionProxyModel->setTypeFilter( typeWidget->itemData(idx).toInt()); } void TransactionView::changedPrefix(const QString &prefix) { if(!transactionProxyModel) return; transactionProxyModel->setAddressPrefix(prefix); } void TransactionView::changedAmount(const QString &amount) { if(!transactionProxyModel) return; qint64 amount_parsed = 0; if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed)) { transactionProxyModel->setMinAmount(amount_parsed); } else { transactionProxyModel->setMinAmount(0); } } void TransactionView::exportClicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Transaction Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(transactionProxyModel); writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole); writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole); writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole); writer.addColumn(tr("Label"), 0, TransactionTableModel::LabelRole); writer.addColumn(tr("Address"), 0, TransactionTableModel::AddressRole); writer.addColumn(tr("Amount"), 0, TransactionTableModel::FormattedAmountRole); writer.addColumn(tr("ID"), 0, TransactionTableModel::TxIDRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void TransactionView::contextualMenu(const QPoint &point) { QModelIndex index = transactionView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void TransactionView::copyAddress() { GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole); } void TransactionView::copyLabel() { GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole); } void TransactionView::copyAmount() { GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole); } void TransactionView::copyTxID() { GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::TxIDRole); } void TransactionView::editLabel() { if(!transactionView->selectionModel() ||!model) return; QModelIndexList selection = transactionView->selectionModel()->selectedRows(); if(!selection.isEmpty()) { AddressTableModel *addressBook = model->getAddressTableModel(); if(!addressBook) return; QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString(); if(address.isEmpty()) { // If this transaction has no associated address, exit return; } // Is address in address book? Address book can miss address when a transaction is // sent from outside the UI. int idx = addressBook->lookupAddress(address); if(idx != -1) { // Edit sending / receiving address QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex()); // Determine type of address, launch appropriate editor dialog type QString type = modelIdx.data(AddressTableModel::TypeRole).toString(); EditAddressDialog dlg(type==AddressTableModel::Receive ? EditAddressDialog::EditReceivingAddress : EditAddressDialog::EditSendingAddress, this); dlg.setModel(addressBook); dlg.loadRow(idx); dlg.exec(); } else { // Add sending address EditAddressDialog dlg(EditAddressDialog::NewSendingAddress, this); dlg.setModel(addressBook); dlg.setAddress(address); dlg.exec(); } } } void TransactionView::showDetails() { if(!transactionView->selectionModel()) return; QModelIndexList selection = transactionView->selectionModel()->selectedRows(); if(!selection.isEmpty()) { TransactionDescDialog dlg(selection.at(0)); dlg.exec(); } } QWidget *TransactionView::createDateRangeWidget() { dateRangeWidget = new QFrame(); dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised); dateRangeWidget->setContentsMargins(1,1,1,1); QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget); layout->setContentsMargins(0,0,0,0); layout->addSpacing(23); layout->addWidget(new QLabel(tr("Range:"))); dateFrom = new QDateTimeEdit(this); dateFrom->setDisplayFormat("dd/MM/yy"); dateFrom->setCalendarPopup(true); dateFrom->setMinimumWidth(100); dateFrom->setDate(QDate::currentDate().addDays(-7)); layout->addWidget(dateFrom); layout->addWidget(new QLabel(tr("to"))); dateTo = new QDateTimeEdit(this); dateTo->setDisplayFormat("dd/MM/yy"); dateTo->setCalendarPopup(true); dateTo->setMinimumWidth(100); dateTo->setDate(QDate::currentDate()); layout->addWidget(dateTo); layout->addStretch(); // Hide by default dateRangeWidget->setVisible(false); // Notify on change connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged())); connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged())); return dateRangeWidget; } void TransactionView::dateRangeChanged() { if(!transactionProxyModel) return; transactionProxyModel->setDateRange( QDateTime(dateFrom->date()), QDateTime(dateTo->date()).addDays(1)); } void TransactionView::focusTransaction(const QModelIndex &idx) { if(!transactionProxyModel) return; QModelIndex targetIdx = transactionProxyModel->mapFromSource(idx); transactionView->scrollTo(targetIdx); transactionView->setCurrentIndex(targetIdx); transactionView->setFocus(); } <commit_msg>Transaction view cleanup<commit_after>#include "transactionview.h" #include "transactionfilterproxy.h" #include "transactionrecord.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "bitcoinunits.h" #include "csvmodelwriter.h" #include "transactiondescdialog.h" #include "editaddressdialog.h" #include "optionsmodel.h" #include "guiutil.h" #include <QScrollBar> #include <QComboBox> #include <QDoubleValidator> #include <QHBoxLayout> #include <QVBoxLayout> #include <QLineEdit> #include <QTableView> #include <QHeaderView> #include <QPushButton> #include <QMessageBox> #include <QPoint> #include <QMenu> #include <QApplication> #include <QClipboard> #include <QLabel> #include <QDateTimeEdit> TransactionView::TransactionView(QWidget *parent) : QWidget(parent), model(0), transactionProxyModel(0), transactionView(0) { // Build filter row setContentsMargins(0,0,0,0); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->setContentsMargins(0,0,0,0); #ifdef Q_OS_MAC hlayout->setSpacing(5); hlayout->addSpacing(26); #else hlayout->setSpacing(0); hlayout->addSpacing(23); #endif dateWidget = new QComboBox(this); #ifdef Q_OS_MAC dateWidget->setFixedWidth(121); #else dateWidget->setFixedWidth(120); #endif dateWidget->addItem(tr("Today"), Today); dateWidget->addItem(tr("All"), All); dateWidget->addItem(tr("This week"), ThisWeek); dateWidget->addItem(tr("This month"), ThisMonth); dateWidget->addItem(tr("Last month"), LastMonth); dateWidget->addItem(tr("This year"), ThisYear); dateWidget->addItem(tr("Range..."), Range); hlayout->addWidget(dateWidget); typeWidget = new QComboBox(this); #ifdef Q_OS_MAC typeWidget->setFixedWidth(121); #else typeWidget->setFixedWidth(120); #endif typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES); typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) | TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther)); typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) | TransactionFilterProxy::TYPE(TransactionRecord::SendToOther)); typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf)); typeWidget->addItem(tr("Mined"), TransactionFilterProxy::TYPE(TransactionRecord::Generated)); typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other)); hlayout->addWidget(typeWidget); addressWidget = new QLineEdit(this); #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ addressWidget->setPlaceholderText(tr("Enter address or label to search")); #endif hlayout->addWidget(addressWidget); amountWidget = new QLineEdit(this); #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ amountWidget->setPlaceholderText(tr("Min amount")); #endif #ifdef Q_OS_MAC amountWidget->setFixedWidth(97); #else amountWidget->setFixedWidth(100); #endif amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this)); hlayout->addWidget(amountWidget); QVBoxLayout *vlayout = new QVBoxLayout(this); vlayout->setContentsMargins(0,0,0,0); vlayout->setSpacing(0); QTableView *view = new QTableView(this); vlayout->addLayout(hlayout); vlayout->addWidget(createDateRangeWidget()); vlayout->addWidget(view); vlayout->setSpacing(0); int width = view->verticalScrollBar()->sizeHint().width(); // Cover scroll bar width with spacing #ifdef Q_OS_MAC hlayout->addSpacing(width+2); #else hlayout->addSpacing(width); #endif // Always show scroll bar view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); view->setTabKeyNavigation(false); view->setContextMenuPolicy(Qt::CustomContextMenu); transactionView = view; // Actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); QAction *copyTxIDAction = new QAction(tr("Copy transaction ID"), this); QAction *editLabelAction = new QAction(tr("Edit label"), this); QAction *showDetailsAction = new QAction(tr("Show transaction details"), this); contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTxIDAction); contextMenu->addAction(editLabelAction); contextMenu->addAction(showDetailsAction); // Connect actions connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int))); connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int))); connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString))); connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString))); connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex))); connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID())); connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel())); connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails())); } void TransactionView::setModel(WalletModel *model) { this->model = model; if(model) { transactionProxyModel = new TransactionFilterProxy(this); transactionProxyModel->setSourceModel(model->getTransactionTableModel()); transactionProxyModel->setDynamicSortFilter(true); transactionProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); transactionProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); transactionProxyModel->setSortRole(Qt::EditRole); transactionView->setModel(transactionProxyModel); transactionView->setAlternatingRowColors(true); transactionView->setSelectionBehavior(QAbstractItemView::SelectRows); transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection); transactionView->setSortingEnabled(true); transactionView->sortByColumn(TransactionTableModel::Date, Qt::DescendingOrder); transactionView->verticalHeader()->hide(); transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Status, 23); transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Date, 100); transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Type, 100); transactionView->horizontalHeader()->setResizeMode( TransactionTableModel::ToAddress, QHeaderView::Stretch); transactionView->horizontalHeader()->setResizeMode( TransactionTableModel::Narration, QHeaderView::Stretch); transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Amount, 100); } } void TransactionView::chooseDate(int idx) { if(!transactionProxyModel) return; QDate current = QDate::currentDate(); dateRangeWidget->setVisible(false); switch(dateWidget->itemData(idx).toInt()) { case All: transactionProxyModel->setDateRange( TransactionFilterProxy::MIN_DATE, TransactionFilterProxy::MAX_DATE); break; case Today: transactionProxyModel->setDateRange( QDateTime(current), TransactionFilterProxy::MAX_DATE); break; case ThisWeek: { // Find last Monday QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1)); transactionProxyModel->setDateRange( QDateTime(startOfWeek), TransactionFilterProxy::MAX_DATE); } break; case ThisMonth: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), current.month(), 1)), TransactionFilterProxy::MAX_DATE); break; case LastMonth: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), current.month()-1, 1)), QDateTime(QDate(current.year(), current.month(), 1))); break; case ThisYear: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), 1, 1)), TransactionFilterProxy::MAX_DATE); break; case Range: dateRangeWidget->setVisible(true); dateRangeChanged(); break; } } void TransactionView::chooseType(int idx) { if(!transactionProxyModel) return; transactionProxyModel->setTypeFilter( typeWidget->itemData(idx).toInt()); } void TransactionView::changedPrefix(const QString &prefix) { if(!transactionProxyModel) return; transactionProxyModel->setAddressPrefix(prefix); } void TransactionView::changedAmount(const QString &amount) { if(!transactionProxyModel) return; qint64 amount_parsed = 0; if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed)) { transactionProxyModel->setMinAmount(amount_parsed); } else { transactionProxyModel->setMinAmount(0); } } void TransactionView::exportClicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Transaction Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(transactionProxyModel); writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole); writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole); writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole); writer.addColumn(tr("Label"), 0, TransactionTableModel::LabelRole); writer.addColumn(tr("Address"), 0, TransactionTableModel::AddressRole); writer.addColumn(tr("Amount"), 0, TransactionTableModel::FormattedAmountRole); writer.addColumn(tr("ID"), 0, TransactionTableModel::TxIDRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void TransactionView::contextualMenu(const QPoint &point) { QModelIndex index = transactionView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void TransactionView::copyAddress() { GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole); } void TransactionView::copyLabel() { GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole); } void TransactionView::copyAmount() { GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole); } void TransactionView::copyTxID() { GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::TxIDRole); } void TransactionView::editLabel() { if(!transactionView->selectionModel() ||!model) return; QModelIndexList selection = transactionView->selectionModel()->selectedRows(); if(!selection.isEmpty()) { AddressTableModel *addressBook = model->getAddressTableModel(); if(!addressBook) return; QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString(); if(address.isEmpty()) { // If this transaction has no associated address, exit return; } // Is address in address book? Address book can miss address when a transaction is // sent from outside the UI. int idx = addressBook->lookupAddress(address); if(idx != -1) { // Edit sending / receiving address QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex()); // Determine type of address, launch appropriate editor dialog type QString type = modelIdx.data(AddressTableModel::TypeRole).toString(); EditAddressDialog dlg(type==AddressTableModel::Receive ? EditAddressDialog::EditReceivingAddress : EditAddressDialog::EditSendingAddress, this); dlg.setModel(addressBook); dlg.loadRow(idx); dlg.exec(); } else { // Add sending address EditAddressDialog dlg(EditAddressDialog::NewSendingAddress, this); dlg.setModel(addressBook); dlg.setAddress(address); dlg.exec(); } } } void TransactionView::showDetails() { if(!transactionView->selectionModel()) return; QModelIndexList selection = transactionView->selectionModel()->selectedRows(); if(!selection.isEmpty()) { TransactionDescDialog dlg(selection.at(0)); dlg.exec(); } } QWidget *TransactionView::createDateRangeWidget() { dateRangeWidget = new QFrame(); dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised); dateRangeWidget->setContentsMargins(1,1,1,1); QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget); layout->setContentsMargins(0,0,0,0); layout->addSpacing(23); layout->addWidget(new QLabel(tr("Range:"))); dateFrom = new QDateTimeEdit(this); dateFrom->setDisplayFormat("dd/MM/yy"); dateFrom->setCalendarPopup(true); dateFrom->setMinimumWidth(100); dateFrom->setDate(QDate::currentDate().addDays(-7)); layout->addWidget(dateFrom); layout->addWidget(new QLabel(tr("to"))); dateTo = new QDateTimeEdit(this); dateTo->setDisplayFormat("dd/MM/yy"); dateTo->setCalendarPopup(true); dateTo->setMinimumWidth(100); dateTo->setDate(QDate::currentDate()); layout->addWidget(dateTo); layout->addStretch(); // Hide by default dateRangeWidget->setVisible(false); // Notify on change connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged())); connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged())); return dateRangeWidget; } void TransactionView::dateRangeChanged() { if(!transactionProxyModel) return; transactionProxyModel->setDateRange( QDateTime(dateFrom->date()), QDateTime(dateTo->date()).addDays(1)); } void TransactionView::focusTransaction(const QModelIndex &idx) { if(!transactionProxyModel) return; QModelIndex targetIdx = transactionProxyModel->mapFromSource(idx); transactionView->scrollTo(targetIdx); transactionView->setCurrentIndex(targetIdx); transactionView->setFocus(); } <|endoftext|>
<commit_before>#ifndef _SG_EVENT_MGR_HXX #define _SG_EVENT_MGR_HXX #include <simgear/props/props.hxx> #include <simgear/structure/subsystem_mgr.hxx> #include "callback.hxx" class SGEventMgr; struct SGTimer { double interval; SGCallback* callback; SGEventMgr* mgr; bool repeat; bool simtime; void run(); }; class SGTimerQueue { public: SGTimerQueue(int preSize=1); ~SGTimerQueue(); void update(double deltaSecs); double now() { return _now; } void insert(SGTimer* timer, double time); SGTimer* remove(SGTimer* timer); SGTimer* remove(); SGTimer* nextTimer() { return _numEntries ? _table[0].timer : 0; } double nextTime() { return -_table[0].pri; } private: // The "priority" is stored as a negative time. This allows the // implemenetation to treat the "top" of the heap as the largest // value and avoids developer mindbugs. ;) struct HeapEntry { double pri; SGTimer* timer; }; int parent(int n) { return ((n+1)/2) - 1; } int lchild(int n) { return ((n+1)*2) - 1; } int rchild(int n) { return ((n+1)*2 + 1) - 1; } double pri(int n) { return _table[n].pri; } void swap(int a, int b) { HeapEntry tmp = _table[a]; _table[a] = _table[b]; _table[b] = tmp; } void siftDown(int n); void siftUp(int n); void growArray(); void check(); double _now; HeapEntry *_table; int _numEntries; int _tableSize; }; class SGEventMgr : public SGSubsystem { public: SGEventMgr() { _rtProp = 0; } ~SGEventMgr() { _rtProp = 0; } virtual void init() {} virtual void update(double delta_time_sec); void setRealtimeProperty(SGPropertyNode* node) { _rtProp = node; } /** * Add a single function callback event as a repeating task. * ex: addTask("foo", &Function ... ) */ template<typename FUNC> inline void addTask(const char* name, const FUNC& f, double interval, double delay=0, bool sim=false) { add(make_callback(f), interval, delay, true, sim); } /** * Add a single function callback event as a one-shot event. * ex: addEvent("foo", &Function ... ) */ template<typename FUNC> inline void addEvent(const char* name, const FUNC& f, double delay, bool sim=false) { add(make_callback(f), 0, delay, false, sim); } /** * Add a object/method pair as a repeating task. * ex: addTask("foo", &object, &ClassName::Method, ...) */ template<class OBJ, typename METHOD> inline void addTask(const char* name, const OBJ& o, METHOD m, double interval, double delay=0, bool sim=false) { add(make_callback(o,m), interval, delay, true, sim); } /** * Add a object/method pair as a repeating task. * ex: addEvent("foo", &object, &ClassName::Method, ...) */ template<class OBJ, typename METHOD> inline void addEvent(const char* name, const OBJ& o, METHOD m, double delay, bool sim=false) { add(make_callback(o,m), 0, delay, false, sim); } private: friend struct SGTimer; void add(SGCallback* cb, double interval, double delay, bool repeat, bool simtime); SGPropertyNode* _freezeProp; SGPropertyNode* _rtProp; SGTimerQueue _rtQueue; SGTimerQueue _simQueue; }; #endif // _SG_EVENT_MGR_HXX <commit_msg>gcc 4.0 fix.<commit_after>#ifndef _SG_EVENT_MGR_HXX #define _SG_EVENT_MGR_HXX #include <simgear/props/props.hxx> #include <simgear/structure/subsystem_mgr.hxx> #include "callback.hxx" class SGEventMgr; struct SGTimer { double interval; SGCallback* callback; SGEventMgr* mgr; bool repeat; bool simtime; void run(); }; class SGTimerQueue { public: SGTimerQueue(int preSize=1); ~SGTimerQueue(); void update(double deltaSecs); double now() { return _now; } void insert(SGTimer* timer, double time); SGTimer* remove(SGTimer* timer); SGTimer* remove(); SGTimer* nextTimer() { return _numEntries ? _table[0].timer : 0; } double nextTime() { return -_table[0].pri; } private: // The "priority" is stored as a negative time. This allows the // implemenetation to treat the "top" of the heap as the largest // value and avoids developer mindbugs. ;) struct HeapEntry { double pri; SGTimer* timer; }; int parent(int n) { return ((n+1)/2) - 1; } int lchild(int n) { return ((n+1)*2) - 1; } int rchild(int n) { return ((n+1)*2 + 1) - 1; } double pri(int n) { return _table[n].pri; } void swap(int a, int b) { HeapEntry tmp = _table[a]; _table[a] = _table[b]; _table[b] = tmp; } void siftDown(int n); void siftUp(int n); void growArray(); // gcc complains there is no function specification anywhere. // void check(); double _now; HeapEntry *_table; int _numEntries; int _tableSize; }; class SGEventMgr : public SGSubsystem { public: SGEventMgr() { _rtProp = 0; } ~SGEventMgr() { _rtProp = 0; } virtual void init() {} virtual void update(double delta_time_sec); void setRealtimeProperty(SGPropertyNode* node) { _rtProp = node; } /** * Add a single function callback event as a repeating task. * ex: addTask("foo", &Function ... ) */ template<typename FUNC> inline void addTask(const char* name, const FUNC& f, double interval, double delay=0, bool sim=false) { add(make_callback(f), interval, delay, true, sim); } /** * Add a single function callback event as a one-shot event. * ex: addEvent("foo", &Function ... ) */ template<typename FUNC> inline void addEvent(const char* name, const FUNC& f, double delay, bool sim=false) { add(make_callback(f), 0, delay, false, sim); } /** * Add a object/method pair as a repeating task. * ex: addTask("foo", &object, &ClassName::Method, ...) */ template<class OBJ, typename METHOD> inline void addTask(const char* name, const OBJ& o, METHOD m, double interval, double delay=0, bool sim=false) { add(make_callback(o,m), interval, delay, true, sim); } /** * Add a object/method pair as a repeating task. * ex: addEvent("foo", &object, &ClassName::Method, ...) */ template<class OBJ, typename METHOD> inline void addEvent(const char* name, const OBJ& o, METHOD m, double delay, bool sim=false) { add(make_callback(o,m), 0, delay, false, sim); } private: friend struct SGTimer; void add(SGCallback* cb, double interval, double delay, bool repeat, bool simtime); SGPropertyNode* _freezeProp; SGPropertyNode* _rtProp; SGTimerQueue _rtQueue; SGTimerQueue _simQueue; }; #endif // _SG_EVENT_MGR_HXX <|endoftext|>
<commit_before>/*! * @file pline_fill.cpp * @brief Simple tool for filling polygonal holes in meshes * @author Bastian Rieck <bastian.rieck@iwr.uni-heidelberg.de> */ #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <string> #include <vector> #include <limits> #include <getopt.h> #include "hole.h" /*! * Processes a .pline file, in which each line consists of a hole, * described as a closed chain of vertices. * * @param filename Filename */ void process_pline_file(std::string filename) { std::ifstream in(filename.c_str()); if(!in.good()) { std::cerr << "pline_fill: Unable to open .pline file \"" << filename << "\"." << std::endl; return; } else std::cout << "pline_fill: Processing file \"" << filename << "\" " << std::flush; std::string line; std::stringstream converter; size_t curr_id = 0; // stores ID of _current_ pline size_t prev_id = 0; // stores ID of _previous_ pline size_t counter = 0; // stores counter for group of plines. Since // several plines may share one ID, the counter // is required to store them in individual // files of the form "<Filename>_<ID>_<Counter>.ply". while(std::getline(in, line)) { // Ignore lines containing a "#" if(line.find_first_of('#') != std::string::npos) continue; converter.str(line); // Data format is straightforward (different fields are assumed to // be separated by whitespace). // // Label ID | number of vertices | id1 x1 y1 z1 n1 n2 n3 id2 x2 y2 z2 ... size_t num_vertices; // Vector of vertices (actually, only the _positions_ and // vertex IDs) for the current polygonal line std::vector< std::pair<v3ctor, size_t> > vertices; converter >> curr_id >> num_vertices; if(curr_id == prev_id) counter++; else counter = 0; // reset counter if the next group of plines is reached for(size_t i = 0; i < num_vertices-1; i++) // ignore last point because it is a repetition of // the first point { std::pair<v3ctor, size_t> vertex_w_id; vertex_w_id.second = std::numeric_limits<size_t>::max(); converter >> vertex_w_id.second >> vertex_w_id.first[0] >> vertex_w_id.first[1] >> vertex_w_id.first[2]; if(vertex_w_id.second == std::numeric_limits<size_t>::max()) { std::cerr << "pline_fill: Could not parse .pline file -- missing a vertex ID\n"; return; } // XXX: Ignore normals double dummy; converter >> dummy >> dummy >> dummy; vertices.push_back(vertex_w_id); } psalm::hole H; H.initialize(vertices); H.triangulate(); // Construct filename converter.str(""); converter.clear(); converter << filename << "_" << std::setw(4) << std::setfill('0') << curr_id << "_" << std::setw(4) << std::setfill('0') << counter << ".ply"; H.save(converter.str()); converter.clear(); line.clear(); std::cout << "." << std::flush; } std::cout << "done." << std::endl; } int main(int argc, char* argv[]) { static option cmd_line_opts[] = { {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; int option = 0; while((option = getopt_long(argc, argv, "h", cmd_line_opts, NULL)) != -1) { switch(option) { case 'h': break; } } // Further command-line parameters are assumed to be input files for // the program. These are handled sequentially. while(optind < argc) process_pline_file(argv[optind++]); return(0); } <commit_msg>Added preliminary workflow for pline_fill program<commit_after>/*! * @file pline_fill.cpp * @brief Simple tool for filling polygonal holes in meshes * @author Bastian Rieck <bastian.rieck@iwr.uni-heidelberg.de> */ #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <string> #include <vector> #include <limits> #include <getopt.h> #include "hole.h" /*! * Processes a .pline file, in which each line consists of a hole, * described as a closed chain of vertices. * * @param filename Filename */ void process_pline_file(std::string filename) { std::ifstream in(filename.c_str()); if(!in.good()) { std::cerr << "pline_fill: Unable to open .pline file \"" << filename << "\"." << std::endl; return; } else std::cout << "pline_fill: Processing file \"" << filename << "\" " << std::flush; std::string line; std::stringstream converter; size_t curr_id = 0; // stores ID of _current_ pline size_t prev_id = 0; // stores ID of _previous_ pline size_t counter = 0; // stores counter for group of plines. Since // several plines may share one ID, the counter // is required to store them in individual // files of the form "<Filename>_<ID>_<Counter>.ply". while(std::getline(in, line)) { // Ignore lines containing a "#" if(line.find_first_of('#') != std::string::npos) continue; converter.str(line); // Data format is straightforward (different fields are assumed to // be separated by whitespace). // // Label ID | number of vertices | id1 x1 y1 z1 n1 n2 n3 id2 x2 y2 z2 ... size_t num_vertices; // Vector of vertices (actually, only the _positions_ and // vertex IDs) for the current polygonal line std::vector< std::pair<v3ctor, size_t> > vertices; converter >> curr_id >> num_vertices; if(curr_id == prev_id) counter++; else counter = 0; // reset counter if the next group of plines is reached for(size_t i = 0; i < num_vertices-1; i++) // ignore last point because it is a repetition of // the first point { std::pair<v3ctor, size_t> vertex_w_id; vertex_w_id.second = std::numeric_limits<size_t>::max(); converter >> vertex_w_id.second >> vertex_w_id.first[0] >> vertex_w_id.first[1] >> vertex_w_id.first[2]; if(vertex_w_id.second == std::numeric_limits<size_t>::max()) { std::cerr << "pline_fill: Could not parse .pline file -- missing a vertex ID\n"; return; } // XXX: Ignore normals double dummy; converter >> dummy >> dummy >> dummy; vertices.push_back(vertex_w_id); } psalm::hole H; H.initialize(vertices); H.triangulate(); try { H.subdivide(psalm::mesh::ALG_LOOP); // Construct filename converter.str(""); converter.clear(); converter << filename << "_" << std::setw(4) << std::setfill('0') << curr_id << "_" << std::setw(4) << std::setfill('0') << counter << ".hole"; H.save(converter.str()); } catch(...) { std::cerr << "pline_fill: Unable to subdivide input data [" << curr_id << "," << counter << "]\n"; } converter.clear(); line.clear(); std::cout << "." << std::flush; } std::cout << "done." << std::endl; } int main(int argc, char* argv[]) { static option cmd_line_opts[] = { {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; int option = 0; while((option = getopt_long(argc, argv, "h", cmd_line_opts, NULL)) != -1) { switch(option) { case 'h': break; } } // Further command-line parameters are assumed to be input files for // the program. These are handled sequentially. while(optind < argc) process_pline_file(argv[optind++]); return(0); } <|endoftext|>
<commit_before>class Solution { public: /** * @param S, T: Two string. * @return: Count the number of distinct subsequences */ int numDistinct(string &S, string &T) { // write your code here vector<vector<int>> t(T.length()+10,vector<int>(S.length()+10,0)); for(int i=0;i<=T.length();i++) t[i][0]=0; for(int i=0;i<=S.length();i++) t[0][i]=1;// 1 ,not 0 for(int i=1;i<=S.length();i++) { if(T[0]==S[i-1]) t[1][i]=t[1][i-1]+1; else t[1][i]=t[1][i-1]; } for(int i=2;i<=T.length();i++) { for(int j=1; j<=S.length();j++) { if(T[i-1]==S[j-1]) t[i][j]=t[i-1][j-1]+t[i][j-1]; else t[i][j]=t[i][j-1]; } } return t[T.length()][S.length()]; } }; <commit_msg>Solving 118<commit_after>class Solution { public: /** * @param S, T: Two string. * @return: Count the number of distinct subsequences */ int numDistinct(string &S, string &T) { // write your code here vector<vector<int>> t(T.length()+10,vector<int>(S.length()+10,0)); for(int i=0;i<=T.length();i++) t[i][0]=0; for(int i=0;i<=S.length();i++) t[0][i]=1;// 1 ,not 0 for(int i=1;i<=S.length();i++) { if(T[0]==S[i-1]) t[1][i]=t[1][i-1]+1; else t[1][i]=t[1][i-1]; } for(int i=2;i<=T.length();i++) { for(int j=1; j<=S.length();j++) { if(T[i-1]==S[j-1]) t[i][j]=t[i-1][j-1]+t[i][j-1]; else t[i][j]=t[i][j-1]; } } return t[T.length()][S.length()]; // } }; <|endoftext|>
<commit_before>/* * Written by Nitin Kumar Maharana * nitin.maharana@gmail.com */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //Using one stack but modifies the input tree. class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; if(root == NULL) return result; stack<TreeNode*> memory; TreeNode *curr; memory.push(root); while(!memory.empty()) { curr = memory.top(); if(curr->left) { memory.push(curr->left); curr->left = NULL; } else if(curr->right) { memory.push(curr->right); curr->right = NULL; } else { result.push_back(curr->val); memory.pop(); } } return result; } };<commit_msg>145. Binary Tree Postorder Traversal - Using one stack<commit_after>/* * Written by Nitin Kumar Maharana * nitin.maharana@gmail.com */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //Using one stack but modifies the input tree. class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; if(root == NULL) return result; stack<TreeNode*> memory; TreeNode *curr; memory.push(root); while(!memory.empty()) { curr = memory.top(); if(curr->left) { memory.push(curr->left); curr->left = NULL; } else if(curr->right) { memory.push(curr->right); curr->right = NULL; } else { result.push_back(curr->val); memory.pop(); } } return result; } }; //Using one stack, Do not modify the input tree, Extra reverse operation on result vector. class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; if(root == NULL) return result; stack<TreeNode*> memory; TreeNode *curr; memory.push(root); while(!memory.empty()) { curr = memory.top(); memory.pop(); result.push_back(curr->val); if(curr->left) memory.push(curr->left); if(curr->right) memory.push(curr->right); } reverse(result.begin(), result.end()); return result; } };<|endoftext|>
<commit_before>class Solution { public: /** * @param n: Given the range of numbers * @param k: Given the numbers of combinations * @return: All the combinations of k numbers out of 1..n */ vector<vector<int> > combine(int n, int k) { // write your code here vector<vector<int> > ans;vector<int> stack; for (int i=1; i<=k; ++i) stack.push_back(i); ans.push_back(stack); while (1){ while (stack.size()>0 && stack.back()==n+stack.size()-k) stack.pop_back(); if (stack.size()==0) break; ++stack[stack.size()-1]; while (stack.size()<k) stack.push_back(stack[stack.size()-1]+1); ans.push_back(stack); } return ans; } };<commit_msg>Solved 152<commit_after>class Solution { public: /** * @param n: Given the range of numbers * @param k: Given the numbers of combinations * @return: All the combinations of k numbers out of 1..n */ vector<vector<int> > combine(int n, int k) { // write your code here vector<vector<int> > ans; vector<int> stack; for (int i=1; i<=k; ++i) stack.push_back(i); ans.push_back(stack); while (1){ while (stack.size()>0 && stack.back()==n+stack.size()-k) stack.pop_back(); if (stack.size()==0) break; ++stack[stack.size()-1]; while (stack.size()<k) stack.push_back(stack[stack.size()-1]+1); ans.push_back(stack); } return ans; // relax the last sequence } };<|endoftext|>
<commit_before>/* The overall strategy is to consider all possible vertices of triangles, and to search through a relevant adjacency list how many triangles there are. First, we split the lines into three grids, and then color these grids: Blue: Lines parallel or perpendicular to the line joining the center of the triangle to the top vertex. Red: Lines parallel or perpendicular to the line joining the center of the triangle to the bottom left vertex. Green: Lines parallel or perpendicular to the line joining the center of the triangle to the bottom right vertex. Notice that for every possible point that can become the vertex of some triangle, the adjacent points can be partitioned into adjacent points in each of the three grids. Hence we can consider the three grids separately when generating the adjaceny list for possible vertices of triangles. Note that we can form an orthogonal basis using each of this grid. For each grid, we set the center of the triangle as the origin. For each color, we have as basis: Blue: (0, 1) is the height of one size 1 triangle along the direction of the top of the triangle from the origin. (1, 0) is the same distance to the right of the origin. Green: (0, 1) is the height of one size 1 triangle along the direction of the bottom left vertex of the triangle from the origin. (1, 0) is the same distance in the perpendicular direction towards the left edge of the triangle. Red: (0, 1) is the height of one size 1 triangle along the direction of the bottom right vertex of the triangle from the origin. (1, 0) is the same distance in the perpendicular direction towards the right edge of the triangle. Denote B, R, G as the bases for the blue, red, and green grids respectively. Let a point P = X^Y denote having coordinates X in basis Y. Let T_{RB} be the transition matrix from B to R. Note that [2; 0]^B = [-1; -1]^R [0; 2/3]^B = [1; -1/3]^R where we exploit the fact that the inradius of an equilateral triangle is 1/3 that of its altitude. This gives us T_{RB} = [-1 1;-1 -1/3] * [1/2 0;0 1/c] = [-1 3;-1 -1] / 2 Note also that T_{RB} = T_{GR} = T_{BG}. This gives us a very clean way to transform coordinates between the different bases. The generation of the adjacency list is relatively trivial afterwards. I used the first method I could think of. You only need to consider one of the three grids, because if M^Y and N^Y are adjacent, then so is M^Z and N^Z for the other Z's. You can use T_{RB} to find (M^Z)_Y, (N^Z)_Y. For the search, I went through each point A, and for each point A, I went through distinct pairs of adjacent points (B, C) such that A, B, C are not collinear. This is to exclude straight lines. If B and C are adjacent, then we have a hit. As an optimization, note that all coordinates have denominator dividing 6, so we can scale everything by 6 and use integers instead of having to deal with fractions. */ #include <iostream> #include <unordered_set> #include <unordered_map> int make_point(int x, int y) { return (x << 16) | (y & 0xFFFF); } int get_x(int point) { return ((point >> 31) & 1) ? (0xFFFF0000 | (point >> 16)) : (point >> 16); } int get_y(int point) { return ((point >> 15) & 1) ? (0xFFFF0000 | (point & 0xFFFF)) : (point & 0xFFFF); } int transform(int point, int basis_changes) { for (int i = 0; i < basis_changes; i++) point = make_point((-get_x(point) + 3 * get_y(point)) / 2, (-get_x(point) - get_y(point)) / 2); return point; } int main() { int n = 36; std::unordered_map<int, std::unordered_set<int>> adjacency; for (int c = 0; c < n; c++) { for (int r1 = 2 * c; r1 < 2 * n; r1++) { for (int r2 = r1 + 1; r2 < 2 * n + 1; r2++) { int offset1 = make_point(6 * c, r1 % 2 == 0 ? 3 * r1 : r1 % 4 == (c % 2 == 0 ? 1 : 3) ? 3 * (r1 - 1) + 4 : 3 * (r1 - 1) + 2); int offset2 = make_point(6 * c, r2 % 2 == 0 ? 3 * r2 : r2 % 4 == (c % 2 == 0 ? 1 : 3) ? 3 * (r2 - 1) + 4 : 3 * (r2 - 1) + 2); int endpoint1 = make_point(get_x(offset1), 4 * n - get_y(offset1)); int endpoint2 = make_point(get_x(offset2), 4 * n - get_y(offset2)); for (int basis = 0; basis < 3; basis++) { adjacency[transform(endpoint1, basis)].emplace(transform(endpoint2, basis)); adjacency[transform(endpoint2, basis)].emplace(transform(endpoint1, basis)); if (c > 0) { adjacency[transform(make_point(-get_x(endpoint1), get_y(endpoint1)), basis)].emplace(transform(make_point(-get_x(endpoint2), get_y(endpoint2)), basis)); adjacency[transform(make_point(-get_x(endpoint2), get_y(endpoint2)), basis)].emplace(transform(make_point(-get_x(endpoint1), get_y(endpoint1)), basis)); } } } } } for (int i = 1; i < n + 1; i++) { for (int c1 = -i; c1 < i; c1++) { for (int c2 = c1 + 1; c2 < i + 1; c2++) { int offset1 = make_point(6 * c1, 6 * i), offset2 = make_point(6 * c2, 6 * i); int endpoint1 = make_point(get_x(offset1), 4 * n - get_y(offset1)); int endpoint2 = make_point(get_x(offset2), 4 * n - get_y(offset2)); for (int basis = 0; basis < 3; basis++) { adjacency[transform(endpoint1, basis)].emplace(transform(endpoint2, basis)); adjacency[transform(endpoint2, basis)].emplace(transform(endpoint1, basis)); } } } } int count = 0; for (auto const &pair : adjacency) { int point = pair.first; std::unordered_set<int> const &adjacent_points = pair.second; for (auto it1 = adjacent_points.begin(); it1 != adjacent_points.end(); ++it1) { auto it2 = it1; ++it2; for (; it2 != adjacent_points.end(); adjacency[*(it2++)].erase(point)) if ((get_y(point) - get_y(*it1)) * (get_x(point) - get_x(*it2)) != (get_y(point) - get_y(*it2)) * (get_x(point) - get_x(*it1))) if (adjacency[*it1].find(*it2) != adjacency[*it1].end() && adjacency[*it2].find(*it1) != adjacency[*it2].end()) count++; adjacency[*it1].erase(point); } } std::cout << count; }<commit_msg>Revised explanation.<commit_after>/* The overall strategy is to consider all possible vertices of triangles, and to search through a relevant adjacency list how many triangles there are. First, we split the lines into three grids, and then color these grids: Blue: Lines parallel or perpendicular to the line joining the center of the triangle to the top vertex. Red: Lines parallel or perpendicular to the line joining the center of the triangle to the bottom left vertex. Green: Lines parallel or perpendicular to the line joining the center of the triangle to the bottom right vertex. Notice that for every possible point that can become the vertex of some triangle, the adjacent points can be partitioned into adjacent points in each of the three grids. Hence we can consider the three grids separately when generating the adjaceny list for possible vertices of triangles. Note that we can form an orthogonal basis using each of this grid. For each grid, we set the center of the triangle as the origin. For each color, we have as basis: Blue: (0, 1) is the height of one size 1 triangle along the direction of the top of the triangle from the origin. (1, 0) is the same distance to the right of the origin. Green: (0, 1) is the height of one size 1 triangle along the direction of the bottom left vertex of the triangle from the origin. (1, 0) is the same distance in the perpendicular direction towards the left edge of the triangle. Red: (0, 1) is the height of one size 1 triangle along the direction of the bottom right vertex of the triangle from the origin. (1, 0) is the same distance in the perpendicular direction towards the right edge of the triangle. Denote B, R, G as the bases for the blue, red, and green grids respectively. Let a point P = X^Y denote having coordinates X in basis Y. Let T_{RB} be the transition matrix from B to R. Note that [2; 0]^B = [-1; -1]^R [0; 2/3]^B = [1; -1/3]^R where we exploit the fact that the inradius of an equilateral triangle is 1/3 that of its altitude. This gives us T_{RB} = [-1 1;-1 -1/3] * [1/2 0;0 3/2] = [-1 3;-1 -1] / 2 Note also that T_{RB} = T_{GR} = T_{BG}. This gives us a very clean way to transform coordinates between the different bases. The generation of the adjacency list is relatively trivial afterwards. I used the first method I could think of. You only need to consider one of the three grids, because if M^Y and N^Y are adjacent, then so is M^Z and N^Z for the other Z's. You can use T_{RB} to find (M^Z)_Y, (N^Z)_Y. For the search, I went through each point A, and for each point A, I went through distinct pairs of adjacent points (B, C) such that A, B, C are not collinear. This is to exclude straight lines. If B and C are adjacent, then we have a hit. As an optimization, note that all coordinates have denominator dividing 6, so we can scale everything by 6 and use integers instead of having to deal with fractions. */ #include <iostream> #include <unordered_set> #include <unordered_map> int make_point(int x, int y) { return (x << 16) | (y & 0xFFFF); } int get_x(int point) { return ((point >> 31) & 1) ? (0xFFFF0000 | (point >> 16)) : (point >> 16); } int get_y(int point) { return ((point >> 15) & 1) ? (0xFFFF0000 | (point & 0xFFFF)) : (point & 0xFFFF); } int transform(int point, int basis_changes) { for (int i = 0; i < basis_changes; i++) point = make_point((-get_x(point) + 3 * get_y(point)) / 2, (-get_x(point) - get_y(point)) / 2); return point; } int main() { int n = 36; std::unordered_map<int, std::unordered_set<int>> adjacency; for (int c = 0; c < n; c++) { for (int r1 = 2 * c; r1 < 2 * n; r1++) { for (int r2 = r1 + 1; r2 < 2 * n + 1; r2++) { int offset1 = make_point(6 * c, r1 % 2 == 0 ? 3 * r1 : r1 % 4 == (c % 2 == 0 ? 1 : 3) ? 3 * (r1 - 1) + 4 : 3 * (r1 - 1) + 2); int offset2 = make_point(6 * c, r2 % 2 == 0 ? 3 * r2 : r2 % 4 == (c % 2 == 0 ? 1 : 3) ? 3 * (r2 - 1) + 4 : 3 * (r2 - 1) + 2); int endpoint1 = make_point(get_x(offset1), 4 * n - get_y(offset1)); int endpoint2 = make_point(get_x(offset2), 4 * n - get_y(offset2)); for (int basis = 0; basis < 3; basis++) { adjacency[transform(endpoint1, basis)].emplace(transform(endpoint2, basis)); adjacency[transform(endpoint2, basis)].emplace(transform(endpoint1, basis)); if (c > 0) { adjacency[transform(make_point(-get_x(endpoint1), get_y(endpoint1)), basis)].emplace(transform(make_point(-get_x(endpoint2), get_y(endpoint2)), basis)); adjacency[transform(make_point(-get_x(endpoint2), get_y(endpoint2)), basis)].emplace(transform(make_point(-get_x(endpoint1), get_y(endpoint1)), basis)); } } } } } for (int i = 1; i < n + 1; i++) { for (int c1 = -i; c1 < i; c1++) { for (int c2 = c1 + 1; c2 < i + 1; c2++) { int offset1 = make_point(6 * c1, 6 * i), offset2 = make_point(6 * c2, 6 * i); int endpoint1 = make_point(get_x(offset1), 4 * n - get_y(offset1)); int endpoint2 = make_point(get_x(offset2), 4 * n - get_y(offset2)); for (int basis = 0; basis < 3; basis++) { adjacency[transform(endpoint1, basis)].emplace(transform(endpoint2, basis)); adjacency[transform(endpoint2, basis)].emplace(transform(endpoint1, basis)); } } } } int count = 0; for (auto const &pair : adjacency) { int point = pair.first; std::unordered_set<int> const &adjacent_points = pair.second; for (auto it1 = adjacent_points.begin(); it1 != adjacent_points.end(); ++it1) { auto it2 = it1; ++it2; for (; it2 != adjacent_points.end(); adjacency[*(it2++)].erase(point)) if ((get_y(point) - get_y(*it1)) * (get_x(point) - get_x(*it2)) != (get_y(point) - get_y(*it2)) * (get_x(point) - get_x(*it1))) if (adjacency[*it1].find(*it2) != adjacency[*it1].end() && adjacency[*it2].find(*it1) != adjacency[*it2].end()) count++; adjacency[*it1].erase(point); } } std::cout << count; }<|endoftext|>
<commit_before>/* * Written by Nitin Kumar Maharana * nitin.maharana@gmail.com */ class Solution { int depthSum(vector<NestedInteger>& nestedList, int depth) { int res = 0; for(auto l: nestedList) { res += (l.isInteger() ? (depth * l.getInteger()) : depthSum(l.getList(), depth + 1)); } return res; } public: int depthSum(vector<NestedInteger>& nestedList) { return depthSum(nestedList, 1); } };<commit_msg>339. Nested List Weight Sum - Code Alignment<commit_after>/* * Written by Nitin Kumar Maharana * nitin.maharana@gmail.com */ class Solution { int depthSum(vector<NestedInteger>& nestedList, int depth) { int res = 0; for(auto l: nestedList) { res += (l.isInteger() ? (depth * l.getInteger()) : depthSum(l.getList(), depth + 1)); } return res; } public: int depthSum(vector<NestedInteger>& nestedList) { return depthSum(nestedList, 1); } };<|endoftext|>
<commit_before>class Solution { public: /** * @param s A string * @return Whether the string is a valid palindrome */ bool isPalindrome(string& s) { // Write your code here int len_s = s.size(),i,j,k; string s1; for (auto ch1:s){ if (::isalnum(ch1)) s1 += ::tolower(ch1); } // cout<< s1.size()<<endl; int len_s1 = s1.size(); if (len_s1 == 0) return true; for (i=0;i<=len_s1-i-1;i++) if (s1[i] != s1[len_s1-1-i]) return false; return true; } };<commit_msg>Solved 415<commit_after>class Solution { public: /** * @param s A string * @return Whether the string is a valid palindrome */ bool isPalindrome(string& s) { // Write your code here int len_s = s.size(),i,j,k; string s1; for (auto ch1:s){ if (::isalnum(ch1)) s1 += ::tolower(ch1); } // cout<< s1.size()<<endl; int len_s1 = s1.size(); if (len_s1 == 0) return true; for (i=0;i<=len_s1-i-1;i++) if (s1[i] != s1[len_s1-1-i]) return false; return true; } }; // Total Runtime: 22 ms<|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: $ */ /* Based on AliPHOSQADataMaker Produces the data needed to calculate the quality assurance. All data must be mergeable objects. P. Christiansen, Lund, January 2008 */ /* Implementation: We have chosen to have the histograms as non-persistent meber to allow better debugging. In the copy constructor we then have to assign the pointers to the existing histograms in the copied list. This have been implemented but not tested. */ #include "AliTPCQADataMakerSim.h" // --- ROOT system --- // --- Standard library --- // --- AliRoot header files --- #include "AliQAChecker.h" #include "AliTPC.h" #include "AliTPCv2.h" #include "AliSimDigits.h" ClassImp(AliTPCQADataMakerSim) //____________________________________________________________________________ AliTPCQADataMakerSim::AliTPCQADataMakerSim() : AliQADataMakerSim(AliQA::GetDetName(AliQA::kTPC), "TPC Sim Quality Assurance Data Maker") { // ctor } //____________________________________________________________________________ AliTPCQADataMakerSim::AliTPCQADataMakerSim(const AliTPCQADataMakerSim& qadm) : AliQADataMakerSim() { //copy ctor SetName((const char*)qadm.GetName()) ; SetTitle((const char*)qadm.GetTitle()); // // Associate class histogram objects to the copies in the list // Could also be done with the indexes // } //__________________________________________________________________ AliTPCQADataMakerSim& AliTPCQADataMakerSim::operator = (const AliTPCQADataMakerSim& qadm ) { // Equal operator. this->~AliTPCQADataMakerSim(); new(this) AliTPCQADataMakerSim(qadm); return *this; } //____________________________________________________________________________ void AliTPCQADataMakerSim::EndOfDetectorCycle(AliQA::TASKINDEX_t task, TObjArray ** list) { //Detector specific actions at end of cycle // do the QA checking AliQAChecker::Instance()->Run(AliQA::kTPC, task, list) ; } //____________________________________________________________________________ void AliTPCQADataMakerSim::InitDigits() { TH1F * histDigitsADC = new TH1F("hDigitsADC", "Digit ADC distribution; ADC; Counts", 1000, 0, 1000); histDigitsADC->Sumw2(); Add2DigitsList(histDigitsADC, kDigitsADC); } //____________________________________________________________________________ void AliTPCQADataMakerSim::InitHits() { TH1F * histHitsNhits = new TH1F("hHitsNhits", "Interactions per primary track in the TPC volume; Number of primary interactions; Counts", 100, 0, 10000); histHitsNhits->Sumw2(); Add2HitsList(histHitsNhits, kNhits); TH1F * histHitsElectrons = new TH1F("hHitsElectrons", "Electrons per interaction (primaries); Electrons; Counts", 300, 0, 300); histHitsElectrons->Sumw2(); Add2HitsList(histHitsElectrons, kElectrons); TH1F * histHitsRadius = new TH1F("hHitsRadius", "Position of interaction (Primary tracks only); Radius; Counts", 300, 0., 300.); histHitsRadius->Sumw2(); Add2HitsList(histHitsRadius, kRadius); TH1F * histHitsPrimPerCm = new TH1F("hHitsPrimPerCm", "Primaries per cm (Primary tracks only); Primaries; Counts", 100, 0., 100.); histHitsPrimPerCm->Sumw2(); Add2HitsList(histHitsPrimPerCm, kPrimPerCm); TH1F * histHitsElectronsPerCm = new TH1F("hHitsElectronsPerCm", "Electrons per cm (Primary tracks only); Electrons; Counts", 300, 0., 300.); histHitsElectronsPerCm->Sumw2(); Add2HitsList(histHitsElectronsPerCm, kElectronsPerCm); } //____________________________________________________________________________ void AliTPCQADataMakerSim::MakeDigits(TTree* digitTree) { TBranch* branch = digitTree->GetBranch("Segment"); AliSimDigits* digArray = 0; branch->SetAddress(&digArray); Int_t nEntries = Int_t(digitTree->GetEntries()); for (Int_t n = 0; n < nEntries; n++) { digitTree->GetEvent(n); if (digArray->First()) do { Float_t dig = digArray->CurrentDigit(); GetDigitsData(kDigitsADC)->Fill(dig); } while (digArray->Next()); } } //____________________________________________________________________________ void AliTPCQADataMakerSim::MakeHits(TTree * hitTree) { // make QA data from Hit Tree const Int_t nTracks = hitTree->GetEntries(); TBranch* branch = hitTree->GetBranch("TPC2"); AliTPCv2* tpc = (AliTPCv2*)gAlice->GetDetector("TPC"); // // loop over tracks // for(Int_t n = 0; n < nTracks; n++){ Int_t nHits = 0; branch->GetEntry(n); AliTPChit* tpcHit = (AliTPChit*)tpc->FirstHit(-1); if (tpcHit) { Float_t dist = 0.; Int_t nprim = 0; Float_t xold = tpcHit->X(); Float_t yold = tpcHit->Y(); Float_t zold = tpcHit->Z(); Float_t radiusOld = TMath::Sqrt(xold*xold + yold*yold); Float_t q = 0.; while(tpcHit) { Float_t x = tpcHit->X(); Float_t y = tpcHit->Y(); Float_t z = tpcHit->Z(); Float_t radius = TMath::Sqrt(x*x + y*y); if(radius>50) { // Skip hits at interaction point nHits++; Int_t trackNo = tpcHit->GetTrack(); if(trackNo==n) { // primary track GetDigitsData(kElectrons)->Fill(tpcHit->fQ); GetDigitsData(kRadius)->Fill(radius); // find the new distance dist += TMath::Sqrt((x-xold)*(x-xold) + (y-yold)*(y-yold) + (z-zold)*(z-zold)); if(dist<1.){ // add data to this 1 cm step nprim++; q += tpcHit->fQ; } else{ // Fill the histograms normalized to per cm if(nprim==1) cout << radius << ", " << radiusOld << ", " << dist << endl; GetDigitsData(kPrimPerCm)->Fill((Float_t)nprim); GetDigitsData(kElectronsPerCm)->Fill(q); dist = 0; q = 0; nprim = 0; } } } radiusOld = radius; xold = x; yold = y; zold = z; tpcHit = (AliTPChit*) tpc->NextHit(); } } GetDigitsData(kNhits)->Fill(nHits); } } <commit_msg>Copy/paste error fixed: using GetHistData instead of GetDigitsData (Yves)<commit_after>/************************************************************************** * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: $ */ /* Based on AliPHOSQADataMaker Produces the data needed to calculate the quality assurance. All data must be mergeable objects. P. Christiansen, Lund, January 2008 */ /* Implementation: We have chosen to have the histograms as non-persistent meber to allow better debugging. In the copy constructor we then have to assign the pointers to the existing histograms in the copied list. This have been implemented but not tested. */ #include "AliTPCQADataMakerSim.h" // --- ROOT system --- // --- Standard library --- // --- AliRoot header files --- #include "AliQAChecker.h" #include "AliTPC.h" #include "AliTPCv2.h" #include "AliSimDigits.h" ClassImp(AliTPCQADataMakerSim) //____________________________________________________________________________ AliTPCQADataMakerSim::AliTPCQADataMakerSim() : AliQADataMakerSim(AliQA::GetDetName(AliQA::kTPC), "TPC Sim Quality Assurance Data Maker") { // ctor } //____________________________________________________________________________ AliTPCQADataMakerSim::AliTPCQADataMakerSim(const AliTPCQADataMakerSim& qadm) : AliQADataMakerSim() { //copy ctor SetName((const char*)qadm.GetName()) ; SetTitle((const char*)qadm.GetTitle()); // // Associate class histogram objects to the copies in the list // Could also be done with the indexes // } //__________________________________________________________________ AliTPCQADataMakerSim& AliTPCQADataMakerSim::operator = (const AliTPCQADataMakerSim& qadm ) { // Equal operator. this->~AliTPCQADataMakerSim(); new(this) AliTPCQADataMakerSim(qadm); return *this; } //____________________________________________________________________________ void AliTPCQADataMakerSim::EndOfDetectorCycle(AliQA::TASKINDEX_t task, TObjArray ** list) { //Detector specific actions at end of cycle // do the QA checking AliQAChecker::Instance()->Run(AliQA::kTPC, task, list) ; } //____________________________________________________________________________ void AliTPCQADataMakerSim::InitDigits() { TH1F * histDigitsADC = new TH1F("hDigitsADC", "Digit ADC distribution; ADC; Counts", 1000, 0, 1000); histDigitsADC->Sumw2(); Add2DigitsList(histDigitsADC, kDigitsADC); } //____________________________________________________________________________ void AliTPCQADataMakerSim::InitHits() { TH1F * histHitsNhits = new TH1F("hHitsNhits", "Interactions per primary track in the TPC volume; Number of primary interactions; Counts", 100, 0, 10000); histHitsNhits->Sumw2(); Add2HitsList(histHitsNhits, kNhits); TH1F * histHitsElectrons = new TH1F("hHitsElectrons", "Electrons per interaction (primaries); Electrons; Counts", 300, 0, 300); histHitsElectrons->Sumw2(); Add2HitsList(histHitsElectrons, kElectrons); TH1F * histHitsRadius = new TH1F("hHitsRadius", "Position of interaction (Primary tracks only); Radius; Counts", 300, 0., 300.); histHitsRadius->Sumw2(); Add2HitsList(histHitsRadius, kRadius); TH1F * histHitsPrimPerCm = new TH1F("hHitsPrimPerCm", "Primaries per cm (Primary tracks only); Primaries; Counts", 100, 0., 100.); histHitsPrimPerCm->Sumw2(); Add2HitsList(histHitsPrimPerCm, kPrimPerCm); TH1F * histHitsElectronsPerCm = new TH1F("hHitsElectronsPerCm", "Electrons per cm (Primary tracks only); Electrons; Counts", 300, 0., 300.); histHitsElectronsPerCm->Sumw2(); Add2HitsList(histHitsElectronsPerCm, kElectronsPerCm); } //____________________________________________________________________________ void AliTPCQADataMakerSim::MakeDigits(TTree* digitTree) { TBranch* branch = digitTree->GetBranch("Segment"); AliSimDigits* digArray = 0; branch->SetAddress(&digArray); Int_t nEntries = Int_t(digitTree->GetEntries()); for (Int_t n = 0; n < nEntries; n++) { digitTree->GetEvent(n); if (digArray->First()) do { Float_t dig = digArray->CurrentDigit(); GetDigitsData(kDigitsADC)->Fill(dig); } while (digArray->Next()); } } //____________________________________________________________________________ void AliTPCQADataMakerSim::MakeHits(TTree * hitTree) { // make QA data from Hit Tree const Int_t nTracks = hitTree->GetEntries(); TBranch* branch = hitTree->GetBranch("TPC2"); AliTPCv2* tpc = (AliTPCv2*)gAlice->GetDetector("TPC"); // // loop over tracks // for(Int_t n = 0; n < nTracks; n++){ Int_t nHits = 0; branch->GetEntry(n); AliTPChit* tpcHit = (AliTPChit*)tpc->FirstHit(-1); if (tpcHit) { Float_t dist = 0.; Int_t nprim = 0; Float_t xold = tpcHit->X(); Float_t yold = tpcHit->Y(); Float_t zold = tpcHit->Z(); Float_t radiusOld = TMath::Sqrt(xold*xold + yold*yold); Float_t q = 0.; while(tpcHit) { Float_t x = tpcHit->X(); Float_t y = tpcHit->Y(); Float_t z = tpcHit->Z(); Float_t radius = TMath::Sqrt(x*x + y*y); if(radius>50) { // Skip hits at interaction point nHits++; Int_t trackNo = tpcHit->GetTrack(); if(trackNo==n) { // primary track GetHitsData(kElectrons)->Fill(tpcHit->fQ); GetHitsData(kRadius)->Fill(radius); // find the new distance dist += TMath::Sqrt((x-xold)*(x-xold) + (y-yold)*(y-yold) + (z-zold)*(z-zold)); if(dist<1.){ // add data to this 1 cm step nprim++; q += tpcHit->fQ; } else{ // Fill the histograms normalized to per cm if(nprim==1) cout << radius << ", " << radiusOld << ", " << dist << endl; GetHitsData(kPrimPerCm)->Fill((Float_t)nprim); GetHitsData(kElectronsPerCm)->Fill(q); dist = 0; q = 0; nprim = 0; } } } radiusOld = radius; xold = x; yold = y; zold = z; tpcHit = (AliTPChit*) tpc->NextHit(); } } GetHitsData(kNhits)->Fill(nHits); } } <|endoftext|>
<commit_before> // ChildView.cpp : implementation of the CChildView class // #include "stdafx.h" #include "Tekenprogramma.h" #include "ChildView.h" #include "AShape.h" #include "ACircle.h" #include "ALine.h" #include "ARectangle.h" #include "Settings.h" #include <vector> #include <iostream> #include <stdlib.h> #ifdef _DEBUG #define new DEBUG_NEW #endif CPoint startPoint; CPoint endPoint; int selected = -1; bool selectionMode = false; // CChildView CChildView::CChildView() { } CChildView::~CChildView() { } BEGIN_MESSAGE_MAP(CChildView, CWnd) ON_WM_PAINT() ON_WM_LBUTTONDOWN() ON_WM_MOUSEMOVE() ON_WM_LBUTTONUP() ON_WM_KEYDOWN(&CChildView::OnKeyDown) ON_COMMAND(ID_EDIT_UNDO, &CChildView::OnEditUndo) ON_COMMAND(ID_FILE_SAVETOFILE, &CChildView::OnFileSavetofile) ON_COMMAND(ID_FILE_OPENFILE, &CChildView::OnFileOpenfile) ON_COMMAND(ID_DELETE_MODE, &CChildView::ToggleDeleteMode) END_MESSAGE_MAP() // CChildView message handlers void CChildView::ToggleDeleteMode() { selectionMode = !selectionMode; } BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs) { if (!CWnd::PreCreateWindow(cs)) return FALSE; cs.dwExStyle |= WS_EX_CLIENTEDGE; cs.style &= ~WS_BORDER; cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW), reinterpret_cast<HBRUSH>(COLOR_WINDOW+1), NULL); return TRUE; } void CChildView::OnPaint() { CPaintDC dc(this); // device context for painting redrawShapes(false); } void CChildView::redrawShapes(boolean draw) { CDC* pDC = GetDC(); for(unsigned int i=0; i<shapes.size(); i++) if(draw) { shapes[i]->draw(pDC); }else{ shapes[i]->undraw(pDC); }; ReleaseDC(pDC); } void CChildView::OnLButtonDown(UINT nFlags, CPoint point) { SetCapture(); CRect windowRect; GetWindowRect(&windowRect); ScreenToClient(&windowRect); if(selectionMode) { if(windowRect.PtInRect(point)) { for(unsigned int i=shapes.size()-1; shapes.size() > 0 && i>0; i--) { if(shapes[i]->isOn(point)) { selected = i; break; return; } } } }else{ if(windowRect.PtInRect(point)) { startPoint = point; AShape* as; if(Settings::shapeSelected == 0) as = new ACircle(); else if(Settings::shapeSelected == 1) as = new ARectangle(); else if(Settings::shapeSelected == 2) as = new ALine(); else as = new ACircle(); as->setStartPoint(point); shapes.push_back(as); } } } void CChildView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { // catch delete key if(nChar == 46) { if(selected != -1) { CDC* pDC = GetDC(); shapes[selected]->undraw(pDC); shapes.erase(shapes.begin() + selected); shapes.shrink_to_fit(); ReleaseDC(pDC); selected = -1; // back to placeholder TRACE("DELETED SHAPE \n"); } } } // Geeft de laatste shape pointer terug. AShape* CChildView::getLastShape() { if(shapes.size() > 0)return shapes[shapes.size()-1]; else return NULL; } void CChildView::OnMouseMove(UINT nFlags, CPoint point) { if(startPoint.x != -1) { SetCapture(); CRect windowRect; GetWindowRect(&windowRect); ScreenToClient(&windowRect); CDC *pDC = GetDC(); if(getLastShape() != NULL && !windowRect.PtInRect(point)) { getLastShape()->isSet = true; ReleaseCapture(); } if(endPoint.x != -1 && getLastShape() != NULL && !getLastShape()->isSet) { getLastShape()->setEndPoint(point); getLastShape()->draw(pDC); } // Kies zwarte pen van de 'stock' (bestaande pen) //pDC->SelectStockObject(SS_BLACKRECT); // Je kunt ook zelf een pen maken: CPen pen; pen.CreatePen(PS_DOT, 1, RGB(255,0,0)); pDC->SelectObject(&pen); ReleaseDC(pDC); endPoint = point; } } void CChildView::OnLButtonUp(UINT nFlags, CPoint point) { CDC* pDC = GetDC(); ReleaseDC(pDC); // Reset start and endpoints for upcoming shapes. startPoint.x = -1; endPoint.x = -1; } void CChildView::OnEditUndo() { CDC* pDC = GetDC(); if(getLastShape()!= NULL && getLastShape() != nullptr){ getLastShape()->undraw(pDC); delete getLastShape(); shapes.pop_back(); shapes.shrink_to_fit(); } ReleaseDC(pDC); } void CChildView::OnFileSavetofile() { TCHAR szFilters[]= _T("Tekeningen (*.painting)|*.painting||"); CFileDialog cfd = CFileDialog(false, _T("painting"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilters, NULL, 0, true); CFile file; if(cfd.DoModal() == IDOK){ string txt = "\xef\xbb\xbf"; // BOM for(unsigned int i=0; i<shapes.size(); i++) txt.append(shapes[i]->getSerialized()); if(file.Open(cfd.GetPathName(), CFile::modeCreate | CFile::modeReadWrite) ) { file.Write(txt.c_str(), txt.size()); file.Flush(); } } } void CChildView::OnFileOpenfile() { TCHAR szFilters[]= _T("Tekeningen (*.painting)|*.painting||"); CFileDialog cfd = CFileDialog(true, _T("painting"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilters, NULL, 0, true); CFile file; string content = ""; if(cfd.DoModal() == IDOK) { // Remove old shapes for(unsigned int i=0; i<shapes.size(); i++) delete shapes[i]; shapes.clear(); // Clear screen CDC* pDC = GetDC(); pDC->SetROP2(R2_WHITE); pDC->Rectangle(0,0,99999,99999); ReleaseDC(pDC); if(file.Open(cfd.GetPathName(), CFile::modeRead | CFile::modeNoTruncate)) { char* buffer = new char[file.GetLength()](); file.Seek(3, CFile::begin); // ignore BOM file.Read(buffer, file.GetLength()); content = buffer; delete buffer; CDC* pDC = GetDC(); vector<AShape*> tmpShapes; short state = 0; short substate = 0; CPoint* tmpCPoint = nullptr; string tmpPoint = ""; for(unsigned int i=0; i<content.size(); i++) { char c = content[i]; if(c == '{') { state = 1; substate = 0; continue; } // entering shape creation if(c == '}') { tmpCPoint->y = atoi(tmpPoint.c_str()); tmpPoint = ""; tmpShapes.at(0)->setEndPoint(*tmpCPoint); tmpShapes.at(0)->draw(pDC); tmpCPoint = nullptr; //reset state = 0; shapes.push_back(tmpShapes.at(0)); tmpShapes.clear(); }; if(state == 1) { if(substate == 0) { switch(c){ case '0': tmpShapes.push_back(new ACircle()); break; case '1': tmpShapes.push_back(new ARectangle()); break; case '2': tmpShapes.push_back(new ALine()); break; default: tmpShapes.push_back(new ACircle()); } i++; substate++; continue; }else if(substate == 1){ // CPoint X if(c == ',') { tmpCPoint = new CPoint(0,0); tmpCPoint->x = atoi(tmpPoint.c_str()); tmpPoint = ""; substate++; continue; }else tmpPoint += c; }else if(substate == 2){ // CPoint Y if(c == ',') { tmpCPoint->y = atoi(tmpPoint.c_str()); tmpPoint = ""; tmpShapes.at(0)->setStartPoint(*tmpCPoint); tmpCPoint = nullptr; //reset substate++; continue; }else tmpPoint += c; } else if(substate == 3){ // CPoint X if(c == ',') { tmpCPoint = new CPoint(0,0); tmpCPoint->x = atoi(tmpPoint.c_str()); tmpPoint = ""; substate++; continue; }else tmpPoint += c; }else if(substate == 4){ // CPoint Y tmpPoint += c; } } } ReleaseDC(pDC); } } } <commit_msg>fixed selection/deletion mode<commit_after> // ChildView.cpp : implementation of the CChildView class // #include "stdafx.h" #include "Tekenprogramma.h" #include "ChildView.h" #include "AShape.h" #include "ACircle.h" #include "ALine.h" #include "ARectangle.h" #include "Settings.h" #include <vector> #include <iostream> #include <stdlib.h> #ifdef _DEBUG #define new DEBUG_NEW #endif CPoint startPoint; CPoint endPoint; int selected = -1; bool selectionMode = false; // CChildView CChildView::CChildView() { } CChildView::~CChildView() { } BEGIN_MESSAGE_MAP(CChildView, CWnd) ON_WM_PAINT() ON_WM_LBUTTONDOWN() ON_WM_MOUSEMOVE() ON_WM_LBUTTONUP() ON_WM_KEYDOWN(&CChildView::OnKeyDown) ON_COMMAND(ID_EDIT_UNDO, &CChildView::OnEditUndo) ON_COMMAND(ID_FILE_SAVETOFILE, &CChildView::OnFileSavetofile) ON_COMMAND(ID_FILE_OPENFILE, &CChildView::OnFileOpenfile) ON_COMMAND(ID_DELETE_MODE, &CChildView::ToggleDeleteMode) END_MESSAGE_MAP() // CChildView message handlers void CChildView::ToggleDeleteMode() { selectionMode = !selectionMode; } BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs) { if (!CWnd::PreCreateWindow(cs)) return FALSE; cs.dwExStyle |= WS_EX_CLIENTEDGE; cs.style &= ~WS_BORDER; cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW), reinterpret_cast<HBRUSH>(COLOR_WINDOW+1), NULL); return TRUE; } void CChildView::OnPaint() { CPaintDC dc(this); // device context for painting redrawShapes(false); } void CChildView::redrawShapes(boolean draw) { CDC* pDC = GetDC(); for(unsigned int i=0; i<shapes.size(); i++) if(draw) { shapes[i]->draw(pDC); }else{ shapes[i]->undraw(pDC); }; ReleaseDC(pDC); } void CChildView::OnLButtonDown(UINT nFlags, CPoint point) { SetCapture(); CRect windowRect; GetWindowRect(&windowRect); ScreenToClient(&windowRect); if(selectionMode) { if(windowRect.PtInRect(point)) { for(unsigned int i=0; i <= shapes.size(); i++) { if(shapes[i]->isOn(point)) { selected = i; break; return; } } } }else{ if(windowRect.PtInRect(point)) { startPoint = point; AShape* as; if(Settings::shapeSelected == 0) as = new ACircle(); else if(Settings::shapeSelected == 1) as = new ARectangle(); else if(Settings::shapeSelected == 2) as = new ALine(); else as = new ACircle(); as->setStartPoint(point); shapes.push_back(as); } } } void CChildView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { // catch delete key if(nChar == 46) { if(selected != -1) { CDC* pDC = GetDC(); shapes[selected]->undraw(pDC); shapes.erase(shapes.begin() + selected); shapes.shrink_to_fit(); ReleaseDC(pDC); selected = -1; // back to placeholder TRACE("DELETED SHAPE \n"); } } } // Geeft de laatste shape pointer terug. AShape* CChildView::getLastShape() { if(shapes.size() > 0)return shapes[shapes.size()-1]; else return NULL; } void CChildView::OnMouseMove(UINT nFlags, CPoint point) { if(startPoint.x != -1) { SetCapture(); CRect windowRect; GetWindowRect(&windowRect); ScreenToClient(&windowRect); CDC *pDC = GetDC(); if(getLastShape() != NULL && !windowRect.PtInRect(point)) { getLastShape()->isSet = true; ReleaseCapture(); } if(endPoint.x != -1 && getLastShape() != NULL && !getLastShape()->isSet) { getLastShape()->setEndPoint(point); getLastShape()->draw(pDC); } // Kies zwarte pen van de 'stock' (bestaande pen) //pDC->SelectStockObject(SS_BLACKRECT); // Je kunt ook zelf een pen maken: CPen pen; pen.CreatePen(PS_DOT, 1, RGB(255,0,0)); pDC->SelectObject(&pen); ReleaseDC(pDC); endPoint = point; } } void CChildView::OnLButtonUp(UINT nFlags, CPoint point) { CDC* pDC = GetDC(); ReleaseDC(pDC); // Reset start and endpoints for upcoming shapes. startPoint.x = -1; endPoint.x = -1; } void CChildView::OnEditUndo() { CDC* pDC = GetDC(); if(getLastShape()!= NULL && getLastShape() != nullptr){ getLastShape()->undraw(pDC); delete getLastShape(); shapes.pop_back(); shapes.shrink_to_fit(); } ReleaseDC(pDC); } void CChildView::OnFileSavetofile() { TCHAR szFilters[]= _T("Tekeningen (*.painting)|*.painting||"); CFileDialog cfd = CFileDialog(false, _T("painting"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilters, NULL, 0, true); CFile file; if(cfd.DoModal() == IDOK){ string txt = "\xef\xbb\xbf"; // BOM for(unsigned int i=0; i<shapes.size(); i++) txt.append(shapes[i]->getSerialized()); if(file.Open(cfd.GetPathName(), CFile::modeCreate | CFile::modeReadWrite) ) { file.Write(txt.c_str(), txt.size()); file.Flush(); } } } void CChildView::OnFileOpenfile() { TCHAR szFilters[]= _T("Tekeningen (*.painting)|*.painting||"); CFileDialog cfd = CFileDialog(true, _T("painting"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilters, NULL, 0, true); CFile file; string content = ""; if(cfd.DoModal() == IDOK) { // Remove old shapes for(unsigned int i=0; i<shapes.size(); i++) delete shapes[i]; shapes.clear(); // Clear screen CDC* pDC = GetDC(); pDC->SetROP2(R2_WHITE); pDC->Rectangle(0,0,99999,99999); ReleaseDC(pDC); if(file.Open(cfd.GetPathName(), CFile::modeRead | CFile::modeNoTruncate)) { char* buffer = new char[file.GetLength()](); file.Seek(3, CFile::begin); // ignore BOM file.Read(buffer, file.GetLength()); content = buffer; delete buffer; CDC* pDC = GetDC(); vector<AShape*> tmpShapes; short state = 0; short substate = 0; CPoint* tmpCPoint = nullptr; string tmpPoint = ""; for(unsigned int i=0; i<content.size(); i++) { char c = content[i]; if(c == '{') { state = 1; substate = 0; continue; } // entering shape creation if(c == '}') { tmpCPoint->y = atoi(tmpPoint.c_str()); tmpPoint = ""; tmpShapes.at(0)->setEndPoint(*tmpCPoint); tmpShapes.at(0)->draw(pDC); tmpCPoint = nullptr; //reset state = 0; shapes.push_back(tmpShapes.at(0)); tmpShapes.clear(); }; if(state == 1) { if(substate == 0) { switch(c){ case '0': tmpShapes.push_back(new ACircle()); break; case '1': tmpShapes.push_back(new ARectangle()); break; case '2': tmpShapes.push_back(new ALine()); break; default: tmpShapes.push_back(new ACircle()); } i++; substate++; continue; }else if(substate == 1){ // CPoint X if(c == ',') { tmpCPoint = new CPoint(0,0); tmpCPoint->x = atoi(tmpPoint.c_str()); tmpPoint = ""; substate++; continue; }else tmpPoint += c; }else if(substate == 2){ // CPoint Y if(c == ',') { tmpCPoint->y = atoi(tmpPoint.c_str()); tmpPoint = ""; tmpShapes.at(0)->setStartPoint(*tmpCPoint); tmpCPoint = nullptr; //reset substate++; continue; }else tmpPoint += c; } else if(substate == 3){ // CPoint X if(c == ',') { tmpCPoint = new CPoint(0,0); tmpCPoint->x = atoi(tmpPoint.c_str()); tmpPoint = ""; substate++; continue; }else tmpPoint += c; }else if(substate == 4){ // CPoint Y tmpPoint += c; } } } ReleaseDC(pDC); } } } <|endoftext|>
<commit_before> #include "register_types.h" #include "object_type_db.h" #include "reference.h" // Wrap for oda #include "engine.h" #include <vector> #include <string> namespace { using std::string; using std::vector; const string *paths = {"patches"}; class ODAModule : public Reference { OBJ_TYPE(ODAModule, Reference); public: ODAModule () : engine_(paths) {} protected: static void _bind_methods () { ObjectTypeDB::bind_method( } private: oda::godot::Engine engine_; }; } // unnamed namespace void register_openda_types () { ObjectTypeDB::register_type<ODAModule>(); } void unregister_openda_types () { // nothing at all? } <commit_msg>Env setup<commit_after> #include "register_types.h" #include "object_type_db.h" #include "reference.h" // Wrap for oda #include "engine.h" #include <vector> #include <string> using std::string; using std::vector; const static string paths[1] = {"patches"}; class ODAModule : public Reference { OBJ_TYPE(ODAModule, Reference); public: ODAModule () : engine_(paths) {} protected: static void _bind_methods () { ObjectTypeDB::bind_method( } private: oda::godot::Engine engine_; }; void register_openda_types () { ObjectTypeDB::register_type<ODAModule>(); } void unregister_openda_types () { // nothing at all? } <|endoftext|>
<commit_before>#include "toast/net/socket.hpp" #include "toast/bootstrap.hpp" #include "toast/bootstrap/loader.hpp" #include "toast/bootstrap/driver.hpp" #include "toast/bootstrap/state.hpp" #include "toast/bootstrap/server.hpp" #include "toast/memory.hpp" #include "toast/filesystem.hpp" #include "toast/logger.hpp" #include "toast/splash.hpp" #include "toast/environment.hpp" #include "toast/state.hpp" #include "toast/util.hpp" #include "toast/crash.hpp" #include "toast/config.hpp" #include "toast/ipc.hpp" #include "toast/bootstrap/utils/log.hpp" #include "toast/provider.hpp" using namespace Toast; Logger _b_log("Toast"); Bootstrap::BootConfig _b_cfg; static DYNAMIC dyn; static std::string provider = "toast_hardware_provider"; template <class ret = void> static ret thp_dynamic_call(DYNAMIC dyn, std::string name) { if (dyn != NULL) { SYMBOL sym = Internal::Loader::get_symbol(dyn, name); if (sym == NULL) return static_cast<ret>(NULL); return reinterpret_cast<ret(*)()>(sym)(); } // This has to be a static cast, or else when ret=void, this does `return NULL` on a void function, // resulting in a compilation error. return static_cast<ret>(NULL); } void bootstrap_shutdown() { _b_log << "Bootstrap Stopped. Freeing Resources."; thp_dynamic_call(dyn, "provider_free"); Log::flush(); Log::close(); Toast::Bootstrap::Loader::free(); Toast::Memory::free_memory(true); // Just kill it. WPILib holds on too long. #ifdef OS_MAC exit(Crash::has_crashed() ? 1 : 0); #else std::quick_exit(Crash::has_crashed() ? 1 : 0); #endif } void init_toast_bootstrap(int argc, char *argv[]) { // Argument Parsing bool loop = true, load = true, load_driver = true; for (int i = 0; i < argc; i++) { char *a = argv[i]; char *b = (i != argc - 1) ? b = argv[i + 1] : NULL; if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) { cout << "toast_launcher [options]\n\n" "\t--no-loop\t Exit Toast immediately after initialization\n" "\t--no-driver\t Do not load Toast Bootstrap Drivers\n" "\t--no-load\t Do not load Toast Modules\n" "\t--provider <provider name>\t Select a hardware provider to use\n" "\n" "\t--util <utility> [utility options]\t Load a Toast Utility (does not load robot code)\n" "\t\tlog2csv \t<files> [-o OUTPUT]\tConvert .tlog (or a directory of .tlog) files to CSV files. Default output to directory containing log file.\n" "\t\tlog_combine \t<files> [-o OUTPUT]\tCombine .tlog (or a directory of .tlog) files into one file, sorting messages by time. Default output to ./combined.csv\n"; return; } else if ((strcmp(a, "--provider") == 0 || strcmp(a, "-p") == 0) && b != NULL) { i++; provider = std::string(b); } else if (strcmp(a, "--no-loop") == 0) loop = false; else if (strcmp(a, "--no-driver") == 0) load_driver = false; else if (strcmp(a, "--no-load") == 0) load = false; else if (strcmp(a, "--util") == 0 && b != nullptr) { // Toast Runtime Utility, skip normal loading. i++; if (strncmp(b, "log2", 4) == 0) { BootstrapUtil::Log::log2something(argc, argv, i); } else if (strcmp(b, "log_combine") == 0) { BootstrapUtil::Log::combine_logs(argc, argv, i); } else { cerr << "[ERR] You wanted to use a utility, but we can't find the one you're looking for!" << endl; } return; } } // End Argument Parsing long long start_time = current_time_millis(); std::string prov_library = Internal::Loader::library_name(provider); dyn = Internal::Loader::load_dynamic_library(prov_library); if (dyn == NULL) { for (std::string s : Filesystem::ls_local("./")) { std::string name = Filesystem::name(s); if (starts_with(name, "provider_") || starts_with(name, "libprovider_")) { dyn = Internal::Loader::load_dynamic_library(name); if (dyn != NULL) break; } } if (dyn == NULL) { cerr << "ERROR: Toast Hardware Provider not present! Toast Cannot Run!" << endl; exit(-1); } } ProviderInfo *info = thp_dynamic_call<ProviderInfo *>(dyn, "provider_info"); Crash::on_shutdown(bootstrap_shutdown); thp_dynamic_call(dyn, "provider_preinit"); Net::Socket::socket_init(); Filesystem::initialize(); Memory::initialize_bootstrap(); IPC::start(-1); Log::initialize("Bootstrap"); _b_log.raw(Splash::get_startup_splash() + "\n"); _b_log.raw("Toast Loaded on OS: [" + Environment::OS::to_string() + "] with Process ID [" + std::to_string(get_pid()) + "]"); _b_log.raw("Hardware Provider: " + std::string(info->name)); _b_cfg.load(); Bootstrap::Web::prepare(); // State Tick Timing (100Hz by default) int tick_frequency = (int)(1000.0 / _b_cfg.timings.states.frequency); States::Internal::set_tick_timing(tick_frequency); thp_dynamic_call(dyn, "provider_predriver"); if (load_driver) { _b_log << "Initializing Driver Loader"; Bootstrap::Driver::initialize(); Bootstrap::Driver::preinit_drivers(); } thp_dynamic_call(dyn, "provider_preload"); if (load) { _b_log << "Initializing Loader"; Bootstrap::Loader::initialize(); } Bootstrap::States::init(); Bootstrap::Web::start(); thp_dynamic_call(dyn, "provider_init"); if (load_driver) { Bootstrap::Driver::init_drivers(); } long long end_time = current_time_millis(); _b_log << "Total Bootstrap Startup Time: " + to_string(end_time - start_time) + "ms"; if (loop) thp_dynamic_call(dyn, "provider_loop"); bootstrap_shutdown(); } Bootstrap::BootConfig *Bootstrap::get_config() { return &_b_cfg; } Toast::Logger *Bootstrap::get_logger() { return &_b_log; } DYNAMIC *Bootstrap::get_provider() { return &dyn; } <commit_msg>Fix std::quick_exit, as sometimes this symbol is not found<commit_after>#include "toast/net/socket.hpp" #include "toast/bootstrap.hpp" #include "toast/bootstrap/loader.hpp" #include "toast/bootstrap/driver.hpp" #include "toast/bootstrap/state.hpp" #include "toast/bootstrap/server.hpp" #include "toast/memory.hpp" #include "toast/filesystem.hpp" #include "toast/logger.hpp" #include "toast/splash.hpp" #include "toast/environment.hpp" #include "toast/state.hpp" #include "toast/util.hpp" #include "toast/crash.hpp" #include "toast/config.hpp" #include "toast/ipc.hpp" #include "toast/bootstrap/utils/log.hpp" #include "toast/provider.hpp" using namespace Toast; Logger _b_log("Toast"); Bootstrap::BootConfig _b_cfg; static DYNAMIC dyn; static std::string provider = "toast_hardware_provider"; template <class ret = void> static ret thp_dynamic_call(DYNAMIC dyn, std::string name) { if (dyn != NULL) { SYMBOL sym = Internal::Loader::get_symbol(dyn, name); if (sym == NULL) return static_cast<ret>(NULL); return reinterpret_cast<ret(*)()>(sym)(); } // This has to be a static cast, or else when ret=void, this does `return NULL` on a void function, // resulting in a compilation error. return static_cast<ret>(NULL); } void bootstrap_shutdown() { _b_log << "Bootstrap Stopped. Freeing Resources."; thp_dynamic_call(dyn, "provider_free"); Log::flush(); Log::close(); Toast::Bootstrap::Loader::free(); Toast::Memory::free_memory(true); // Just kill it. WPILib holds on too long. #ifndef ROBORIO exit(Crash::has_crashed() ? 1 : 0); #else std::quick_exit(Crash::has_crashed() ? 1 : 0); #endif } void init_toast_bootstrap(int argc, char *argv[]) { // Argument Parsing bool loop = true, load = true, load_driver = true; for (int i = 0; i < argc; i++) { char *a = argv[i]; char *b = (i != argc - 1) ? b = argv[i + 1] : NULL; if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) { cout << "toast_launcher [options]\n\n" "\t--no-loop\t Exit Toast immediately after initialization\n" "\t--no-driver\t Do not load Toast Bootstrap Drivers\n" "\t--no-load\t Do not load Toast Modules\n" "\t--provider <provider name>\t Select a hardware provider to use\n" "\n" "\t--util <utility> [utility options]\t Load a Toast Utility (does not load robot code)\n" "\t\tlog2csv \t<files> [-o OUTPUT]\tConvert .tlog (or a directory of .tlog) files to CSV files. Default output to directory containing log file.\n" "\t\tlog_combine \t<files> [-o OUTPUT]\tCombine .tlog (or a directory of .tlog) files into one file, sorting messages by time. Default output to ./combined.csv\n"; return; } else if ((strcmp(a, "--provider") == 0 || strcmp(a, "-p") == 0) && b != NULL) { i++; provider = std::string(b); } else if (strcmp(a, "--no-loop") == 0) loop = false; else if (strcmp(a, "--no-driver") == 0) load_driver = false; else if (strcmp(a, "--no-load") == 0) load = false; else if (strcmp(a, "--util") == 0 && b != nullptr) { // Toast Runtime Utility, skip normal loading. i++; if (strncmp(b, "log2", 4) == 0) { BootstrapUtil::Log::log2something(argc, argv, i); } else if (strcmp(b, "log_combine") == 0) { BootstrapUtil::Log::combine_logs(argc, argv, i); } else { cerr << "[ERR] You wanted to use a utility, but we can't find the one you're looking for!" << endl; } return; } } // End Argument Parsing long long start_time = current_time_millis(); std::string prov_library = Internal::Loader::library_name(provider); dyn = Internal::Loader::load_dynamic_library(prov_library); if (dyn == NULL) { for (std::string s : Filesystem::ls_local("./")) { std::string name = Filesystem::name(s); if (starts_with(name, "provider_") || starts_with(name, "libprovider_")) { dyn = Internal::Loader::load_dynamic_library(name); if (dyn != NULL) break; } } if (dyn == NULL) { cerr << "ERROR: Toast Hardware Provider not present! Toast Cannot Run!" << endl; exit(-1); } } ProviderInfo *info = thp_dynamic_call<ProviderInfo *>(dyn, "provider_info"); Crash::on_shutdown(bootstrap_shutdown); thp_dynamic_call(dyn, "provider_preinit"); Net::Socket::socket_init(); Filesystem::initialize(); Memory::initialize_bootstrap(); IPC::start(-1); Log::initialize("Bootstrap"); _b_log.raw(Splash::get_startup_splash() + "\n"); _b_log.raw("Toast Loaded on OS: [" + Environment::OS::to_string() + "] with Process ID [" + std::to_string(get_pid()) + "]"); _b_log.raw("Hardware Provider: " + std::string(info->name)); _b_cfg.load(); Bootstrap::Web::prepare(); // State Tick Timing (100Hz by default) int tick_frequency = (int)(1000.0 / _b_cfg.timings.states.frequency); States::Internal::set_tick_timing(tick_frequency); thp_dynamic_call(dyn, "provider_predriver"); if (load_driver) { _b_log << "Initializing Driver Loader"; Bootstrap::Driver::initialize(); Bootstrap::Driver::preinit_drivers(); } thp_dynamic_call(dyn, "provider_preload"); if (load) { _b_log << "Initializing Loader"; Bootstrap::Loader::initialize(); } Bootstrap::States::init(); Bootstrap::Web::start(); thp_dynamic_call(dyn, "provider_init"); if (load_driver) { Bootstrap::Driver::init_drivers(); } long long end_time = current_time_millis(); _b_log << "Total Bootstrap Startup Time: " + to_string(end_time - start_time) + "ms"; if (loop) thp_dynamic_call(dyn, "provider_loop"); bootstrap_shutdown(); } Bootstrap::BootConfig *Bootstrap::get_config() { return &_b_cfg; } Toast::Logger *Bootstrap::get_logger() { return &_b_log; } DYNAMIC *Bootstrap::get_provider() { return &dyn; } <|endoftext|>
<commit_before>#include "static.h" #include "page.h" #include "../render.h" using namespace Render; void Html::quickStart(){ header("Thanks"); o << "<div class=\"message\">Now that you've registered you can upload tracks: just click your name at the top right corner of the page.</div>"; footer(); } void Html::faq(){ header("FAQ"); o << "<h2>Frequently Asked Questions</h2><div class=\"faq\">" "<div><h4>What is this?</h4>" "<p>A place for artists to publish their MLP-related music, and get in touch with their audience.</p></div>" "<div><h4>Why?</h4>" "<p>Because there is no other central repository for MLP music.</p></div>" "<div><h4>Why not [INSERT SITE HERE]?</h4>" "<p>Because we try to make the publishing and listening process as smooth as can be. No ads, no limits, no downsides.</p></div>" "<div><h4>Who are you anyway?</h4>" "<p>We're two developers: <a href=\"/user/1\">codl</a> and <a href=\"/user/2\">fmang</a>. For more information check the <a href=\"/credits\">credits</a>.</p></div>" "<div><h4>I've got a question/problem/idea!</h4>" "<p>What are you waiting for? Drop us a line at contact@eqbeats.org.</p></div>" "</div>"; footer(); } void Html::credits(){ header("Credits"); o << "<h2>Credits</h2><div class=\"credits\">" "<h4>Staff</h4>" "<ul>" "<li><a href=\"/user/1\">codl</a></li>" "<li><a href=\"/user/2\">fmang</a></li>" "</ul>" "<h4>Support</h4>" "<ul>" "<li><a href=\"/user/3\">AspectOfTheStorm</a></li>" "<li><a href=\"/user/6\">Makkon</a></li>" "</ul>" "<h4>Design</h4>" "<ul>" "<li><a href=\"http://www.slt.fr\">SLT</a> - Logo</li>" "<li><a href=\"http://blackm3sh.deviantart.com/art/Rarity-Filly-203377463\">BlackM3sh</a> - Filly Rarity</li>" "<li><a href=\"http://p.yusukekamiyamane.com/\">Yusuke Kamiyamane</a> - Fugue icon set</li>" "</ul></div>"; footer(); } <commit_msg>credits: added Karai<commit_after>#include "static.h" #include "page.h" #include "../render.h" using namespace Render; void Html::quickStart(){ header("Thanks"); o << "<div class=\"message\">Now that you've registered you can upload tracks: just click your name at the top right corner of the page.</div>"; footer(); } void Html::faq(){ header("FAQ"); o << "<h2>Frequently Asked Questions</h2><div class=\"faq\">" "<div><h4>What is this?</h4>" "<p>A place for artists to publish their MLP-related music, and get in touch with their audience.</p></div>" "<div><h4>Why?</h4>" "<p>Because there is no other central repository for MLP music.</p></div>" "<div><h4>Why not [INSERT SITE HERE]?</h4>" "<p>Because we try to make the publishing and listening process as smooth as can be. No ads, no limits, no downsides.</p></div>" "<div><h4>Who are you anyway?</h4>" "<p>We're two developers: <a href=\"/user/1\">codl</a> and <a href=\"/user/2\">fmang</a>. For more information check the <a href=\"/credits\">credits</a>.</p></div>" "<div><h4>I've got a question/problem/idea!</h4>" "<p>What are you waiting for? Drop us a line at contact@eqbeats.org.</p></div>" "</div>"; footer(); } void Html::credits(){ header("Credits"); o << "<h2>Credits</h2><div class=\"credits\">" "<h4>Staff</h4>" "<ul>" "<li><a href=\"/user/1\">codl</a></li>" "<li><a href=\"/user/2\">fmang</a></li>" "</ul>" "<h4>Support</h4>" "<ul>" "<li><a href=\"/user/3\">AspectOfTheStorm</a></li>" "<li><a href=\"/user/6\">Makkon</a></li>" "<li><a href=\"/user/68\">Karai</a></li>" "</ul>" "<h4>Design</h4>" "<ul>" "<li><a href=\"http://www.slt.fr\">SLT</a> - Logo</li>" "<li><a href=\"http://blackm3sh.deviantart.com/art/Rarity-Filly-203377463\">BlackM3sh</a> - Filly Rarity</li>" "<li><a href=\"http://p.yusukekamiyamane.com/\">Yusuke Kamiyamane</a> - Fugue icon set</li>" "</ul></div>"; footer(); } <|endoftext|>
<commit_before>#define SPICA_PHOTON_MAP_EXPORT #include "photon_map.h" #include <ctime> #include "../utils/sampler.h" #include "../random/random_sampler.h" #include "scene.h" #include "camera.h" #include "render_parameters.h" namespace spica { Photon::Photon() : _position() , _flux() , _direction() , _normal() { } Photon::Photon(const Vector3D& position, const Color& flux, const Vector3D& direction, const Vector3D& normal) : _position(position) , _flux(flux) , _direction(direction) , _normal(normal) { } Photon::Photon(const Photon& photon) : _position() , _flux() , _direction() , _normal() { this->operator=(photon); } Photon::~Photon() { } Photon& Photon::operator=(const Photon& photon) { this->_position = photon._position; this->_flux = photon._flux; this->_direction = photon._direction; this->_normal = photon._normal; return *this; } double Photon::get(int id) const { return _position.get(id); } double Photon::distance(const Photon& p1, const Photon& p2) { return (p1._position - p2._position).norm(); } Photon Photon::sample(const Scene& scene, Stack<double>& rstk, const int numPhotons) { /* const int lightID = scene.lightID(); if (lightID >= 0) { const IGeometry* light = scene.get(lightID); const double r1 = rseq.next(); const double r2 = rseq.next(); Vector3D posLight, normalLight; sampler::on(light, &posLight, &normalLight, r1, r2); Color currentFlux = Color(light->area() * scene.getMaterial(lightID).emission * PI / numPhotons); return Photon(posLight, currentFlux, normalLight, normalLight); } else { return scene.envmap().samplePhoton(rseq, numPhotons); } */ Assertion(false, "This is not implemented!!"); return Photon(); } PhotonMap::PhotonMap() : _kdtree() { } PhotonMap::~PhotonMap() { } void PhotonMap::clear() { _kdtree.release(); } void PhotonMap::construct(const Scene& scene, const RenderParameters& params, BsdfType absorbBsdf) { std::cout << "Shooting photons..." << std::endl; // Random number generator RandomSampler* samplers = new RandomSampler[kNumThreads]; for (int i = 0; i < kNumThreads; i++) { switch (params.randomType()) { case PSEUDO_RANDOM_TWISTER: samplers[i] = Random::factory((unsigned int)i); break; case QUASI_MONTE_CARLO: samplers[i] = Halton::factory(250, true, (unsigned int)i); break; default: std::cerr << "Unknown random sampler type !!" << std::endl; std::abort(); } } // Distribute tasks const int np = params.castPhotons(); const int taskPerThread = (np + kNumThreads - 1) / kNumThreads; std::vector<std::vector<Photon> > photons(kNumThreads); // Shooting photons int proc = 0; for (int t = 0; t < taskPerThread; t++) { ompfor (int threadID = 0; threadID < kNumThreads; threadID++) { // Request random numbers in each thread Stack<double> rstk; samplers[threadID].request(&rstk, 250); // Generate sample on the light const int lightID = scene.sampleLight(rstk.pop()); const Triangle& light = scene.getTriangle(lightID); const Color lightEmt = scene.getEmittance(lightID); Vector3D posLight, normalLight; sampler::onTriangle(light, &posLight, &normalLight, rstk.pop(), rstk.pop()); Color flux = Color(scene.totalLightArea() * lightEmt * PI / params.castPhotons()); Vector3D dir; sampler::onHemisphere(normalLight, &dir, rstk.pop(), rstk.pop()); // Trace photon Ray ray(posLight, dir); tracePhoton(scene, ray, params, flux, rstk, 0, absorbBsdf, &photons[threadID]); } proc += kNumThreads; if (proc % 1000 == 0) { printf("%6.2f %% processed...\r", 100.0 * proc / params.castPhotons()); } } printf("\n"); // Deallocate memories delete[] samplers; // Contruct tree structure printf("Constructing photon map -> "); clear(); std::vector<Photon> photonsAll; for (int i = 0; i < kNumThreads; i++) { photonsAll.insert(photonsAll.end(), photons[i].begin(), photons[i].end()); } _kdtree.construct(photonsAll); printf("OK\n"); } Color PhotonMap::evaluate(const Vector3D& position, const Vector3D& normal, int gatherPhotons, double gatherRadius) const { // Find k-nearest neightbors Photon query(position, Color(), Vector3D(), normal); std::vector<Photon> photons; knnFind(query, &photons, gatherPhotons, gatherRadius); const int numPhotons = static_cast<int>(photons.size()); std::vector<Photon> validPhotons; std::vector<double> distances; double maxdist = 0.0; for (int i = 0; i < numPhotons; i++) { const Vector3D diff = query.position() - photons[i].position(); const double dist = diff.norm(); const double dt = Vector3D::dot(normal, diff) / dist; if (std::abs(dt) < gatherRadius * gatherRadius * 0.01) { validPhotons.push_back(photons[i]); distances.push_back(dist); maxdist = std::max(maxdist, dist); } } // Cone filter const int numValidPhotons = static_cast<int>(validPhotons.size()); const double k = 1.1; Color totalFlux = Color(0.0, 0.0, 0.0); for (int i = 0; i < numValidPhotons; i++) { const double w = 1.0 - (distances[i] / (k * maxdist)); const Color v = Color(photons[i].flux() * INV_PI); totalFlux += w * v; } totalFlux /= (1.0 - 2.0 / (3.0 * k)); if (maxdist > EPS) { return Color(totalFlux / (PI * maxdist * maxdist)); } return Color(0.0, 0.0, 0.0); } void PhotonMap::knnFind(const Photon& photon, std::vector<Photon>* photons, const int gatherPhotons, const double gatherRadius) const { KnnQuery query(K_NEAREST | EPSILON_BALL, gatherPhotons, gatherRadius); _kdtree.knnSearch(photon, query, photons); } void PhotonMap::tracePhoton(const Scene& scene, const Ray& ray, const RenderParameters& params, const Color& flux, Stack<double>& rstk, int bounces, BsdfType absorbBsdf, std::vector<Photon>* photons) { // Too many bounces terminate recursion if (bounces >= params.bounceLimit()) { return; } // Request random numbers const double rands[3] = { rstk.pop(), rstk.pop(), rstk.pop() }; // Remove photon with zero flux if (max3(flux.red(), flux.green(), flux.blue()) <= 0.0) { return; } // If not hit the scene, then break Intersection isect; if (!scene.intersect(ray, isect)) { return; } // Hitting object const int objID = isect.objectId(); const BSDF& bsdf = scene.getBsdf(objID); const Color& refl = bsdf.reflectance(); const Hitpoint& hpoint = isect.hitpoint(); const bool into = Vector3D::dot(hpoint.normal(), ray.direction()) < 0.0; const Vector3D orientNormal = (into ? 1.0 : -1.0) * hpoint.normal(); double photonPdf = 1.0; if (bsdf.type() & absorbBsdf) { photons->push_back(Photon(hpoint.position(), flux, ray.direction(), hpoint.normal())); // Russian roulette const double prob = (refl.red() + refl.green() + refl.blue()) / 3.0; if (rands[0] < prob) { // Reflection photonPdf *= prob; } else { // Absorption return; } } double samplePdf = 1.0; Vector3D nextdir; bsdf.sample(ray.direction(), hpoint.normal(), rands[1], rands[2], &nextdir, &samplePdf); Ray nextRay(hpoint.position(), nextdir); Color nextFlux = Color((flux * refl) / (samplePdf * photonPdf)); // Next bounce tracePhoton(scene, nextRay, params, nextFlux, rstk, bounces + 1, absorbBsdf, photons); } } // namespace spica <commit_msg>Update the usage of random number generator in photon map construction.<commit_after>#define SPICA_PHOTON_MAP_EXPORT #include "photon_map.h" #include <ctime> #include "../utils/sampler.h" #include "../random/random_sampler.h" #include "scene.h" #include "camera.h" #include "render_parameters.h" namespace spica { Photon::Photon() : _position() , _flux() , _direction() , _normal() { } Photon::Photon(const Vector3D& position, const Color& flux, const Vector3D& direction, const Vector3D& normal) : _position(position) , _flux(flux) , _direction(direction) , _normal(normal) { } Photon::Photon(const Photon& photon) : _position() , _flux() , _direction() , _normal() { this->operator=(photon); } Photon::~Photon() { } Photon& Photon::operator=(const Photon& photon) { this->_position = photon._position; this->_flux = photon._flux; this->_direction = photon._direction; this->_normal = photon._normal; return *this; } double Photon::get(int id) const { return _position.get(id); } double Photon::distance(const Photon& p1, const Photon& p2) { return (p1._position - p2._position).norm(); } Photon Photon::sample(const Scene& scene, Stack<double>& rstk, const int numPhotons) { /* const int lightID = scene.lightID(); if (lightID >= 0) { const IGeometry* light = scene.get(lightID); const double r1 = rseq.next(); const double r2 = rseq.next(); Vector3D posLight, normalLight; sampler::on(light, &posLight, &normalLight, r1, r2); Color currentFlux = Color(light->area() * scene.getMaterial(lightID).emission * PI / numPhotons); return Photon(posLight, currentFlux, normalLight, normalLight); } else { return scene.envmap().samplePhoton(rseq, numPhotons); } */ Assertion(false, "This is not implemented!!"); return Photon(); } PhotonMap::PhotonMap() : _kdtree() { } PhotonMap::~PhotonMap() { } void PhotonMap::clear() { _kdtree.release(); } void PhotonMap::construct(const Scene& scene, const RenderParameters& params, BsdfType absorbBsdf) { std::cout << "Shooting photons..." << std::endl; // Random number generator RandomSampler* samplers = new RandomSampler[kNumThreads]; for (int i = 0; i < kNumThreads; i++) { switch (params.randomType()) { case PSEUDO_RANDOM_TWISTER: samplers[i] = Random::factory((unsigned int)(time(0) + i)); break; case QUASI_MONTE_CARLO: samplers[i] = Halton::factory(250, true, (unsigned int)(time(0) + i)); break; default: std::cerr << "Unknown random sampler type !!" << std::endl; std::abort(); } } // Distribute tasks const int np = params.castPhotons(); const int taskPerThread = (np + kNumThreads - 1) / kNumThreads; std::vector<std::vector<Photon> > photons(kNumThreads); // Shooting photons int proc = 0; for (int t = 0; t < taskPerThread; t++) { ompfor (int threadID = 0; threadID < kNumThreads; threadID++) { // Request random numbers in each thread Stack<double> rstk; samplers[threadID].request(&rstk, 250); // Generate sample on the light const int lightID = scene.sampleLight(rstk.pop()); const Triangle& light = scene.getTriangle(lightID); const Color lightEmt = scene.getEmittance(lightID); Vector3D posLight, normalLight; sampler::onTriangle(light, &posLight, &normalLight, rstk.pop(), rstk.pop()); Color flux = Color(scene.totalLightArea() * lightEmt * PI / params.castPhotons()); Vector3D dir; sampler::onHemisphere(normalLight, &dir, rstk.pop(), rstk.pop()); // Trace photon Ray ray(posLight, dir); tracePhoton(scene, ray, params, flux, rstk, 0, absorbBsdf, &photons[threadID]); } proc += kNumThreads; if (proc % 1000 == 0) { printf("%6.2f %% processed...\r", 100.0 * proc / params.castPhotons()); } } printf("\n"); // Deallocate memories delete[] samplers; // Contruct tree structure printf("Constructing photon map -> "); clear(); std::vector<Photon> photonsAll; for (int i = 0; i < kNumThreads; i++) { photonsAll.insert(photonsAll.end(), photons[i].begin(), photons[i].end()); } _kdtree.construct(photonsAll); printf("OK\n"); } Color PhotonMap::evaluate(const Vector3D& position, const Vector3D& normal, int gatherPhotons, double gatherRadius) const { // Find k-nearest neightbors Photon query(position, Color(), Vector3D(), normal); std::vector<Photon> photons; knnFind(query, &photons, gatherPhotons, gatherRadius); const int numPhotons = static_cast<int>(photons.size()); std::vector<Photon> validPhotons; std::vector<double> distances; double maxdist = 0.0; for (int i = 0; i < numPhotons; i++) { const Vector3D diff = query.position() - photons[i].position(); const double dist = diff.norm(); const double dt = Vector3D::dot(normal, diff) / dist; if (std::abs(dt) < gatherRadius * gatherRadius * 0.01) { validPhotons.push_back(photons[i]); distances.push_back(dist); maxdist = std::max(maxdist, dist); } } // Cone filter const int numValidPhotons = static_cast<int>(validPhotons.size()); const double k = 1.1; Color totalFlux = Color(0.0, 0.0, 0.0); for (int i = 0; i < numValidPhotons; i++) { const double w = 1.0 - (distances[i] / (k * maxdist)); const Color v = Color(photons[i].flux() * INV_PI); totalFlux += w * v; } totalFlux /= (1.0 - 2.0 / (3.0 * k)); if (maxdist > EPS) { return Color(totalFlux / (PI * maxdist * maxdist)); } return Color(0.0, 0.0, 0.0); } void PhotonMap::knnFind(const Photon& photon, std::vector<Photon>* photons, const int gatherPhotons, const double gatherRadius) const { KnnQuery query(K_NEAREST | EPSILON_BALL, gatherPhotons, gatherRadius); _kdtree.knnSearch(photon, query, photons); } void PhotonMap::tracePhoton(const Scene& scene, const Ray& ray, const RenderParameters& params, const Color& flux, Stack<double>& rstk, int bounces, BsdfType absorbBsdf, std::vector<Photon>* photons) { // Too many bounces terminate recursion if (bounces >= params.bounceLimit()) { return; } // Request random numbers const double rands[3] = { rstk.pop(), rstk.pop(), rstk.pop() }; // Remove photon with zero flux if (max3(flux.red(), flux.green(), flux.blue()) <= 0.0) { return; } // If not hit the scene, then break Intersection isect; if (!scene.intersect(ray, isect)) { return; } // Hitting object const int objID = isect.objectId(); const BSDF& bsdf = scene.getBsdf(objID); const Color& refl = bsdf.reflectance(); const Hitpoint& hpoint = isect.hitpoint(); const bool into = Vector3D::dot(hpoint.normal(), ray.direction()) < 0.0; const Vector3D orientNormal = (into ? 1.0 : -1.0) * hpoint.normal(); double photonPdf = 1.0; if (bsdf.type() & absorbBsdf) { photons->push_back(Photon(hpoint.position(), flux, ray.direction(), hpoint.normal())); // Russian roulette const double prob = (refl.red() + refl.green() + refl.blue()) / 3.0; if (rands[0] < prob) { // Reflection photonPdf *= prob; } else { // Absorption return; } } double samplePdf = 1.0; Vector3D nextdir; bsdf.sample(ray.direction(), hpoint.normal(), rands[1], rands[2], &nextdir, &samplePdf); Ray nextRay(hpoint.position(), nextdir); Color nextFlux = Color((flux * refl) / (samplePdf * photonPdf)); // Next bounce tracePhoton(scene, nextRay, params, nextFlux, rstk, bounces + 1, absorbBsdf, photons); } } // namespace spica <|endoftext|>
<commit_before>/******************************************************************************* * c7a/api/reduce.hpp * * DIANode for a reduce operation. Performs the actual reduce operation * * Part of Project c7a. * * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_REDUCE_HEADER #define C7A_API_REDUCE_HEADER #include <c7a/api/dop_node.hpp> #include <c7a/common/functional.hpp> #include <c7a/common/logger.hpp> #include <c7a/core/reduce_post_table.hpp> #include <c7a/core/reduce_pre_table.hpp> #include <functional> #include <string> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> namespace c7a { namespace api { //! \addtogroup api Interface //! \{ /*! * A DIANode which performs a Reduce operation. Reduce groups the elements in a * DIA by their key and reduces every key bucket to a single element each. The * ReduceNode stores the key_extractor and the reduce_function UDFs. The * chainable LOps ahead of the Reduce operation are stored in the Stack. The * ReduceNode has the type ValueType, which is the result type of the * reduce_function. * * \tparam ValueType Output type of the Reduce operation * \tparam Stack Function stack, which contains the chained lambdas between the * last and this DIANode. * \tparam KeyExtractor Type of the key_extractor function. * \tparam ReduceFunction Type of the reduce_function. * \tparam RobustKey Whether to reuse the key once extracted in during pre reduce * (false) or let the post reduce extract the key again (true). */ template <typename ValueType, typename ParentDIARef, typename KeyExtractor, typename ReduceFunction, const bool RobustKey, typename InputType> class ReduceNode : public DOpNode<ValueType> { static const bool debug = false; using Super = DOpNode<ValueType>; using Key = typename common::FunctionTraits<KeyExtractor>::result_type; using Value = typename common::FunctionTraits<ReduceFunction>::result_type; using ReduceArg = typename common::FunctionTraits<ReduceFunction> ::template arg<0>; typedef std::pair<Key, Value> KeyValuePair; using Super::context_; using Super::result_file_; public: /*! * Constructor for a ReduceNode. Sets the DataManager, parent, stack, * key_extractor and reduce_function. * * \param parent Parent DIARef. * and this node * \param key_extractor Key extractor function * \param reduce_function Reduce function */ ReduceNode(const ParentDIARef& parent, KeyExtractor key_extractor, ReduceFunction reduce_function, StatsNode* stats_node) : DOpNode<ValueType>(parent.ctx(), { parent.node() }, "Reduce", stats_node), key_extractor_(key_extractor), reduce_function_(reduce_function), channel_(parent.ctx().data_manager().GetNewChannel()), emitters_(channel_->OpenWriters()), reduce_pre_table_(parent.ctx().number_worker(), key_extractor, reduce_function_, emitters_) { // Hook PreOp auto pre_op_fn = [=](const InputType& input) { PreOp(input); }; // close the function stack with our pre op and register it at // parent node for output auto lop_chain = parent.stack().push(pre_op_fn).emit(); parent.node()->RegisterChild(lop_chain); } //! Virtual destructor for a ReduceNode. virtual ~ReduceNode() { } /*! * Actually executes the reduce operation. Uses the member functions PreOp, * MainOp and PostOp. */ void Execute() override { this->StartExecutionTimer(); MainOp(); this->StopExecutionTimer(); } void PushData() override { // TODO(ms): this is not what should happen: every thing is reduced again: using ReduceTable = core::ReducePostTable<KeyExtractor, ReduceFunction, false>; ReduceTable table(key_extractor_, reduce_function_, DIANode<ValueType>::callbacks()); if (RobustKey) { //we actually want to wire up callbacks in the ctor and NOT use this blocking method auto reader = channel_->OpenReader(); sLOG << "reading data from" << channel_->id() << "to push into post table which flushes to" << result_file_.ToString(); while (reader.HasNext()) { table.Insert(reader.template Next<Value>()); } table.Flush(); } else { //we actually want to wire up callbacks in the ctor and NOT use this blocking method auto reader = channel_->OpenReader(); sLOG << "reading data from" << channel_->id() << "to push into post table which flushes to" << result_file_.ToString(); while (reader.HasNext()) { table.Insert(reader.template Next<KeyValuePair>()); } table.Flush(); } } void Dispose() override { } /*! * Produces a function stack, which only contains the PostOp function. * \return PostOp function stack */ auto ProduceStack() { // Hook PostOp auto post_op_fn = [=](const ValueType& elem, auto emit_func) { return this->PostOp(elem, emit_func); }; return MakeFunctionStack<ValueType>(post_op_fn); } /*! * Returns "[ReduceNode]" and its id as a string. * \return "[ReduceNode]" */ std::string ToString() override { return "[ReduceNode] Id: " + result_file_.ToString(); } private: //!Key extractor function KeyExtractor key_extractor_; //!Reduce function ReduceFunction reduce_function_; data::ChannelPtr channel_; std::vector<data::BlockWriter> emitters_; core::ReducePreTable<Key, Value, KeyExtractor, ReduceFunction, RobustKey> reduce_pre_table_; //! Locally hash elements of the current DIA onto buckets and reduce each //! bucket to a single value, afterwards send data to another worker given //! by the shuffle algorithm. void PreOp(const InputType& input) { reduce_pre_table_.Insert(input); } //!Receive elements from other workers. auto MainOp() { LOG << ToString() << " running main op"; //Flush hash table before the postOp reduce_pre_table_.Flush(); reduce_pre_table_.CloseEmitter(); } //! Hash recieved elements onto buckets and reduce each bucket to a single value. template <typename Emitter> void PostOp(ValueType input, Emitter emit_func) { emit_func(input); } }; template <typename ValueType, typename Stack> template <typename KeyExtractor, typename ReduceFunction> auto DIARef<ValueType, Stack>::ReduceBy( const KeyExtractor &key_extractor, const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, ValueType>::value, "ReduceFunction has the wrong output type"); static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor> ::template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("ReduceBy", "DOp"); using ReduceResultNode = ReduceNode<DOpResult, DIARef, KeyExtractor, ReduceFunction, true, ValueType>; auto shared_node = std::make_shared<ReduceResultNode>(*this, key_extractor, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } template <typename ValueType, typename Stack> template <typename ReduceFunction> auto DIARef<ValueType, Stack>::ReducePair( const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert(common::is_pair<ValueType>::value, "ValueType is not a pair"); static_assert( std::is_convertible< typename ValueType::second_type, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< typename ValueType::second_type, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, typename ValueType::second_type>::value, "ReduceFunction has the wrong output type"); using Key = typename ValueType::first_type; StatsNode* stats_node = AddChildStatsNode("ReducePair", "DOp"); using ReduceResultNode = ReduceNode<DOpResult, DIARef, std::function<Key(Key)>, ReduceFunction, false, ValueType>; auto shared_node = std::make_shared<ReduceResultNode>(*this, [](Key key) { //This function should not be //called, it is only here to //give the key type to the //hashtables. assert(1 == 0); key = key; return Key(); }, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } template <typename ValueType, typename Stack> template <typename KeyExtractor, typename ReduceFunction> auto DIARef<ValueType, Stack>::ReduceByKey( const KeyExtractor &key_extractor, const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, ValueType>::value, "ReduceFunction has the wrong output type"); static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor>:: template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("Reduce", "DOp"); using ReduceResultNode = ReduceNode<DOpResult, DIARef, KeyExtractor, ReduceFunction, false, ValueType>; auto shared_node = std::make_shared<ReduceResultNode>(*this, key_extractor, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } //! \} } // namespace api } // namespace c7a #endif // !C7A_API_REDUCE_HEADER /******************************************************************************/ <commit_msg>Removing lots of lambda-fu in ReduceNode, which is the identity.<commit_after>/******************************************************************************* * c7a/api/reduce.hpp * * DIANode for a reduce operation. Performs the actual reduce operation * * Part of Project c7a. * * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_REDUCE_HEADER #define C7A_API_REDUCE_HEADER #include <c7a/api/dop_node.hpp> #include <c7a/common/functional.hpp> #include <c7a/common/logger.hpp> #include <c7a/core/reduce_post_table.hpp> #include <c7a/core/reduce_pre_table.hpp> #include <functional> #include <string> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> namespace c7a { namespace api { //! \addtogroup api Interface //! \{ /*! * A DIANode which performs a Reduce operation. Reduce groups the elements in a * DIA by their key and reduces every key bucket to a single element each. The * ReduceNode stores the key_extractor and the reduce_function UDFs. The * chainable LOps ahead of the Reduce operation are stored in the Stack. The * ReduceNode has the type ValueType, which is the result type of the * reduce_function. * * \tparam ValueType Output type of the Reduce operation * \tparam Stack Function stack, which contains the chained lambdas between the * last and this DIANode. * \tparam KeyExtractor Type of the key_extractor function. * \tparam ReduceFunction Type of the reduce_function. * \tparam RobustKey Whether to reuse the key once extracted in during pre reduce * (false) or let the post reduce extract the key again (true). */ template <typename ValueType, typename ParentDIARef, typename KeyExtractor, typename ReduceFunction, const bool RobustKey, typename InputType> class ReduceNode : public DOpNode<ValueType> { static const bool debug = false; using Super = DOpNode<ValueType>; using Key = typename common::FunctionTraits<KeyExtractor>::result_type; using Value = typename common::FunctionTraits<ReduceFunction>::result_type; using ReduceArg = typename common::FunctionTraits<ReduceFunction> ::template arg<0>; typedef std::pair<Key, Value> KeyValuePair; using Super::context_; using Super::result_file_; public: /*! * Constructor for a ReduceNode. Sets the DataManager, parent, stack, * key_extractor and reduce_function. * * \param parent Parent DIARef. * and this node * \param key_extractor Key extractor function * \param reduce_function Reduce function */ ReduceNode(const ParentDIARef& parent, KeyExtractor key_extractor, ReduceFunction reduce_function, StatsNode* stats_node) : DOpNode<ValueType>(parent.ctx(), { parent.node() }, "Reduce", stats_node), key_extractor_(key_extractor), reduce_function_(reduce_function), channel_(parent.ctx().data_manager().GetNewChannel()), emitters_(channel_->OpenWriters()), reduce_pre_table_(parent.ctx().number_worker(), key_extractor, reduce_function_, emitters_) { // Hook PreOp auto pre_op_fn = [=](const InputType& input) { PreOp(input); }; // close the function stack with our pre op and register it at // parent node for output auto lop_chain = parent.stack().push(pre_op_fn).emit(); parent.node()->RegisterChild(lop_chain); } //! Virtual destructor for a ReduceNode. virtual ~ReduceNode() { } /*! * Actually executes the reduce operation. Uses the member functions PreOp, * MainOp and PostOp. */ void Execute() override { this->StartExecutionTimer(); MainOp(); this->StopExecutionTimer(); } void PushData() override { // TODO(ms): this is not what should happen: every thing is reduced again: using ReduceTable = core::ReducePostTable<KeyExtractor, ReduceFunction, false>; ReduceTable table(key_extractor_, reduce_function_, DIANode<ValueType>::callbacks()); if (RobustKey) { //we actually want to wire up callbacks in the ctor and NOT use this blocking method auto reader = channel_->OpenReader(); sLOG << "reading data from" << channel_->id() << "to push into post table which flushes to" << result_file_.ToString(); while (reader.HasNext()) { table.Insert(reader.template Next<Value>()); } table.Flush(); } else { //we actually want to wire up callbacks in the ctor and NOT use this blocking method auto reader = channel_->OpenReader(); sLOG << "reading data from" << channel_->id() << "to push into post table which flushes to" << result_file_.ToString(); while (reader.HasNext()) { table.Insert(reader.template Next<KeyValuePair>()); } table.Flush(); } } void Dispose() override { } /*! * Produces a function stack, which only contains the PostOp function. * \return PostOp function stack */ auto ProduceStack() { return FunctionStack<ValueType>(); } /*! * Returns "[ReduceNode]" and its id as a string. * \return "[ReduceNode]" */ std::string ToString() override { return "[ReduceNode] Id: " + result_file_.ToString(); } private: //!Key extractor function KeyExtractor key_extractor_; //!Reduce function ReduceFunction reduce_function_; data::ChannelPtr channel_; std::vector<data::BlockWriter> emitters_; core::ReducePreTable<Key, Value, KeyExtractor, ReduceFunction, RobustKey> reduce_pre_table_; //! Locally hash elements of the current DIA onto buckets and reduce each //! bucket to a single value, afterwards send data to another worker given //! by the shuffle algorithm. void PreOp(const InputType& input) { reduce_pre_table_.Insert(input); } //!Receive elements from other workers. auto MainOp() { LOG << ToString() << " running main op"; //Flush hash table before the postOp reduce_pre_table_.Flush(); reduce_pre_table_.CloseEmitter(); } }; template <typename ValueType, typename Stack> template <typename KeyExtractor, typename ReduceFunction> auto DIARef<ValueType, Stack>::ReduceBy( const KeyExtractor &key_extractor, const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, ValueType>::value, "ReduceFunction has the wrong output type"); static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor> ::template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("ReduceBy", "DOp"); using ReduceResultNode = ReduceNode<DOpResult, DIARef, KeyExtractor, ReduceFunction, true, ValueType>; auto shared_node = std::make_shared<ReduceResultNode>(*this, key_extractor, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } template <typename ValueType, typename Stack> template <typename ReduceFunction> auto DIARef<ValueType, Stack>::ReducePair( const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert(common::is_pair<ValueType>::value, "ValueType is not a pair"); static_assert( std::is_convertible< typename ValueType::second_type, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< typename ValueType::second_type, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, typename ValueType::second_type>::value, "ReduceFunction has the wrong output type"); using Key = typename ValueType::first_type; StatsNode* stats_node = AddChildStatsNode("ReducePair", "DOp"); using ReduceResultNode = ReduceNode<DOpResult, DIARef, std::function<Key(Key)>, ReduceFunction, false, ValueType>; auto shared_node = std::make_shared<ReduceResultNode>(*this, [](Key key) { //This function should not be //called, it is only here to //give the key type to the //hashtables. assert(1 == 0); key = key; return Key(); }, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } template <typename ValueType, typename Stack> template <typename KeyExtractor, typename ReduceFunction> auto DIARef<ValueType, Stack>::ReduceByKey( const KeyExtractor &key_extractor, const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, ValueType>::value, "ReduceFunction has the wrong output type"); static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor>:: template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("Reduce", "DOp"); using ReduceResultNode = ReduceNode<DOpResult, DIARef, KeyExtractor, ReduceFunction, false, ValueType>; auto shared_node = std::make_shared<ReduceResultNode>(*this, key_extractor, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } //! \} } // namespace api } // namespace c7a #endif // !C7A_API_REDUCE_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>#include <algorithm> #include <cassert> #include <mutex> #include <tuple> #include <utility> #include "ReadWriteLock.h" #include "bitset/Bitset.h" #include "malloc_debug.h" #include <array> #include <atomic> #include "free.h" #include "global.h" #include "malloc.h" #include "shared.h" #include "stuff.h" // http://preshing.com/20131125/acquire-and-release-fences-dont-work-the-way-youd-expect/ // # version 2.0 // - from a pointer get the node header and in the node header get a pointer to // the extent header to support random access free(). Maybe have a tag in the // node header like Thread id to make global::free easier. // - use memmap instead of sbrk to more freely allow for reclamation of // large unused ranges of global free-list memory. Without being blocked by a // single high sbrk reservation. // sp::RefCounter Pools in global // # TODO // 1. local::free_list // * best fit // * local::malloc coalesce local free list // * only single mallocing thread is allowed the dequeuing // * multiple free threads is allowed to enqueue // * high & low watermark on free list size based on total allocated by thread // * global::alloc(minimum, desired) desired size is optional to fulfil // * local -> global free list reclamation based on high watermark // // 2. Local pool reclamation from global // * Non-thread local free() // * detect if all pooled memory is reclaimed // * counter in Pools of how much memory is present in the different pool // * does not include local::free list // * increase on local::alloc(Node/Extent) // * decrease on local::dealloc(Node/Extent) // * global will look in local::Pool reclamation before sbrk? // * on g::dealloc_pool() will check if Pools::size is 0 if so directly reclaim // * Shared local::Polls lock used by free from other threads not local // malloc&free // // 3. local::free_list free reclamation // * logic for reclaim on TL free the Extent // * logic for reclaim on non-TL free the Extent // // 4. Differentiate global and global_Pool storage // * refactor to two different files // // 5. global::free_list // * (shrinking/reclamation/release/dealloc) reclaim usuable mem to sbrk // * change interface for global::alloc to N 4096 pages not X bytes // // 9. global::free_list // * how to better coalesce global::free_list pages // * first fit // // 10. local::free_list allocation strategy // * allow externally to register a callback to control allocation strategy // * hint of how much memory will be needed generally or specific bucketSz // * hint to over allocate by haveing a % in local free list // // 11. memory leaks detect // * print statistics for all non-freed memory // // 12. assert less than sbrk(0) // * sp_free(ptr < sbrk(0)), sp_realloc(ptr < sbrk(0)) ... // TODO optimizations // - Some kind of TL cache with a reference to the most referenced Pools used // for non-TL free:ing. // - A range of the highest & lowest memory address used to determine if it is // necessary to walk through the Nodes // - on PoolsRAII level // - on Pool level // - a optimized collections of Pool:s used for free:ing in addition to the // Pool[60] used for allocating // {{{ static thread_local local::Pools local_pools; // }}} namespace local { static std::size_t pool_index(std::size_t size) noexcept { assert(size % 8 == 0); return util::trailing_zeros(size) - std::size_t(3); } // local::pool_index() static local::Pool & pool_for(local::Pools &pools, std::size_t sz) noexcept { const std::size_t index = pool_index(sz); return pools[index]; } // local::pool_for() static void * alloc(local::Pools &pools, std::size_t sz) noexcept { // printf("local::alloc(%zu)\n", sz); // TODO local alloc void *const result = global::alloc(sz); if (result) { pools.pools->total_alloc.fetch_add(sz); } return result; } // local::alloc() /* * @start - node start * desc - */ static header::Node * next_node(header::Node *const start) noexcept { return start->next.load(); } // local::next_node() /* * @param start - extent start * @param index - * @desc - */ static void * pointer_at(header::Node *start, std::size_t index) noexcept { // printf("pointer_at(start,index(%zu))\n", index); // Pool[Extent[Node[nodeHDR,extHDR],Node[nodeHDR]...]...] // The first NodeHeader in the extent contains data while intermediate // NodeHeader does not containt this data. assert(start->type == header::NodeType::HEAD); size_t hdrSz(header::SIZE); size_t buckets = start->buckets; const size_t bucket_size = start->bucket_size; node_start: const size_t node_size = start->node_size; const size_t data_size(node_size - hdrSz); size_t nodeBuckets = std::min(data_size / start->bucket_size, buckets); if (index < nodeBuckets) { // the index is in range of current node uintptr_t startPtr = reinterpret_cast<uintptr_t>(start); uintptr_t data_start = startPtr + hdrSz; return reinterpret_cast<void *>(data_start + (index * bucket_size)); } // the index is out of range, go to next node header::Node *const next = next_node(start); index = index - nodeBuckets; buckets = buckets - nodeBuckets; if (buckets > 0) { assert(next != nullptr); assert(next->type == header::NodeType::LINK); start = next; // the same extent but a new node hdrSz = sizeof(header::Node); goto node_start; } else { // out of bound // TODO implementation fault or runtime? assert(false); } } // local::pointer_at() /* * @start - extent start * desc - Used by malloc & free */ static header::Node * next_extent(header::Node *start) noexcept { assert(start != nullptr); start: header::Node *const next = next_node(start); if (next) { if (next->type == header::NodeType::HEAD) { return next; } start = next; goto start; } return nullptr; } // local::next_intent() /* * @start - extent start * desc - Used by malloc */ static void * reserve(header::Node *const node) noexcept { if (node->type == header::NodeType::HEAD) { header::Extent *const eHdr = header::extent(node); auto &reservations = eHdr->reserved; // printf("reservations.swap_first(true,buckets(%zu))\n", nHdr->buckets); const std::size_t limit = node->buckets; const std::size_t index = reservations.swap_first(true, limit); if (index != reservations.npos) { return pointer_at(node, index); } } return nullptr; } // local::reserve() static std::size_t calc_min_node(std::size_t bucketSz) noexcept { assert(bucketSz >= 8); assert(bucketSz % 8 == 0); constexpr std::size_t min_alloc = SP_MALLOC_PAGE_SIZE; constexpr std::size_t max_alloc = min_alloc * 4; if (bucketSz + header::SIZE > max_alloc) { return util::round_up(bucketSz + header::SIZE, min_alloc); } constexpr std::size_t lookup[] = // { // /*___8:*/ min_alloc, /*__16:*/ min_alloc * 2, /*__32:*/ max_alloc, /*__64:*/ max_alloc, /*_128:*/ max_alloc, /*_256:*/ max_alloc, /*_512:*/ max_alloc, /*1024:*/ max_alloc, /*2048:*/ max_alloc, /*4096:*/ max_alloc, /*8192:*/ min_alloc * 5, // }; return lookup[pool_index(bucketSz)]; } /* * @bucketSz - Normailzed size of bucket * desc - Used by malloc */ static header::Node * alloc_extent(local::Pools &pools, std::size_t bucketSz) noexcept { // printf("alloc_extent(%zu)\n", bucketSz); std::size_t nodeSz = calc_min_node(bucketSz); void *const raw = alloc(pools, nodeSz); if (raw) { return header::init_node(raw, nodeSz, bucketSz); } return nullptr; } // local::alloc_extent() static bool should_expand_extent(header::Node *) { return false; } static header::Node * enqueue_new_extent(local::Pools &pools, std::atomic<header::Node *> &w, std::size_t bucketSz) noexcept { header::Node *const current = local::alloc_extent(pools, bucketSz); if (current) { // TODO some kind of fence to ensure construction before publication // std::atomic_thread_fence(std::memory_order_release); header::Node *start = nullptr; if (!w.compare_exchange_strong(start, current)) { // should never fail // TODO local::dealloc_extent(current) assert(false); } } return current; } // local::enqueue_new_extent() /* * @size - extent start * desc - Used by malloc */ static void expand_extent(void *const) noexcept { // TODO } // local::extend_extent() } // namespace local /* *=========================================================== *=======DEBUG=============================================== *=========================================================== */ #ifdef SP_TEST namespace debug { std::size_t malloc_count_alloc() { std::size_t result(0); for (std::size_t i(8); i > 0; i <<= 1) { result += malloc_count_alloc(i); } return result; } static std::size_t count_reserved(header::Extent &ext, std::size_t buckets) { std::size_t result(0); auto &b = ext.reserved; for (std::size_t idx(0); idx < buckets; ++idx) { if (b.test(idx)) { result++; } } return result; } std::size_t malloc_count_alloc(std::size_t sz) { std::size_t result(0); local::Pool &pool = local::pool_for(local_pools, sz); sp::SharedLock guard(pool.lock); if (guard) { header::Node *current = pool.start.next.load(); start: if (current) { assert(current->type == header::NodeType::HEAD); auto ext = header::extent(current); assert(ext != nullptr); result += count_reserved(*ext, current->buckets); current = local::next_extent(current); goto start; } } return result; } } // namespace debug #endif /* *=========================================================== *=======PUBLIC============================================== *=========================================================== */ void * sp_malloc(std::size_t length) noexcept { if (length == 0) { return nullptr; } const std::size_t bucketSz = util::round_even(length); local::Pool &pool = pool_for(local_pools, bucketSz); sp::SharedLock guard{pool.lock}; if (guard) { header::Node *start = &pool.start; if (start) { reserve_start: void *result = local::reserve(start); if (result) { return result; } else { header::Node *const next = local::next_extent(start); if (next) { start = next; goto reserve_start; } else { if (local::should_expand_extent(start)) { local::expand_extent(start); } else { start = local::enqueue_new_extent(local_pools, start->next, bucketSz); } if (start) { goto reserve_start; } // out of memory return nullptr; } } } else { // only TL allowed to malloc meaning no alloc contention header::Node *current = local::enqueue_new_extent(local_pools, pool.start.next, bucketSz); if (current) { void *const result = local::reserve(current); // Since only one allocator this must succeed. assert(result); return result; } assert(false); // out of memory return nullptr; } } // SharedLock // We should never get to here assert(false); return nullptr; } // ::sp_malloc() bool sp_free(void *const ptr) noexcept { if (!ptr) { return true; } using shared::FreeCode; auto result = shared::free(local_pools, ptr); if (result == FreeCode::NOT_FOUND) { result = global::free(ptr); } return result == FreeCode::FREED || result == FreeCode::FREED_RECLAIM; } // ::sp_free() std::size_t sp_usable_size(void *const ptr) noexcept { if (!ptr) { return 0; } auto lresult = shared::usable_size(local_pools, ptr); if (lresult) { return lresult.get(); } auto result = global::usable_size(ptr); return result.get_or(0); } // ::sp_usable_size() void * sp_realloc(void *const ptr, std::size_t length) noexcept { if (!ptr) { return nullptr; } if (length == 0) { sp_free(ptr); return nullptr; } auto lresult = shared::realloc(local_pools, ptr, length); if (lresult) { return lresult.get(); } auto result = global::realloc(ptr, length); return result.get_or(nullptr); } //::sp_realloc <commit_msg>comment<commit_after>#include <algorithm> #include <cassert> #include <mutex> #include <tuple> #include <utility> #include "ReadWriteLock.h" #include "bitset/Bitset.h" #include "malloc_debug.h" #include <array> #include <atomic> #include "free.h" #include "global.h" #include "malloc.h" #include "shared.h" #include "stuff.h" // http://preshing.com/20131125/acquire-and-release-fences-dont-work-the-way-youd-expect/ // # version 2.0 // - from a pointer get the node header and in the node header get a pointer to // the extent header to support random access free(). Maybe have a tag in the // node header like Thread id to make global::free easier. // `node::Header header_for(ptr);` // - use memmap instead of sbrk to more freely allow for reclamation of // large unused ranges of global free-list memory. Without being blocked by a // single high sbrk reservation. // sp::RefCounter Pools in global // # TODO // 1. local::free_list // * best fit // * local::malloc coalesce local free list // * only single mallocing thread is allowed the dequeuing // * multiple free threads is allowed to enqueue // * high & low watermark on free list size based on total allocated by thread // * global::alloc(minimum, desired) desired size is optional to fulfil // * local -> global free list reclamation based on high watermark // // 2. Local pool reclamation from global // * Non-thread local free() // * detect if all pooled memory is reclaimed // * counter in Pools of how much memory is present in the different pool // * does not include local::free list // * increase on local::alloc(Node/Extent) // * decrease on local::dealloc(Node/Extent) // * global will look in local::Pool reclamation before sbrk? // * on g::dealloc_pool() will check if Pools::size is 0 if so directly reclaim // * Shared local::Polls lock used by free from other threads not local // malloc&free // // 3. local::free_list free reclamation // * logic for reclaim on TL free the Extent // * logic for reclaim on non-TL free the Extent // // 4. Differentiate global and global_Pool storage // * refactor to two different files // // 5. global::free_list // * (shrinking/reclamation/release/dealloc) reclaim usuable mem to sbrk // * change interface for global::alloc to N 4096 pages not X bytes // // 9. global::free_list // * how to better coalesce global::free_list pages // * first fit // // 10. local::free_list allocation strategy // * allow externally to register a callback to control allocation strategy // * hint of how much memory will be needed generally or specific bucketSz // * hint to over allocate by haveing a % in local free list // // 11. memory leaks detect // * print statistics for all non-freed memory // // 12. assert less than sbrk(0) // * sp_free(ptr < sbrk(0)), sp_realloc(ptr < sbrk(0)) ... // TODO optimizations // - Some kind of TL cache with a reference to the most referenced Pools used // for non-TL free:ing. // - A range of the highest & lowest memory address used to determine if it is // necessary to walk through the Nodes // - on PoolsRAII level // - on Pool level // - An optimized collections of Pool:s used for free:ing in addition to the // Pool[60] used for allocating // - skip `this` when global::free() // {{{ static thread_local local::Pools local_pools; // }}} namespace local { static std::size_t pool_index(std::size_t size) noexcept { assert(size % 8 == 0); return util::trailing_zeros(size) - std::size_t(3); } // local::pool_index() static local::Pool & pool_for(local::Pools &pools, std::size_t sz) noexcept { const std::size_t index = pool_index(sz); return pools[index]; } // local::pool_for() static void * alloc(local::Pools &pools, std::size_t sz) noexcept { // printf("local::alloc(%zu)\n", sz); // TODO local alloc void *const result = global::alloc(sz); if (result) { pools.pools->total_alloc.fetch_add(sz); } return result; } // local::alloc() /* * @start - node start * desc - */ static header::Node * next_node(header::Node *const start) noexcept { return start->next.load(); } // local::next_node() /* * @param start - extent start * @param index - * @desc - */ static void * pointer_at(header::Node *start, std::size_t index) noexcept { // printf("pointer_at(start,index(%zu))\n", index); // Pool[Extent[Node[nodeHDR,extHDR],Node[nodeHDR]...]...] // The first NodeHeader in the extent contains data while intermediate // NodeHeader does not containt this data. assert(start->type == header::NodeType::HEAD); size_t hdrSz(header::SIZE); size_t buckets = start->buckets; const size_t bucket_size = start->bucket_size; node_start: const size_t node_size = start->node_size; const size_t data_size(node_size - hdrSz); size_t nodeBuckets = std::min(data_size / start->bucket_size, buckets); if (index < nodeBuckets) { // the index is in range of current node uintptr_t startPtr = reinterpret_cast<uintptr_t>(start); uintptr_t data_start = startPtr + hdrSz; return reinterpret_cast<void *>(data_start + (index * bucket_size)); } // the index is out of range, go to next node header::Node *const next = next_node(start); index = index - nodeBuckets; buckets = buckets - nodeBuckets; if (buckets > 0) { assert(next != nullptr); assert(next->type == header::NodeType::LINK); start = next; // the same extent but a new node hdrSz = sizeof(header::Node); goto node_start; } else { // out of bound // TODO implementation fault or runtime? assert(false); } } // local::pointer_at() /* * @start - extent start * desc - Used by malloc & free */ static header::Node * next_extent(header::Node *start) noexcept { assert(start != nullptr); start: header::Node *const next = next_node(start); if (next) { if (next->type == header::NodeType::HEAD) { return next; } start = next; goto start; } return nullptr; } // local::next_intent() /* * @start - extent start * desc - Used by malloc */ static void * reserve(header::Node *const node) noexcept { if (node->type == header::NodeType::HEAD) { header::Extent *const eHdr = header::extent(node); auto &reservations = eHdr->reserved; // printf("reservations.swap_first(true,buckets(%zu))\n", nHdr->buckets); const std::size_t limit = node->buckets; const std::size_t index = reservations.swap_first(true, limit); if (index != reservations.npos) { return pointer_at(node, index); } } return nullptr; } // local::reserve() static std::size_t calc_min_node(std::size_t bucketSz) noexcept { assert(bucketSz >= 8); assert(bucketSz % 8 == 0); constexpr std::size_t min_alloc = SP_MALLOC_PAGE_SIZE; constexpr std::size_t max_alloc = min_alloc * 4; if (bucketSz + header::SIZE > max_alloc) { return util::round_up(bucketSz + header::SIZE, min_alloc); } constexpr std::size_t lookup[] = // { // /*___8:*/ min_alloc, /*__16:*/ min_alloc * 2, /*__32:*/ max_alloc, /*__64:*/ max_alloc, /*_128:*/ max_alloc, /*_256:*/ max_alloc, /*_512:*/ max_alloc, /*1024:*/ max_alloc, /*2048:*/ max_alloc, /*4096:*/ max_alloc, /*8192:*/ min_alloc * 5, // }; return lookup[pool_index(bucketSz)]; } /* * @bucketSz - Normailzed size of bucket * desc - Used by malloc */ static header::Node * alloc_extent(local::Pools &pools, std::size_t bucketSz) noexcept { // printf("alloc_extent(%zu)\n", bucketSz); std::size_t nodeSz = calc_min_node(bucketSz); void *const raw = alloc(pools, nodeSz); if (raw) { return header::init_node(raw, nodeSz, bucketSz); } return nullptr; } // local::alloc_extent() static bool should_expand_extent(header::Node *) { return false; } static header::Node * enqueue_new_extent(local::Pools &pools, std::atomic<header::Node *> &w, std::size_t bucketSz) noexcept { header::Node *const current = local::alloc_extent(pools, bucketSz); if (current) { // TODO some kind of fence to ensure construction before publication // std::atomic_thread_fence(std::memory_order_release); header::Node *start = nullptr; if (!w.compare_exchange_strong(start, current)) { // should never fail // TODO local::dealloc_extent(current) assert(false); } } return current; } // local::enqueue_new_extent() /* * @size - extent start * desc - Used by malloc */ static void expand_extent(void *const) noexcept { // TODO } // local::extend_extent() } // namespace local /* *=========================================================== *=======DEBUG=============================================== *=========================================================== */ #ifdef SP_TEST namespace debug { std::size_t malloc_count_alloc() { std::size_t result(0); for (std::size_t i(8); i > 0; i <<= 1) { result += malloc_count_alloc(i); } return result; } static std::size_t count_reserved(header::Extent &ext, std::size_t buckets) { std::size_t result(0); auto &b = ext.reserved; for (std::size_t idx(0); idx < buckets; ++idx) { if (b.test(idx)) { result++; } } return result; } std::size_t malloc_count_alloc(std::size_t sz) { std::size_t result(0); local::Pool &pool = local::pool_for(local_pools, sz); sp::SharedLock guard(pool.lock); if (guard) { header::Node *current = pool.start.next.load(); start: if (current) { assert(current->type == header::NodeType::HEAD); auto ext = header::extent(current); assert(ext != nullptr); result += count_reserved(*ext, current->buckets); current = local::next_extent(current); goto start; } } return result; } } // namespace debug #endif /* *=========================================================== *=======PUBLIC============================================== *=========================================================== */ void * sp_malloc(std::size_t length) noexcept { if (length == 0) { return nullptr; } const std::size_t bucketSz = util::round_even(length); local::Pool &pool = pool_for(local_pools, bucketSz); sp::SharedLock guard{pool.lock}; if (guard) { header::Node *start = &pool.start; if (start) { reserve_start: void *result = local::reserve(start); if (result) { return result; } else { header::Node *const next = local::next_extent(start); if (next) { start = next; goto reserve_start; } else { if (local::should_expand_extent(start)) { local::expand_extent(start); } else { start = local::enqueue_new_extent(local_pools, start->next, bucketSz); } if (start) { goto reserve_start; } // out of memory return nullptr; } } } else { // only TL allowed to malloc meaning no alloc contention header::Node *current = local::enqueue_new_extent(local_pools, pool.start.next, bucketSz); if (current) { void *const result = local::reserve(current); // Since only one allocator this must succeed. assert(result); return result; } assert(false); // out of memory return nullptr; } } // SharedLock // We should never get to here assert(false); return nullptr; } // ::sp_malloc() bool sp_free(void *const ptr) noexcept { if (!ptr) { return true; } using shared::FreeCode; auto result = shared::free(local_pools, ptr); if (result == FreeCode::NOT_FOUND) { result = global::free(ptr); } return result == FreeCode::FREED || result == FreeCode::FREED_RECLAIM; } // ::sp_free() std::size_t sp_usable_size(void *const ptr) noexcept { if (!ptr) { return 0; } auto lresult = shared::usable_size(local_pools, ptr); if (lresult) { return lresult.get(); } auto result = global::usable_size(ptr); return result.get_or(0); } // ::sp_usable_size() void * sp_realloc(void *const ptr, std::size_t length) noexcept { if (!ptr) { return nullptr; } if (length == 0) { sp_free(ptr); return nullptr; } auto lresult = shared::realloc(local_pools, ptr, length); if (lresult) { return lresult.get(); } auto result = global::realloc(ptr, length); return result.get_or(nullptr); } //::sp_realloc <|endoftext|>
<commit_before>// Copyright (c) 2013 Maciej Gajewski #include "profiling_gui/flowdiagram.hpp" #include <QGraphicsLineItem> #include <QGraphicsRectItem> #include <QDebug> namespace profiling_gui { FlowDiagram::FlowDiagram(QObject *parent) : QObject(parent) { } void FlowDiagram::loadFile(const QString& path, QGraphicsScene* scene) { _scene = scene; profiling_reader::reader reader(path.toStdString()); _ticksPerNs = reader.ticks_per_ns(); // collect data reader.for_each_by_time([this](const profiling_reader::record_type& record) { this->onRecord(record); }); // build items for(const ThreadData& thread : _threads) { auto* item = new QGraphicsLineItem(thread.minTime, thread.y, thread.maxTime, thread.y); QPen pen(Qt::black); pen.setCosmetic(true); item->setPen(pen); scene->addItem(item); } } double FlowDiagram::ticksToTime(qint64 ticks) const { return ticks / _ticksPerNs; } static QColor idToColor(std::uintptr_t id) { Qt::GlobalColor colors[] = { Qt::red, Qt::cyan, Qt::green, Qt::magenta, Qt::darkYellow, Qt::darkCyan, Qt::yellow, Qt::darkRed }; std::size_t hash = std::hash<std::uintptr_t>()(id); return colors[(hash>>4) % 8]; } void FlowDiagram::onRecord(const profiling_reader::record_type& record) { static const double THREAD_Y_SPACING = 100.0; static const double CORO_H = 5; if (!_threads.contains(record.thread_id)) { ThreadData newThread; newThread.minTime = ticksToTime(record.time); newThread.y = _threads.size() * THREAD_Y_SPACING; _threads.insert(record.thread_id, newThread); } ThreadData& thread = _threads[record.thread_id]; thread.maxTime = ticksToTime(record.time); // coroutines if (record.object_type == "coroutine") { CoroutineData& coroutine = _coroutines[record.object_id]; if (!coroutine.color.isValid()) coroutine.color = idToColor(record.object_id); if (record.event == "created") coroutine.name = QString::fromStdString(record.data); if (record.event == "enter") { //qWarning() << "Corotuine: enter. id=" << record.object_id << ", time= " << record.time << ",thread=" << record.thread_id; coroutine.enters[record.thread_id] = ticksToTime(record.time); } if (record.event == "exit") { if(!coroutine.enters.contains(record.thread_id)) { qWarning() << "Corotuine: exit without enter! id=" << record.object_id << ", time= " << record.time << ",thread=" << record.thread_id; } else { double enterX = coroutine.enters[record.thread_id]; coroutine.enters.remove(record.thread_id); double exitX = ticksToTime(record.time); double y = thread.y; auto* item = new QGraphicsRectItem(enterX, y-CORO_H, exitX-enterX, CORO_H*2); item->setToolTip(coroutine.name); item->setBrush(coroutine.color); QPen pen(Qt::black); pen.setCosmetic(true); item->setPen(pen); _scene->addItem(item); } } } } } <commit_msg>random colors instead hash-based ones used for coroutines<commit_after>// Copyright (c) 2013 Maciej Gajewski #include "profiling_gui/flowdiagram.hpp" #include <QGraphicsLineItem> #include <QGraphicsRectItem> #include <QDebug> #include <random> namespace profiling_gui { FlowDiagram::FlowDiagram(QObject *parent) : QObject(parent) { } void FlowDiagram::loadFile(const QString& path, QGraphicsScene* scene) { _scene = scene; profiling_reader::reader reader(path.toStdString()); _ticksPerNs = reader.ticks_per_ns(); // collect data reader.for_each_by_time([this](const profiling_reader::record_type& record) { this->onRecord(record); }); // build items for(const ThreadData& thread : _threads) { auto* item = new QGraphicsLineItem(thread.minTime, thread.y, thread.maxTime, thread.y); QPen pen(Qt::black); pen.setCosmetic(true); item->setPen(pen); scene->addItem(item); } } double FlowDiagram::ticksToTime(qint64 ticks) const { return ticks / _ticksPerNs; } static QColor randomColor() { static std::minstd_rand0 generator; int h = std::uniform_int_distribution<int>(0, 255)(generator); int s = 172; int v = 172; return QColor::fromHsv(h, s, v); } void FlowDiagram::onRecord(const profiling_reader::record_type& record) { static const double THREAD_Y_SPACING = 100.0; static const double CORO_H = 5; if (!_threads.contains(record.thread_id)) { ThreadData newThread; newThread.minTime = ticksToTime(record.time); newThread.y = _threads.size() * THREAD_Y_SPACING; _threads.insert(record.thread_id, newThread); } ThreadData& thread = _threads[record.thread_id]; thread.maxTime = ticksToTime(record.time); // coroutines if (record.object_type == "coroutine") { CoroutineData& coroutine = _coroutines[record.object_id]; if (!coroutine.color.isValid()) coroutine.color = randomColor(); if (record.event == "created") coroutine.name = QString::fromStdString(record.data); if (record.event == "enter") { //qWarning() << "Corotuine: enter. id=" << record.object_id << ", time= " << record.time << ",thread=" << record.thread_id; coroutine.enters[record.thread_id] = ticksToTime(record.time); } if (record.event == "exit") { if(!coroutine.enters.contains(record.thread_id)) { qWarning() << "Corotuine: exit without enter! id=" << record.object_id << ", time= " << record.time << ",thread=" << record.thread_id; } else { double enterX = coroutine.enters[record.thread_id]; coroutine.enters.remove(record.thread_id); double exitX = ticksToTime(record.time); double y = thread.y; auto* item = new QGraphicsRectItem(enterX, y-CORO_H, exitX-enterX, CORO_H*2); item->setToolTip(coroutine.name); item->setBrush(coroutine.color); QPen pen(Qt::black); pen.setCosmetic(true); item->setPen(pen); _scene->addItem(item); } } } } } <|endoftext|>
<commit_before><commit_msg>193 - Graph Coloring<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2008-2012 Juli Mallett. 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 AUTHOR 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 AUTHOR 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 <unistd.h> #include <common/buffer.h> #include <common/endian.h> #include <event/action.h> #include <event/callback.h> #include <event/event_main.h> #include "wanproxy_config.h" static void usage(void); int main(int argc, char *argv[]) { std::string configfile(""); bool quiet, verbose; int ch; quiet = false; verbose = false; INFO("/wanproxy") << "WANProxy"; INFO("/wanproxy") << "Copyright (c) 2008-2013 WANProxy.org."; INFO("/wanproxy") << "All rights reserved."; while ((ch = getopt(argc, argv, "c:qv")) != -1) { switch (ch) { case 'c': configfile = optarg; break; case 'q': quiet = true; break; case 'v': verbose = true; break; default: usage(); } } if (configfile == "") usage(); if (quiet && verbose) usage(); if (verbose) { Log::mask(".?", Log::Debug); } else if (quiet) { Log::mask(".?", Log::Error); } else { Log::mask(".?", Log::Info); } WANProxyConfig config; if (!config.configure(configfile)) { ERROR("/wanproxy") << "Could not configure proxies."; return (1); } event_main(); } static void usage(void) { INFO("/wanproxy/usage") << "wanproxy [-q | -v] -c configfile"; exit(1); } <commit_msg>Bump years.<commit_after>/* * Copyright (c) 2008-2014 Juli Mallett. 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 AUTHOR 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 AUTHOR 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 <unistd.h> #include <common/buffer.h> #include <common/endian.h> #include <event/action.h> #include <event/callback.h> #include <event/event_main.h> #include "wanproxy_config.h" static void usage(void); int main(int argc, char *argv[]) { std::string configfile(""); bool quiet, verbose; int ch; quiet = false; verbose = false; INFO("/wanproxy") << "WANProxy"; INFO("/wanproxy") << "Copyright (c) 2008-2014 WANProxy.org."; INFO("/wanproxy") << "All rights reserved."; while ((ch = getopt(argc, argv, "c:qv")) != -1) { switch (ch) { case 'c': configfile = optarg; break; case 'q': quiet = true; break; case 'v': verbose = true; break; default: usage(); } } if (configfile == "") usage(); if (quiet && verbose) usage(); if (verbose) { Log::mask(".?", Log::Debug); } else if (quiet) { Log::mask(".?", Log::Error); } else { Log::mask(".?", Log::Info); } WANProxyConfig config; if (!config.configure(configfile)) { ERROR("/wanproxy") << "Could not configure proxies."; return (1); } event_main(); } static void usage(void) { INFO("/wanproxy/usage") << "wanproxy [-q | -v] -c configfile"; exit(1); } <|endoftext|>
<commit_before>#include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <dlfcn.h> #include <signal.h> #include <iostream> #include <vector> #include <string> #include <map> #include "config.h" #include "hal.h" #include "hal/hal_priv.h" using namespace std; #define SOCKET_PATH "/tmp/rtapi_fifo" template<class T> T DLSYM(void *handle, const string &name) { return (T)(dlsym(handle, name.c_str())); } template<class T> T DLSYM(void *handle, const char *name) { return (T)(dlsym(handle, name)); } static std::map<string, void*> modules; extern "C" int schedule(void) { return sched_yield(); } static int instance_count = 0; static int force_exit = 0; static int do_newinst_cmd(string type, string name, string arg) { void *module = modules["hal_lib"]; if(!module) { cerr << "hal_lib not loaded\n"; return -1; } hal_comp_t *(*find_comp_by_name)(char*) = DLSYM<hal_comp_t*(*)(char *)>(module, "halpr_find_comp_by_name"); if(!find_comp_by_name) { cerr << "halpr_find_comp_by_name not found\n"; return -1; } hal_comp_t *comp = find_comp_by_name((char*)type.c_str()); if(!comp) { cerr << "Component not found\n"; return -1; } return comp->make((char*)name.c_str(), (char*)arg.c_str()); } static int do_one_item(char item_type_char, const string &param_value, void *vitem, int idx=0) { switch(item_type_char) { case 'l': { long *litem = *(long**) vitem; litem[idx] = strtol(param_value.c_str(), NULL, 0); return 0; } case 'i': { int *iitem = *(int**) vitem; iitem[idx] = strtol(param_value.c_str(), NULL, 0); return 0; } case 's': { char **sitem = *(char***) vitem; sitem[idx] = strdup(param_value.c_str()); return 0; } default: cerr << "Cannot understand: " << param_value << " (type " << item_type_char << ")\n"; return -1; } return 0; } static int do_comp_args(void *module, vector<string> args) { for(unsigned i=1; i < args.size(); i++) { string &s = args[i]; unsigned idx = s.find('='); if(idx == string::npos) { cerr << "Cannot understand: " << s << endl; return -1; } string param_name(s, 0, idx); string param_value(s, idx+1); void *item=DLSYM<void*>(module, "rtapi_info_address_" + param_name); if(!item) { cerr << "Cannot understand: (NULL item) " << s << "\n"; cerr << dlerror() << endl; return -1; } char **item_type=DLSYM<char**>(module, "rtapi_info_type_" + param_name); if(!item_type || !*item_type) { cerr << "Cannot understand: (NULL type) " << s << dlerror() << "\n"; return -1; } string item_type_string = *item_type; char item_type_char = item_type_string.size() ? item_type_string[item_type_string.size() - 1] : 0; if(item_type_string.size() > 1) { int a, b; char c; int r = sscanf(item_type_string.c_str(), "%d-%d%c", &a, &b, &c); if(r != 3) { cerr << "Cannot understand: " << s << " (sscanf " << item_type_string << ")\n"; return -1; } size_t idx = 0; int i = 0; while(idx != string::npos) { if(i == b) { cerr << "Too many items for " << s << "\n"; return -1; } size_t idx1 = param_value.find(",", idx); string substr(param_value, idx, idx1 - idx); int result = do_one_item(item_type_char, substr, item, i); if(result != 0) return result; i++; idx = idx1 == string::npos ? idx1 : idx1 + 1; } } else { int result = do_one_item(item_type_char, param_value, item); if(result != 0) return result; } } return 0; } static int do_load_cmd(string name, vector<string> args) { void *w = modules[name]; if(w == NULL) { char what[LINELEN+1]; snprintf(what, LINELEN, "%s/%s.so", EMC2_RTLIB_DIR, name.c_str()); void *module = modules[name] = dlopen(what, RTLD_GLOBAL | RTLD_LAZY); if(!module) { printf("%s: dlopen: %s\n", name.c_str(), dlerror()); return -1; } /// XXX handle arguments int (*start)(void) = DLSYM<int(*)(void)>(module, "rtapi_app_main"); if(!start) { printf("%s: dlsym: %s\n", name.c_str(), dlerror()); return -1; } int result; result = do_comp_args(module, args); if(result < 0) { dlclose(module); return -1; } if ((result=start()) < 0) { printf("%s: rtapi_app_main: %d\n", name.c_str(), result); return result; } else { instance_count ++; return 0; } } else { printf("%s: already exists\n", name.c_str()); return -1; } } static int do_unload_cmd(string name) { void *w = modules[name]; if(w == NULL) { printf("%s: not loaded\n", name.c_str()); return -1; } else { int (*stop)(void) = DLSYM<int(*)(void)>(w, "rtapi_app_exit"); if(stop) stop(); modules.erase(modules.find(name)); dlclose(w); instance_count --; } return 0; } static int read_number(int fd) { int r = 0, neg=1; char ch; while(1) { int res = read(fd, &ch, 1); if(res != 1) return -1; if(ch == '-') neg = -1; else if(ch == ' ') return r * neg; else r = 10 * r + ch - '0'; } } static string read_string(int fd) { int len = read_number(fd); char buf[len]; read(fd, buf, len); return string(buf, len); } static vector<string> read_strings(int fd) { vector<string> result; int count = read_number(fd); for(int i=0; i<count; i++) { result.push_back(read_string(fd)); } return result; } static void write_number(string &buf, int num) { char numbuf[10]; sprintf(numbuf, "%d ", num); buf = buf + numbuf; } static void write_string(string &buf, string s) { write_number(buf, s.size()); buf += s; } static void write_strings(int fd, vector<string> strings) { string buf; write_number(buf, strings.size()); for(unsigned int i=0; i<strings.size(); i++) { write_string(buf, strings[i]); } write(fd, buf.data(), buf.size()); } static void print_strings(vector<string> strings) { cout << "STRINGS:"; for(unsigned int i=0; i<strings.size(); i++) { cout << " " << strings[i]; } cout << "\n"; } static int handle_command(vector<string> args) { if(args.size() == 1 && args[0] == "exit") { force_exit = 1; return 0; } else if(args.size() >= 2 && args[0] == "load") { string name = args[1]; args.erase(args.begin()); return do_load_cmd(name, args); } else if(args.size() == 2 && args[0] == "unload") { return do_unload_cmd(args[1]); } else if(args.size() == 3 && args[0] == "newinst") { return do_newinst_cmd(args[1], args[2], ""); } else if(args.size() == 4 && args[0] == "newinst") { return do_newinst_cmd(args[1], args[2], args[3]); } else { cout << "Unrecognized command: "; print_strings(args); return -1; } } static int slave(int fd, vector<string> args) { write_strings(fd, args); int result = read_number(fd); return result; } static int master(int fd, vector<string> args) { dlopen(NULL, RTLD_GLOBAL); do_load_cmd("hal_lib", vector<string>()); instance_count = 0; if(args.size()) { int result = handle_command(args); if(result != 0) return result; if(force_exit || instance_count == 0) return 0; } do { struct sockaddr_un client_addr; memset(&client_addr, 0, sizeof(client_addr)); socklen_t len = sizeof(client_addr); int fd1 = accept(fd, (sockaddr*)&client_addr, &len); if(fd1 < 0) { perror("accept"); return -1; } else { int result = handle_command(read_strings(fd1)); string buf; write_number(buf, result); write(fd1, buf.data(), buf.size()); close(fd1); } } while(!force_exit && instance_count > 0); return 0; } int main(int argc, char **argv) { vector<string> args; for(int i=1; i<argc; i++) { args.push_back(string(argv[i])); } become_master: int fd = socket(PF_UNIX, SOCK_STREAM, 0); if(fd == -1) { perror("socket"); exit(1); } struct sockaddr_un addr = { AF_UNIX, SOCKET_PATH }; int result = bind(fd, (sockaddr*)&addr, sizeof(addr)); if(result == 0) { int result = listen(fd, 10); if(result != 0) { perror("bind"); exit(1); } result = master(fd, args); unlink(SOCKET_PATH); return result; } else if( errno == EADDRINUSE) { for(int i=0; i < 3 ; i++) { result = connect(fd, (sockaddr*)&addr, sizeof(addr)); if(result == 0) break; sleep(1); } if(result < 0 && errno == ECONNREFUSED) { unlink(SOCKET_PATH); fprintf(stdout, "Waited 3 seconds for master. giving up.\n"); close(fd); goto become_master; } if(result < 0) { perror("connect"); exit(1); } return slave(fd, args); } else { perror("bind"); exit(1); } } <commit_msg>don't write things to stdout<commit_after>#include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <dlfcn.h> #include <signal.h> #include <iostream> #include <vector> #include <string> #include <map> #include "config.h" #include "rtapi.h" #include "hal.h" #include "hal/hal_priv.h" using namespace std; #define SOCKET_PATH "/tmp/rtapi_fifo" template<class T> T DLSYM(void *handle, const string &name) { return (T)(dlsym(handle, name.c_str())); } template<class T> T DLSYM(void *handle, const char *name) { return (T)(dlsym(handle, name)); } static std::map<string, void*> modules; extern "C" int schedule(void) { return sched_yield(); } static int instance_count = 0; static int force_exit = 0; static int do_newinst_cmd(string type, string name, string arg) { void *module = modules["hal_lib"]; if(!module) { cerr << "hal_lib not loaded\n"; return -1; } hal_comp_t *(*find_comp_by_name)(char*) = DLSYM<hal_comp_t*(*)(char *)>(module, "halpr_find_comp_by_name"); if(!find_comp_by_name) { cerr << "halpr_find_comp_by_name not found\n"; return -1; } hal_comp_t *comp = find_comp_by_name((char*)type.c_str()); if(!comp) { cerr << "Component not found\n"; return -1; } return comp->make((char*)name.c_str(), (char*)arg.c_str()); } static int do_one_item(char item_type_char, const string &param_value, void *vitem, int idx=0) { switch(item_type_char) { case 'l': { long *litem = *(long**) vitem; litem[idx] = strtol(param_value.c_str(), NULL, 0); return 0; } case 'i': { int *iitem = *(int**) vitem; iitem[idx] = strtol(param_value.c_str(), NULL, 0); return 0; } case 's': { char **sitem = *(char***) vitem; sitem[idx] = strdup(param_value.c_str()); return 0; } default: cerr << "Cannot understand: " << param_value << " (type " << item_type_char << ")\n"; return -1; } return 0; } static int do_comp_args(void *module, vector<string> args) { for(unsigned i=1; i < args.size(); i++) { string &s = args[i]; size_t idx = s.find('='); if(idx == string::npos) { cerr << "Cannot understand: " << s << endl; return -1; } string param_name(s, 0, idx); string param_value(s, idx+1); void *item=DLSYM<void*>(module, "rtapi_info_address_" + param_name); if(!item) { cerr << "Cannot understand: (NULL item) " << s << "\n"; cerr << dlerror() << endl; return -1; } char **item_type=DLSYM<char**>(module, "rtapi_info_type_" + param_name); if(!item_type || !*item_type) { cerr << "Cannot understand: (NULL type) " << s << dlerror() << "\n"; return -1; } string item_type_string = *item_type; char item_type_char = item_type_string.size() ? item_type_string[item_type_string.size() - 1] : 0; if(item_type_string.size() > 1) { int a, b; char c; int r = sscanf(item_type_string.c_str(), "%d-%d%c", &a, &b, &c); if(r != 3) { cerr << "Cannot understand: " << s << " (sscanf " << item_type_string << ")\n"; return -1; } size_t idx = 0; int i = 0; while(idx != string::npos) { if(i == b) { cerr << "Too many items for " << s << "\n"; return -1; } size_t idx1 = param_value.find(",", idx); string substr(param_value, idx, idx1 - idx); int result = do_one_item(item_type_char, substr, item, i); if(result != 0) return result; i++; idx = idx1 == string::npos ? idx1 : idx1 + 1; } } else { int result = do_one_item(item_type_char, param_value, item); if(result != 0) return result; } } return 0; } static int do_load_cmd(string name, vector<string> args) { void *w = modules[name]; if(w == NULL) { char what[LINELEN+1]; snprintf(what, LINELEN, "%s/%s.so", EMC2_RTLIB_DIR, name.c_str()); void *module = modules[name] = dlopen(what, RTLD_GLOBAL | RTLD_LAZY); if(!module) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: dlopen: %s\n", name.c_str(), dlerror()); return -1; } /// XXX handle arguments int (*start)(void) = DLSYM<int(*)(void)>(module, "rtapi_app_main"); if(!start) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: dlsym: %s\n", name.c_str(), dlerror()); return -1; } int result; result = do_comp_args(module, args); if(result < 0) { dlclose(module); return -1; } if ((result=start()) < 0) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: rtapi_app_main: %d\n", name.c_str(), result); return result; } else { instance_count ++; return 0; } } else { rtapi_print_msg(RTAPI_MSG_ERR, "%s: already exists\n", name.c_str()); return -1; } } static int do_unload_cmd(string name) { void *w = modules[name]; if(w == NULL) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: not loaded\n", name.c_str()); return -1; } else { int (*stop)(void) = DLSYM<int(*)(void)>(w, "rtapi_app_exit"); if(stop) stop(); modules.erase(modules.find(name)); dlclose(w); instance_count --; } return 0; } static int read_number(int fd) { int r = 0, neg=1; char ch; while(1) { int res = read(fd, &ch, 1); if(res != 1) return -1; if(ch == '-') neg = -1; else if(ch == ' ') return r * neg; else r = 10 * r + ch - '0'; } } static string read_string(int fd) { int len = read_number(fd); char buf[len]; read(fd, buf, len); return string(buf, len); } static vector<string> read_strings(int fd) { vector<string> result; int count = read_number(fd); for(int i=0; i<count; i++) { result.push_back(read_string(fd)); } return result; } static void write_number(string &buf, int num) { char numbuf[10]; sprintf(numbuf, "%d ", num); buf = buf + numbuf; } static void write_string(string &buf, string s) { write_number(buf, s.size()); buf += s; } static void write_strings(int fd, vector<string> strings) { string buf; write_number(buf, strings.size()); for(unsigned int i=0; i<strings.size(); i++) { write_string(buf, strings[i]); } write(fd, buf.data(), buf.size()); } static void print_strings(vector<string> strings) { cerr << "STRINGS:"; for(unsigned int i=0; i<strings.size(); i++) { cerr << " " << strings[i]; } cerr << "\n"; } static int handle_command(vector<string> args) { if(args.size() == 1 && args[0] == "exit") { force_exit = 1; return 0; } else if(args.size() >= 2 && args[0] == "load") { string name = args[1]; args.erase(args.begin()); return do_load_cmd(name, args); } else if(args.size() == 2 && args[0] == "unload") { return do_unload_cmd(args[1]); } else if(args.size() == 3 && args[0] == "newinst") { return do_newinst_cmd(args[1], args[2], ""); } else if(args.size() == 4 && args[0] == "newinst") { return do_newinst_cmd(args[1], args[2], args[3]); } else { cerr << "Unrecognized command: "; print_strings(args); return -1; } } static int slave(int fd, vector<string> args) { write_strings(fd, args); int result = read_number(fd); return result; } static int master(int fd, vector<string> args) { dlopen(NULL, RTLD_GLOBAL); do_load_cmd("hal_lib", vector<string>()); instance_count = 0; if(args.size()) { int result = handle_command(args); if(result != 0) return result; if(force_exit || instance_count == 0) return 0; } do { struct sockaddr_un client_addr; memset(&client_addr, 0, sizeof(client_addr)); socklen_t len = sizeof(client_addr); int fd1 = accept(fd, (sockaddr*)&client_addr, &len); if(fd1 < 0) { perror("accept"); return -1; } else { int result = handle_command(read_strings(fd1)); string buf; write_number(buf, result); write(fd1, buf.data(), buf.size()); close(fd1); } } while(!force_exit && instance_count > 0); return 0; } int main(int argc, char **argv) { vector<string> args; for(int i=1; i<argc; i++) { args.push_back(string(argv[i])); } become_master: int fd = socket(PF_UNIX, SOCK_STREAM, 0); if(fd == -1) { perror("socket"); exit(1); } struct sockaddr_un addr = { AF_UNIX, SOCKET_PATH }; int result = bind(fd, (sockaddr*)&addr, sizeof(addr)); if(result == 0) { int result = listen(fd, 10); if(result != 0) { perror("bind"); exit(1); } result = master(fd, args); unlink(SOCKET_PATH); return result; } else if( errno == EADDRINUSE) { for(int i=0; i < 3 ; i++) { result = connect(fd, (sockaddr*)&addr, sizeof(addr)); if(result == 0) break; sleep(1); } if(result < 0 && errno == ECONNREFUSED) { unlink(SOCKET_PATH); fprintf(stderr, "Waited 3 seconds for master. giving up.\n"); close(fd); goto become_master; } if(result < 0) { perror("connect"); exit(1); } return slave(fd, args); } else { perror("bind"); exit(1); } } <|endoftext|>
<commit_before>// // C++ Implementation: TaskManager // // Description: // // // Author: Douglas Scott <netdscott@netscape.net>, (C) 2010 // // #include "TaskManager.h" #include "Lockable.h" #include <pthread.h> #include <stack> #include <stdio.h> #include <assert.h> #undef DEBUG #ifndef RT_THREAD_COUNT #define RT_THREAD_COUNT 2 #endif #ifdef MACOSX #include <dispatch/dispatch.h> class Semaphore { public: Semaphore(unsigned inStartingValue=0) : mSema(dispatch_semaphore_create((long)inStartingValue)) {} ~Semaphore() { mSema = NULL; } void wait() { dispatch_semaphore_wait(mSema, DISPATCH_TIME_FOREVER); } // each thread will wait on this void post() { dispatch_semaphore_signal(mSema); } // when done, each thread calls this private: dispatch_semaphore_t mSema; }; #else #include <semaphore.h> class Semaphore { public: Semaphore(unsigned inStartingValue=0) { sem_init(&mSema, 0, inStartingValue); } ~Semaphore() { sem_destroy(&mSema); } void wait() { sem_wait(&mSema); } // each thread will wait on this void post() { sem_post(&mSema); } // when done, each thread calls this private: sem_t mSema; }; #endif class Notifiable { public: virtual void notify(int inIndex) = 0; }; class Notifier { public: Notifier(Notifiable *inTarget, int inIndex) : mTarget(inTarget), mIndex(inIndex) {} void notify() { mTarget->notify(mIndex); } private: Notifiable *mTarget; int mIndex; }; class TaskThread : public Notifier { public: TaskThread(Notifiable *inTarget, int inIndex) : Notifier(inTarget, inIndex), mTask(NULL) { pthread_create(&mThread, NULL, sProcess, this); } ~TaskThread() { start(NULL); pthread_join(mThread, NULL); } inline void start(Task *inTask); protected: void run(); static void *sProcess(void *inContext); private: pthread_t mThread; Semaphore mSema; Task * mTask; }; inline void TaskThread::start(Task *inTask) { mTask = inTask; #ifdef DEBUG printf("TaskThread::start(%p): posting for Task %p\n", this, inTask); #endif mSema.post(); } void TaskThread::run() { #ifdef DEBUG printf("TaskThread %p running\n", this); #endif bool done = false; do { mSema.wait(); #ifdef DEBUG printf("TaskThread %p woke up -- about to run mTask %p\n", this, mTask); #endif if (mTask) { mTask->run(); delete mTask; } else { done = true; } notify(); } while (!done); #ifdef DEBUG printf("TaskThread %p exiting\n", this); #endif } void *TaskThread::sProcess(void *inContext) { TaskThread *This = (TaskThread *) inContext; This->run(); return NULL; } class ThreadPool : private Lockable, private Notifiable { public: ThreadPool() : mThreadSema(RT_THREAD_COUNT), mRequestCount(0), mWaitSema(0) { for(int i=0; i<RT_THREAD_COUNT; ++i) { mThreads[i] = new TaskThread(this, i); mIndices.push(i); } } ~ThreadPool() { for(int i=0; i<RT_THREAD_COUNT; ++i) delete mThreads[i]; } inline TaskThread &getAvailableThread(); virtual void notify(int inIndex); void setRequestCount(int count) { mRequestCount = count; } void wait() { mWaitSema.wait(); } private: TaskThread *mThreads[RT_THREAD_COUNT]; std::stack<int> mIndices; Semaphore mThreadSema; int mRequestCount; // Number of thread requests made that have not notified Semaphore mWaitSema; }; // Block until a thread is free and return it TaskThread& ThreadPool::getAvailableThread() { mThreadSema.wait(); lock(); int tIndex = mIndices.top(); mIndices.pop(); unlock(); #ifdef DEBUG printf("ThreadPool returning thread[%d]\n", tIndex); #endif return *mThreads[tIndex]; } // Let thread pool know that the thread at index inIndex is available void ThreadPool::notify(int inIndex) { lock(); #ifdef DEBUG printf("ThreadPool notified for index %d\n", inIndex); #endif mIndices.push(inIndex); int newCount = --mRequestCount; unlock(); mThreadSema.post(); if (newCount == 0) { #ifdef DEBUG printf("ThreadPool mRequestCount: %d\n", newCount); printf("ThreadPool posting to wait semaphore\n"); #endif mWaitSema.post(); } } TaskManagerImpl::TaskManagerImpl() : mThreadPool(new ThreadPool) {} TaskManagerImpl::~TaskManagerImpl() { delete mThreadPool; } void TaskManagerImpl::addTask(Task *inTask) { mThreadPool->getAvailableThread().start(inTask); } void TaskManagerImpl::setRequestCount(int count) { mThreadPool->setRequestCount(count); } void TaskManagerImpl::wait() { #ifdef DEBUG printf("TaskManagerImpl::wait waiting on ThreadPool...\n"); #endif mThreadPool->wait(); #ifdef DEBUG printf("TaskManagerImpl::wait done\n"); #endif } TaskManager::TaskManager() : mImpl(new TaskManagerImpl) { } TaskManager::~TaskManager() { delete mImpl; } void TaskManager::waitForCompletion() { mImpl->wait(); } <commit_msg>Setting thread scheduling and priority.<commit_after>// // C++ Implementation: TaskManager // // Description: // // // Author: Douglas Scott <netdscott@netscape.net>, (C) 2010 // // #include "TaskManager.h" #include "Lockable.h" #include <pthread.h> #include <stack> #include <stdio.h> #include <assert.h> #undef DEBUG #ifndef RT_THREAD_COUNT #define RT_THREAD_COUNT 2 #endif #ifdef MACOSX #include <dispatch/dispatch.h> class Semaphore { public: Semaphore(unsigned inStartingValue=0) : mSema(dispatch_semaphore_create((long)inStartingValue)) {} ~Semaphore() { mSema = NULL; } void wait() { dispatch_semaphore_wait(mSema, DISPATCH_TIME_FOREVER); } // each thread will wait on this void post() { dispatch_semaphore_signal(mSema); } // when done, each thread calls this private: dispatch_semaphore_t mSema; }; #else #include <semaphore.h> class Semaphore { public: Semaphore(unsigned inStartingValue=0) { sem_init(&mSema, 0, inStartingValue); } ~Semaphore() { sem_destroy(&mSema); } void wait() { sem_wait(&mSema); } // each thread will wait on this void post() { sem_post(&mSema); } // when done, each thread calls this private: sem_t mSema; }; #endif class Notifiable { public: virtual void notify(int inIndex) = 0; }; class Notifier { public: Notifier(Notifiable *inTarget, int inIndex) : mTarget(inTarget), mIndex(inIndex) {} void notify() { mTarget->notify(mIndex); } private: Notifiable *mTarget; int mIndex; }; class TaskThread : public Notifier { public: TaskThread(Notifiable *inTarget, int inIndex) : Notifier(inTarget, inIndex), mTask(NULL) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setschedpolicy(&attr, SCHED_RR); pthread_create(&mThread, &attr, sProcess, this); pthread_attr_destroy(&attr); } ~TaskThread() { start(NULL); pthread_join(mThread, NULL); } inline void start(Task *inTask); protected: void run(); static void *sProcess(void *inContext); private: pthread_t mThread; Semaphore mSema; Task * mTask; }; inline void TaskThread::start(Task *inTask) { mTask = inTask; #ifdef DEBUG printf("TaskThread::start(%p): posting for Task %p\n", this, inTask); #endif mSema.post(); } void TaskThread::run() { #ifdef DEBUG printf("TaskThread %p running\n", this); #endif bool done = false; do { mSema.wait(); #ifdef DEBUG printf("TaskThread %p woke up -- about to run mTask %p\n", this, mTask); #endif if (mTask) { mTask->run(); delete mTask; } else { done = true; } notify(); } while (!done); #ifdef DEBUG printf("TaskThread %p exiting\n", this); #endif } void *TaskThread::sProcess(void *inContext) { TaskThread *This = (TaskThread *) inContext; if (setpriority(PRIO_PROCESS, 0, -20) != 0) { perror("TaskThread::sProcess: setpriority() failed."); } This->run(); return NULL; } class ThreadPool : private Lockable, private Notifiable { public: ThreadPool() : mThreadSema(RT_THREAD_COUNT), mRequestCount(0), mWaitSema(0) { for(int i=0; i<RT_THREAD_COUNT; ++i) { mThreads[i] = new TaskThread(this, i); mIndices.push(i); } } ~ThreadPool() { for(int i=0; i<RT_THREAD_COUNT; ++i) delete mThreads[i]; } inline TaskThread &getAvailableThread(); virtual void notify(int inIndex); void setRequestCount(int count) { mRequestCount = count; } void wait() { mWaitSema.wait(); } private: TaskThread *mThreads[RT_THREAD_COUNT]; std::stack<int> mIndices; Semaphore mThreadSema; int mRequestCount; // Number of thread requests made that have not notified Semaphore mWaitSema; }; // Block until a thread is free and return it TaskThread& ThreadPool::getAvailableThread() { mThreadSema.wait(); lock(); int tIndex = mIndices.top(); mIndices.pop(); unlock(); #ifdef DEBUG printf("ThreadPool returning thread[%d]\n", tIndex); #endif return *mThreads[tIndex]; } // Let thread pool know that the thread at index inIndex is available void ThreadPool::notify(int inIndex) { lock(); #ifdef DEBUG printf("ThreadPool notified for index %d\n", inIndex); #endif mIndices.push(inIndex); int newCount = --mRequestCount; unlock(); mThreadSema.post(); if (newCount == 0) { #ifdef DEBUG printf("ThreadPool mRequestCount: %d\n", newCount); printf("ThreadPool posting to wait semaphore\n"); #endif mWaitSema.post(); } } TaskManagerImpl::TaskManagerImpl() : mThreadPool(new ThreadPool) {} TaskManagerImpl::~TaskManagerImpl() { delete mThreadPool; } void TaskManagerImpl::addTask(Task *inTask) { mThreadPool->getAvailableThread().start(inTask); } void TaskManagerImpl::setRequestCount(int count) { mThreadPool->setRequestCount(count); } void TaskManagerImpl::wait() { #ifdef DEBUG printf("TaskManagerImpl::wait waiting on ThreadPool...\n"); #endif mThreadPool->wait(); #ifdef DEBUG printf("TaskManagerImpl::wait done\n"); #endif } TaskManager::TaskManager() : mImpl(new TaskManagerImpl) { } TaskManager::~TaskManager() { delete mImpl; } void TaskManager::waitForCompletion() { mImpl->wait(); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright RTK 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 "rtkTestConfiguration.h" #include "rtkfdk_ggo.h" #include "rtkGgoFunctions.h" #include "rtkConfiguration.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkProjectionsReader.h" #include "rtkDisplacedDetectorImageFilter.h" #include "rtkParkerShortScanImageFilter.h" #include "rtkFDKConeBeamReconstructionFilter.h" #if CUDA_FOUND # include "rtkCudaFDKConeBeamReconstructionFilter.h" #endif #if OPENCL_FOUND # include "rtkOpenCLFDKConeBeamReconstructionFilter.h" #endif #include "rtkFDKWarpBackProjectionImageFilter.h" #include "rtkCyclicDeformationImageFilter.h" #include <itkRegularExpressionSeriesFileNames.h> #include <itkStreamingImageFilter.h> #include <itkImageFileWriter.h> int main(int argc, char * argv[]) { GGO(rtkfdk, args_info); typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(args_info.path_arg); names->SetNumericSort(false); names->SetRegularExpression(args_info.regexp_arg); names->SetSubMatch(0); if(args_info.verbose_flag) std::cout << "Regular expression matches " << names->GetFileNames().size() << " file(s)..." << std::endl; // Projections reader typedef rtk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( names->GetFileNames() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->GenerateOutputInformation() ); itk::TimeProbe readerProbe; if(!args_info.lowmem_flag) { if(args_info.verbose_flag) std::cout << "Reading... " << std::flush; readerProbe.Start(); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ) readerProbe.Stop(); if(args_info.verbose_flag) std::cout << "It took " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl; } // Geometry if(args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() ) // Displaced detector weighting typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType; DDFType::Pointer ddf = DDFType::New(); ddf->SetInput( reader->GetOutput() ); ddf->SetGeometry( geometryReader->GetOutputObject() ); // Short scan image filter typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType; PSSFType::Pointer pssf = PSSFType::New(); pssf->SetInput( ddf->GetOutput() ); pssf->SetGeometry( geometryReader->GetOutputObject() ); pssf->InPlaceOff(); // Create reconstructed image typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New(); rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkfdk>(constantImageSource, args_info); // Motion-compensated objects for the compensation of a cyclic deformation. // Although these will only be used if the command line options for motion // compensation are set, we still create the object before hand to avoid auto // destruction. typedef itk::Vector<float,3> DVFPixelType; typedef itk::Image< DVFPixelType, 3 > DVFImageType; typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType; typedef itk::ImageFileReader<DeformationType::InputImageType> DVFReaderType; DVFReaderType::Pointer dvfReader = DVFReaderType::New(); DeformationType::Pointer def = DeformationType::New(); def->SetInput(dvfReader->GetOutput()); typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType; WarpBPType::Pointer bp = WarpBPType::New(); bp->SetDeformation(def); bp->SetGeometry( geometryReader->GetOutputObject() ); // This macro sets options for fdk filter which I can not see how to do better // because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR) #define SET_FELDKAMP_OPTIONS(f) \ f->SetInput( 0, constantImageSource->GetOutput() ); \ f->SetInput( 1, pssf->GetOutput() ); \ f->SetGeometry( geometryReader->GetOutputObject() ); \ f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \ f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg); \ f->GetRampFilter()->SetHannCutFrequencyY(args_info.hannY_arg); // FDK reconstruction filtering itk::ImageToImageFilter<OutputImageType, OutputImageType>::Pointer feldkamp; typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType; #if CUDA_FOUND typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType; #endif #if OPENCL_FOUND typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType; #endif if(!strcmp(args_info.hardware_arg, "cpu") ) { feldkamp = FDKCPUType::New(); SET_FELDKAMP_OPTIONS( dynamic_cast<FDKCPUType*>(feldkamp.GetPointer()) ); // Motion compensated CBCT settings if(args_info.signal_given && args_info.dvf_given) { dvfReader->SetFileName(args_info.dvf_arg); def->SetSignalFilename(args_info.signal_arg); dynamic_cast<FDKCPUType*>(feldkamp.GetPointer())->SetBackProjectionFilter( bp.GetPointer() ); } } else if(!strcmp(args_info.hardware_arg, "cuda") ) { #if CUDA_FOUND feldkamp = FDKCUDAType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKCUDAType*>(feldkamp.GetPointer()) ); #else std::cerr << "The program has not been compiled with cuda option" << std::endl; return EXIT_FAILURE; #endif } else if(!strcmp(args_info.hardware_arg, "opencl") ) { #if OPENCL_FOUND feldkamp = FDKOPENCLType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKOPENCLType*>(feldkamp.GetPointer()) ); #else std::cerr << "The program has not been compiled with opencl option" << std::endl; return EXIT_FAILURE; #endif } // Streaming depending on streaming capability of writer typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType; StreamerType::Pointer streamerBP = StreamerType::New(); streamerBP->SetInput( feldkamp->GetOutput() ); streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg ); // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( streamerBP->GetOutput() ); if(args_info.verbose_flag) std::cout << "Reconstructing and writing... " << std::flush; itk::TimeProbe writerProbe; writerProbe.Start(); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ); writerProbe.Stop(); if(args_info.verbose_flag) { std::cout << "It took " << writerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl; if(!strcmp(args_info.hardware_arg, "cpu") ) static_cast<FDKCPUType* >(feldkamp.GetPointer())->PrintTiming(std::cout); #if CUDA_FOUND else if(!strcmp(args_info.hardware_arg, "cuda") ) static_cast<FDKCUDAType*>(feldkamp.GetPointer())->PrintTiming(std::cout); #endif #if OPENCL_FOUND else if(!strcmp(args_info.hardware_arg, "opencl") ) static_cast<FDKOPENCLType*>(feldkamp.GetPointer())->PrintTiming(std::cout); #endif std::cout << std::endl; } return EXIT_SUCCESS; } <commit_msg>Was not compiling with BUILD_TESTING=OFF<commit_after>/*========================================================================= * * Copyright RTK 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 "rtkfdk_ggo.h" #include "rtkGgoFunctions.h" #include "rtkConfiguration.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkProjectionsReader.h" #include "rtkDisplacedDetectorImageFilter.h" #include "rtkParkerShortScanImageFilter.h" #include "rtkFDKConeBeamReconstructionFilter.h" #if CUDA_FOUND # include "rtkCudaFDKConeBeamReconstructionFilter.h" #endif #if OPENCL_FOUND # include "rtkOpenCLFDKConeBeamReconstructionFilter.h" #endif #include "rtkFDKWarpBackProjectionImageFilter.h" #include "rtkCyclicDeformationImageFilter.h" #include <itkRegularExpressionSeriesFileNames.h> #include <itkStreamingImageFilter.h> #include <itkImageFileWriter.h> int main(int argc, char * argv[]) { GGO(rtkfdk, args_info); typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(args_info.path_arg); names->SetNumericSort(false); names->SetRegularExpression(args_info.regexp_arg); names->SetSubMatch(0); if(args_info.verbose_flag) std::cout << "Regular expression matches " << names->GetFileNames().size() << " file(s)..." << std::endl; // Projections reader typedef rtk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( names->GetFileNames() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->GenerateOutputInformation() ); itk::TimeProbe readerProbe; if(!args_info.lowmem_flag) { if(args_info.verbose_flag) std::cout << "Reading... " << std::flush; readerProbe.Start(); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ) readerProbe.Stop(); if(args_info.verbose_flag) std::cout << "It took " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl; } // Geometry if(args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() ) // Displaced detector weighting typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType; DDFType::Pointer ddf = DDFType::New(); ddf->SetInput( reader->GetOutput() ); ddf->SetGeometry( geometryReader->GetOutputObject() ); // Short scan image filter typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType; PSSFType::Pointer pssf = PSSFType::New(); pssf->SetInput( ddf->GetOutput() ); pssf->SetGeometry( geometryReader->GetOutputObject() ); pssf->InPlaceOff(); // Create reconstructed image typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New(); rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkfdk>(constantImageSource, args_info); // Motion-compensated objects for the compensation of a cyclic deformation. // Although these will only be used if the command line options for motion // compensation are set, we still create the object before hand to avoid auto // destruction. typedef itk::Vector<float,3> DVFPixelType; typedef itk::Image< DVFPixelType, 3 > DVFImageType; typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType; typedef itk::ImageFileReader<DeformationType::InputImageType> DVFReaderType; DVFReaderType::Pointer dvfReader = DVFReaderType::New(); DeformationType::Pointer def = DeformationType::New(); def->SetInput(dvfReader->GetOutput()); typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType; WarpBPType::Pointer bp = WarpBPType::New(); bp->SetDeformation(def); bp->SetGeometry( geometryReader->GetOutputObject() ); // This macro sets options for fdk filter which I can not see how to do better // because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR) #define SET_FELDKAMP_OPTIONS(f) \ f->SetInput( 0, constantImageSource->GetOutput() ); \ f->SetInput( 1, pssf->GetOutput() ); \ f->SetGeometry( geometryReader->GetOutputObject() ); \ f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \ f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg); \ f->GetRampFilter()->SetHannCutFrequencyY(args_info.hannY_arg); // FDK reconstruction filtering itk::ImageToImageFilter<OutputImageType, OutputImageType>::Pointer feldkamp; typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType; #if CUDA_FOUND typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType; #endif #if OPENCL_FOUND typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType; #endif if(!strcmp(args_info.hardware_arg, "cpu") ) { feldkamp = FDKCPUType::New(); SET_FELDKAMP_OPTIONS( dynamic_cast<FDKCPUType*>(feldkamp.GetPointer()) ); // Motion compensated CBCT settings if(args_info.signal_given && args_info.dvf_given) { dvfReader->SetFileName(args_info.dvf_arg); def->SetSignalFilename(args_info.signal_arg); dynamic_cast<FDKCPUType*>(feldkamp.GetPointer())->SetBackProjectionFilter( bp.GetPointer() ); } } else if(!strcmp(args_info.hardware_arg, "cuda") ) { #if CUDA_FOUND feldkamp = FDKCUDAType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKCUDAType*>(feldkamp.GetPointer()) ); #else std::cerr << "The program has not been compiled with cuda option" << std::endl; return EXIT_FAILURE; #endif } else if(!strcmp(args_info.hardware_arg, "opencl") ) { #if OPENCL_FOUND feldkamp = FDKOPENCLType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKOPENCLType*>(feldkamp.GetPointer()) ); #else std::cerr << "The program has not been compiled with opencl option" << std::endl; return EXIT_FAILURE; #endif } // Streaming depending on streaming capability of writer typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType; StreamerType::Pointer streamerBP = StreamerType::New(); streamerBP->SetInput( feldkamp->GetOutput() ); streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg ); // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( streamerBP->GetOutput() ); if(args_info.verbose_flag) std::cout << "Reconstructing and writing... " << std::flush; itk::TimeProbe writerProbe; writerProbe.Start(); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ); writerProbe.Stop(); if(args_info.verbose_flag) { std::cout << "It took " << writerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl; if(!strcmp(args_info.hardware_arg, "cpu") ) static_cast<FDKCPUType* >(feldkamp.GetPointer())->PrintTiming(std::cout); #if CUDA_FOUND else if(!strcmp(args_info.hardware_arg, "cuda") ) static_cast<FDKCUDAType*>(feldkamp.GetPointer())->PrintTiming(std::cout); #endif #if OPENCL_FOUND else if(!strcmp(args_info.hardware_arg, "opencl") ) static_cast<FDKOPENCLType*>(feldkamp.GetPointer())->PrintTiming(std::cout); #endif std::cout << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "reportgenerator.h" /** * @brief ReportGenerator::ReportGenerator * The constructor will assign parameters to the class members. * @param proj, the current project that we are creating document for. * @param file_handler, the file_handler that is used to get path information for saving. */ ReportGenerator::ReportGenerator(Project* proj, FileHandler *file_handler) { this->proj = proj; this->file_handler = file_handler; } /** * @brief ReportGenerator::~ReportGenerator * destructor to remove allocated memory. */ ReportGenerator::~ReportGenerator() { delete word; } /** * @brief ReportGenerator::create_report * This method will do 5 steps to create a word document, load it with bookmarks and save it. */ void ReportGenerator::create_report() { //1. START APPLICATION word = new QAxObject("Word.Application"); if(!word->isNull()){ //2.OPEN THE DOCUMENT QAxObject* doc = word->querySubObject("Documents"); doc->dynamicCall("Add()"); word->setProperty("Visible",false); // second bool to hide application when opened. //3.GET TO THE CONTENTS QAxObject* active_document = word->querySubObject("ActiveDocument"); QAxObject* active_window = active_document->querySubObject( "ActiveWindow" ); QAxObject* selection = active_window->querySubObject( "Selection" ); // Save all for project bookmarks in a list. create_list_of_names(); // Make sure there is bookmarks to put in report. if(!all_bookmarks.empty()){ //4. ADD IMAGES FROM BOOKMARK FOLDER add_bookmarks(selection); //5. SAVE AND CLOSE FILE QString file_path = save_report(active_document); this->proj->add_report(file_path.toStdString()); } close_report(doc, word); }else{ qWarning("could not find Word instance"); } } /** * @brief ReportGenerator::create_list_of_names * This method will take all bookmarks for all videos in a * project and put their path and description in a list. * Change in this method if reports should only be based on the current * video that is selected and not the entire project. Changes will be needed * on other places aswell. */ void ReportGenerator::create_list_of_names() { std::map<ID, VideoProject*> videos = proj->get_videos(); // get all bookmarks for a project by iterating over each videos bookmarks. for(std::pair<ID, VideoProject*> video : videos) { std::vector<Bookmark *> bookmark_list = video.second->get_bookmarks(); for(Bookmark* video_bookmark : bookmark_list) { std::string bookmark_path = video_bookmark->get_file_path().toStdString(); std::string bookmark_description = video_bookmark->get_description().toStdString(); all_bookmarks.push_back(std::make_pair(bookmark_path, bookmark_description)); } } } /** * @brief ReportGenerator::resize_picture * This method will make all images to be of the same size with a width * that is based on the constant IMAGE_WIDTH_REFERENCE. All images will keep * its aspect ratio. * @param pic_path, path to the bookmark that is to be resized. * @param inline_shape, A word specific object that is a shape where its * layout is "inline" with the rest of the document. */ void ReportGenerator::resize_picture(QString pic_path, QAxObject* inline_shape) { QImage image = QImage(pic_path); int const original_height = image.height(); int const original_width = image.width(); //Scale all images to have same width but keep aspect ratio double multiply_factor = IMAGE_WIDTH_REFERENCE/original_width; inline_shape->dynamicCall( "Height", (multiply_factor*original_height)); inline_shape->dynamicCall( "Width", IMAGE_WIDTH_REFERENCE); } /** * @brief ReportGenerator::add_paragraph * This adds paragraphs (spaces) between the bookmarks in the * document to make it more readable. To increase or decrease the number * of paragraphs change the number of times the loop is executed. * @param selection, the selector in the active document. */ void ReportGenerator::add_paragraph(QAxObject* selection) { selection->dynamicCall( "Collapse(int)", 0 ); for (int i = 0; i < 2; ++i) { selection->dynamicCall( "InsertParagraphAfter()" ); } selection->dynamicCall( "Collapse(int)", 0 ); } /** * @brief ReportGenerator::add_bookmarks * This method will add all bookmarks for the current project * to the document. * @param selection, the selector in the active document. */ void ReportGenerator::add_bookmarks(QAxObject* selection) { QAxObject* shapes = selection->querySubObject( "InlineShapes" ); for (std::pair<std::string, std::string> bookmark : all_bookmarks) { QString pic_path = QString::fromStdString(bookmark.first); //Fix to make path work with windows word //application when spaces are involved pic_path.replace("/", "\\\\"); QAxObject* inline_shape = shapes->querySubObject( "AddPicture(const QString&,bool,bool,QVariant)", pic_path, false, true); resize_picture(pic_path, inline_shape); // Center image selection->querySubObject( "ParagraphFormat" )->setProperty( "Alignment", 1 ); //adds description beneath image selection->dynamicCall( "InsertParagraphAfter()" ); selection->dynamicCall("InsertAfter(const QString&)", QString::fromStdString(bookmark.second)); // Add paragraphs between images add_paragraph(selection); } } /** * @brief ReportGenerator::date_time_generator * calculates the current time and date and changes the format * to use "_" instead of ":" since it is not allowed in word application * to save file names that have a colon in the name. * @return string, the current time and date. */ std::string ReportGenerator::date_time_generator() { time_t now = time(0); std::string dt = ctime(&now); std::replace( dt.begin(), dt.end(), ':', '-'); std::replace( dt.begin(), dt.end(), ' ' , '_'); dt.erase(std::remove(dt.begin(), dt.end(), '\n'), dt.end()); return dt; } /** * @brief ReportGenerator::save_report * This method will save the word document in the project folder. * The name will be based on the project and current date and time. * @param active_document, the document that is selected */ QString ReportGenerator::save_report(QAxObject* active_document) { std::string dt = date_time_generator(); std::string proj_path = file_handler->get_dir(proj->dir).absolutePath().toStdString(); std::string path = proj_path.append("/").append(proj->name).append("_").append(dt).append(".docx"); active_document->dynamicCall("SaveAs (const QString&)", QString::fromStdString(path)); return QString::fromStdString(path); } /** * @brief ReportGenerator::close_report * This method will close the document and quit the the word application that are sent in * as a parameter. * @param doc, document instance * @param word, word application */ void ReportGenerator::close_report(QAxObject* doc, QAxObject* word) { doc->dynamicCall("Close()"); word->dynamicCall("Quit()"); } <commit_msg>changed type declaration<commit_after>#include "reportgenerator.h" /** * @brief ReportGenerator::ReportGenerator * The constructor will assign parameters to the class members. * @param proj, the current project that we are creating document for. * @param file_handler, the file_handler that is used to get path information for saving. */ ReportGenerator::ReportGenerator(Project* proj, FileHandler *file_handler) { this->proj = proj; this->file_handler = file_handler; } /** * @brief ReportGenerator::~ReportGenerator * destructor to remove allocated memory. */ ReportGenerator::~ReportGenerator() { delete word; } /** * @brief ReportGenerator::create_report * This method will do 5 steps to create a word document, load it with bookmarks and save it. */ void ReportGenerator::create_report() { //1. START APPLICATION word = new QAxObject("Word.Application"); if(!word->isNull()){ //2.OPEN THE DOCUMENT QAxObject* doc = word->querySubObject("Documents"); doc->dynamicCall("Add()"); word->setProperty("Visible",false); // second bool to hide application when opened. //3.GET TO THE CONTENTS QAxObject* active_document = word->querySubObject("ActiveDocument"); QAxObject* active_window = active_document->querySubObject( "ActiveWindow" ); QAxObject* selection = active_window->querySubObject( "Selection" ); // Save all for project bookmarks in a list. create_list_of_names(); // Make sure there is bookmarks to put in report. if(!all_bookmarks.empty()){ //4. ADD IMAGES FROM BOOKMARK FOLDER add_bookmarks(selection); //5. SAVE AND CLOSE FILE QString file_path = save_report(active_document); this->proj->add_report(file_path.toStdString()); } close_report(doc, word); }else{ qWarning("could not find Word instance"); } } /** * @brief ReportGenerator::create_list_of_names * This method will take all bookmarks for all videos in a * project and put their path and description in a list. * Change in this method if reports should only be based on the current * video that is selected and not the entire project. Changes will be needed * on other places aswell. */ void ReportGenerator::create_list_of_names() { std::map<ID, VideoProject*> videos = proj->get_videos(); // get all bookmarks for a project by iterating over each videos bookmarks. for(std::pair<ID, VideoProject*> video : videos) { std::map<ID, Bookmark *> bookmark_list = video.second->get_bookmarks(); for(std::pair<ID,Bookmark*> vid_bm_pair : bookmark_list) { Bookmark* video_bookmark = vid_bm_pair.second; std::string bookmark_path = video_bookmark->get_file_path().toStdString(); std::string bookmark_description = video_bookmark->get_description().toStdString(); all_bookmarks.push_back(std::make_pair(bookmark_path, bookmark_description)); } } } /** * @brief ReportGenerator::resize_picture * This method will make all images to be of the same size with a width * that is based on the constant IMAGE_WIDTH_REFERENCE. All images will keep * its aspect ratio. * @param pic_path, path to the bookmark that is to be resized. * @param inline_shape, A word specific object that is a shape where its * layout is "inline" with the rest of the document. */ void ReportGenerator::resize_picture(QString pic_path, QAxObject* inline_shape) { QImage image = QImage(pic_path); int const original_height = image.height(); int const original_width = image.width(); //Scale all images to have same width but keep aspect ratio double multiply_factor = IMAGE_WIDTH_REFERENCE/original_width; inline_shape->dynamicCall( "Height", (multiply_factor*original_height)); inline_shape->dynamicCall( "Width", IMAGE_WIDTH_REFERENCE); } /** * @brief ReportGenerator::add_paragraph * This adds paragraphs (spaces) between the bookmarks in the * document to make it more readable. To increase or decrease the number * of paragraphs change the number of times the loop is executed. * @param selection, the selector in the active document. */ void ReportGenerator::add_paragraph(QAxObject* selection) { selection->dynamicCall( "Collapse(int)", 0 ); for (int i = 0; i < 2; ++i) { selection->dynamicCall( "InsertParagraphAfter()" ); } selection->dynamicCall( "Collapse(int)", 0 ); } /** * @brief ReportGenerator::add_bookmarks * This method will add all bookmarks for the current project * to the document. * @param selection, the selector in the active document. */ void ReportGenerator::add_bookmarks(QAxObject* selection) { QAxObject* shapes = selection->querySubObject( "InlineShapes" ); for (std::pair<std::string, std::string> bookmark : all_bookmarks) { QString pic_path = QString::fromStdString(bookmark.first); //Fix to make path work with windows word //application when spaces are involved pic_path.replace("/", "\\\\"); QAxObject* inline_shape = shapes->querySubObject( "AddPicture(const QString&,bool,bool,QVariant)", pic_path, false, true); resize_picture(pic_path, inline_shape); // Center image selection->querySubObject( "ParagraphFormat" )->setProperty( "Alignment", 1 ); //adds description beneath image selection->dynamicCall( "InsertParagraphAfter()" ); selection->dynamicCall("InsertAfter(const QString&)", QString::fromStdString(bookmark.second)); // Add paragraphs between images add_paragraph(selection); } } /** * @brief ReportGenerator::date_time_generator * calculates the current time and date and changes the format * to use "_" instead of ":" since it is not allowed in word application * to save file names that have a colon in the name. * @return string, the current time and date. */ std::string ReportGenerator::date_time_generator() { time_t now = time(0); std::string dt = ctime(&now); std::replace( dt.begin(), dt.end(), ':', '-'); std::replace( dt.begin(), dt.end(), ' ' , '_'); dt.erase(std::remove(dt.begin(), dt.end(), '\n'), dt.end()); return dt; } /** * @brief ReportGenerator::save_report * This method will save the word document in the project folder. * The name will be based on the project and current date and time. * @param active_document, the document that is selected */ QString ReportGenerator::save_report(QAxObject* active_document) { std::string dt = date_time_generator(); std::string proj_path = file_handler->get_dir(proj->dir).absolutePath().toStdString(); std::string path = proj_path.append("/").append(proj->name).append("_").append(dt).append(".docx"); active_document->dynamicCall("SaveAs (const QString&)", QString::fromStdString(path)); return QString::fromStdString(path); } /** * @brief ReportGenerator::close_report * This method will close the document and quit the the word application that are sent in * as a parameter. * @param doc, document instance * @param word, word application */ void ReportGenerator::close_report(QAxObject* doc, QAxObject* word) { doc->dynamicCall("Close()"); word->dynamicCall("Quit()"); } <|endoftext|>
<commit_before>#ifndef ecmdStructs_H #define ecmdStructs_H // Copyright ********************************************************** // // File ecmdStructs.H // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 2003 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ****************************************************** /** @file ecmdStructs.H @brief All the Structures required for the eCMD Capi */ //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <stdint.h> //-------------------------------------------------------------------- // Forward References //-------------------------------------------------------------------- //-------------------------------------------------------------------- // Defines //-------------------------------------------------------------------- #define ECMD_CAPI_VERSION ".1" #define ECMD_MAX_CHIP_TYPE_LENGTH 15 ///< @see ecmdChipTarget // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- ----- ------------------------------- // willsj Initial Creation // // End Change Log ***************************************************** /** @brief Structure used to designate which cec object you would like the function to operate on */ struct ecmdChipTarget { char chipType[ECMD_MAX_CHIP_TYPE_LENGTH]; ///< name of chip to access uint32_t cage; ///< cage that contains node with chip uint32_t node; ///< node that contains chip uint32_t pos; ///< position of chip within node uint32_t core; ///< which core on chip to access, if chip is multi-core uint32_t thread; ///< which thread on chip to access, if chip is multi-threaded uint8_t cageLoopValid; ///< Tell the calling function that this function operates at a cage level uint8_t nodeLoopValid; ///< Tell the calling function that this function operates at a node level uint8_t posLoopValid; ///< Tell the calling function that this function operates at a pos level uint8_t coreLoopValid; ///< Tell the calling function that this function operates at a core level uint8_t threadLoopValid; ///< Tell the calling function that this function operates at a thread level uint8_t loopValidChecked; ///< Flag that indicates that we have signaled to the user level how to loop }; #endif <commit_msg>Initial start on query structures<commit_after>#ifndef ecmdStructs_H #define ecmdStructs_H // Copyright ********************************************************** // // File ecmdStructs.H // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 2003 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ****************************************************** /** @file ecmdStructs.H @brief All the Structures required for the eCMD Capi */ //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <stdint.h> #include <list.h> /* For STL list */ //-------------------------------------------------------------------- // Forward References //-------------------------------------------------------------------- //-------------------------------------------------------------------- // Defines //-------------------------------------------------------------------- #define ECMD_CAPI_VERSION ".1" ///< eCMD API Version #define ECMD_MAX_CHIP_TYPE_LENGTH 15 ///< @see ecmdChipTarget // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- ----- ------------------------------- // willsj Initial Creation // // End Change Log ***************************************************** /** @brief Structure used to designate which cec object you would like the function to operate on */ struct ecmdChipTarget { char chipType[ECMD_MAX_CHIP_TYPE_LENGTH]; ///< name of chip to access uint32_t cage; ///< cage that contains node with chip uint32_t node; ///< node that contains chip uint32_t pos; ///< position of chip within node uint32_t core; ///< which core on chip to access, if chip is multi-core uint32_t thread; ///< which thread on chip to access, if chip is multi-threaded uint8_t cageLoopValid; ///< Tell the calling function that this function operates at a cage level uint8_t nodeLoopValid; ///< Tell the calling function that this function operates at a node level uint8_t posLoopValid; ///< Tell the calling function that this function operates at a pos level uint8_t coreLoopValid; ///< Tell the calling function that this function operates at a core level uint8_t threadLoopValid; ///< Tell the calling function that this function operates at a thread level uint8_t loopValidChecked; ///< Flag that indicates that we have signaled to the user level how to loop }; enum ecmdChipInterfaceType_t { ECMD_INTERFACE_ACCESS, ECMD_INTERFACE_CFAM }; struct ecmdChipData { uint32_t pos; uint8_t procCores; uint8_t procThreads; uint32_t chipEc; /** @brief Used for the ecmdQueryFileLocation function to specify the file type you are looking for */ enum ecmdFileType_t { ECMD_FILE_SCANDEF, ///< Scandef file type ECMD_FILE_SPYDEF, ///< Spy Definition file ECMD_FILE_ARRAYDEF ///< Array Definition file }; #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2006 George Staikos <staikos@kde.org> * Copyright (C) 2006 Dirk Mueller <mueller@kde.org> * Copyright (C) 2006 Zack Rusin <zack@kde.org> * Copyright (C) 2006 Simon Hausmann <hausmann@kde.org> * * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 <qwebpage.h> #include <qwebframe.h> #include <qwebsettings.h> #include <QtGui> #include <QDebug> class InfoWidget :public QProgressBar { Q_OBJECT public: InfoWidget(QWidget *parent) : QProgressBar(parent), m_progress(0) { setMinimum(0); setMaximum(100); } QSize sizeHint() const { QSize size(100, 20); return size; } public slots: void startLoad() { setValue(m_progress); show(); } void changeLoad(int change) { m_progress = change; setValue(change); } void endLoad() { QTimer::singleShot(1000, this, SLOT(hide())); m_progress = 0; } protected: int m_progress; }; class HoverLabel : public QWidget { Q_OBJECT public: HoverLabel(QWidget *parent=0) : QWidget(parent), m_animating(false), m_percent(0) { m_timer.setInterval(1000/30); m_hideTimer.setInterval(500); m_hideTimer.setSingleShot(true); connect(&m_timer, SIGNAL(timeout()), this, SLOT(update())); connect(&m_hideTimer, SIGNAL(timeout()), this, SLOT(hide())); } public slots: void setHoverLink(const QString &link) { m_link = link; if (m_link.isEmpty()) { m_hideTimer.start(); } else { m_hideTimer.stop(); m_oldSize = m_newSize; m_newSize = sizeForFont(); resetAnimation(); updateSize(); show(); repaint(); } } QSize sizeForFont() const { QFont f = font(); QFontMetrics fm(f); return QSize(fm.width(m_link) + 10, fm.height() + 6); } QSize sizeHint() const { if (!m_animating) return sizeForFont(); else return (m_newSize.width() > m_oldSize.width()) ? m_newSize : m_oldSize; } void updateSize() { QRect r = geometry(); QSize newSize = sizeHint(); r = QRect(r.x(), r.y(), newSize.width(), newSize.height()); setGeometry(r); } void resetAnimation() { m_animating = true; m_percent = 0; if (!m_timer.isActive()) m_timer.start(); } protected: void paintEvent(QPaintEvent *e) { QPainter p(this); p.setClipRect(e->rect()); p.setPen(QPen(Qt::black, 1)); QLinearGradient gradient(rect().topLeft(), rect().bottomLeft()); gradient.setColorAt(0, QColor(255, 255, 255, 220)); gradient.setColorAt(1, QColor(193, 193, 193, 220)); p.setBrush(QBrush(gradient)); QSize size; { //draw a nicely rounded corner rectangle. to avoid unwanted // borders we move the coordinates outsize the our clip region size = interpolate(m_oldSize, m_newSize, m_percent); QRect r(-1, 0, size.width(), size.height()+2); const int roundness = 20; QPainterPath path; path.moveTo(r.x(), r.y()); path.lineTo(r.topRight().x()-roundness, r.topRight().y()); path.cubicTo(r.topRight().x(), r.topRight().y(), r.topRight().x(), r.topRight().y(), r.topRight().x(), r.topRight().y() + roundness); path.lineTo(r.bottomRight()); path.lineTo(r.bottomLeft()); path.closeSubpath(); p.setRenderHint(QPainter::Antialiasing); p.drawPath(path); } if (m_animating) { if (qFuzzyCompare(m_percent, 1)) { m_animating = false; m_percent = 0; m_timer.stop(); } else { m_percent += 0.1; if (m_percent >= 0.99) { m_percent = 1; } } } QString txt; QFontMetrics fm(fontMetrics()); txt = fm.elidedText(m_link, Qt::ElideRight, size.width()-5); p.drawText(5, height()-6, txt); } private: QSize interpolate(const QSize &src, const QSize &dst, qreal percent) { int widthDiff = int((dst.width() - src.width()) * percent); int heightDiff = int((dst.height() - src.height()) * percent); return QSize(src.width() + widthDiff, src.height() + heightDiff); } QString m_link; bool m_animating; QTimer m_timer; QTimer m_hideTimer; QSize m_oldSize; QSize m_newSize; qreal m_percent; }; class SearchEdit; class ClearButton : public QPushButton { Q_OBJECT public: ClearButton(QWidget *w) : QPushButton(w) { setMinimumSize(24, 24); setFixedSize(24, 24); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } void paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); int height = parentWidget()->geometry().height(); int width = height; //parentWidget()->geometry().width(); painter.setRenderHint(QPainter::Antialiasing, true); painter.setPen(Qt::lightGray); painter.setBrush(isDown() ? QColor(140, 140, 190) : underMouse() ? QColor(220, 220, 255) : QColor(200, 200, 230) ); painter.drawEllipse(4, 4, width - 8, height - 8); painter.setPen(Qt::white); int border = 8; painter.drawLine(border, border, width - border, height - border); painter.drawLine(border, height - border, width - border, border); } }; class SearchEdit : public QLineEdit { Q_OBJECT public: SearchEdit(const QString &str, QWidget *parent = 0) : QLineEdit(str, parent) { setMinimumSize(QSize(400, 24)); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setStyleSheet(":enabled { padding-right: 27px }"); clearButton = new ClearButton(this); clearButton->setGeometry(QRect(geometry().right() - 27, geometry().top() - 2, geometry().right(), geometry().bottom())); clearButton->setVisible(true); clearButton->setCursor(Qt::ArrowCursor); connect(clearButton, SIGNAL(clicked()), this, SLOT(clear())); clearButton->setToolTip("Clear"); } ~SearchEdit() { } protected: virtual void paintEvent(QPaintEvent *e) { QLineEdit::paintEvent(e); if(text().isEmpty()) clearButton->setVisible(false); else clearButton->setVisible(true); } virtual void resizeEvent(QResizeEvent *) { clearButton->setParent(this); clearButton->setGeometry(QRect(width()-27, 0, 24, 24)); } virtual void moveEvent(QMoveEvent *) { clearButton->setParent(this); clearButton->setGeometry(QRect(width()-27, 1, 24, 24)); } QPushButton *clearButton; }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(const QUrl &url) { page = new QWebPage(this); InfoWidget *info = new InfoWidget(page); info->setGeometry(20, 20, info->sizeHint().width(), info->sizeHint().height()); connect(page, SIGNAL(loadStarted(QWebFrame*)), info, SLOT(startLoad())); connect(page, SIGNAL(loadProgressChanged(int)), info, SLOT(changeLoad(int))); connect(page, SIGNAL(loadFinished(QWebFrame*)), info, SLOT(endLoad())); connect(page, SIGNAL(loadFinished(QWebFrame*)), this, SLOT(loadFinished())); connect(page, SIGNAL(titleChanged(const QString&)), this, SLOT(setWindowTitle(const QString&))); connect(page, SIGNAL(hoveringOverLink(const QString&, const QString&)), this, SLOT(showLinkHover(const QString&, const QString&))); setCentralWidget(page); QToolBar *bar = addToolBar("Navigation"); urlEdit = new SearchEdit(url.toString()); connect(urlEdit, SIGNAL(returnPressed()), SLOT(changeLocation())); bar->addAction("Go back", page, SLOT(goBack())); bar->addAction("Stop", page, SLOT(stop())); bar->addAction("Go forward", page, SLOT(goForward())); bar->addWidget(urlEdit); hoverLabel = new HoverLabel(this); hoverLabel->hide(); page->open(url); info->raise(); } protected slots: void changeLocation() { QUrl url(urlEdit->text()); page->open(url); } void loadFinished() { urlEdit->setText(page->url().toString()); } void showLinkHover(const QString &link, const QString &toolTip) { //statusBar()->showMessage(link); hoverLabel->setHoverLink(link); if (!toolTip.isEmpty()) QToolTip::showText(QCursor::pos(), toolTip); } protected: void resizeEvent(QResizeEvent *) { QSize hoverSize = hoverLabel->sizeHint(); hoverLabel->setGeometry(0, height()-hoverSize.height(), 300, hoverSize.height()); } private: QWebPage *page; QLineEdit *urlEdit; HoverLabel *hoverLabel; }; #include "main.moc" int main(int argc, char **argv) { QString url = QString("%1/%2").arg(QDir::homePath()).arg(QLatin1String("index.html")); QApplication app(argc, argv); QWebSettings settings = QWebSettings::global(); settings.setAttribute(QWebSettings::PluginsEnabled); QWebSettings::setGlobal(settings); const QStringList args = app.arguments(); if (args.count() > 1) url = args.at(1); MainWindow window(url); window.show(); return app.exec(); } <commit_msg>Missed this file as part of #23832<commit_after>/* * Copyright (C) 2006 George Staikos <staikos@kde.org> * Copyright (C) 2006 Dirk Mueller <mueller@kde.org> * Copyright (C) 2006 Zack Rusin <zack@kde.org> * Copyright (C) 2006 Simon Hausmann <hausmann@kde.org> * * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 <qwebpage.h> #include <qwebframe.h> #include <qwebsettings.h> #include <QtGui> #include <QDebug> class InfoWidget :public QProgressBar { Q_OBJECT public: InfoWidget(QWidget *parent) : QProgressBar(parent), m_progress(0) { setMinimum(0); setMaximum(100); } QSize sizeHint() const { QSize size(100, 20); return size; } public slots: void startLoad() { setValue(m_progress); show(); } void changeLoad(int change) { m_progress = change; setValue(change); } void endLoad() { QTimer::singleShot(1000, this, SLOT(hide())); m_progress = 0; } protected: int m_progress; }; class HoverLabel : public QWidget { Q_OBJECT public: HoverLabel(QWidget *parent=0) : QWidget(parent), m_animating(false), m_percent(0) { m_timer.setInterval(1000/30); m_hideTimer.setInterval(500); m_hideTimer.setSingleShot(true); connect(&m_timer, SIGNAL(timeout()), this, SLOT(update())); connect(&m_hideTimer, SIGNAL(timeout()), this, SLOT(hide())); } public slots: void setHoverLink(const QString &link) { m_link = link; if (m_link.isEmpty()) { m_hideTimer.start(); } else { m_hideTimer.stop(); m_oldSize = m_newSize; m_newSize = sizeForFont(); resetAnimation(); updateSize(); show(); repaint(); } } QSize sizeForFont() const { QFont f = font(); QFontMetrics fm(f); return QSize(fm.width(m_link) + 10, fm.height() + 6); } QSize sizeHint() const { if (!m_animating) return sizeForFont(); else return (m_newSize.width() > m_oldSize.width()) ? m_newSize : m_oldSize; } void updateSize() { QRect r = geometry(); QSize newSize = sizeHint(); r = QRect(r.x(), r.y(), newSize.width(), newSize.height()); setGeometry(r); } void resetAnimation() { m_animating = true; m_percent = 0; if (!m_timer.isActive()) m_timer.start(); } protected: void paintEvent(QPaintEvent *e) { QPainter p(this); p.setClipRect(e->rect()); p.setPen(QPen(Qt::black, 1)); QLinearGradient gradient(rect().topLeft(), rect().bottomLeft()); gradient.setColorAt(0, QColor(255, 255, 255, 220)); gradient.setColorAt(1, QColor(193, 193, 193, 220)); p.setBrush(QBrush(gradient)); QSize size; { //draw a nicely rounded corner rectangle. to avoid unwanted // borders we move the coordinates outsize the our clip region size = interpolate(m_oldSize, m_newSize, m_percent); QRect r(-1, 0, size.width(), size.height()+2); const int roundness = 20; QPainterPath path; path.moveTo(r.x(), r.y()); path.lineTo(r.topRight().x()-roundness, r.topRight().y()); path.cubicTo(r.topRight().x(), r.topRight().y(), r.topRight().x(), r.topRight().y(), r.topRight().x(), r.topRight().y() + roundness); path.lineTo(r.bottomRight()); path.lineTo(r.bottomLeft()); path.closeSubpath(); p.setRenderHint(QPainter::Antialiasing); p.drawPath(path); } if (m_animating) { if (qFuzzyCompare(m_percent, 1)) { m_animating = false; m_percent = 0; m_timer.stop(); } else { m_percent += 0.1; if (m_percent >= 0.99) { m_percent = 1; } } } QString txt; QFontMetrics fm(fontMetrics()); txt = fm.elidedText(m_link, Qt::ElideRight, size.width()-5); p.drawText(5, height()-6, txt); } private: QSize interpolate(const QSize &src, const QSize &dst, qreal percent) { int widthDiff = int((dst.width() - src.width()) * percent); int heightDiff = int((dst.height() - src.height()) * percent); return QSize(src.width() + widthDiff, src.height() + heightDiff); } QString m_link; bool m_animating; QTimer m_timer; QTimer m_hideTimer; QSize m_oldSize; QSize m_newSize; qreal m_percent; }; class SearchEdit; class ClearButton : public QPushButton { Q_OBJECT public: ClearButton(QWidget *w) : QPushButton(w) { setMinimumSize(24, 24); setFixedSize(24, 24); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } void paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); int height = parentWidget()->geometry().height(); int width = height; //parentWidget()->geometry().width(); painter.setRenderHint(QPainter::Antialiasing, true); painter.setPen(Qt::lightGray); painter.setBrush(isDown() ? QColor(140, 140, 190) : underMouse() ? QColor(220, 220, 255) : QColor(200, 200, 230) ); painter.drawEllipse(4, 4, width - 8, height - 8); painter.setPen(Qt::white); int border = 8; painter.drawLine(border, border, width - border, height - border); painter.drawLine(border, height - border, width - border, border); } }; class SearchEdit : public QLineEdit { Q_OBJECT public: SearchEdit(const QString &str, QWidget *parent = 0) : QLineEdit(str, parent) { setMinimumSize(QSize(400, 24)); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setStyleSheet(":enabled { padding-right: 27px }"); clearButton = new ClearButton(this); clearButton->setGeometry(QRect(geometry().right() - 27, geometry().top() - 2, geometry().right(), geometry().bottom())); clearButton->setVisible(true); #ifndef QT_NO_CURSOR clearButton->setCursor(Qt::ArrowCursor); #endif #ifndef QT_NO_TOOLTIP clearButton->setToolTip("Clear"); #endif connect(clearButton, SIGNAL(clicked()), this, SLOT(clear())); } ~SearchEdit() { } protected: virtual void paintEvent(QPaintEvent *e) { QLineEdit::paintEvent(e); if(text().isEmpty()) clearButton->setVisible(false); else clearButton->setVisible(true); } virtual void resizeEvent(QResizeEvent *) { clearButton->setParent(this); clearButton->setGeometry(QRect(width()-27, 0, 24, 24)); } virtual void moveEvent(QMoveEvent *) { clearButton->setParent(this); clearButton->setGeometry(QRect(width()-27, 1, 24, 24)); } QPushButton *clearButton; }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(const QUrl &url) { page = new QWebPage(this); InfoWidget *info = new InfoWidget(page); info->setGeometry(20, 20, info->sizeHint().width(), info->sizeHint().height()); connect(page, SIGNAL(loadStarted(QWebFrame*)), info, SLOT(startLoad())); connect(page, SIGNAL(loadProgressChanged(int)), info, SLOT(changeLoad(int))); connect(page, SIGNAL(loadFinished(QWebFrame*)), info, SLOT(endLoad())); connect(page, SIGNAL(loadFinished(QWebFrame*)), this, SLOT(loadFinished())); connect(page, SIGNAL(titleChanged(const QString&)), this, SLOT(setWindowTitle(const QString&))); connect(page, SIGNAL(hoveringOverLink(const QString&, const QString&)), this, SLOT(showLinkHover(const QString&, const QString&))); setCentralWidget(page); QToolBar *bar = addToolBar("Navigation"); urlEdit = new SearchEdit(url.toString()); connect(urlEdit, SIGNAL(returnPressed()), SLOT(changeLocation())); bar->addAction("Go back", page, SLOT(goBack())); bar->addAction("Stop", page, SLOT(stop())); bar->addAction("Go forward", page, SLOT(goForward())); bar->addWidget(urlEdit); hoverLabel = new HoverLabel(this); hoverLabel->hide(); page->open(url); info->raise(); } protected slots: void changeLocation() { QUrl url(urlEdit->text()); page->open(url); } void loadFinished() { urlEdit->setText(page->url().toString()); } void showLinkHover(const QString &link, const QString &toolTip) { //statusBar()->showMessage(link); hoverLabel->setHoverLink(link); #ifndef QT_NO_TOOLTIP if (!toolTip.isEmpty()) QToolTip::showText(QCursor::pos(), toolTip); #endif } protected: void resizeEvent(QResizeEvent *) { QSize hoverSize = hoverLabel->sizeHint(); hoverLabel->setGeometry(0, height()-hoverSize.height(), 300, hoverSize.height()); } private: QWebPage *page; QLineEdit *urlEdit; HoverLabel *hoverLabel; }; #include "main.moc" int main(int argc, char **argv) { QString url = QString("%1/%2").arg(QDir::homePath()).arg(QLatin1String("index.html")); QApplication app(argc, argv); QWebSettings settings = QWebSettings::global(); settings.setAttribute(QWebSettings::PluginsEnabled); QWebSettings::setGlobal(settings); const QStringList args = app.arguments(); if (args.count() > 1) url = args.at(1); MainWindow window(url); window.show(); return app.exec(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: types.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:47:36 $ * * 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 _TYPES_HXX #define _TYPES_HXX #include <tools/ref.hxx> #include <basobj.hxx> class SvSlotElementList; struct SvSlotElement; /******************** class SvMetaAttribute *****************************/ SV_DECL_REF(SvMetaType) SV_DECL_REF(SvMetaAttribute) SV_DECL_PERSIST_LIST(SvMetaAttribute,SvMetaAttribute *) class SvMetaAttribute : public SvMetaReference { SvMetaTypeRef aType; SvNumberIdentifier aSlotId; SvBOOL aAutomation; SvBOOL aExport; SvBOOL aReadonly; SvBOOL aIsCollection; SvBOOL aReadOnlyDoc; SvBOOL aHidden; BOOL bNewAttr; protected: #ifdef IDL_COMPILER virtual void WriteCSource( SvIdlDataBase & rBase, SvStream & rOutStm, BOOL bSet ); ULONG MakeSlotValue( SvIdlDataBase & rBase, BOOL bVariable ) const; virtual void WriteAttributes( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); virtual void ReadAttributesSvIdl( SvIdlDataBase & rBase, SvTokenStream & rInStm ); virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); #endif public: SV_DECL_META_FACTORY1( SvMetaAttribute, SvMetaReference, 2 ) SvMetaAttribute(); SvMetaAttribute( SvMetaType * ); void SetNewAttribute( BOOL bNew ) { bNewAttr = bNew; } BOOL IsNewAttribute() const { return bNewAttr; } BOOL GetReadonly() const; void SetSlotId( const SvNumberIdentifier & rId ) { aSlotId = rId; } const SvNumberIdentifier & GetSlotId() const; void SetExport( BOOL bSet ) { aExport = bSet; } BOOL GetExport() const; void SetHidden( BOOL bSet ) { aHidden = bSet; } BOOL GetHidden() const; void SetAutomation( BOOL bSet ) { aAutomation = bSet; } BOOL GetAutomation() const; void SetIsCollection( BOOL bSet ) { aIsCollection = bSet; } BOOL GetIsCollection() const; void SetReadOnlyDoc( BOOL bSet ) { aReadOnlyDoc = bSet; } BOOL GetReadOnlyDoc() const; void SetType( SvMetaType * pT ) { aType = pT; } SvMetaType * GetType() const; virtual BOOL IsMethod() const; virtual BOOL IsVariable() const; virtual ByteString GetMangleName( BOOL bVariable ) const; // void FillSbxObject( SbxInfo * pInfo, USHORT nSbxFlags = 0 ); // virtual void FillSbxObject( SvIdlDataBase & rBase, SbxObject * pObj, BOOL bVariable ); #ifdef IDL_COMPILER virtual BOOL Test( SvIdlDataBase &, SvTokenStream & rInStm ); virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void WriteParam( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType ); void WriteRecursiv_Impl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute ); virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); ULONG MakeSfx( ByteString * pAtrrArray ); virtual void Insert( SvSlotElementList&, const ByteString & rPrefix, SvIdlDataBase& ); virtual void WriteHelpId( SvIdlDataBase & rBase, SvStream & rOutStm, Table * pIdTable ); virtual void WriteSrc( SvIdlDataBase & rBase, SvStream & rOutStm, Table * pIdTable ); virtual void WriteCSV( SvIdlDataBase&, SvStream& ); void FillIDTable(Table *pIDTable); ByteString Compare( SvMetaAttribute *pAttr ); #endif }; SV_IMPL_REF(SvMetaAttribute) SV_IMPL_PERSIST_LIST(SvMetaAttribute,SvMetaAttribute *) /******************** class SvType *********************************/ enum { CALL_VALUE, CALL_POINTER, CALL_REFERENCE }; enum { TYPE_METHOD, TYPE_STRUCT, TYPE_BASE, TYPE_ENUM, TYPE_UNION, TYPE_CLASS, TYPE_POINTER }; class SvMetaType : public SvMetaExtern { SvBOOL aIn; // Eingangsparameter SvBOOL aOut; // Returnparameter Svint aCall0, aCall1; Svint aSbxDataType; SvIdentifier aSvName; SvIdentifier aSbxName; SvIdentifier aOdlName; SvIdentifier aCName; SvIdentifier aBasicPostfix; SvIdentifier aBasicName; SvMetaAttributeMemberList * pAttrList; int nType; BOOL bIsItem; BOOL bIsShell; char cParserChar; #ifdef IDL_COMPILER void WriteSfx( const ByteString & rItemName, SvIdlDataBase & rBase, SvStream & rOutStm ); protected: BOOL ReadNamesSvIdl( SvIdlDataBase & rBase, SvTokenStream & rInStm ); virtual void ReadAttributesSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void ReadContextSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteContextSvIdl( SvIdlDataBase &, SvStream & rOutStm, USHORT nTab ); virtual void WriteContext( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); virtual void WriteAttributes( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); BOOL ReadHeaderSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); void WriteHeaderSvIdl( SvIdlDataBase &, SvStream & rOutStm, USHORT nTab ); #endif public: SV_DECL_META_FACTORY1( SvMetaType, SvMetaExtern, 18 ) SvMetaType(); SvMetaType( const ByteString & rTypeName, char cParserChar, const ByteString & rCName ); SvMetaType( const ByteString & rTypeName, const ByteString & rSbxName, const ByteString & rOdlName, char cParserChar, const ByteString & rCName, const ByteString & rBasicName, const ByteString & rBasicPostfix/*, SbxDataType nT = SbxEMPTY */); SvMetaAttributeMemberList & GetAttrList() const; ULONG GetAttrCount() const { return pAttrList ? pAttrList->Count() : 0L; } void AppendAttr( SvMetaAttribute * pAttr ) { GetAttrList().Append( pAttr ); } void SetType( int nT ); int GetType() const { return nType; } SvMetaType * GetBaseType() const; SvMetaType * GetReturnType() const; BOOL IsItem() const { return bIsItem; } BOOL IsShell() const { return bIsShell; } // void SetSbxDataType( SbxDataType nT ) // { aSbxDataType = (int)nT; } // SbxDataType GetSbxDataType() const; void SetIn( BOOL b ) { aIn = b; } BOOL GetIn() const; void SetOut( BOOL b ) { aOut = b; } BOOL GetOut() const; void SetCall0( int e ); int GetCall0() const; void SetCall1( int e); int GetCall1() const; void SetBasicName(const ByteString& rName) { aBasicName = rName; } const ByteString & GetBasicName() const; ByteString GetBasicPostfix() const; const ByteString & GetSvName() const; const ByteString & GetSbxName() const; const ByteString & GetOdlName() const; const ByteString & GetCName() const; char GetParserChar() const { return cParserChar; } virtual BOOL SetName( const ByteString & rName, SvIdlDataBase * = NULL ); // void FillSbxObject( SbxVariable * pObj, BOOL bVariable ); #ifdef IDL_COMPILER virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); ByteString GetCString() const; void WriteSvIdlType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); void WriteOdlType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); void AppendParserString (ByteString &rString); ULONG MakeSfx( ByteString * pAtrrArray ); virtual void WriteSfx( SvIdlDataBase & rBase, SvStream & rOutStm ); //BOOL ReadTypePrefix( SvIdlDataBase &, SvTokenStream & rInStm ); BOOL ReadMethodArgs( SvIdlDataBase & rBase, SvTokenStream & rInStm ); void WriteTypePrefix( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType ); void WriteMethodArgs( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType ); void WriteTheType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType ); ByteString GetParserString() const; void WriteParamNames( SvIdlDataBase & rBase, SvStream & rOutStm, const ByteString & rChief ); #endif }; SV_IMPL_REF(SvMetaType) DECLARE_LIST(SvMetaTypeList,SvMetaType *) SV_DECL_IMPL_PERSIST_LIST(SvMetaType,SvMetaType *) /******************** class SvTypeString *********************************/ class SvMetaTypeString : public SvMetaType { public: SV_DECL_META_FACTORY1( SvMetaTypeString, SvMetaType, 19 ) SvMetaTypeString(); }; SV_DECL_IMPL_REF(SvMetaTypeString) SV_DECL_IMPL_PERSIST_LIST(SvMetaTypeString,SvMetaTypeString *) /******************** class SvMetaEnumValue **********************************/ class SvMetaEnumValue : public SvMetaName { ByteString aEnumValue; public: SV_DECL_META_FACTORY1( SvMetaEnumValue, SvMetaName, 20 ) SvMetaEnumValue(); #ifdef IDL_COMPILER virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); #endif }; SV_DECL_IMPL_REF(SvMetaEnumValue) SV_DECL_IMPL_PERSIST_LIST(SvMetaEnumValue,SvMetaEnumValue *) /******************** class SvTypeEnum *********************************/ class SvMetaTypeEnum : public SvMetaType { SvMetaEnumValueMemberList aEnumValueList; ByteString aPrefix; protected: #ifdef IDL_COMPILER virtual void ReadContextSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteContextSvIdl( SvIdlDataBase &, SvStream & rOutStm, USHORT nTab ); virtual void WriteContext( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); #endif public: SV_DECL_META_FACTORY1( SvMetaTypeEnum, SvMetaType, 21 ) SvMetaTypeEnum(); USHORT GetMaxValue() const; ULONG Count() const { return aEnumValueList.Count(); } const ByteString & GetPrefix() const { return aPrefix; } SvMetaEnumValue * GetObject( ULONG n ) const { return aEnumValueList.GetObject( n ); } #ifdef IDL_COMPILER virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); #endif }; SV_DECL_IMPL_REF(SvMetaTypeEnum) SV_DECL_IMPL_PERSIST_LIST(SvMetaTypeEnum,SvMetaTypeEnum *) /******************** class SvTypeVoid ***********************************/ class SvMetaTypevoid : public SvMetaType { public: SV_DECL_META_FACTORY1( SvMetaTypevoid, SvMetaName, 22 ) SvMetaTypevoid(); }; SV_DECL_IMPL_REF(SvMetaTypevoid) SV_DECL_IMPL_PERSIST_LIST(SvMetaTypevoid,SvMetaTypevoid *) #endif // _TYPES_HXX <commit_msg>INTEGRATION: CWS warnings01 (1.2.8); FILE MERGED 2005/10/27 16:03:14 sb 1.2.8.1: #i53898# Made code warning-free.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: types.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2006-06-19 10:40:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TYPES_HXX #define _TYPES_HXX #include <tools/ref.hxx> #include <basobj.hxx> class SvSlotElementList; struct SvSlotElement; /******************** class SvMetaAttribute *****************************/ SV_DECL_REF(SvMetaType) SV_DECL_REF(SvMetaAttribute) SV_DECL_PERSIST_LIST(SvMetaAttribute,SvMetaAttribute *) class SvMetaAttribute : public SvMetaReference { SvMetaTypeRef aType; SvNumberIdentifier aSlotId; SvBOOL aAutomation; SvBOOL aExport; SvBOOL aReadonly; SvBOOL aIsCollection; SvBOOL aReadOnlyDoc; SvBOOL aHidden; BOOL bNewAttr; protected: #ifdef IDL_COMPILER virtual void WriteCSource( SvIdlDataBase & rBase, SvStream & rOutStm, BOOL bSet ); ULONG MakeSlotValue( SvIdlDataBase & rBase, BOOL bVariable ) const; virtual void WriteAttributes( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); virtual void ReadAttributesSvIdl( SvIdlDataBase & rBase, SvTokenStream & rInStm ); virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); #endif public: SV_DECL_META_FACTORY1( SvMetaAttribute, SvMetaReference, 2 ) SvMetaAttribute(); SvMetaAttribute( SvMetaType * ); void SetNewAttribute( BOOL bNew ) { bNewAttr = bNew; } BOOL IsNewAttribute() const { return bNewAttr; } BOOL GetReadonly() const; void SetSlotId( const SvNumberIdentifier & rId ) { aSlotId = rId; } const SvNumberIdentifier & GetSlotId() const; void SetExport( BOOL bSet ) { aExport = bSet; } BOOL GetExport() const; void SetHidden( BOOL bSet ) { aHidden = bSet; } BOOL GetHidden() const; void SetAutomation( BOOL bSet ) { aAutomation = bSet; } BOOL GetAutomation() const; void SetIsCollection( BOOL bSet ) { aIsCollection = bSet; } BOOL GetIsCollection() const; void SetReadOnlyDoc( BOOL bSet ) { aReadOnlyDoc = bSet; } BOOL GetReadOnlyDoc() const; void SetType( SvMetaType * pT ) { aType = pT; } SvMetaType * GetType() const; virtual BOOL IsMethod() const; virtual BOOL IsVariable() const; virtual ByteString GetMangleName( BOOL bVariable ) const; // void FillSbxObject( SbxInfo * pInfo, USHORT nSbxFlags = 0 ); // virtual void FillSbxObject( SvIdlDataBase & rBase, SbxObject * pObj, BOOL bVariable ); #ifdef IDL_COMPILER virtual BOOL Test( SvIdlDataBase &, SvTokenStream & rInStm ); virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void WriteParam( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType ); void WriteRecursiv_Impl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute ); virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); ULONG MakeSfx( ByteString * pAtrrArray ); virtual void Insert( SvSlotElementList&, const ByteString & rPrefix, SvIdlDataBase& ); virtual void WriteHelpId( SvIdlDataBase & rBase, SvStream & rOutStm, Table * pIdTable ); virtual void WriteSrc( SvIdlDataBase & rBase, SvStream & rOutStm, Table * pIdTable ); virtual void WriteCSV( SvIdlDataBase&, SvStream& ); void FillIDTable(Table *pIDTable); ByteString Compare( SvMetaAttribute *pAttr ); #endif }; SV_IMPL_REF(SvMetaAttribute) SV_IMPL_PERSIST_LIST(SvMetaAttribute,SvMetaAttribute *) /******************** class SvType *********************************/ enum { CALL_VALUE, CALL_POINTER, CALL_REFERENCE }; enum { TYPE_METHOD, TYPE_STRUCT, TYPE_BASE, TYPE_ENUM, TYPE_UNION, TYPE_CLASS, TYPE_POINTER }; class SvMetaType : public SvMetaExtern { SvBOOL aIn; // Eingangsparameter SvBOOL aOut; // Returnparameter Svint aCall0, aCall1; Svint aSbxDataType; SvIdentifier aSvName; SvIdentifier aSbxName; SvIdentifier aOdlName; SvIdentifier aCName; SvIdentifier aBasicPostfix; SvIdentifier aBasicName; SvMetaAttributeMemberList * pAttrList; int nType; BOOL bIsItem; BOOL bIsShell; char cParserChar; #ifdef IDL_COMPILER void WriteSfxItem( const ByteString & rItemName, SvIdlDataBase & rBase, SvStream & rOutStm ); protected: BOOL ReadNamesSvIdl( SvIdlDataBase & rBase, SvTokenStream & rInStm ); virtual void ReadAttributesSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void ReadContextSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteContextSvIdl( SvIdlDataBase &, SvStream & rOutStm, USHORT nTab ); virtual void WriteContext( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); virtual void WriteAttributes( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); BOOL ReadHeaderSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); void WriteHeaderSvIdl( SvIdlDataBase &, SvStream & rOutStm, USHORT nTab ); #endif public: SV_DECL_META_FACTORY1( SvMetaType, SvMetaExtern, 18 ) SvMetaType(); SvMetaType( const ByteString & rTypeName, char cParserChar, const ByteString & rCName ); SvMetaType( const ByteString & rTypeName, const ByteString & rSbxName, const ByteString & rOdlName, char cParserChar, const ByteString & rCName, const ByteString & rBasicName, const ByteString & rBasicPostfix/*, SbxDataType nT = SbxEMPTY */); SvMetaAttributeMemberList & GetAttrList() const; ULONG GetAttrCount() const { return pAttrList ? pAttrList->Count() : 0L; } void AppendAttr( SvMetaAttribute * pAttr ) { GetAttrList().Append( pAttr ); } void SetType( int nT ); int GetType() const { return nType; } SvMetaType * GetBaseType() const; SvMetaType * GetReturnType() const; BOOL IsItem() const { return bIsItem; } BOOL IsShell() const { return bIsShell; } // void SetSbxDataType( SbxDataType nT ) // { aSbxDataType = (int)nT; } // SbxDataType GetSbxDataType() const; void SetIn( BOOL b ) { aIn = b; } BOOL GetIn() const; void SetOut( BOOL b ) { aOut = b; } BOOL GetOut() const; void SetCall0( int e ); int GetCall0() const; void SetCall1( int e); int GetCall1() const; void SetBasicName(const ByteString& rName) { aBasicName = rName; } const ByteString & GetBasicName() const; ByteString GetBasicPostfix() const; const ByteString & GetSvName() const; const ByteString & GetSbxName() const; const ByteString & GetOdlName() const; const ByteString & GetCName() const; char GetParserChar() const { return cParserChar; } virtual BOOL SetName( const ByteString & rName, SvIdlDataBase * = NULL ); // void FillSbxObject( SbxVariable * pObj, BOOL bVariable ); #ifdef IDL_COMPILER virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); ByteString GetCString() const; void WriteSvIdlType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); void WriteOdlType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); void AppendParserString (ByteString &rString); ULONG MakeSfx( ByteString * pAtrrArray ); virtual void WriteSfx( SvIdlDataBase & rBase, SvStream & rOutStm ); //BOOL ReadTypePrefix( SvIdlDataBase &, SvTokenStream & rInStm ); BOOL ReadMethodArgs( SvIdlDataBase & rBase, SvTokenStream & rInStm ); void WriteTypePrefix( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType ); void WriteMethodArgs( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType ); void WriteTheType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType ); ByteString GetParserString() const; void WriteParamNames( SvIdlDataBase & rBase, SvStream & rOutStm, const ByteString & rChief ); #endif }; SV_IMPL_REF(SvMetaType) DECLARE_LIST(SvMetaTypeList,SvMetaType *) SV_DECL_IMPL_PERSIST_LIST(SvMetaType,SvMetaType *) /******************** class SvTypeString *********************************/ class SvMetaTypeString : public SvMetaType { public: SV_DECL_META_FACTORY1( SvMetaTypeString, SvMetaType, 19 ) SvMetaTypeString(); }; SV_DECL_IMPL_REF(SvMetaTypeString) SV_DECL_IMPL_PERSIST_LIST(SvMetaTypeString,SvMetaTypeString *) /******************** class SvMetaEnumValue **********************************/ class SvMetaEnumValue : public SvMetaName { ByteString aEnumValue; public: SV_DECL_META_FACTORY1( SvMetaEnumValue, SvMetaName, 20 ) SvMetaEnumValue(); #ifdef IDL_COMPILER virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); #endif }; SV_DECL_IMPL_REF(SvMetaEnumValue) SV_DECL_IMPL_PERSIST_LIST(SvMetaEnumValue,SvMetaEnumValue *) /******************** class SvTypeEnum *********************************/ class SvMetaTypeEnum : public SvMetaType { SvMetaEnumValueMemberList aEnumValueList; ByteString aPrefix; protected: #ifdef IDL_COMPILER virtual void ReadContextSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteContextSvIdl( SvIdlDataBase &, SvStream & rOutStm, USHORT nTab ); virtual void WriteContext( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); #endif public: SV_DECL_META_FACTORY1( SvMetaTypeEnum, SvMetaType, 21 ) SvMetaTypeEnum(); USHORT GetMaxValue() const; ULONG Count() const { return aEnumValueList.Count(); } const ByteString & GetPrefix() const { return aPrefix; } SvMetaEnumValue * GetObject( ULONG n ) const { return aEnumValueList.GetObject( n ); } #ifdef IDL_COMPILER virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm ); virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab ); virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType, WriteAttribute = 0 ); #endif }; SV_DECL_IMPL_REF(SvMetaTypeEnum) SV_DECL_IMPL_PERSIST_LIST(SvMetaTypeEnum,SvMetaTypeEnum *) /******************** class SvTypeVoid ***********************************/ class SvMetaTypevoid : public SvMetaType { public: SV_DECL_META_FACTORY1( SvMetaTypevoid, SvMetaName, 22 ) SvMetaTypevoid(); }; SV_DECL_IMPL_REF(SvMetaTypevoid) SV_DECL_IMPL_PERSIST_LIST(SvMetaTypevoid,SvMetaTypevoid *) #endif // _TYPES_HXX <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/shelf_layout_manager.h" #include "ash/launcher/launcher.h" #include "ash/screen_ash.h" #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/shell_window_ids.h" #include "ash/system/tray/system_tray.h" #include "ash/wm/workspace/workspace_manager.h" #include "base/auto_reset.h" #include "ui/aura/event.h" #include "ui/aura/event_filter.h" #include "ui/aura/root_window.h" #include "ui/gfx/compositor/layer.h" #include "ui/gfx/compositor/layer_animation_observer.h" #include "ui/gfx/compositor/layer_animator.h" #include "ui/gfx/compositor/scoped_layer_animation_settings.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { namespace { // Delay before showing/hiding the launcher after the mouse enters the launcher. const int kAutoHideDelayMS = 500; ui::Layer* GetLayer(views::Widget* widget) { return widget->GetNativeView()->layer(); } } // namespace // static const int ShelfLayoutManager::kWorkspaceAreaBottomInset = 2; // static const int ShelfLayoutManager::kAutoHideHeight = 2; // Notifies ShelfLayoutManager any time the mouse moves. class ShelfLayoutManager::AutoHideEventFilter : public aura::EventFilter { public: explicit AutoHideEventFilter(ShelfLayoutManager* shelf); virtual ~AutoHideEventFilter(); // Overridden from aura::EventFilter: virtual bool PreHandleKeyEvent(aura::Window* target, aura::KeyEvent* event) OVERRIDE; virtual bool PreHandleMouseEvent(aura::Window* target, aura::MouseEvent* event) OVERRIDE; virtual ui::TouchStatus PreHandleTouchEvent(aura::Window* target, aura::TouchEvent* event) OVERRIDE; virtual ui::GestureStatus PreHandleGestureEvent( aura::Window* target, aura::GestureEvent* event) OVERRIDE; private: ShelfLayoutManager* shelf_; DISALLOW_COPY_AND_ASSIGN(AutoHideEventFilter); }; ShelfLayoutManager::AutoHideEventFilter::AutoHideEventFilter( ShelfLayoutManager* shelf) : shelf_(shelf) { Shell::GetInstance()->AddRootWindowEventFilter(this); } ShelfLayoutManager::AutoHideEventFilter::~AutoHideEventFilter() { Shell::GetInstance()->RemoveRootWindowEventFilter(this); } bool ShelfLayoutManager::AutoHideEventFilter::PreHandleKeyEvent( aura::Window* target, aura::KeyEvent* event) { return false; // Always let the event propagate. } bool ShelfLayoutManager::AutoHideEventFilter::PreHandleMouseEvent( aura::Window* target, aura::MouseEvent* event) { if (event->type() == ui::ET_MOUSE_MOVED) shelf_->UpdateAutoHideState(); return false; // Not handled. } ui::TouchStatus ShelfLayoutManager::AutoHideEventFilter::PreHandleTouchEvent( aura::Window* target, aura::TouchEvent* event) { return ui::TOUCH_STATUS_UNKNOWN; // Not handled. } ui::GestureStatus ShelfLayoutManager::AutoHideEventFilter::PreHandleGestureEvent( aura::Window* target, aura::GestureEvent* event) { return ui::GESTURE_STATUS_UNKNOWN; // Not handled. } //////////////////////////////////////////////////////////////////////////////// // ShelfLayoutManager, public: ShelfLayoutManager::ShelfLayoutManager(views::Widget* status) : in_layout_(false), auto_hide_behavior_(SHELF_AUTO_HIDE_BEHAVIOR_DEFAULT), shelf_height_(status->GetWindowScreenBounds().height()), launcher_(NULL), status_(status), workspace_manager_(NULL), window_overlaps_shelf_(false) { } ShelfLayoutManager::~ShelfLayoutManager() { } void ShelfLayoutManager::SetAutoHideBehavior(ShelfAutoHideBehavior behavior) { if (auto_hide_behavior_ == behavior) return; auto_hide_behavior_ = behavior; UpdateVisibilityState(); } gfx::Rect ShelfLayoutManager::GetMaximizedWindowBounds( aura::Window* window) const { // TODO: needs to be multi-mon aware. gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(window)); if (auto_hide_behavior_ == SHELF_AUTO_HIDE_BEHAVIOR_DEFAULT || auto_hide_behavior_ == SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS) { bounds.set_height(bounds.height() - kAutoHideHeight); return bounds; } // SHELF_AUTO_HIDE_BEHAVIOR_NEVER maximized windows don't get any taller. return GetUnmaximizedWorkAreaBounds(window); } gfx::Rect ShelfLayoutManager::GetUnmaximizedWorkAreaBounds( aura::Window* window) const { // TODO: needs to be multi-mon aware. gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(window)); bounds.set_height(bounds.height() - shelf_height_); return bounds; } void ShelfLayoutManager::SetLauncher(Launcher* launcher) { if (launcher == launcher_) return; launcher_ = launcher; shelf_height_ = std::max(status_->GetWindowScreenBounds().height(), launcher_widget()->GetWindowScreenBounds().height()); LayoutShelf(); } void ShelfLayoutManager::LayoutShelf() { AutoReset<bool> auto_reset_in_layout(&in_layout_, true); StopAnimating(); TargetBounds target_bounds; CalculateTargetBounds(state_, &target_bounds); if (launcher_widget()) { GetLayer(launcher_widget())->SetOpacity(target_bounds.opacity); launcher_widget()->SetBounds(target_bounds.launcher_bounds); launcher_->SetStatusWidth( target_bounds.status_bounds.width()); } GetLayer(status_)->SetOpacity(target_bounds.opacity); status_->SetBounds(target_bounds.status_bounds); Shell::GetInstance()->SetMonitorWorkAreaInsets( Shell::GetRootWindow(), target_bounds.work_area_insets); UpdateHitTestBounds(); } void ShelfLayoutManager::UpdateVisibilityState() { ShellDelegate* delegate = Shell::GetInstance()->delegate(); if (delegate && delegate->IsScreenLocked()) { SetState(VISIBLE); } else { WorkspaceManager::WindowState window_state( workspace_manager_->GetWindowState()); switch (window_state) { case WorkspaceManager::WINDOW_STATE_FULL_SCREEN: SetState(HIDDEN); break; case WorkspaceManager::WINDOW_STATE_MAXIMIZED: SetState(auto_hide_behavior_ != SHELF_AUTO_HIDE_BEHAVIOR_NEVER ? AUTO_HIDE : VISIBLE); break; case WorkspaceManager::WINDOW_STATE_WINDOW_OVERLAPS_SHELF: case WorkspaceManager::WINDOW_STATE_DEFAULT: SetState(auto_hide_behavior_ == SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS ? AUTO_HIDE : VISIBLE); SetWindowOverlapsShelf(window_state == WorkspaceManager::WINDOW_STATE_WINDOW_OVERLAPS_SHELF); } } } void ShelfLayoutManager::UpdateAutoHideState() { if (CalculateAutoHideState(state_.visibility_state) != state_.auto_hide_state) { // Don't change state immediately. Instead delay for a bit. if (!auto_hide_timer_.IsRunning()) { auto_hide_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kAutoHideDelayMS), this, &ShelfLayoutManager::UpdateAutoHideStateNow); } } else { auto_hide_timer_.Stop(); } } void ShelfLayoutManager::SetWindowOverlapsShelf(bool value) { window_overlaps_shelf_ = value; UpdateShelfBackground(internal::BackgroundAnimator::CHANGE_ANIMATE); } //////////////////////////////////////////////////////////////////////////////// // ShelfLayoutManager, aura::LayoutManager implementation: void ShelfLayoutManager::OnWindowResized() { LayoutShelf(); } void ShelfLayoutManager::OnWindowAddedToLayout(aura::Window* child) { } void ShelfLayoutManager::OnWillRemoveWindowFromLayout(aura::Window* child) { } void ShelfLayoutManager::OnChildWindowVisibilityChanged(aura::Window* child, bool visible) { } void ShelfLayoutManager::SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) { SetChildBoundsDirect(child, requested_bounds); if (!in_layout_) LayoutShelf(); } //////////////////////////////////////////////////////////////////////////////// // ShelfLayoutManager, private: void ShelfLayoutManager::SetState(VisibilityState visibility_state) { State state; state.visibility_state = visibility_state; state.auto_hide_state = CalculateAutoHideState(visibility_state); if (state_.Equals(state)) return; // Nothing changed. if (state.visibility_state == AUTO_HIDE) { // When state is AUTO_HIDE we need to track when the mouse is over the // launcher to unhide the shelf. AutoHideEventFilter does that for us. if (!event_filter_.get()) event_filter_.reset(new AutoHideEventFilter(this)); } else { event_filter_.reset(NULL); } auto_hide_timer_.Stop(); // Animating the background when transitioning from auto-hide & hidden to // visibile is janking. Update the background immediately in this case. internal::BackgroundAnimator::ChangeType change_type = (state_.visibility_state == AUTO_HIDE && state_.auto_hide_state == AUTO_HIDE_HIDDEN && state.visibility_state == VISIBLE) ? internal::BackgroundAnimator::CHANGE_IMMEDIATE : internal::BackgroundAnimator::CHANGE_ANIMATE; StopAnimating(); state_ = state; TargetBounds target_bounds; CalculateTargetBounds(state_, &target_bounds); if (launcher_widget()) { ui::ScopedLayerAnimationSettings launcher_animation_setter( GetLayer(launcher_widget())->GetAnimator()); launcher_animation_setter.SetTransitionDuration( base::TimeDelta::FromMilliseconds(130)); launcher_animation_setter.SetTweenType(ui::Tween::EASE_OUT); GetLayer(launcher_widget())->SetBounds(target_bounds.launcher_bounds); GetLayer(launcher_widget())->SetOpacity(target_bounds.opacity); } ui::ScopedLayerAnimationSettings status_animation_setter( GetLayer(status_)->GetAnimator()); status_animation_setter.SetTransitionDuration( base::TimeDelta::FromMilliseconds(130)); status_animation_setter.SetTweenType(ui::Tween::EASE_OUT); GetLayer(status_)->SetBounds(target_bounds.status_bounds); GetLayer(status_)->SetOpacity(target_bounds.opacity); Shell::GetInstance()->SetMonitorWorkAreaInsets( Shell::GetRootWindow(), target_bounds.work_area_insets); UpdateHitTestBounds(); UpdateShelfBackground(change_type); } void ShelfLayoutManager::StopAnimating() { if (launcher_widget()) GetLayer(launcher_widget())->GetAnimator()->StopAnimating(); GetLayer(status_)->GetAnimator()->StopAnimating(); } void ShelfLayoutManager::CalculateTargetBounds( const State& state, TargetBounds* target_bounds) const { const gfx::Rect& available_bounds( status_->GetNativeView()->GetRootWindow()->bounds()); int y = available_bounds.bottom(); int shelf_height = 0; if (state.visibility_state == VISIBLE || (state.visibility_state == AUTO_HIDE && state.auto_hide_state == AUTO_HIDE_SHOWN)) shelf_height = shelf_height_; else if (state.visibility_state == AUTO_HIDE && state.auto_hide_state == AUTO_HIDE_HIDDEN) shelf_height = kAutoHideHeight; y -= shelf_height; gfx::Rect status_bounds(status_->GetWindowScreenBounds()); // The status widget should extend to the bottom and right edges. target_bounds->status_bounds = gfx::Rect( available_bounds.right() - status_bounds.width(), y + shelf_height_ - status_bounds.height(), status_bounds.width(), status_bounds.height()); if (launcher_widget()) { gfx::Rect launcher_bounds(launcher_widget()->GetWindowScreenBounds()); target_bounds->launcher_bounds = gfx::Rect( available_bounds.x(), y + (shelf_height_ - launcher_bounds.height()) / 2, available_bounds.width(), launcher_bounds.height()); } target_bounds->opacity = (state.visibility_state == VISIBLE || state.visibility_state == AUTO_HIDE) ? 1.0f : 0.0f; target_bounds->work_area_insets = gfx::Insets(0, 0, shelf_height, 0); } void ShelfLayoutManager::UpdateShelfBackground( BackgroundAnimator::ChangeType type) { bool launcher_paints = GetLauncherPaintsBackground(); if (launcher_) launcher_->SetPaintsBackground(launcher_paints, type); // SystemTray normally draws a background, but we don't want it to draw a // background when the launcher does. if (Shell::GetInstance()->tray()) Shell::GetInstance()->tray()->SetPaintsBackground(!launcher_paints, type); } bool ShelfLayoutManager::GetLauncherPaintsBackground() const { return window_overlaps_shelf_ || state_.visibility_state == AUTO_HIDE; } void ShelfLayoutManager::UpdateAutoHideStateNow() { SetState(state_.visibility_state); } ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->tray() && shell->tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; } void ShelfLayoutManager::UpdateHitTestBounds() { gfx::Insets insets; // Only modify the hit test when the shelf is visible, so we don't mess with // hover hit testing in the auto-hide state. if (state_.visibility_state == VISIBLE) { // Let clicks at the very top of the launcher through so windows can be // resized with the bottom-right corner and bottom edge. insets.Set(kWorkspaceAreaBottomInset, 0, 0, 0); } if (launcher_widget() && launcher_widget()->GetNativeWindow()) launcher_widget()->GetNativeWindow()->set_hit_test_bounds_override_outer( insets); status_->GetNativeWindow()->set_hit_test_bounds_override_outer(insets); } } // namespace internal } // namespace ash <commit_msg>Tweaks launcher auto-hide behavior so that we show after 200ms delay (after the mouse stops moving), but hide immediately.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/shelf_layout_manager.h" #include "ash/launcher/launcher.h" #include "ash/screen_ash.h" #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/shell_window_ids.h" #include "ash/system/tray/system_tray.h" #include "ash/wm/workspace/workspace_manager.h" #include "base/auto_reset.h" #include "ui/aura/event.h" #include "ui/aura/event_filter.h" #include "ui/aura/root_window.h" #include "ui/gfx/compositor/layer.h" #include "ui/gfx/compositor/layer_animation_observer.h" #include "ui/gfx/compositor/layer_animator.h" #include "ui/gfx/compositor/scoped_layer_animation_settings.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { namespace { // Delay before showing the launcher. This is after the mouse stops moving. const int kAutoHideDelayMS = 200; ui::Layer* GetLayer(views::Widget* widget) { return widget->GetNativeView()->layer(); } } // namespace // static const int ShelfLayoutManager::kWorkspaceAreaBottomInset = 2; // static const int ShelfLayoutManager::kAutoHideHeight = 2; // Notifies ShelfLayoutManager any time the mouse moves. class ShelfLayoutManager::AutoHideEventFilter : public aura::EventFilter { public: explicit AutoHideEventFilter(ShelfLayoutManager* shelf); virtual ~AutoHideEventFilter(); // Overridden from aura::EventFilter: virtual bool PreHandleKeyEvent(aura::Window* target, aura::KeyEvent* event) OVERRIDE; virtual bool PreHandleMouseEvent(aura::Window* target, aura::MouseEvent* event) OVERRIDE; virtual ui::TouchStatus PreHandleTouchEvent(aura::Window* target, aura::TouchEvent* event) OVERRIDE; virtual ui::GestureStatus PreHandleGestureEvent( aura::Window* target, aura::GestureEvent* event) OVERRIDE; private: ShelfLayoutManager* shelf_; DISALLOW_COPY_AND_ASSIGN(AutoHideEventFilter); }; ShelfLayoutManager::AutoHideEventFilter::AutoHideEventFilter( ShelfLayoutManager* shelf) : shelf_(shelf) { Shell::GetInstance()->AddRootWindowEventFilter(this); } ShelfLayoutManager::AutoHideEventFilter::~AutoHideEventFilter() { Shell::GetInstance()->RemoveRootWindowEventFilter(this); } bool ShelfLayoutManager::AutoHideEventFilter::PreHandleKeyEvent( aura::Window* target, aura::KeyEvent* event) { return false; // Always let the event propagate. } bool ShelfLayoutManager::AutoHideEventFilter::PreHandleMouseEvent( aura::Window* target, aura::MouseEvent* event) { if (event->type() == ui::ET_MOUSE_MOVED) shelf_->UpdateAutoHideState(); return false; // Not handled. } ui::TouchStatus ShelfLayoutManager::AutoHideEventFilter::PreHandleTouchEvent( aura::Window* target, aura::TouchEvent* event) { return ui::TOUCH_STATUS_UNKNOWN; // Not handled. } ui::GestureStatus ShelfLayoutManager::AutoHideEventFilter::PreHandleGestureEvent( aura::Window* target, aura::GestureEvent* event) { return ui::GESTURE_STATUS_UNKNOWN; // Not handled. } //////////////////////////////////////////////////////////////////////////////// // ShelfLayoutManager, public: ShelfLayoutManager::ShelfLayoutManager(views::Widget* status) : in_layout_(false), auto_hide_behavior_(SHELF_AUTO_HIDE_BEHAVIOR_DEFAULT), shelf_height_(status->GetWindowScreenBounds().height()), launcher_(NULL), status_(status), workspace_manager_(NULL), window_overlaps_shelf_(false) { } ShelfLayoutManager::~ShelfLayoutManager() { } void ShelfLayoutManager::SetAutoHideBehavior(ShelfAutoHideBehavior behavior) { if (auto_hide_behavior_ == behavior) return; auto_hide_behavior_ = behavior; UpdateVisibilityState(); } gfx::Rect ShelfLayoutManager::GetMaximizedWindowBounds( aura::Window* window) const { // TODO: needs to be multi-mon aware. gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(window)); if (auto_hide_behavior_ == SHELF_AUTO_HIDE_BEHAVIOR_DEFAULT || auto_hide_behavior_ == SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS) { bounds.set_height(bounds.height() - kAutoHideHeight); return bounds; } // SHELF_AUTO_HIDE_BEHAVIOR_NEVER maximized windows don't get any taller. return GetUnmaximizedWorkAreaBounds(window); } gfx::Rect ShelfLayoutManager::GetUnmaximizedWorkAreaBounds( aura::Window* window) const { // TODO: needs to be multi-mon aware. gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(window)); bounds.set_height(bounds.height() - shelf_height_); return bounds; } void ShelfLayoutManager::SetLauncher(Launcher* launcher) { if (launcher == launcher_) return; launcher_ = launcher; shelf_height_ = std::max(status_->GetWindowScreenBounds().height(), launcher_widget()->GetWindowScreenBounds().height()); LayoutShelf(); } void ShelfLayoutManager::LayoutShelf() { AutoReset<bool> auto_reset_in_layout(&in_layout_, true); StopAnimating(); TargetBounds target_bounds; CalculateTargetBounds(state_, &target_bounds); if (launcher_widget()) { GetLayer(launcher_widget())->SetOpacity(target_bounds.opacity); launcher_widget()->SetBounds(target_bounds.launcher_bounds); launcher_->SetStatusWidth( target_bounds.status_bounds.width()); } GetLayer(status_)->SetOpacity(target_bounds.opacity); status_->SetBounds(target_bounds.status_bounds); Shell::GetInstance()->SetMonitorWorkAreaInsets( Shell::GetRootWindow(), target_bounds.work_area_insets); UpdateHitTestBounds(); } void ShelfLayoutManager::UpdateVisibilityState() { ShellDelegate* delegate = Shell::GetInstance()->delegate(); if (delegate && delegate->IsScreenLocked()) { SetState(VISIBLE); } else { WorkspaceManager::WindowState window_state( workspace_manager_->GetWindowState()); switch (window_state) { case WorkspaceManager::WINDOW_STATE_FULL_SCREEN: SetState(HIDDEN); break; case WorkspaceManager::WINDOW_STATE_MAXIMIZED: SetState(auto_hide_behavior_ != SHELF_AUTO_HIDE_BEHAVIOR_NEVER ? AUTO_HIDE : VISIBLE); break; case WorkspaceManager::WINDOW_STATE_WINDOW_OVERLAPS_SHELF: case WorkspaceManager::WINDOW_STATE_DEFAULT: SetState(auto_hide_behavior_ == SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS ? AUTO_HIDE : VISIBLE); SetWindowOverlapsShelf(window_state == WorkspaceManager::WINDOW_STATE_WINDOW_OVERLAPS_SHELF); } } } void ShelfLayoutManager::UpdateAutoHideState() { AutoHideState auto_hide_state = CalculateAutoHideState(state_.visibility_state); if (auto_hide_state != state_.auto_hide_state) { if (auto_hide_state == AUTO_HIDE_HIDDEN) { // Hides happen immediately. SetState(state_.visibility_state); } else { auto_hide_timer_.Stop(); auto_hide_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kAutoHideDelayMS), this, &ShelfLayoutManager::UpdateAutoHideStateNow); } } else { auto_hide_timer_.Stop(); } } void ShelfLayoutManager::SetWindowOverlapsShelf(bool value) { window_overlaps_shelf_ = value; UpdateShelfBackground(internal::BackgroundAnimator::CHANGE_ANIMATE); } //////////////////////////////////////////////////////////////////////////////// // ShelfLayoutManager, aura::LayoutManager implementation: void ShelfLayoutManager::OnWindowResized() { LayoutShelf(); } void ShelfLayoutManager::OnWindowAddedToLayout(aura::Window* child) { } void ShelfLayoutManager::OnWillRemoveWindowFromLayout(aura::Window* child) { } void ShelfLayoutManager::OnChildWindowVisibilityChanged(aura::Window* child, bool visible) { } void ShelfLayoutManager::SetChildBounds(aura::Window* child, const gfx::Rect& requested_bounds) { SetChildBoundsDirect(child, requested_bounds); if (!in_layout_) LayoutShelf(); } //////////////////////////////////////////////////////////////////////////////// // ShelfLayoutManager, private: void ShelfLayoutManager::SetState(VisibilityState visibility_state) { State state; state.visibility_state = visibility_state; state.auto_hide_state = CalculateAutoHideState(visibility_state); if (state_.Equals(state)) return; // Nothing changed. if (state.visibility_state == AUTO_HIDE) { // When state is AUTO_HIDE we need to track when the mouse is over the // launcher to unhide the shelf. AutoHideEventFilter does that for us. if (!event_filter_.get()) event_filter_.reset(new AutoHideEventFilter(this)); } else { event_filter_.reset(NULL); } auto_hide_timer_.Stop(); // Animating the background when transitioning from auto-hide & hidden to // visibile is janking. Update the background immediately in this case. internal::BackgroundAnimator::ChangeType change_type = (state_.visibility_state == AUTO_HIDE && state_.auto_hide_state == AUTO_HIDE_HIDDEN && state.visibility_state == VISIBLE) ? internal::BackgroundAnimator::CHANGE_IMMEDIATE : internal::BackgroundAnimator::CHANGE_ANIMATE; StopAnimating(); state_ = state; TargetBounds target_bounds; CalculateTargetBounds(state_, &target_bounds); if (launcher_widget()) { ui::ScopedLayerAnimationSettings launcher_animation_setter( GetLayer(launcher_widget())->GetAnimator()); launcher_animation_setter.SetTransitionDuration( base::TimeDelta::FromMilliseconds(130)); launcher_animation_setter.SetTweenType(ui::Tween::EASE_OUT); GetLayer(launcher_widget())->SetBounds(target_bounds.launcher_bounds); GetLayer(launcher_widget())->SetOpacity(target_bounds.opacity); } ui::ScopedLayerAnimationSettings status_animation_setter( GetLayer(status_)->GetAnimator()); status_animation_setter.SetTransitionDuration( base::TimeDelta::FromMilliseconds(130)); status_animation_setter.SetTweenType(ui::Tween::EASE_OUT); GetLayer(status_)->SetBounds(target_bounds.status_bounds); GetLayer(status_)->SetOpacity(target_bounds.opacity); Shell::GetInstance()->SetMonitorWorkAreaInsets( Shell::GetRootWindow(), target_bounds.work_area_insets); UpdateHitTestBounds(); UpdateShelfBackground(change_type); } void ShelfLayoutManager::StopAnimating() { if (launcher_widget()) GetLayer(launcher_widget())->GetAnimator()->StopAnimating(); GetLayer(status_)->GetAnimator()->StopAnimating(); } void ShelfLayoutManager::CalculateTargetBounds( const State& state, TargetBounds* target_bounds) const { const gfx::Rect& available_bounds( status_->GetNativeView()->GetRootWindow()->bounds()); int y = available_bounds.bottom(); int shelf_height = 0; if (state.visibility_state == VISIBLE || (state.visibility_state == AUTO_HIDE && state.auto_hide_state == AUTO_HIDE_SHOWN)) shelf_height = shelf_height_; else if (state.visibility_state == AUTO_HIDE && state.auto_hide_state == AUTO_HIDE_HIDDEN) shelf_height = kAutoHideHeight; y -= shelf_height; gfx::Rect status_bounds(status_->GetWindowScreenBounds()); // The status widget should extend to the bottom and right edges. target_bounds->status_bounds = gfx::Rect( available_bounds.right() - status_bounds.width(), y + shelf_height_ - status_bounds.height(), status_bounds.width(), status_bounds.height()); if (launcher_widget()) { gfx::Rect launcher_bounds(launcher_widget()->GetWindowScreenBounds()); target_bounds->launcher_bounds = gfx::Rect( available_bounds.x(), y + (shelf_height_ - launcher_bounds.height()) / 2, available_bounds.width(), launcher_bounds.height()); } target_bounds->opacity = (state.visibility_state == VISIBLE || state.visibility_state == AUTO_HIDE) ? 1.0f : 0.0f; target_bounds->work_area_insets = gfx::Insets(0, 0, shelf_height, 0); } void ShelfLayoutManager::UpdateShelfBackground( BackgroundAnimator::ChangeType type) { bool launcher_paints = GetLauncherPaintsBackground(); if (launcher_) launcher_->SetPaintsBackground(launcher_paints, type); // SystemTray normally draws a background, but we don't want it to draw a // background when the launcher does. if (Shell::GetInstance()->tray()) Shell::GetInstance()->tray()->SetPaintsBackground(!launcher_paints, type); } bool ShelfLayoutManager::GetLauncherPaintsBackground() const { return window_overlaps_shelf_ || state_.visibility_state == AUTO_HIDE; } void ShelfLayoutManager::UpdateAutoHideStateNow() { SetState(state_.visibility_state); } ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->tray() && shell->tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; } void ShelfLayoutManager::UpdateHitTestBounds() { gfx::Insets insets; // Only modify the hit test when the shelf is visible, so we don't mess with // hover hit testing in the auto-hide state. if (state_.visibility_state == VISIBLE) { // Let clicks at the very top of the launcher through so windows can be // resized with the bottom-right corner and bottom edge. insets.Set(kWorkspaceAreaBottomInset, 0, 0, 0); } if (launcher_widget() && launcher_widget()->GetNativeWindow()) launcher_widget()->GetNativeWindow()->set_hit_test_bounds_override_outer( insets); status_->GetNativeWindow()->set_hit_test_bounds_override_outer(insets); } } // namespace internal } // namespace ash <|endoftext|>
<commit_before>// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/metro_viewer/chrome_metro_viewer_process_host_aurawin.h" #include "ash/shell.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part_aurawin.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search_engines/util.h" #include "chrome/browser/ui/ash/ash_init.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/env_vars.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/web_contents.h" #include "ui/aura/remote_root_window_host_win.h" #include "ui/surface/accelerated_surface_win.h" #include "url/gurl.h" namespace { void CloseOpenAshBrowsers() { BrowserList* browser_list = BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH); if (browser_list) { for (BrowserList::const_iterator i = browser_list->begin(); i != browser_list->end(); ++i) { Browser* browser = *i; browser->window()->Close(); // If the attempt to Close the browser fails due to unload handlers on // the page or in progress downloads, etc, destroy all tabs on the page. while (browser->tab_strip_model()->count()) delete browser->tab_strip_model()->GetWebContentsAt(0); } } } void OpenURL(const GURL& url) { chrome::NavigateParams params( ProfileManager::GetDefaultProfileOrOffTheRecord(), GURL(url), content::PAGE_TRANSITION_TYPED); params.disposition = NEW_FOREGROUND_TAB; params.host_desktop_type = chrome::HOST_DESKTOP_TYPE_ASH; chrome::Navigate(&params); } } // namespace ChromeMetroViewerProcessHost::ChromeMetroViewerProcessHost() : MetroViewerProcessHost( content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::IO)) { g_browser_process->AddRefModule(); } void ChromeMetroViewerProcessHost::OnChannelError() { // TODO(cpu): At some point we only close the browser. Right now this // is very convenient for developing. DLOG(INFO) << "viewer channel error : Quitting browser"; // Unset environment variable to let breakpad know that metro process wasn't // connected. ::SetEnvironmentVariableA(env_vars::kMetroConnected, NULL); aura::RemoteRootWindowHostWin::Instance()->Disconnected(); g_browser_process->ReleaseModule(); CloseOpenAshBrowsers(); chrome::CloseAsh(); // Tell the rest of Chrome about it. content::NotificationService::current()->Notify( chrome::NOTIFICATION_ASH_SESSION_ENDED, content::NotificationService::AllSources(), content::NotificationService::NoDetails()); // This will delete the MetroViewerProcessHost object. Don't access member // variables/functions after this call. g_browser_process->platform_part()->OnMetroViewerProcessTerminated(); } void ChromeMetroViewerProcessHost::OnChannelConnected(int32 /*peer_pid*/) { DLOG(INFO) << "ChromeMetroViewerProcessHost::OnChannelConnected: "; // Set environment variable to let breakpad know that metro process was // connected. ::SetEnvironmentVariableA(env_vars::kMetroConnected, "1"); } void ChromeMetroViewerProcessHost::OnSetTargetSurface( gfx::NativeViewId target_surface) { HWND hwnd = reinterpret_cast<HWND>(target_surface); // Tell our root window host that the viewer has connected. aura::RemoteRootWindowHostWin::Instance()->Connected(this, hwnd); // Now start the Ash shell environment. chrome::OpenAsh(); ash::Shell::GetInstance()->CreateLauncher(); ash::Shell::GetInstance()->ShowLauncher(); // Tell the rest of Chrome that Ash is running. content::NotificationService::current()->Notify( chrome::NOTIFICATION_ASH_SESSION_STARTED, content::NotificationService::AllSources(), content::NotificationService::NoDetails()); } void ChromeMetroViewerProcessHost::OnOpenURL(const string16& url) { OpenURL(GURL(url)); } void ChromeMetroViewerProcessHost::OnHandleSearchRequest( const string16& search_string) { GURL url(GetDefaultSearchURLForSearchTerms( ProfileManager::GetDefaultProfileOrOffTheRecord(), search_string)); if (url.is_valid()) OpenURL(url); } <commit_msg>Restart in Desktop if Metro tries to start up without GPU<commit_after>// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/metro_viewer/chrome_metro_viewer_process_host_aurawin.h" #include "ash/shell.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part_aurawin.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search_engines/util.h" #include "chrome/browser/ui/ash/ash_init.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/env_vars.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/web_contents.h" #include "ui/aura/remote_root_window_host_win.h" #include "ui/surface/accelerated_surface_win.h" #include "url/gurl.h" namespace { void CloseOpenAshBrowsers() { BrowserList* browser_list = BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH); if (browser_list) { for (BrowserList::const_iterator i = browser_list->begin(); i != browser_list->end(); ++i) { Browser* browser = *i; browser->window()->Close(); // If the attempt to Close the browser fails due to unload handlers on // the page or in progress downloads, etc, destroy all tabs on the page. while (browser->tab_strip_model()->count()) delete browser->tab_strip_model()->GetWebContentsAt(0); } } } void OpenURL(const GURL& url) { chrome::NavigateParams params( ProfileManager::GetDefaultProfileOrOffTheRecord(), GURL(url), content::PAGE_TRANSITION_TYPED); params.disposition = NEW_FOREGROUND_TAB; params.host_desktop_type = chrome::HOST_DESKTOP_TYPE_ASH; chrome::Navigate(&params); } } // namespace ChromeMetroViewerProcessHost::ChromeMetroViewerProcessHost() : MetroViewerProcessHost( content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::IO)) { g_browser_process->AddRefModule(); } void ChromeMetroViewerProcessHost::OnChannelError() { // TODO(cpu): At some point we only close the browser. Right now this // is very convenient for developing. DLOG(INFO) << "viewer channel error : Quitting browser"; // Unset environment variable to let breakpad know that metro process wasn't // connected. ::SetEnvironmentVariableA(env_vars::kMetroConnected, NULL); aura::RemoteRootWindowHostWin::Instance()->Disconnected(); g_browser_process->ReleaseModule(); CloseOpenAshBrowsers(); chrome::CloseAsh(); // Tell the rest of Chrome about it. content::NotificationService::current()->Notify( chrome::NOTIFICATION_ASH_SESSION_ENDED, content::NotificationService::AllSources(), content::NotificationService::NoDetails()); // This will delete the MetroViewerProcessHost object. Don't access member // variables/functions after this call. g_browser_process->platform_part()->OnMetroViewerProcessTerminated(); } void ChromeMetroViewerProcessHost::OnChannelConnected(int32 /*peer_pid*/) { DLOG(INFO) << "ChromeMetroViewerProcessHost::OnChannelConnected: "; // Set environment variable to let breakpad know that metro process was // connected. ::SetEnvironmentVariableA(env_vars::kMetroConnected, "1"); if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL)) { DLOG(INFO) << "No GPU access, attempting to restart in Desktop\n"; chrome::AttemptRestartToDesktopMode(); } } void ChromeMetroViewerProcessHost::OnSetTargetSurface( gfx::NativeViewId target_surface) { HWND hwnd = reinterpret_cast<HWND>(target_surface); // Tell our root window host that the viewer has connected. aura::RemoteRootWindowHostWin::Instance()->Connected(this, hwnd); // Now start the Ash shell environment. chrome::OpenAsh(); ash::Shell::GetInstance()->CreateLauncher(); ash::Shell::GetInstance()->ShowLauncher(); // Tell the rest of Chrome that Ash is running. content::NotificationService::current()->Notify( chrome::NOTIFICATION_ASH_SESSION_STARTED, content::NotificationService::AllSources(), content::NotificationService::NoDetails()); } void ChromeMetroViewerProcessHost::OnOpenURL(const string16& url) { OpenURL(GURL(url)); } void ChromeMetroViewerProcessHost::OnHandleSearchRequest( const string16& search_string) { GURL url(GetDefaultSearchURLForSearchTerms( ProfileManager::GetDefaultProfileOrOffTheRecord(), search_string)); if (url.is_valid()) OpenURL(url); } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/notification_conversion_helper.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/notifications/notification_test_util.h" #include "chrome/common/extensions/api/notifications.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/message_center/notification.h" #include "ui/message_center/notification_types.h" #include "url/gurl.h" class NotificationConversionHelperTest : public testing::Test { public: NotificationConversionHelperTest() {} virtual void SetUp() OVERRIDE {} virtual void TearDown() OVERRIDE {} protected: scoped_ptr<Notification> CreateNotification( message_center::NotificationType type) { message_center::RichNotificationData optional_fields; optional_fields.priority = 1; optional_fields.context_message = base::UTF8ToUTF16("I am a context message."); optional_fields.timestamp = base::Time::FromDoubleT(12345678.9); optional_fields.buttons.push_back( message_center::ButtonInfo(base::UTF8ToUTF16("Button 1"))); optional_fields.buttons.push_back( message_center::ButtonInfo(base::UTF8ToUTF16("Button 2"))); optional_fields.clickable = false; if (type == message_center::NOTIFICATION_TYPE_IMAGE) optional_fields.image = gfx::Image(); if (type == message_center::NOTIFICATION_TYPE_MULTIPLE) { optional_fields.items.push_back(message_center::NotificationItem( base::UTF8ToUTF16("Item 1 Title"), base::UTF8ToUTF16("Item 1 Message"))); optional_fields.items.push_back(message_center::NotificationItem( base::UTF8ToUTF16("Item 2 Title"), base::UTF8ToUTF16("Item 2 Message"))); } if (type == message_center::NOTIFICATION_TYPE_PROGRESS) optional_fields.progress = 50; NotificationDelegate* delegate(new MockNotificationDelegate("id1")); SkBitmap bitmap; bitmap.allocN32Pixels(1, 1); bitmap.eraseColor(SkColorSetRGB(1, 2, 3)); gfx::Image icon = gfx::Image::CreateFrom1xBitmap(bitmap); scoped_ptr<Notification> notification(new Notification( type, GURL(), base::UTF8ToUTF16("Title"), base::UTF8ToUTF16("This is a message."), icon, blink::WebTextDirectionDefault, message_center::NotifierId(message_center::NotifierId::APPLICATION, "Notifier 1"), base::UTF8ToUTF16("Notifier's Name"), base::UTF8ToUTF16("id1"), optional_fields, delegate)); return notification.Pass(); } private: DISALLOW_COPY_AND_ASSIGN(NotificationConversionHelperTest); }; // TODO(liyanhou): This test is disabled due to memory leaks. Fix and re-enable. // http://crbug.com/403759 TEST_F(NotificationConversionHelperTest, DISABLED_NotificationToNotificationOptions) { // Create a notification of image type scoped_ptr<Notification> notification1 = CreateNotification(message_center::NOTIFICATION_TYPE_IMAGE); scoped_ptr<extensions::api::notifications::NotificationOptions> options1( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification1), options1.get()); EXPECT_EQ(options1->type, extensions::api::notifications::TEMPLATE_TYPE_IMAGE); EXPECT_EQ(*(options1->title), "Title"); EXPECT_EQ(*(options1->message), "This is a message."); EXPECT_EQ(*(options1->priority), 1); EXPECT_EQ(*(options1->context_message), "I am a context message."); EXPECT_FALSE(*(options1->is_clickable)); EXPECT_EQ(*(options1->event_time), 12345678.9); EXPECT_EQ(options1->buttons->at(0)->title, "Button 1"); EXPECT_EQ(options1->buttons->at(1)->title, "Button 2"); EXPECT_EQ(options1->icon_bitmap->width, 1); EXPECT_EQ(options1->icon_bitmap->height, 1); // Create a notification of progress type scoped_ptr<Notification> notification2 = CreateNotification(message_center::NOTIFICATION_TYPE_PROGRESS); scoped_ptr<extensions::api::notifications::NotificationOptions> options2( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification2), options2.get()); EXPECT_EQ(options2->type, extensions::api::notifications::TEMPLATE_TYPE_PROGRESS); EXPECT_EQ(*(options2->progress), 50); // Create a notification of multiple type scoped_ptr<Notification> notification3 = CreateNotification(message_center::NOTIFICATION_TYPE_MULTIPLE); scoped_ptr<extensions::api::notifications::NotificationOptions> options3( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification3), options3.get()); EXPECT_EQ(options3->type, extensions::api::notifications::TEMPLATE_TYPE_LIST); EXPECT_EQ(options3->items->at(0)->title, "Item 1 Title"); EXPECT_EQ(options3->items->at(0)->message, "Item 1 Message"); EXPECT_EQ(options3->items->at(1)->title, "Item 2 Title"); EXPECT_EQ(options3->items->at(1)->message, "Item 2 Message"); } <commit_msg>Revert 289542 "Disable leaky NotificationToNotificationOptions"<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/notification_conversion_helper.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/notifications/notification_test_util.h" #include "chrome/common/extensions/api/notifications.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/message_center/notification.h" #include "ui/message_center/notification_types.h" #include "url/gurl.h" class NotificationConversionHelperTest : public testing::Test { public: NotificationConversionHelperTest() {} virtual void SetUp() OVERRIDE {} virtual void TearDown() OVERRIDE {} protected: scoped_ptr<Notification> CreateNotification( message_center::NotificationType type) { message_center::RichNotificationData optional_fields; optional_fields.priority = 1; optional_fields.context_message = base::UTF8ToUTF16("I am a context message."); optional_fields.timestamp = base::Time::FromDoubleT(12345678.9); optional_fields.buttons.push_back( message_center::ButtonInfo(base::UTF8ToUTF16("Button 1"))); optional_fields.buttons.push_back( message_center::ButtonInfo(base::UTF8ToUTF16("Button 2"))); optional_fields.clickable = false; if (type == message_center::NOTIFICATION_TYPE_IMAGE) optional_fields.image = gfx::Image(); if (type == message_center::NOTIFICATION_TYPE_MULTIPLE) { optional_fields.items.push_back(message_center::NotificationItem( base::UTF8ToUTF16("Item 1 Title"), base::UTF8ToUTF16("Item 1 Message"))); optional_fields.items.push_back(message_center::NotificationItem( base::UTF8ToUTF16("Item 2 Title"), base::UTF8ToUTF16("Item 2 Message"))); } if (type == message_center::NOTIFICATION_TYPE_PROGRESS) optional_fields.progress = 50; NotificationDelegate* delegate(new MockNotificationDelegate("id1")); SkBitmap bitmap; bitmap.allocN32Pixels(1, 1); bitmap.eraseColor(SkColorSetRGB(1, 2, 3)); gfx::Image icon = gfx::Image::CreateFrom1xBitmap(bitmap); scoped_ptr<Notification> notification(new Notification( type, GURL(), base::UTF8ToUTF16("Title"), base::UTF8ToUTF16("This is a message."), icon, blink::WebTextDirectionDefault, message_center::NotifierId(message_center::NotifierId::APPLICATION, "Notifier 1"), base::UTF8ToUTF16("Notifier's Name"), base::UTF8ToUTF16("id1"), optional_fields, delegate)); return notification.Pass(); } private: DISALLOW_COPY_AND_ASSIGN(NotificationConversionHelperTest); }; TEST_F(NotificationConversionHelperTest, NotificationToNotificationOptions) { // Create a notification of image type scoped_ptr<Notification> notification1 = CreateNotification(message_center::NOTIFICATION_TYPE_IMAGE); scoped_ptr<extensions::api::notifications::NotificationOptions> options1( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification1), options1.get()); EXPECT_EQ(options1->type, extensions::api::notifications::TEMPLATE_TYPE_IMAGE); EXPECT_EQ(*(options1->title), "Title"); EXPECT_EQ(*(options1->message), "This is a message."); EXPECT_EQ(*(options1->priority), 1); EXPECT_EQ(*(options1->context_message), "I am a context message."); EXPECT_FALSE(*(options1->is_clickable)); EXPECT_EQ(*(options1->event_time), 12345678.9); EXPECT_EQ(options1->buttons->at(0)->title, "Button 1"); EXPECT_EQ(options1->buttons->at(1)->title, "Button 2"); EXPECT_EQ(options1->icon_bitmap->width, 1); EXPECT_EQ(options1->icon_bitmap->height, 1); // Create a notification of progress type scoped_ptr<Notification> notification2 = CreateNotification(message_center::NOTIFICATION_TYPE_PROGRESS); scoped_ptr<extensions::api::notifications::NotificationOptions> options2( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification2), options2.get()); EXPECT_EQ(options2->type, extensions::api::notifications::TEMPLATE_TYPE_PROGRESS); EXPECT_EQ(*(options2->progress), 50); // Create a notification of multiple type scoped_ptr<Notification> notification3 = CreateNotification(message_center::NOTIFICATION_TYPE_MULTIPLE); scoped_ptr<extensions::api::notifications::NotificationOptions> options3( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification3), options3.get()); EXPECT_EQ(options3->type, extensions::api::notifications::TEMPLATE_TYPE_LIST); EXPECT_EQ(options3->items->at(0)->title, "Item 1 Title"); EXPECT_EQ(options3->items->at(0)->message, "Item 1 Message"); EXPECT_EQ(options3->items->at(1)->title, "Item 2 Title"); EXPECT_EQ(options3->items->at(1)->message, "Item 2 Message"); } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/autofill/password_generation_popup_controller_impl.h" #include <math.h> #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversion_utils.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/autofill/password_generation_popup_observer.h" #include "chrome/browser/ui/autofill/password_generation_popup_view.h" #include "chrome/browser/ui/autofill/popup_constants.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/common/url_constants.h" #include "components/autofill/content/common/autofill_messages.h" #include "components/autofill/core/browser/password_generator.h" #include "components/password_manager/core/browser/password_manager.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/google_chrome_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/rect_conversions.h" #include "ui/gfx/text_utils.h" namespace autofill { base::WeakPtr<PasswordGenerationPopupControllerImpl> PasswordGenerationPopupControllerImpl::GetOrCreate( base::WeakPtr<PasswordGenerationPopupControllerImpl> previous, const gfx::RectF& bounds, const PasswordForm& form, int max_length, password_manager::PasswordManager* password_manager, PasswordGenerationPopupObserver* observer, content::WebContents* web_contents, gfx::NativeView container_view) { if (previous.get() && previous->element_bounds() == bounds && previous->web_contents() == web_contents && previous->container_view() == container_view) { return previous; } if (previous.get()) previous->Hide(); PasswordGenerationPopupControllerImpl* controller = new PasswordGenerationPopupControllerImpl( bounds, form, max_length, password_manager, observer, web_contents, container_view); return controller->GetWeakPtr(); } PasswordGenerationPopupControllerImpl::PasswordGenerationPopupControllerImpl( const gfx::RectF& bounds, const PasswordForm& form, int max_length, password_manager::PasswordManager* password_manager, PasswordGenerationPopupObserver* observer, content::WebContents* web_contents, gfx::NativeView container_view) : form_(form), password_manager_(password_manager), observer_(observer), generator_(new PasswordGenerator(max_length)), controller_common_(bounds, container_view, web_contents), view_(NULL), font_list_(ResourceBundle::GetSharedInstance().GetFontList( ResourceBundle::SmallFont)), password_selected_(false), display_password_(false), weak_ptr_factory_(this) { controller_common_.SetKeyPressCallback( base::Bind(&PasswordGenerationPopupControllerImpl::HandleKeyPressEvent, base::Unretained(this))); std::vector<base::string16> pieces; base::SplitStringDontTrim( l10n_util::GetStringUTF16(IDS_PASSWORD_GENERATION_PROMPT), '|', // separator &pieces); DCHECK_EQ(3u, pieces.size()); link_range_ = gfx::Range(pieces[0].size(), pieces[0].size() + pieces[1].size()); help_text_ = JoinString(pieces, base::string16()); } PasswordGenerationPopupControllerImpl::~PasswordGenerationPopupControllerImpl() {} base::WeakPtr<PasswordGenerationPopupControllerImpl> PasswordGenerationPopupControllerImpl::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } bool PasswordGenerationPopupControllerImpl::HandleKeyPressEvent( const content::NativeWebKeyboardEvent& event) { switch (event.windowsKeyCode) { case ui::VKEY_UP: case ui::VKEY_DOWN: PasswordSelected(true); return true; case ui::VKEY_ESCAPE: Hide(); return true; case ui::VKEY_RETURN: case ui::VKEY_TAB: // We suppress tab if the password is selected because we will // automatically advance focus anyway. return PossiblyAcceptPassword(); default: return false; } } bool PasswordGenerationPopupControllerImpl::PossiblyAcceptPassword() { if (password_selected_) { PasswordAccepted(); // This will delete |this|. return true; } return false; } void PasswordGenerationPopupControllerImpl::PasswordSelected(bool selected) { if (!display_password_ || selected == password_selected_) return; password_selected_ = selected; view_->PasswordSelectionUpdated(); view_->UpdateBoundsAndRedrawPopup(); } void PasswordGenerationPopupControllerImpl::PasswordAccepted() { if (!display_password_) return; web_contents()->GetRenderViewHost()->Send( new AutofillMsg_GeneratedPasswordAccepted( web_contents()->GetRenderViewHost()->GetRoutingID(), current_password_)); password_manager_->SetFormHasGeneratedPassword(form_); Hide(); } int PasswordGenerationPopupControllerImpl::GetDesiredWidth() { // Minimum width in pixels. const int minimum_required_width = 300; // If the width of the field is longer than the minimum, use that instead. int width = std::max(minimum_required_width, controller_common_.RoundedElementBounds().width()); if (display_password_) { // Make sure that the width will always be large enough to display the // password and suggestion on one line. width = std::max(width, gfx::GetStringWidth(current_password_ + SuggestedText(), font_list_) + 2 * kHorizontalPadding); } return width; } int PasswordGenerationPopupControllerImpl::GetDesiredHeight(int width) { // Note that this wrapping isn't exactly what the popup will do. It shouldn't // line break in the middle of the link, but as long as the link isn't longer // than given width this shouldn't affect the height calculated here. The // default width should be wide enough to prevent this from being an issue. int total_length = gfx::GetStringWidth(HelpText(), font_list_); int usable_width = width - 2 * kHorizontalPadding; int text_height = static_cast<int>(ceil(static_cast<double>(total_length)/usable_width)) * font_list_.GetFontSize(); int help_section_height = text_height + 2 * kHelpVerticalPadding; int password_section_height = 0; if (display_password_) { password_section_height = font_list_.GetFontSize() + 2 * kPasswordVerticalPadding; } return (2 * kPopupBorderThickness + help_section_height + password_section_height); } void PasswordGenerationPopupControllerImpl::CalculateBounds() { int popup_width = GetDesiredWidth(); int popup_height = GetDesiredHeight(popup_width); popup_bounds_ = controller_common_.GetPopupBounds(popup_height, popup_width); int sub_view_width = popup_bounds_.width() - 2 * kPopupBorderThickness; // Calculate the bounds for the rest of the elements given the bounds of // the popup. if (display_password_) { password_bounds_ = gfx::Rect( kPopupBorderThickness, kPopupBorderThickness, sub_view_width, font_list_.GetFontSize() + 2 * kPasswordVerticalPadding); divider_bounds_ = gfx::Rect(kPopupBorderThickness, password_bounds_.bottom(), sub_view_width, 1 /* divider heigth*/); } else { password_bounds_ = gfx::Rect(); divider_bounds_ = gfx::Rect(); } int help_y = std::max(kPopupBorderThickness, divider_bounds_.bottom()); int help_height = popup_bounds_.height() - help_y - kPopupBorderThickness; help_bounds_ = gfx::Rect( kPopupBorderThickness, help_y, sub_view_width, help_height); } void PasswordGenerationPopupControllerImpl::Show(bool display_password) { display_password_ = display_password; if (display_password_) current_password_ = base::ASCIIToUTF16(generator_->Generate()); CalculateBounds(); if (!view_) { view_ = PasswordGenerationPopupView::Create(this); view_->Show(); } else { view_->UpdateBoundsAndRedrawPopup(); } controller_common_.RegisterKeyPressCallback(); if (observer_) observer_->OnPopupShown(display_password_); } void PasswordGenerationPopupControllerImpl::HideAndDestroy() { Hide(); } void PasswordGenerationPopupControllerImpl::Hide() { controller_common_.RemoveKeyPressCallback(); if (view_) view_->Hide(); if (observer_) observer_->OnPopupHidden(); delete this; } void PasswordGenerationPopupControllerImpl::ViewDestroyed() { view_ = NULL; Hide(); } void PasswordGenerationPopupControllerImpl::OnSavedPasswordsLinkClicked() { // TODO(gcasto): Change this to navigate to account central once passwords // are visible there. Browser* browser = chrome::FindBrowserWithWebContents(controller_common_.web_contents()); content::OpenURLParams params( GURL(chrome::kAutoPasswordGenerationLearnMoreURL), content::Referrer(), NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false); browser->OpenURL(params); } void PasswordGenerationPopupControllerImpl::SetSelectionAtPoint( const gfx::Point& point) { PasswordSelected(password_bounds_.Contains(point)); } bool PasswordGenerationPopupControllerImpl::AcceptSelectedLine() { if (!password_selected_) return false; PasswordAccepted(); return true; } void PasswordGenerationPopupControllerImpl::SelectionCleared() { PasswordSelected(false); } gfx::NativeView PasswordGenerationPopupControllerImpl::container_view() { return controller_common_.container_view(); } const gfx::FontList& PasswordGenerationPopupControllerImpl::font_list() const { return font_list_; } const gfx::Rect& PasswordGenerationPopupControllerImpl::popup_bounds() const { return popup_bounds_; } const gfx::Rect& PasswordGenerationPopupControllerImpl::password_bounds() const { return password_bounds_; } const gfx::Rect& PasswordGenerationPopupControllerImpl::divider_bounds() const { return divider_bounds_; } const gfx::Rect& PasswordGenerationPopupControllerImpl::help_bounds() const { return help_bounds_; } bool PasswordGenerationPopupControllerImpl::display_password() const { return display_password_; } bool PasswordGenerationPopupControllerImpl::password_selected() const { return password_selected_; } base::string16 PasswordGenerationPopupControllerImpl::password() const { return current_password_; } base::string16 PasswordGenerationPopupControllerImpl::SuggestedText() { return l10n_util::GetStringUTF16(IDS_PASSWORD_GENERATION_SUGGESTION); } const base::string16& PasswordGenerationPopupControllerImpl::HelpText() { return help_text_; } const gfx::Range& PasswordGenerationPopupControllerImpl::HelpTextLinkRange() { return link_range_; } } // namespace autofill <commit_msg>Revert of [Mac] Unselect generated password when mouse leaves password bounds. (https://codereview.chromium.org/282093006/)<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/autofill/password_generation_popup_controller_impl.h" #include <math.h> #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversion_utils.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/autofill/password_generation_popup_observer.h" #include "chrome/browser/ui/autofill/password_generation_popup_view.h" #include "chrome/browser/ui/autofill/popup_constants.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/common/url_constants.h" #include "components/autofill/content/common/autofill_messages.h" #include "components/autofill/core/browser/password_generator.h" #include "components/password_manager/core/browser/password_manager.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/google_chrome_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/rect_conversions.h" #include "ui/gfx/text_utils.h" namespace autofill { base::WeakPtr<PasswordGenerationPopupControllerImpl> PasswordGenerationPopupControllerImpl::GetOrCreate( base::WeakPtr<PasswordGenerationPopupControllerImpl> previous, const gfx::RectF& bounds, const PasswordForm& form, int max_length, password_manager::PasswordManager* password_manager, PasswordGenerationPopupObserver* observer, content::WebContents* web_contents, gfx::NativeView container_view) { if (previous.get() && previous->element_bounds() == bounds && previous->web_contents() == web_contents && previous->container_view() == container_view) { return previous; } if (previous.get()) previous->Hide(); PasswordGenerationPopupControllerImpl* controller = new PasswordGenerationPopupControllerImpl( bounds, form, max_length, password_manager, observer, web_contents, container_view); return controller->GetWeakPtr(); } PasswordGenerationPopupControllerImpl::PasswordGenerationPopupControllerImpl( const gfx::RectF& bounds, const PasswordForm& form, int max_length, password_manager::PasswordManager* password_manager, PasswordGenerationPopupObserver* observer, content::WebContents* web_contents, gfx::NativeView container_view) : form_(form), password_manager_(password_manager), observer_(observer), generator_(new PasswordGenerator(max_length)), controller_common_(bounds, container_view, web_contents), view_(NULL), font_list_(ResourceBundle::GetSharedInstance().GetFontList( ResourceBundle::SmallFont)), password_selected_(false), display_password_(false), weak_ptr_factory_(this) { controller_common_.SetKeyPressCallback( base::Bind(&PasswordGenerationPopupControllerImpl::HandleKeyPressEvent, base::Unretained(this))); std::vector<base::string16> pieces; base::SplitStringDontTrim( l10n_util::GetStringUTF16(IDS_PASSWORD_GENERATION_PROMPT), '|', // separator &pieces); DCHECK_EQ(3u, pieces.size()); link_range_ = gfx::Range(pieces[0].size(), pieces[0].size() + pieces[1].size()); help_text_ = JoinString(pieces, base::string16()); } PasswordGenerationPopupControllerImpl::~PasswordGenerationPopupControllerImpl() {} base::WeakPtr<PasswordGenerationPopupControllerImpl> PasswordGenerationPopupControllerImpl::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } bool PasswordGenerationPopupControllerImpl::HandleKeyPressEvent( const content::NativeWebKeyboardEvent& event) { switch (event.windowsKeyCode) { case ui::VKEY_UP: case ui::VKEY_DOWN: PasswordSelected(true); return true; case ui::VKEY_ESCAPE: Hide(); return true; case ui::VKEY_RETURN: case ui::VKEY_TAB: // We suppress tab if the password is selected because we will // automatically advance focus anyway. return PossiblyAcceptPassword(); default: return false; } } bool PasswordGenerationPopupControllerImpl::PossiblyAcceptPassword() { if (password_selected_) { PasswordAccepted(); // This will delete |this|. return true; } return false; } void PasswordGenerationPopupControllerImpl::PasswordSelected(bool selected) { if (!display_password_) return; password_selected_ = selected; view_->PasswordSelectionUpdated(); view_->UpdateBoundsAndRedrawPopup(); } void PasswordGenerationPopupControllerImpl::PasswordAccepted() { if (!display_password_) return; web_contents()->GetRenderViewHost()->Send( new AutofillMsg_GeneratedPasswordAccepted( web_contents()->GetRenderViewHost()->GetRoutingID(), current_password_)); password_manager_->SetFormHasGeneratedPassword(form_); Hide(); } int PasswordGenerationPopupControllerImpl::GetDesiredWidth() { // Minimum width in pixels. const int minimum_required_width = 300; // If the width of the field is longer than the minimum, use that instead. int width = std::max(minimum_required_width, controller_common_.RoundedElementBounds().width()); if (display_password_) { // Make sure that the width will always be large enough to display the // password and suggestion on one line. width = std::max(width, gfx::GetStringWidth(current_password_ + SuggestedText(), font_list_) + 2 * kHorizontalPadding); } return width; } int PasswordGenerationPopupControllerImpl::GetDesiredHeight(int width) { // Note that this wrapping isn't exactly what the popup will do. It shouldn't // line break in the middle of the link, but as long as the link isn't longer // than given width this shouldn't affect the height calculated here. The // default width should be wide enough to prevent this from being an issue. int total_length = gfx::GetStringWidth(HelpText(), font_list_); int usable_width = width - 2 * kHorizontalPadding; int text_height = static_cast<int>(ceil(static_cast<double>(total_length)/usable_width)) * font_list_.GetFontSize(); int help_section_height = text_height + 2 * kHelpVerticalPadding; int password_section_height = 0; if (display_password_) { password_section_height = font_list_.GetFontSize() + 2 * kPasswordVerticalPadding; } return (2 * kPopupBorderThickness + help_section_height + password_section_height); } void PasswordGenerationPopupControllerImpl::CalculateBounds() { int popup_width = GetDesiredWidth(); int popup_height = GetDesiredHeight(popup_width); popup_bounds_ = controller_common_.GetPopupBounds(popup_height, popup_width); int sub_view_width = popup_bounds_.width() - 2 * kPopupBorderThickness; // Calculate the bounds for the rest of the elements given the bounds of // the popup. if (display_password_) { password_bounds_ = gfx::Rect( kPopupBorderThickness, kPopupBorderThickness, sub_view_width, font_list_.GetFontSize() + 2 * kPasswordVerticalPadding); divider_bounds_ = gfx::Rect(kPopupBorderThickness, password_bounds_.bottom(), sub_view_width, 1 /* divider heigth*/); } else { password_bounds_ = gfx::Rect(); divider_bounds_ = gfx::Rect(); } int help_y = std::max(kPopupBorderThickness, divider_bounds_.bottom()); int help_height = popup_bounds_.height() - help_y - kPopupBorderThickness; help_bounds_ = gfx::Rect( kPopupBorderThickness, help_y, sub_view_width, help_height); } void PasswordGenerationPopupControllerImpl::Show(bool display_password) { display_password_ = display_password; if (display_password_) current_password_ = base::ASCIIToUTF16(generator_->Generate()); CalculateBounds(); if (!view_) { view_ = PasswordGenerationPopupView::Create(this); view_->Show(); } else { view_->UpdateBoundsAndRedrawPopup(); } controller_common_.RegisterKeyPressCallback(); if (observer_) observer_->OnPopupShown(display_password_); } void PasswordGenerationPopupControllerImpl::HideAndDestroy() { Hide(); } void PasswordGenerationPopupControllerImpl::Hide() { controller_common_.RemoveKeyPressCallback(); if (view_) view_->Hide(); if (observer_) observer_->OnPopupHidden(); delete this; } void PasswordGenerationPopupControllerImpl::ViewDestroyed() { view_ = NULL; Hide(); } void PasswordGenerationPopupControllerImpl::OnSavedPasswordsLinkClicked() { // TODO(gcasto): Change this to navigate to account central once passwords // are visible there. Browser* browser = chrome::FindBrowserWithWebContents(controller_common_.web_contents()); content::OpenURLParams params( GURL(chrome::kAutoPasswordGenerationLearnMoreURL), content::Referrer(), NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false); browser->OpenURL(params); } void PasswordGenerationPopupControllerImpl::SetSelectionAtPoint( const gfx::Point& point) { if (password_bounds_.Contains(point)) PasswordSelected(true); } bool PasswordGenerationPopupControllerImpl::AcceptSelectedLine() { if (!password_selected_) return false; PasswordAccepted(); return true; } void PasswordGenerationPopupControllerImpl::SelectionCleared() { PasswordSelected(false); } gfx::NativeView PasswordGenerationPopupControllerImpl::container_view() { return controller_common_.container_view(); } const gfx::FontList& PasswordGenerationPopupControllerImpl::font_list() const { return font_list_; } const gfx::Rect& PasswordGenerationPopupControllerImpl::popup_bounds() const { return popup_bounds_; } const gfx::Rect& PasswordGenerationPopupControllerImpl::password_bounds() const { return password_bounds_; } const gfx::Rect& PasswordGenerationPopupControllerImpl::divider_bounds() const { return divider_bounds_; } const gfx::Rect& PasswordGenerationPopupControllerImpl::help_bounds() const { return help_bounds_; } bool PasswordGenerationPopupControllerImpl::display_password() const { return display_password_; } bool PasswordGenerationPopupControllerImpl::password_selected() const { return password_selected_; } base::string16 PasswordGenerationPopupControllerImpl::password() const { return current_password_; } base::string16 PasswordGenerationPopupControllerImpl::SuggestedText() { return l10n_util::GetStringUTF16(IDS_PASSWORD_GENERATION_SUGGESTION); } const base::string16& PasswordGenerationPopupControllerImpl::HelpText() { return help_text_; } const gfx::Range& PasswordGenerationPopupControllerImpl::HelpTextLinkRange() { return link_range_; } } // namespace autofill <|endoftext|>
<commit_before>// // Log.hpp // MusicPlayer // // Created by Albert Zeyer on 07.01.14. // Copyright (c) 2014 Albert Zeyer. All rights reserved. // #ifndef MusicPlayer_Log_hpp #define MusicPlayer_Log_hpp #include <iostream> #include <sstream> #include <string> #include <time.h> #include <sys/time.h> struct Log { std::string name; bool needNewPrefix; Log(const std::string& _name) : name(_name) { resetPrefix(); } void resetPrefix() { needNewPrefix = true; } void printPrefix() { struct timeval t; gettimeofday(&t, NULL); struct tm* now = gmtime( &t.tv_sec ); char timestamp[256]; strftime(timestamp, sizeof(timestamp), "%Y-%m-%d_%H.%M.%S", now); int millisecs = (t.tv_usec / 1000) % 1000; char ms_str[5]; sprintf(ms_str, "%.03d", millisecs); (*this) << "[" << name.c_str() << ":" << timestamp << "." << ms_str << "] "; } Log& operator<<(const char* s) { if(needNewPrefix) { printPrefix(); needNewPrefix = false; } std::cout << s; return *this; } void flush() { std::cout.flush(); } }; inline Log& endl(Log& s) { s << "\n"; s.resetPrefix(); s.flush(); return s; } inline Log& operator<<(Log& s, Log& f(Log&)) { return f(s); } template<typename T> inline Log& operator<<(Log& s, const T& v) { std::stringstream ss; ss << v; s << ss.str().c_str(); return s; } #endif <commit_msg>small fix<commit_after>// // Log.hpp // MusicPlayer // // Created by Albert Zeyer on 07.01.14. // Copyright (c) 2014 Albert Zeyer. All rights reserved. // #ifndef MusicPlayer_Log_hpp #define MusicPlayer_Log_hpp #include <iostream> #include <sstream> #include <string> #include <time.h> #include <sys/time.h> struct Log { std::string name; bool needNewPrefix; Log(const std::string& _name) : name(_name) { resetPrefix(); } void resetPrefix() { needNewPrefix = true; } void printPrefix() { struct timeval t; gettimeofday(&t, NULL); struct tm* now = gmtime( &t.tv_sec ); char timestamp[256]; strftime(timestamp, sizeof(timestamp), "%Y-%m-%d_%H.%M.%S", now); int millisecs = (t.tv_usec / 1000) % 1000; char ms_str[5]; sprintf(ms_str, "%.03d", millisecs); std::cout << "[" << name.c_str() << ":" << timestamp << "." << ms_str << "] "; } Log& operator<<(const char* s) { if(needNewPrefix) { printPrefix(); needNewPrefix = false; } std::cout << s; return *this; } void flush() { std::cout.flush(); } }; inline Log& endl(Log& s) { s << "\n"; s.resetPrefix(); s.flush(); return s; } inline Log& operator<<(Log& s, Log& f(Log&)) { return f(s); } template<typename T> inline Log& operator<<(Log& s, const T& v) { std::stringstream ss; ss << v; s << ss.str().c_str(); return s; } #endif <|endoftext|>
<commit_before>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2020 by Kaushik Ghose. Some rights reserved, see LICENSE */ #include <exception> #include <string> #include "serialize.hpp" namespace groho { Serialize::Serialize( double dt, const std::vector<NAIFbody>& objects, fs::path path) { if (fs::exists(path)) { if (!fs::is_directory(path)) { throw std::runtime_error("Output path must be directory"); } } else { fs::create_directories(path); } history.reserve(objects.size()); for (size_t i = 0; i < objects.size(); i++) { auto fname = path / (std::to_string(int(objects[i])) + "-pos.bin"); history.emplace_back(dt, objects[i], fname); } } void Serialize::append(const v3d_vec_t& pos) { for (size_t i = 0; i < history.size(); i++) { history[i].sample(pos[i]); } } } <commit_msg>Change naming scheme for files<commit_after>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2020 by Kaushik Ghose. Some rights reserved, see LICENSE */ #include <exception> #include <string> #include "serialize.hpp" namespace groho { Serialize::Serialize( double dt, const std::vector<NAIFbody>& objects, fs::path path) { if (fs::exists(path)) { if (!fs::is_directory(path)) { throw std::runtime_error("Output path must be directory"); } } else { fs::create_directories(path); } history.reserve(objects.size()); for (size_t i = 0; i < objects.size(); i++) { auto fname = path / ("pos" + std::to_string(int(objects[i])) + ".bin"); history.emplace_back(dt, objects[i], fname); } } void Serialize::append(const v3d_vec_t& pos) { for (size_t i = 0; i < history.size(); i++) { history[i].sample(pos[i]); } } } <|endoftext|>
<commit_before>/** ** \file scheduler/scheduler.cc ** \brief Implementation of scheduler::Scheduler. */ //#define ENABLE_DEBUG_TRACES #include <cassert> #include <libport/compiler.hh> #include <libport/containers.hh> #include <libport/foreach.hh> #include "kernel/userver.hh" #include "scheduler/scheduler.hh" #include "scheduler/job.hh" namespace scheduler { // This function is required to start a new job using the libcoroutine. // Its only purpose is to create the context and start the execution // of the new job. static void run_job (void* job) { static_cast<Job*>(job)->run(); } void Scheduler::add_job (Job* job) { assert (job); assert (!libport::has (jobs_, job)); assert (!libport::has (jobs_to_start_, job)); jobs_to_start_.push_back (job); } libport::utime_t Scheduler::work () { #ifdef ENABLE_DEBUG_TRACES static int cycle = 0; #endif ECHO ("======================================================== cycle " << ++cycle); // Set to true when at least one job has been started bool job_started = !jobs_to_start_.empty (); // Start new jobs jobs to_start; std::swap (to_start, jobs_to_start_); foreach (Job* job, to_start) { assert (job); ECHO ("will start job " << job); // Job will start for a very short time and do a yield_front() to // be restarted below in the course of the regular cycle. assert (!current_job_); current_job_ = job; Coro_startCoro_ (self_, job->coro_get(), job, run_job); } // Start deferred jobs for (libport::ufloat current_time = ::urbiserver->getTime (); !deferred_jobs_.empty(); deferred_jobs_.pop ()) { deferred_job j = deferred_jobs_.top (); if (current_time < j.get<0>()) break; jobs_.push_back (j.get<1> ()); } // If something is going to happen, or if we have just started a // new job, add the list of jobs waiting for something to happen // on the pending jobs queue. if (!if_change_jobs_.empty() && (job_started || !jobs_.empty())) { jobs to_resume; std::swap (to_resume, if_change_jobs_); foreach (Job* job, to_resume) jobs_.push_back (job); } // Run all the jobs in the run queue once. jobs pending; std::swap (pending, jobs_); ECHO (pending.size() << " jobs in the queue for this cycle"); foreach (Job* job, pending) { assert (job); assert (!job->terminated ()); ECHO ("will resume job " << job); Coro_switchTo_ (self_, job->coro_get ()); ECHO ("back from job " << job); } // Do we have some work to do now? if (!jobs_.empty ()) return 0; // Do we have deferred jobs? if (!deferred_jobs_.empty ()) return deferred_jobs_.top ().get<0> (); // Ok, let's say, we'll be called again in one hour. return ::urbiserver->getTime() + 3600000000LL; } void Scheduler::switch_back (Job* job) { // Switch back to the scheduler. assert (current_job_); current_job_ = 0; Coro_switchTo_ (job->coro_get (), self_); // We regained control, we are again in the context of the job. assert (!current_job_); current_job_ = job; ECHO ("job " << job << " resumed"); } void Scheduler::resume_scheduler (Job* job) { // If the job has not terminated, put it at the back of the run queue // so that the run queue order is preserved between work cycles. if (!job->terminated ()) jobs_.push_back (job); switch_back (job); } void Scheduler::resume_scheduler_front (Job* job) { // Put the job in front of the queue. If the job asks to be requeued, // it is not terminated. assert (!job->terminated ()); jobs_.push_front (job); switch_back (job); } void Scheduler::resume_scheduler_until (Job* job, libport::utime_t deadline) { // Put the job in the deferred queue. If the job asks to be requeued, // it is not terminated. assert (!job->terminated ()); deferred_jobs_.push (boost::make_tuple (deadline, job)); switch_back (job); } void Scheduler::resume_scheduler_suspend (Job* job) { suspended_jobs_.push_back (job); switch_back (job); } void Scheduler::resume_scheduler_things_changed (Job* job) { if_change_jobs_.push_back (job); switch_back (job); } void Scheduler::resume_job (Job* job) { // Suspended job may have been killed externally, in which case it // will not appear in the list of suspended jobs. if (libport::has (suspended_jobs_, job)) { jobs_.push_back (job); suspended_jobs_.remove (job); } } void Scheduler::killall_jobs () { ECHO ("killing all jobs!"); // This implementation is quite inefficient because it will call // kill_job() for each job. But who cares? We are killing everyone // anyway. while (!jobs_to_start_.empty ()) jobs_to_start_.pop_front (); while (!suspended_jobs_.empty ()) kill_job (suspended_jobs_.front ()); while (!if_change_jobs_.empty ()) kill_job (if_change_jobs_.front ()); while (!jobs_.empty ()) kill_job (jobs_.front ()); while (!deferred_jobs_.empty ()) kill_job (deferred_jobs_.top ().get<1>()); } void Scheduler::unschedule_job (Job* job) { assert (job); assert (job != current_job_); ECHO ("unscheduling job " << job); // First of all, tell the job it has been terminated unless it has // been registered with us but not yet started. if (!libport::has (jobs_to_start_, job)) job->terminate_now (); // Remove the job from the queues where it could be stored jobs_to_start_.remove (job); jobs_.remove (job); suspended_jobs_.remove (job); if_change_jobs_.remove (job); // We have no remove() on a priority queue, regenerate a queue without // this job. { deferred_jobs old_deferred; std::swap (old_deferred, deferred_jobs_); while (!old_deferred.empty ()) { deferred_job j = old_deferred.top (); old_deferred.pop (); if (j.get<1>() != job) deferred_jobs_.push (j); } } } void Scheduler::kill_job (Job* job) { assert (job != current_job_); ECHO ("deleting job " << job); delete job; } bool operator> (const deferred_job& left, const deferred_job& right) { return left.get<0>() > right.get<0>(); } } // namespace scheduler <commit_msg>Do not build a new list and use std::swap when clear can be used<commit_after>/** ** \file scheduler/scheduler.cc ** \brief Implementation of scheduler::Scheduler. */ //#define ENABLE_DEBUG_TRACES #include <cassert> #include <libport/compiler.hh> #include <libport/containers.hh> #include <libport/foreach.hh> #include "kernel/userver.hh" #include "scheduler/scheduler.hh" #include "scheduler/job.hh" namespace scheduler { // This function is required to start a new job using the libcoroutine. // Its only purpose is to create the context and start the execution // of the new job. static void run_job (void* job) { static_cast<Job*>(job)->run(); } void Scheduler::add_job (Job* job) { assert (job); assert (!libport::has (jobs_, job)); assert (!libport::has (jobs_to_start_, job)); jobs_to_start_.push_back (job); } libport::utime_t Scheduler::work () { #ifdef ENABLE_DEBUG_TRACES static int cycle = 0; #endif ECHO ("======================================================== cycle " << ++cycle); // Set to true when at least one job has been started bool job_started = !jobs_to_start_.empty (); // Start new jobs jobs to_start; std::swap (to_start, jobs_to_start_); foreach (Job* job, to_start) { assert (job); ECHO ("will start job " << job); // Job will start for a very short time and do a yield_front() to // be restarted below in the course of the regular cycle. assert (!current_job_); current_job_ = job; Coro_startCoro_ (self_, job->coro_get(), job, run_job); } // Start deferred jobs for (libport::ufloat current_time = ::urbiserver->getTime (); !deferred_jobs_.empty(); deferred_jobs_.pop ()) { deferred_job j = deferred_jobs_.top (); if (current_time < j.get<0>()) break; jobs_.push_back (j.get<1> ()); } // If something is going to happen, or if we have just started a // new job, add the list of jobs waiting for something to happen // on the pending jobs queue. if (!if_change_jobs_.empty() && (job_started || !jobs_.empty())) { foreach (Job* job, if_change_jobs_) jobs_.push_back (job); if_change_jobs_.clear (); } // Run all the jobs in the run queue once. jobs pending; std::swap (pending, jobs_); ECHO (pending.size() << " jobs in the queue for this cycle"); foreach (Job* job, pending) { assert (job); assert (!job->terminated ()); ECHO ("will resume job " << job); Coro_switchTo_ (self_, job->coro_get ()); ECHO ("back from job " << job); } // Do we have some work to do now? if (!jobs_.empty ()) return 0; // Do we have deferred jobs? if (!deferred_jobs_.empty ()) return deferred_jobs_.top ().get<0> (); // Ok, let's say, we'll be called again in one hour. return ::urbiserver->getTime() + 3600000000LL; } void Scheduler::switch_back (Job* job) { // Switch back to the scheduler. assert (current_job_); current_job_ = 0; Coro_switchTo_ (job->coro_get (), self_); // We regained control, we are again in the context of the job. assert (!current_job_); current_job_ = job; ECHO ("job " << job << " resumed"); } void Scheduler::resume_scheduler (Job* job) { // If the job has not terminated, put it at the back of the run queue // so that the run queue order is preserved between work cycles. if (!job->terminated ()) jobs_.push_back (job); switch_back (job); } void Scheduler::resume_scheduler_front (Job* job) { // Put the job in front of the queue. If the job asks to be requeued, // it is not terminated. assert (!job->terminated ()); jobs_.push_front (job); switch_back (job); } void Scheduler::resume_scheduler_until (Job* job, libport::utime_t deadline) { // Put the job in the deferred queue. If the job asks to be requeued, // it is not terminated. assert (!job->terminated ()); deferred_jobs_.push (boost::make_tuple (deadline, job)); switch_back (job); } void Scheduler::resume_scheduler_suspend (Job* job) { suspended_jobs_.push_back (job); switch_back (job); } void Scheduler::resume_scheduler_things_changed (Job* job) { if_change_jobs_.push_back (job); switch_back (job); } void Scheduler::resume_job (Job* job) { // Suspended job may have been killed externally, in which case it // will not appear in the list of suspended jobs. if (libport::has (suspended_jobs_, job)) { jobs_.push_back (job); suspended_jobs_.remove (job); } } void Scheduler::killall_jobs () { ECHO ("killing all jobs!"); // This implementation is quite inefficient because it will call // kill_job() for each job. But who cares? We are killing everyone // anyway. while (!jobs_to_start_.empty ()) jobs_to_start_.pop_front (); while (!suspended_jobs_.empty ()) kill_job (suspended_jobs_.front ()); while (!if_change_jobs_.empty ()) kill_job (if_change_jobs_.front ()); while (!jobs_.empty ()) kill_job (jobs_.front ()); while (!deferred_jobs_.empty ()) kill_job (deferred_jobs_.top ().get<1>()); } void Scheduler::unschedule_job (Job* job) { assert (job); assert (job != current_job_); ECHO ("unscheduling job " << job); // First of all, tell the job it has been terminated unless it has // been registered with us but not yet started. if (!libport::has (jobs_to_start_, job)) job->terminate_now (); // Remove the job from the queues where it could be stored jobs_to_start_.remove (job); jobs_.remove (job); suspended_jobs_.remove (job); if_change_jobs_.remove (job); // We have no remove() on a priority queue, regenerate a queue without // this job. { deferred_jobs old_deferred; std::swap (old_deferred, deferred_jobs_); while (!old_deferred.empty ()) { deferred_job j = old_deferred.top (); old_deferred.pop (); if (j.get<1>() != job) deferred_jobs_.push (j); } } } void Scheduler::kill_job (Job* job) { assert (job != current_job_); ECHO ("deleting job " << job); delete job; } bool operator> (const deferred_job& left, const deferred_job& right) { return left.get<0>() > right.get<0>(); } } // namespace scheduler <|endoftext|>
<commit_before>#include <vector> #include <string> #include <cstdlib> #include <botan/botan.h> #include <botan/lookup.h> #include <botan/look_pk.h> #include <botan/filters.h> #if defined(BOTAN_HAS_RANDPOOL) #include <botan/randpool.h> #endif #if defined(BOTAN_HAS_X931_RNG) #include <botan/x931_rng.h> #endif #include "common.h" using namespace Botan; /* A weird little hack to fit S2K algorithms into the validation suite You probably wouldn't ever want to actually use the S2K algorithms like this, the raw S2K interface is more convenient for actually using them */ class S2K_Filter : public Filter { public: void write(const byte in[], u32bit len) { passphrase += std::string(reinterpret_cast<const char*>(in), len); } void end_msg() { s2k->change_salt(salt, salt.size()); s2k->set_iterations(iterations); SymmetricKey x = s2k->derive_key(outlen, passphrase); send(x.bits_of()); } S2K_Filter(S2K* algo, const SymmetricKey& s, u32bit o, u32bit i) { s2k = algo; outlen = o; iterations = i; salt = s.bits_of(); } ~S2K_Filter() { delete s2k; } private: std::string passphrase; S2K* s2k; SecureVector<byte> salt; u32bit outlen, iterations; }; /* Not too useful generally; just dumps random bits for benchmarking */ class RNG_Filter : public Filter { public: void write(const byte[], u32bit); RNG_Filter(RandomNumberGenerator* r) : rng(r) {} ~RNG_Filter() { delete rng; } private: RandomNumberGenerator* rng; }; class KDF_Filter : public Filter { public: void write(const byte in[], u32bit len) { secret.append(in, len); } void end_msg() { SymmetricKey x = kdf->derive_key(outlen, secret, secret.size(), salt, salt.size()); send(x.bits_of(), x.length()); } KDF_Filter(KDF* algo, const SymmetricKey& s, u32bit o) { kdf = algo; outlen = o; salt = s.bits_of(); } ~KDF_Filter() { delete kdf; } private: SecureVector<byte> secret; SecureVector<byte> salt; KDF* kdf; u32bit outlen; }; Filter* lookup_s2k(const std::string& algname, const std::vector<std::string>& params) { S2K* s2k = 0; try { s2k = get_s2k(algname); } catch(...) { } if(s2k) return new S2K_Filter(s2k, params[0], to_u32bit(params[1]), to_u32bit(params[2])); return 0; } void RNG_Filter::write(const byte[], u32bit length) { if(length) { SecureVector<byte> out(length); rng->randomize(out, out.size()); send(out); } } Filter* lookup_rng(const std::string& algname, const std::string& key) { RandomNumberGenerator* prng = 0; #if defined(BOTAN_HAS_X931_RNG) if(algname == "X9.31-RNG(TripleDES)") prng = new ANSI_X931_RNG(get_block_cipher("TripleDES"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-128)") prng = new ANSI_X931_RNG(get_block_cipher("AES-128"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-192)") prng = new ANSI_X931_RNG(get_block_cipher("AES-192"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-256)") prng = new ANSI_X931_RNG(get_block_cipher("AES-256"), new Fixed_Output_RNG(decode_hex(key))); #endif #if defined(BOTAN_HAS_X931_RNG) and defined(BOTAN_HAS_RANDPOOL) // these are used for benchmarking: AES-256/SHA-256 matches library // defaults, so benchmark reflects real-world performance (maybe) if(!prng && (algname == "Randpool" || algname == "X9.31-RNG")) { Randpool* randpool = new Randpool(get_block_cipher("AES-256"), get_mac("HMAC(SHA-256)")); randpool->add_entropy(reinterpret_cast<const byte*>(key.c_str()), key.length()); if(algname == "Randpool") prng = randpool; else prng = new ANSI_X931_RNG(get_block_cipher("AES-256"), randpool); } #endif if(prng) return new RNG_Filter(prng); return 0; } Filter* lookup_kdf(const std::string& algname, const std::string& salt, const std::string& params) { KDF* kdf = 0; try { kdf = get_kdf(algname); } catch(...) { return 0; } if(kdf) return new KDF_Filter(kdf, salt, to_u32bit(params)); return 0; } <commit_msg>Remove spurious include of <botan/look_pk.h> from dolook2.cpp<commit_after>#include <vector> #include <string> #include <cstdlib> #include <botan/botan.h> #include <botan/lookup.h> #include <botan/filters.h> #if defined(BOTAN_HAS_RANDPOOL) #include <botan/randpool.h> #endif #if defined(BOTAN_HAS_X931_RNG) #include <botan/x931_rng.h> #endif #include "common.h" using namespace Botan; /* A weird little hack to fit S2K algorithms into the validation suite You probably wouldn't ever want to actually use the S2K algorithms like this, the raw S2K interface is more convenient for actually using them */ class S2K_Filter : public Filter { public: void write(const byte in[], u32bit len) { passphrase += std::string(reinterpret_cast<const char*>(in), len); } void end_msg() { s2k->change_salt(salt, salt.size()); s2k->set_iterations(iterations); SymmetricKey x = s2k->derive_key(outlen, passphrase); send(x.bits_of()); } S2K_Filter(S2K* algo, const SymmetricKey& s, u32bit o, u32bit i) { s2k = algo; outlen = o; iterations = i; salt = s.bits_of(); } ~S2K_Filter() { delete s2k; } private: std::string passphrase; S2K* s2k; SecureVector<byte> salt; u32bit outlen, iterations; }; /* Not too useful generally; just dumps random bits for benchmarking */ class RNG_Filter : public Filter { public: void write(const byte[], u32bit); RNG_Filter(RandomNumberGenerator* r) : rng(r) {} ~RNG_Filter() { delete rng; } private: RandomNumberGenerator* rng; }; class KDF_Filter : public Filter { public: void write(const byte in[], u32bit len) { secret.append(in, len); } void end_msg() { SymmetricKey x = kdf->derive_key(outlen, secret, secret.size(), salt, salt.size()); send(x.bits_of(), x.length()); } KDF_Filter(KDF* algo, const SymmetricKey& s, u32bit o) { kdf = algo; outlen = o; salt = s.bits_of(); } ~KDF_Filter() { delete kdf; } private: SecureVector<byte> secret; SecureVector<byte> salt; KDF* kdf; u32bit outlen; }; Filter* lookup_s2k(const std::string& algname, const std::vector<std::string>& params) { S2K* s2k = 0; try { s2k = get_s2k(algname); } catch(...) { } if(s2k) return new S2K_Filter(s2k, params[0], to_u32bit(params[1]), to_u32bit(params[2])); return 0; } void RNG_Filter::write(const byte[], u32bit length) { if(length) { SecureVector<byte> out(length); rng->randomize(out, out.size()); send(out); } } Filter* lookup_rng(const std::string& algname, const std::string& key) { RandomNumberGenerator* prng = 0; #if defined(BOTAN_HAS_X931_RNG) if(algname == "X9.31-RNG(TripleDES)") prng = new ANSI_X931_RNG(get_block_cipher("TripleDES"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-128)") prng = new ANSI_X931_RNG(get_block_cipher("AES-128"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-192)") prng = new ANSI_X931_RNG(get_block_cipher("AES-192"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-256)") prng = new ANSI_X931_RNG(get_block_cipher("AES-256"), new Fixed_Output_RNG(decode_hex(key))); #endif #if defined(BOTAN_HAS_X931_RNG) and defined(BOTAN_HAS_RANDPOOL) // these are used for benchmarking: AES-256/SHA-256 matches library // defaults, so benchmark reflects real-world performance (maybe) if(!prng && (algname == "Randpool" || algname == "X9.31-RNG")) { Randpool* randpool = new Randpool(get_block_cipher("AES-256"), get_mac("HMAC(SHA-256)")); randpool->add_entropy(reinterpret_cast<const byte*>(key.c_str()), key.length()); if(algname == "Randpool") prng = randpool; else prng = new ANSI_X931_RNG(get_block_cipher("AES-256"), randpool); } #endif if(prng) return new RNG_Filter(prng); return 0; } Filter* lookup_kdf(const std::string& algname, const std::string& salt, const std::string& params) { KDF* kdf = 0; try { kdf = get_kdf(algname); } catch(...) { return 0; } if(kdf) return new KDF_Filter(kdf, salt, to_u32bit(params)); return 0; } <|endoftext|>
<commit_before>#include "OBJ.h" OBJ::OBJ(std::string p) { path = ""; } OBJ::OBJ(char * p) { path = p; } void OBJ::load(Mesh * m) { std::ifstream in(path); std::vector<std::string> tokens; Group * g = new Group(); m->push_group(g); Vertex * v; bool createGroup = false; Face * face; std::vector<std::string> f; while(!in.eof()) { std::string line; std::getline(in, line); tokens = split(line.c_str(), ' '); switch(line[0]) { case 'v': /* if (tokens.size() == 4) { */ v = new Vertex( atof(tokens.at(1).c_str()), atof(tokens.at(2).c_str()), atof(tokens.at(3).c_str())); switch(line[1]) { case 't': break; //TODO case 'n': m->push_normal(v); break; default: m->push_vertex(v); break; } /* } */ break; case 'f': face = new Face(); for (int i = 1; i < tokens.size(); i++) { f = split(tokens[i], '/'); face->push_vertex(atoi(f[0].c_str()) - 1); /* face->push_vertex(f[1]); */ face->push_normal(atoi(f[2].c_str()) - 1); } g->push_face(face); break; case 'g': if (createGroup) { if (tokens.size() == 1) { g = new Group(); } else { g = new Group(tokens.at(1)); } m->push_group(g); } else { createGroup = true; } break; } } } std::vector<std::string> OBJ::split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } std::vector<std::string>& OBJ::split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } <commit_msg>Fix vt flaw<commit_after>#include "OBJ.h" OBJ::OBJ(std::string p) { path = ""; } OBJ::OBJ(char * p) { path = p; } void OBJ::load(Mesh * m) { std::ifstream in(path); std::vector<std::string> tokens; Group * g = new Group(); m->push_group(g); Vertex * v; bool createGroup = false; Face * face; std::vector<std::string> f; int count = 0; while(!in.eof()) { std::cout << ++count << std::endl; std::string line; std::getline(in, line); tokens = split(line.c_str(), ' '); switch(line[0]) { case 'v': if (tokens.size() == 4) { v = new Vertex( atof(tokens.at(1).c_str()), atof(tokens.at(2).c_str()), atof(tokens.at(3).c_str())); switch(line[1]) { case 't': break; //TODO case 'n': m->push_normal(v); break; default: m->push_vertex(v); break; } } break; case 'f': face = new Face(); for (int i = 1; i < tokens.size(); i++) { f = split(tokens[i], '/'); face->push_vertex(atoi(f[0].c_str()) - 1); /* face->push_vertex(f[1]); */ face->push_normal(atoi(f[2].c_str()) - 1); } g->push_face(face); break; case 'g': if (createGroup) { if (tokens.size() == 1) { g = new Group(); } else { g = new Group(tokens.at(1)); } m->push_group(g); } else { createGroup = true; } break; } } } std::vector<std::string> OBJ::split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } std::vector<std::string>& OBJ::split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/util/util.hpp> #include "DataArrayHDF5.hpp" #include "h5x/H5DataSet.hpp" #include "DimensionHDF5.hpp" using namespace std; using namespace nix::base; namespace nix { namespace hdf5 { DataArrayHDF5::DataArrayHDF5(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block, const H5Group &group) : EntityWithSourcesHDF5(file, block, group) { dimension_group = this->group().openOptGroup("dimensions"); } DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const H5Group &group, const string &id, const string &type, const string &name) : DataArrayHDF5(file, block, group, id, type, name, util::getTime()) { } DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const H5Group &group, const string &id, const string &type, const string &name, time_t time) : EntityWithSourcesHDF5(file, block, group, id, type, name, time) { dimension_group = this->group().openOptGroup("dimensions"); } //-------------------------------------------------- // Element getters and setters //-------------------------------------------------- boost::optional<std::string> DataArrayHDF5::label() const { boost::optional<std::string> ret; string value; bool have_attr = group().getAttr("label", value); if (have_attr) { ret = value; } return ret; } void DataArrayHDF5::label(const string &label) { group().setAttr("label", label); forceUpdatedAt(); } void DataArrayHDF5::label(const none_t t) { if (group().hasAttr("label")) { group().removeAttr("label"); } forceUpdatedAt(); } boost::optional<std::string> DataArrayHDF5::unit() const { boost::optional<std::string> ret; string value; bool have_attr = group().getAttr("unit", value); if (have_attr) { ret = value; } return ret; } void DataArrayHDF5::unit(const string &unit) { group().setAttr("unit", unit); forceUpdatedAt(); } void DataArrayHDF5::unit(const none_t t) { if (group().hasAttr("unit")) { group().removeAttr("unit"); } forceUpdatedAt(); } // TODO use defaults boost::optional<double> DataArrayHDF5::expansionOrigin() const { boost::optional<double> ret; double expansion_origin; bool have_attr = group().getAttr("expansion_origin", expansion_origin); if (have_attr) { ret = expansion_origin; } return ret; } void DataArrayHDF5::expansionOrigin(double expansion_origin) { group().setAttr("expansion_origin", expansion_origin); forceUpdatedAt(); } void DataArrayHDF5::expansionOrigin(const none_t t) { if (group().hasAttr("expansion_origin")) { group().removeAttr("expansion_origin"); } forceUpdatedAt(); } // TODO use defaults vector<double> DataArrayHDF5::polynomCoefficients() const { vector<double> polynom_coefficients; if (group().hasData("polynom_coefficients")) { DataSet ds = group().openData("polynom_coefficients"); ds.read(polynom_coefficients, true); } return polynom_coefficients; } void DataArrayHDF5::polynomCoefficients(const vector<double> &coefficients) { DataSet ds; if (group().hasData("polynom_coefficients")) { ds = group().openData("polynom_coefficients"); ds.setExtent({coefficients.size()}); } else { ds = group().createData("polynom_coefficients", H5T_NATIVE_DOUBLE, {coefficients.size()}); } ds.write(coefficients); forceUpdatedAt(); } void DataArrayHDF5::polynomCoefficients(const none_t t) { if (group().hasData("polynom_coefficients")) { group().removeData("polynom_coefficients"); } forceUpdatedAt(); } //-------------------------------------------------- // Methods concerning dimensions //-------------------------------------------------- ndsize_t DataArrayHDF5::dimensionCount() const { boost::optional<H5Group> g = dimension_group(); ndsize_t count = 0; if (g) { count = g->objectCount(); } return count; } shared_ptr<IDimension> DataArrayHDF5::getDimension(ndsize_t index) const { shared_ptr<IDimension> dim; boost::optional<H5Group> g = dimension_group(); if (g) { string str_id = util::numToStr(index); if (g->hasGroup(str_id)) { H5Group group = g->openGroup(str_id, false); dim = openDimensionHDF5(group, index); } } return dim; } std::shared_ptr<base::ISetDimension> DataArrayHDF5::createSetDimension(ndsize_t index) { H5Group g = createDimensionGroup(index); return make_shared<SetDimensionHDF5>(g, index); } std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createRangeDimension(ndsize_t index, const std::vector<double> &ticks) { H5Group g = createDimensionGroup(index); return make_shared<RangeDimensionHDF5>(g, index, ticks); } std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createAliasRangeDimension() { H5Group g = createDimensionGroup(1); return make_shared<RangeDimensionHDF5>(g, 1, *this); } std::shared_ptr<base::ISampledDimension> DataArrayHDF5::createSampledDimension(ndsize_t index, double sampling_interval) { H5Group g = createDimensionGroup(index); return make_shared<SampledDimensionHDF5>(g, index, sampling_interval); } H5Group DataArrayHDF5::createDimensionGroup(ndsize_t index) { boost::optional<H5Group> g = dimension_group(true); ndsize_t dim_max = dimensionCount() + 1; if (index > dim_max || index <= 0) throw new runtime_error("Invalid dimension index: has to be 0 < index <= " + util::numToStr(dim_max)); string str_id = util::numToStr(index); if (g->hasGroup(str_id)) { g->removeGroup(str_id); } return g->openGroup(str_id, true); } bool DataArrayHDF5::deleteDimension(ndsize_t index) { bool deleted = false; ndsize_t dim_count = dimensionCount(); string str_id = util::numToStr(index); boost::optional<H5Group> g = dimension_group(); if (g) { if (g->hasGroup(str_id)) { g->removeGroup(str_id); deleted = true; } if (deleted && index < dim_count) { for (ndsize_t old_id = index + 1; old_id <= dim_count; old_id++) { string str_old_id = util::numToStr(old_id); string str_new_id = util::numToStr(old_id - 1); g->renameGroup(str_old_id, str_new_id); } } } return deleted; } //-------------------------------------------------- // Other methods and functions //-------------------------------------------------- DataArrayHDF5::~DataArrayHDF5() { } void DataArrayHDF5::createData(DataType dtype, const NDSize &size) { if (group().hasData("data")) { throw ConsistencyError("DataArray's hdf5 data group already exists!"); } h5x::DataType fileType = data_type_to_h5_filetype(dtype); group().createData("data", fileType, size); } bool DataArrayHDF5::hasData() const { return group().hasData("data"); } void DataArrayHDF5::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) { if (!group().hasData("data")) { throw ConsistencyError("DataArray with missing h5df DataSet"); } DataSet ds = group().openData("data"); DataSpace fileSpace = ds.getSpace(); DataSpace memSpace = DataSpace::create(count, false); if (offset && count) { fileSpace.hyperslab(count, offset); } else if (offset && !count) { fileSpace.hyperslab(NDSize(offset.size(), 1), offset); } h5x::DataType memType = data_type_to_h5_memtype(dtype); ds.write(data, memType, memSpace, fileSpace); } void DataArrayHDF5::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const { if (!group().hasData("data")) { throw ConsistencyError("DataArray with missing h5df DataSet"); } DataSet ds = group().openData("data"); h5x::DataType memType = data_type_to_h5_memtype(dtype); if (offset.size()) { Selection fileSel = ds.createSelection(); // if count.size() == 0, i.e. we want to read a scalar, // we have to supply something that fileSel can make sense of fileSel.select(count ? count : NDSize(offset.size(), 1), offset); Selection memSel(DataSpace::create(count, false)); ds.read(memType, data, fileSel, memSel); } else { ds.read(memType, count, data); } } NDSize DataArrayHDF5::dataExtent(void) const { if (!group().hasData("data")) { return NDSize{}; } DataSet ds = group().openData("data"); return ds.size(); } void DataArrayHDF5::dataExtent(const NDSize &extent) { if (!group().hasData("data")) { throw runtime_error("Data field not found in DataArray!"); } DataSet ds = group().openData("data"); ds.setExtent(extent); } DataType DataArrayHDF5::dataType(void) const { if (!group().hasData("data")) { return DataType::Nothing; } DataSet ds = group().openData("data"); const h5x::DataType dtype = ds.dataType(); return data_type_from_h5(dtype); } } // ns nix::hdf5 } // ns nix <commit_msg>[hdf5] DataArray::read use generic DataSet::read<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/util/util.hpp> #include "DataArrayHDF5.hpp" #include "h5x/H5DataSet.hpp" #include "DimensionHDF5.hpp" using namespace std; using namespace nix::base; namespace nix { namespace hdf5 { DataArrayHDF5::DataArrayHDF5(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block, const H5Group &group) : EntityWithSourcesHDF5(file, block, group) { dimension_group = this->group().openOptGroup("dimensions"); } DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const H5Group &group, const string &id, const string &type, const string &name) : DataArrayHDF5(file, block, group, id, type, name, util::getTime()) { } DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const H5Group &group, const string &id, const string &type, const string &name, time_t time) : EntityWithSourcesHDF5(file, block, group, id, type, name, time) { dimension_group = this->group().openOptGroup("dimensions"); } //-------------------------------------------------- // Element getters and setters //-------------------------------------------------- boost::optional<std::string> DataArrayHDF5::label() const { boost::optional<std::string> ret; string value; bool have_attr = group().getAttr("label", value); if (have_attr) { ret = value; } return ret; } void DataArrayHDF5::label(const string &label) { group().setAttr("label", label); forceUpdatedAt(); } void DataArrayHDF5::label(const none_t t) { if (group().hasAttr("label")) { group().removeAttr("label"); } forceUpdatedAt(); } boost::optional<std::string> DataArrayHDF5::unit() const { boost::optional<std::string> ret; string value; bool have_attr = group().getAttr("unit", value); if (have_attr) { ret = value; } return ret; } void DataArrayHDF5::unit(const string &unit) { group().setAttr("unit", unit); forceUpdatedAt(); } void DataArrayHDF5::unit(const none_t t) { if (group().hasAttr("unit")) { group().removeAttr("unit"); } forceUpdatedAt(); } // TODO use defaults boost::optional<double> DataArrayHDF5::expansionOrigin() const { boost::optional<double> ret; double expansion_origin; bool have_attr = group().getAttr("expansion_origin", expansion_origin); if (have_attr) { ret = expansion_origin; } return ret; } void DataArrayHDF5::expansionOrigin(double expansion_origin) { group().setAttr("expansion_origin", expansion_origin); forceUpdatedAt(); } void DataArrayHDF5::expansionOrigin(const none_t t) { if (group().hasAttr("expansion_origin")) { group().removeAttr("expansion_origin"); } forceUpdatedAt(); } // TODO use defaults vector<double> DataArrayHDF5::polynomCoefficients() const { vector<double> polynom_coefficients; if (group().hasData("polynom_coefficients")) { DataSet ds = group().openData("polynom_coefficients"); ds.read(polynom_coefficients, true); } return polynom_coefficients; } void DataArrayHDF5::polynomCoefficients(const vector<double> &coefficients) { DataSet ds; if (group().hasData("polynom_coefficients")) { ds = group().openData("polynom_coefficients"); ds.setExtent({coefficients.size()}); } else { ds = group().createData("polynom_coefficients", H5T_NATIVE_DOUBLE, {coefficients.size()}); } ds.write(coefficients); forceUpdatedAt(); } void DataArrayHDF5::polynomCoefficients(const none_t t) { if (group().hasData("polynom_coefficients")) { group().removeData("polynom_coefficients"); } forceUpdatedAt(); } //-------------------------------------------------- // Methods concerning dimensions //-------------------------------------------------- ndsize_t DataArrayHDF5::dimensionCount() const { boost::optional<H5Group> g = dimension_group(); ndsize_t count = 0; if (g) { count = g->objectCount(); } return count; } shared_ptr<IDimension> DataArrayHDF5::getDimension(ndsize_t index) const { shared_ptr<IDimension> dim; boost::optional<H5Group> g = dimension_group(); if (g) { string str_id = util::numToStr(index); if (g->hasGroup(str_id)) { H5Group group = g->openGroup(str_id, false); dim = openDimensionHDF5(group, index); } } return dim; } std::shared_ptr<base::ISetDimension> DataArrayHDF5::createSetDimension(ndsize_t index) { H5Group g = createDimensionGroup(index); return make_shared<SetDimensionHDF5>(g, index); } std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createRangeDimension(ndsize_t index, const std::vector<double> &ticks) { H5Group g = createDimensionGroup(index); return make_shared<RangeDimensionHDF5>(g, index, ticks); } std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createAliasRangeDimension() { H5Group g = createDimensionGroup(1); return make_shared<RangeDimensionHDF5>(g, 1, *this); } std::shared_ptr<base::ISampledDimension> DataArrayHDF5::createSampledDimension(ndsize_t index, double sampling_interval) { H5Group g = createDimensionGroup(index); return make_shared<SampledDimensionHDF5>(g, index, sampling_interval); } H5Group DataArrayHDF5::createDimensionGroup(ndsize_t index) { boost::optional<H5Group> g = dimension_group(true); ndsize_t dim_max = dimensionCount() + 1; if (index > dim_max || index <= 0) throw new runtime_error("Invalid dimension index: has to be 0 < index <= " + util::numToStr(dim_max)); string str_id = util::numToStr(index); if (g->hasGroup(str_id)) { g->removeGroup(str_id); } return g->openGroup(str_id, true); } bool DataArrayHDF5::deleteDimension(ndsize_t index) { bool deleted = false; ndsize_t dim_count = dimensionCount(); string str_id = util::numToStr(index); boost::optional<H5Group> g = dimension_group(); if (g) { if (g->hasGroup(str_id)) { g->removeGroup(str_id); deleted = true; } if (deleted && index < dim_count) { for (ndsize_t old_id = index + 1; old_id <= dim_count; old_id++) { string str_old_id = util::numToStr(old_id); string str_new_id = util::numToStr(old_id - 1); g->renameGroup(str_old_id, str_new_id); } } } return deleted; } //-------------------------------------------------- // Other methods and functions //-------------------------------------------------- DataArrayHDF5::~DataArrayHDF5() { } void DataArrayHDF5::createData(DataType dtype, const NDSize &size) { if (group().hasData("data")) { throw ConsistencyError("DataArray's hdf5 data group already exists!"); } h5x::DataType fileType = data_type_to_h5_filetype(dtype); group().createData("data", fileType, size); } bool DataArrayHDF5::hasData() const { return group().hasData("data"); } void DataArrayHDF5::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) { if (!group().hasData("data")) { throw ConsistencyError("DataArray with missing h5df DataSet"); } DataSet ds = group().openData("data"); DataSpace fileSpace = ds.getSpace(); DataSpace memSpace = DataSpace::create(count, false); if (offset && count) { fileSpace.hyperslab(count, offset); } else if (offset && !count) { fileSpace.hyperslab(NDSize(offset.size(), 1), offset); } h5x::DataType memType = data_type_to_h5_memtype(dtype); ds.write(data, memType, memSpace, fileSpace); } void DataArrayHDF5::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const { if (!group().hasData("data")) { throw ConsistencyError("DataArray with missing h5df DataSet"); } DataSet ds = group().openData("data"); DataSpace memSpace = DataSpace::create(count, false); DataSpace fileSpace = ds.getSpace(); if (offset && count) { fileSpace.hyperslab(count, offset); } else if (offset && !count) { fileSpace.hyperslab(NDSize(offset.size(), 1), offset); } h5x::DataType memType = data_type_to_h5_memtype(dtype); ds.read(data, memType, memSpace, fileSpace); } NDSize DataArrayHDF5::dataExtent(void) const { if (!group().hasData("data")) { return NDSize{}; } DataSet ds = group().openData("data"); return ds.size(); } void DataArrayHDF5::dataExtent(const NDSize &extent) { if (!group().hasData("data")) { throw runtime_error("Data field not found in DataArray!"); } DataSet ds = group().openData("data"); ds.setExtent(extent); } DataType DataArrayHDF5::dataType(void) const { if (!group().hasData("data")) { return DataType::Nothing; } DataSet ds = group().openData("data"); const h5x::DataType dtype = ds.dataType(); return data_type_from_h5(dtype); } } // ns nix::hdf5 } // ns nix <|endoftext|>
<commit_before>//===--- Quality.cpp --------------------------------------------*- C++-*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===---------------------------------------------------------------------===// #include "Quality.h" #include "index/Index.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/SourceManager.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" namespace clang { namespace clangd { using namespace llvm; static bool hasDeclInMainFile(const Decl &D) { auto &SourceMgr = D.getASTContext().getSourceManager(); for (auto *Redecl : D.redecls()) { auto Loc = SourceMgr.getSpellingLoc(Redecl->getLocation()); if (SourceMgr.isWrittenInMainFile(Loc)) return true; } return false; } void SymbolQualitySignals::merge(const CodeCompletionResult &SemaCCResult) { SemaCCPriority = SemaCCResult.Priority; if (SemaCCResult.Availability == CXAvailability_Deprecated) Deprecated = true; } void SymbolQualitySignals::merge(const Symbol &IndexResult) { References = std::max(IndexResult.References, References); } float SymbolQualitySignals::evaluate() const { float Score = 1; // This avoids a sharp gradient for tail symbols, and also neatly avoids the // question of whether 0 references means a bad symbol or missing data. if (References >= 3) Score *= std::log(References); if (SemaCCPriority) // Map onto a 0-2 interval, so we don't reward/penalize non-Sema results. // Priority 80 is a really bad score. Score *= 2 - std::min<float>(80, SemaCCPriority) / 40; if (Deprecated) Score *= 0.1f; return Score; } raw_ostream &operator<<(raw_ostream &OS, const SymbolQualitySignals &S) { OS << formatv("=== Symbol quality: {0}\n", S.evaluate()); if (S.SemaCCPriority) OS << formatv("\tSemaCCPriority: {0}\n", S.SemaCCPriority); OS << formatv("\tReferences: {0}\n", S.References); OS << formatv("\tDeprecated: {0}\n", S.Deprecated); return OS; } static SymbolRelevanceSignals::AccessibleScope ComputeScope(const NamedDecl &D) { bool InClass; for (const DeclContext *DC = D.getDeclContext(); !DC->isFileContext(); DC = DC->getParent()) { if (DC->isFunctionOrMethod()) return SymbolRelevanceSignals::FunctionScope; InClass = InClass || DC->isRecord(); } if (InClass) return SymbolRelevanceSignals::ClassScope; // This threshold could be tweaked, e.g. to treat module-visible as global. if (D.getLinkageInternal() < ExternalLinkage) return SymbolRelevanceSignals::FileScope; return SymbolRelevanceSignals::GlobalScope; } void SymbolRelevanceSignals::merge(const Symbol &IndexResult) { // FIXME: Index results always assumed to be at global scope. If Scope becomes // relevant to non-completion requests, we should recognize class members etc. } void SymbolRelevanceSignals::merge(const CodeCompletionResult &SemaCCResult) { if (SemaCCResult.Availability == CXAvailability_NotAvailable || SemaCCResult.Availability == CXAvailability_NotAccessible) Forbidden = true; if (SemaCCResult.Declaration) { // We boost things that have decls in the main file. // The real proximity scores would be more general when we have them. float DeclProximity = hasDeclInMainFile(*SemaCCResult.Declaration) ? 1.0 : 0.0; ProximityScore = std::max(DeclProximity, ProximityScore); } // Declarations are scoped, others (like macros) are assumed global. if (SemaCCResult.Kind == CodeCompletionResult::RK_Declaration) Scope = std::min(Scope, ComputeScope(*SemaCCResult.Declaration)); } float SymbolRelevanceSignals::evaluate() const { float Score = 1; if (Forbidden) return 0; Score *= NameMatch; // Proximity scores are [0,1] and we translate them into a multiplier in the // range from 1 to 2. Score *= 1 + ProximityScore; // Symbols like local variables may only be referenced within their scope. // Conversely if we're in that scope, it's likely we'll reference them. if (Query == CodeComplete) { // The narrower the scope where a symbol is visible, the more likely it is // to be relevant when it is available. switch (Scope) { case GlobalScope: break; case FileScope: Score *= 1.5; case ClassScope: Score *= 2; case FunctionScope: Score *= 4; } } return Score; } raw_ostream &operator<<(raw_ostream &OS, const SymbolRelevanceSignals &S) { OS << formatv("=== Symbol relevance: {0}\n", S.evaluate()); OS << formatv("\tName match: {0}\n", S.NameMatch); OS << formatv("\tForbidden: {0}\n", S.Forbidden); return OS; } float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance) { return SymbolQuality * SymbolRelevance; } // Produces an integer that sorts in the same order as F. // That is: a < b <==> encodeFloat(a) < encodeFloat(b). static uint32_t encodeFloat(float F) { static_assert(std::numeric_limits<float>::is_iec559, ""); constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1); // Get the bits of the float. Endianness is the same as for integers. uint32_t U = FloatToBits(F); // IEEE 754 floats compare like sign-magnitude integers. if (U & TopBit) // Negative float. return 0 - U; // Map onto the low half of integers, order reversed. return U + TopBit; // Positive floats map onto the high half of integers. } std::string sortText(float Score, llvm::StringRef Name) { // We convert -Score to an integer, and hex-encode for readability. // Example: [0.5, "foo"] -> "41000000foo" std::string S; llvm::raw_string_ostream OS(S); write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower, /*Width=*/2 * sizeof(Score)); OS << Name; OS.flush(); return S; } } // namespace clangd } // namespace clang <commit_msg>[clangd] Quality fixes (uninit var, missing debug output, pattern decl CCRs).<commit_after>//===--- Quality.cpp --------------------------------------------*- C++-*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===---------------------------------------------------------------------===// #include "Quality.h" #include "index/Index.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/SourceManager.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" namespace clang { namespace clangd { using namespace llvm; static bool hasDeclInMainFile(const Decl &D) { auto &SourceMgr = D.getASTContext().getSourceManager(); for (auto *Redecl : D.redecls()) { auto Loc = SourceMgr.getSpellingLoc(Redecl->getLocation()); if (SourceMgr.isWrittenInMainFile(Loc)) return true; } return false; } void SymbolQualitySignals::merge(const CodeCompletionResult &SemaCCResult) { SemaCCPriority = SemaCCResult.Priority; if (SemaCCResult.Availability == CXAvailability_Deprecated) Deprecated = true; } void SymbolQualitySignals::merge(const Symbol &IndexResult) { References = std::max(IndexResult.References, References); } float SymbolQualitySignals::evaluate() const { float Score = 1; // This avoids a sharp gradient for tail symbols, and also neatly avoids the // question of whether 0 references means a bad symbol or missing data. if (References >= 3) Score *= std::log(References); if (SemaCCPriority) // Map onto a 0-2 interval, so we don't reward/penalize non-Sema results. // Priority 80 is a really bad score. Score *= 2 - std::min<float>(80, SemaCCPriority) / 40; if (Deprecated) Score *= 0.1f; return Score; } raw_ostream &operator<<(raw_ostream &OS, const SymbolQualitySignals &S) { OS << formatv("=== Symbol quality: {0}\n", S.evaluate()); if (S.SemaCCPriority) OS << formatv("\tSemaCCPriority: {0}\n", S.SemaCCPriority); OS << formatv("\tReferences: {0}\n", S.References); OS << formatv("\tDeprecated: {0}\n", S.Deprecated); return OS; } static SymbolRelevanceSignals::AccessibleScope ComputeScope(const NamedDecl &D) { bool InClass = true; for (const DeclContext *DC = D.getDeclContext(); !DC->isFileContext(); DC = DC->getParent()) { if (DC->isFunctionOrMethod()) return SymbolRelevanceSignals::FunctionScope; InClass = InClass || DC->isRecord(); } if (InClass) return SymbolRelevanceSignals::ClassScope; // This threshold could be tweaked, e.g. to treat module-visible as global. if (D.getLinkageInternal() < ExternalLinkage) return SymbolRelevanceSignals::FileScope; return SymbolRelevanceSignals::GlobalScope; } void SymbolRelevanceSignals::merge(const Symbol &IndexResult) { // FIXME: Index results always assumed to be at global scope. If Scope becomes // relevant to non-completion requests, we should recognize class members etc. } void SymbolRelevanceSignals::merge(const CodeCompletionResult &SemaCCResult) { if (SemaCCResult.Availability == CXAvailability_NotAvailable || SemaCCResult.Availability == CXAvailability_NotAccessible) Forbidden = true; if (SemaCCResult.Declaration) { // We boost things that have decls in the main file. // The real proximity scores would be more general when we have them. float DeclProximity = hasDeclInMainFile(*SemaCCResult.Declaration) ? 1.0 : 0.0; ProximityScore = std::max(DeclProximity, ProximityScore); } // Declarations are scoped, others (like macros) are assumed global. if (SemaCCResult.Declaration) Scope = std::min(Scope, ComputeScope(*SemaCCResult.Declaration)); } float SymbolRelevanceSignals::evaluate() const { float Score = 1; if (Forbidden) return 0; Score *= NameMatch; // Proximity scores are [0,1] and we translate them into a multiplier in the // range from 1 to 2. Score *= 1 + ProximityScore; // Symbols like local variables may only be referenced within their scope. // Conversely if we're in that scope, it's likely we'll reference them. if (Query == CodeComplete) { // The narrower the scope where a symbol is visible, the more likely it is // to be relevant when it is available. switch (Scope) { case GlobalScope: break; case FileScope: Score *= 1.5; case ClassScope: Score *= 2; case FunctionScope: Score *= 4; } } return Score; } raw_ostream &operator<<(raw_ostream &OS, const SymbolRelevanceSignals &S) { OS << formatv("=== Symbol relevance: {0}\n", S.evaluate()); OS << formatv("\tName match: {0}\n", S.NameMatch); OS << formatv("\tForbidden: {0}\n", S.Forbidden); OS << formatv("\tProximity: {0}\n", S.ProximityScore); OS << formatv("\tQuery type: {0}\n", static_cast<int>(S.Query)); OS << formatv("\tScope: {0}\n", static_cast<int>(S.Scope)); return OS; } float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance) { return SymbolQuality * SymbolRelevance; } // Produces an integer that sorts in the same order as F. // That is: a < b <==> encodeFloat(a) < encodeFloat(b). static uint32_t encodeFloat(float F) { static_assert(std::numeric_limits<float>::is_iec559, ""); constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1); // Get the bits of the float. Endianness is the same as for integers. uint32_t U = FloatToBits(F); // IEEE 754 floats compare like sign-magnitude integers. if (U & TopBit) // Negative float. return 0 - U; // Map onto the low half of integers, order reversed. return U + TopBit; // Positive floats map onto the high half of integers. } std::string sortText(float Score, llvm::StringRef Name) { // We convert -Score to an integer, and hex-encode for readability. // Example: [0.5, "foo"] -> "41000000foo" std::string S; llvm::raw_string_ostream OS(S); write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower, /*Width=*/2 * sizeof(Score)); OS << Name; OS.flush(); return S; } } // namespace clangd } // namespace clang <|endoftext|>
<commit_before>/** The MIT License (MIT) Copyright (c) 2016 Ryotaro Onuki 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 "ntp.h" #include <TimeLib.h> #include <WiFiUdp.h> #include "config.h" #include <Time.h> // NTP Servers: IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov // IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov // IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov WiFiUDP Udp; unsigned int localPort = 8888; // local port to listen for UDP packets void ntp_begin() { println_dbg("Starting NTP UDP"); Udp.begin(localPort); print_dbg("Local port: "); println_dbg(Udp.localPort()); println_dbg("waiting for sync"); setSyncProvider(getNtpTime); char s[20]; const char* format = "%04d/%02d/%02d %02d:%02d:%02d"; // JST time_t n = now(); time_t t = localtime(n, 9); sprintf(s, format, year(t), month(t), day(t), hour(t), minute(t), second(t)); print_dbg("JST : "); println_dbg(s); } time_t localtime(time_t t, int timeZone) { return t + timeZone * SECS_PER_HOUR; } /*-------- NTP code ----------*/ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets time_t getNtpTime() { while (Udp.parsePacket() > 0) ; // discard any previously received packets println_dbg("Transmit NTP Request"); sendNTPpacket(timeServer); uint32_t beginWait = millis(); while (millis() - beginWait < 1500) { int size = Udp.parsePacket(); if (size >= NTP_PACKET_SIZE) { println_dbg("Receive NTP Response"); Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer unsigned long secsSince1900; // convert four bytes starting at location 40 to a long integer secsSince1900 = (unsigned long)packetBuffer[40] << 24; secsSince1900 |= (unsigned long)packetBuffer[41] << 16; secsSince1900 |= (unsigned long)packetBuffer[42] << 8; secsSince1900 |= (unsigned long)packetBuffer[43]; return secsSince1900 - 2208988800UL; } } println_dbg("No NTP Response :-("); return 0; // return 0 if unable to get the time } // send an NTP request to the time server at the given address void sendNTPpacket(IPAddress &address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } <commit_msg>NTPサーバーアドレスを変更 #12<commit_after>/** The MIT License (MIT) Copyright (c) 2016 Ryotaro Onuki 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 "ntp.h" #include <TimeLib.h> #include <WiFiUdp.h> #include "config.h" #include <Time.h> // NTP Servers: IPAddress timeServer(210, 173, 160, 57); // ntp.jst.mfeed.ad.jp WiFiUDP Udp; unsigned int localPort = 8888; // local port to listen for UDP packets void ntp_begin() { println_dbg("Starting NTP UDP"); Udp.begin(localPort); print_dbg("Local port: "); println_dbg(Udp.localPort()); println_dbg("waiting for sync"); setSyncProvider(getNtpTime); char s[20]; const char* format = "%04d/%02d/%02d %02d:%02d:%02d"; // JST time_t n = now(); time_t t = localtime(n, 9); sprintf(s, format, year(t), month(t), day(t), hour(t), minute(t), second(t)); print_dbg("JST : "); println_dbg(s); } time_t localtime(time_t t, int timeZone) { return t + timeZone * SECS_PER_HOUR; } /*-------- NTP code ----------*/ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets time_t getNtpTime() { while (Udp.parsePacket() > 0) ; // discard any previously received packets println_dbg("Transmit NTP Request"); sendNTPpacket(timeServer); uint32_t beginWait = millis(); while (millis() - beginWait < 1500) { int size = Udp.parsePacket(); if (size >= NTP_PACKET_SIZE) { println_dbg("Receive NTP Response"); Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer unsigned long secsSince1900; // convert four bytes starting at location 40 to a long integer secsSince1900 = (unsigned long)packetBuffer[40] << 24; secsSince1900 |= (unsigned long)packetBuffer[41] << 16; secsSince1900 |= (unsigned long)packetBuffer[42] << 8; secsSince1900 |= (unsigned long)packetBuffer[43]; return secsSince1900 - 2208988800UL; } } println_dbg("No NTP Response :-("); return 0; // return 0 if unable to get the time } // send an NTP request to the time server at the given address void sendNTPpacket(IPAddress &address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <string.h> #include <getopt.h> #include <iostream> #include "cli.hpp" #include <brotli/enc/encode.h> #include "trace_file.hpp" #include "trace_ostream.hpp" static const char *synopsis = "Repack a trace file with different compression."; static void usage(void) { std::cout << "usage: apitrace repack [options] <in-trace-file> <out-trace-file>\n" << synopsis << "\n" << "\n" << "Snappy compression allows for faster replay and smaller memory footprint,\n" << "at the expense of a slightly smaller compression ratio than zlib\n" << "\n" << " -b,--brotli Use Brotli compression\n" << " -z,--zlib Use ZLib compression\n" << "\n"; } const static char * shortOptions = "hbz"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"brotli", optional_argument, 0, 'b'}, {"zlib", no_argument, 0, 'z'}, {0, 0, 0, 0} }; enum Format { FORMAT_SNAPPY = 0, FORMAT_ZLIB, FORMAT_BROTLI, }; class BrotliTraceIn : public brotli::BrotliIn { private: trace::File *stream; char buf[1 << 16]; bool eof = false; public: BrotliTraceIn(trace::File *s) : stream(s) { } ~BrotliTraceIn() { } const void * Read(size_t n, size_t* bytes_read) override { if (n > sizeof buf) { n = sizeof buf; } else if (n == 0) { return eof ? nullptr : buf; } *bytes_read = stream->read(buf, n); if (*bytes_read == 0) { eof = true; return nullptr; } return buf; } }; static int repack_generic(trace::File *inFile, trace::OutStream *outFile) { const size_t size = 8192; char *buf = new char[size]; size_t read; while ((read = inFile->read(buf, size)) != 0) { outFile->write(buf, read); } delete [] buf; return EXIT_SUCCESS; } static int repack_brotli(trace::File *inFile, const char *outFileName, int quality) { brotli::BrotliParams params; // Brotli default quality is 11, but there are problems using quality // higher than 9: // // - Some traces cause compression to be extremely slow. Possibly the same // issue as https://github.com/google/brotli/issues/330 // - Some traces get lower compression ratio with 11 than 9. Possibly the // same issue as https://github.com/google/brotli/issues/222 params.quality = 9; // The larger the window, the higher the compression ratio and // decompression speeds, so choose the maximum. params.lgwin = 24; if (quality > 0) { params.quality = quality; } BrotliTraceIn in(inFile); FILE *fout = fopen(outFileName, "wb"); if (!fout) { return EXIT_FAILURE; } assert(fout); brotli::BrotliFileOut out(fout); if (!BrotliCompress(params, &in, &out)) { std::cerr << "error: brotli compression failed\n"; return EXIT_FAILURE; } fclose(fout); return EXIT_SUCCESS; } static int repack(const char *inFileName, const char *outFileName, Format format, int quality) { int ret = EXIT_FAILURE; trace::File *inFile = trace::File::createForRead(inFileName); if (!inFile) { return 1; } trace::OutStream *outFile = nullptr; if (format == FORMAT_SNAPPY) { outFile = trace::createSnappyStream(outFileName); } else if (format == FORMAT_BROTLI) { ret = repack_brotli(inFile, outFileName, quality); delete inFile; return ret; } else if (format == FORMAT_ZLIB) { outFile = trace::createZLibStream(outFileName); } if (outFile) { ret = repack_generic(inFile, outFile); delete outFile; } delete inFile; return ret; } static int command(int argc, char *argv[]) { Format format = FORMAT_SNAPPY; int opt; int quality = -1; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case 'b': format = FORMAT_BROTLI; if (optarg) { quality = atoi(optarg); } break; case 'z': format = FORMAT_ZLIB; break; default: std::cerr << "error: unexpected option `" << (char)opt << "`\n"; usage(); return 1; } } if (argc != optind + 2) { std::cerr << "error: insufficient number of arguments\n"; usage(); return 1; } return repack(argv[optind], argv[optind + 1], format, quality); } const Command repack_command = { "repack", synopsis, usage, command }; <commit_msg>cli: Do CRC check of the compressed Brotli file.<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <string.h> #include <getopt.h> #include <iostream> #include <memory> #include "cli.hpp" #include <brotli/enc/encode.h> #include <zlib.h> // for crc32 #include "trace_file.hpp" #include "trace_ostream.hpp" static const char *synopsis = "Repack a trace file with different compression."; static void usage(void) { std::cout << "usage: apitrace repack [options] <in-trace-file> <out-trace-file>\n" << synopsis << "\n" << "\n" << "Snappy compression allows for faster replay and smaller memory footprint,\n" << "at the expense of a slightly smaller compression ratio than zlib\n" << "\n" << " -b,--brotli Use Brotli compression\n" << " -z,--zlib Use ZLib compression\n" << "\n"; } const static char * shortOptions = "hbz"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"brotli", optional_argument, 0, 'b'}, {"zlib", no_argument, 0, 'z'}, {0, 0, 0, 0} }; enum Format { FORMAT_SNAPPY = 0, FORMAT_ZLIB, FORMAT_BROTLI, }; class BrotliTraceIn : public brotli::BrotliIn { private: trace::File *stream; char buf[1 << 16]; bool eof = false; public: uLong crc; BrotliTraceIn(trace::File *s) : stream(s) { crc = crc32(0L, Z_NULL, 0); } ~BrotliTraceIn() { } const void * Read(size_t n, size_t* bytes_read) override { if (n > sizeof buf) { n = sizeof buf; } else if (n == 0) { return eof ? nullptr : buf; } *bytes_read = stream->read(buf, n); if (*bytes_read == 0) { eof = true; return nullptr; } crc32(crc, reinterpret_cast<const Bytef *>(buf), *bytes_read); return buf; } }; static int repack_generic(trace::File *inFile, trace::OutStream *outFile) { const size_t size = 8192; char *buf = new char[size]; size_t read; while ((read = inFile->read(buf, size)) != 0) { outFile->write(buf, read); } delete [] buf; return EXIT_SUCCESS; } static int repack_brotli(trace::File *inFile, const char *outFileName, int quality) { brotli::BrotliParams params; // Brotli default quality is 11, but there are problems using quality // higher than 9: // // - Some traces cause compression to be extremely slow. Possibly the same // issue as https://github.com/google/brotli/issues/330 // - Some traces get lower compression ratio with 11 than 9. Possibly the // same issue as https://github.com/google/brotli/issues/222 params.quality = 9; // The larger the window, the higher the compression ratio and // decompression speeds, so choose the maximum. params.lgwin = 24; if (quality > 0) { params.quality = quality; } BrotliTraceIn in(inFile); FILE *fout = fopen(outFileName, "wb"); if (!fout) { return EXIT_FAILURE; } assert(fout); brotli::BrotliFileOut out(fout); if (!BrotliCompress(params, &in, &out)) { std::cerr << "error: brotli compression failed\n"; return EXIT_FAILURE; } fclose(fout); std::unique_ptr<trace::File> outFileIn(trace::File::createBrotli()); if (!outFileIn->open(outFileName)) { std::cerr << "error: failed to open " << outFileName << " for reading\n"; return EXIT_FAILURE; } BrotliTraceIn outIn(outFileIn.get()); size_t bytes_read; do { outIn.Read(65536, &bytes_read); } while (bytes_read > 0); if (in.crc != outIn.crc) { std::cerr << "error: CRC mismatch reading " << outFileName << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } static int repack(const char *inFileName, const char *outFileName, Format format, int quality) { int ret = EXIT_FAILURE; trace::File *inFile = trace::File::createForRead(inFileName); if (!inFile) { return 1; } trace::OutStream *outFile = nullptr; if (format == FORMAT_SNAPPY) { outFile = trace::createSnappyStream(outFileName); } else if (format == FORMAT_BROTLI) { ret = repack_brotli(inFile, outFileName, quality); delete inFile; return ret; } else if (format == FORMAT_ZLIB) { outFile = trace::createZLibStream(outFileName); } if (outFile) { ret = repack_generic(inFile, outFile); delete outFile; } delete inFile; return ret; } static int command(int argc, char *argv[]) { Format format = FORMAT_SNAPPY; int opt; int quality = -1; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case 'b': format = FORMAT_BROTLI; if (optarg) { quality = atoi(optarg); } break; case 'z': format = FORMAT_ZLIB; break; default: std::cerr << "error: unexpected option `" << (char)opt << "`\n"; usage(); return 1; } } if (argc != optind + 2) { std::cerr << "error: insufficient number of arguments\n"; usage(); return 1; } return repack(argv[optind], argv[optind + 1], format, quality); } const Command repack_command = { "repack", synopsis, usage, command }; <|endoftext|>
<commit_before><commit_msg>TODO-721: WIP<commit_after><|endoftext|>
<commit_before> #include <stdio.h> #include <vector> #include <time.h> #include <libmemcached/memcached.h> using namespace std; #define MAX_HOST 255 /* Returns random number between [min, max] */ size_t random(size_t min, size_t max) { return rand() % (max - min + 1) + min; } /* Helpful typedefs */ typedef pair<char*, size_t> payload_t; /* Defines a load in terms of ratio of deletes, updates, inserts, and * reads. */ struct load_t { public: load_t() : deletes(1), updates(4), inserts(8), reads(64) {} load_t(int d, int u, int i, int r) : deletes(d), updates(u), inserts(i), reads(r) {} enum load_op_t { delete_op, update_op, insert_op, read_op }; // Generates an operation to perform using the ratios as // probabilities. load_op_t toss() { int total = deletes + updates + inserts + reads; int rand_op = random(0, total - 1); int acc = 0; if(rand_op >= acc && rand_op < (acc += deletes)) return delete_op; if(rand_op >= acc && rand_op < (acc += updates)) return update_op; if(rand_op >= acc && rand_op < (acc += inserts)) return insert_op; if(rand_op >= acc && rand_op < (acc += reads)) return read_op; fprintf(stderr, "Something horrible has happened with the toss\n"); exit(-1); } void print() { printf("%d/%d/%d/%d", deletes, updates, inserts, reads); } public: int deletes; int updates; int inserts; int reads; }; /* Defines a distribution of values, from min to max. */ struct distr_t { public: distr_t(int _min, int _max) : min(_min), max(_max) {} distr_t() : min(8), max(16) {} // Generates a random payload within given bounds. It is the // user's responsibility to clean up the payload. void toss(payload_t *payload) { // generate the size int s = random(min, max); // malloc and fill memory char *l = (char*)malloc(s); for(int i = 0; i < s; i++) { l[i] = random(65, 90); } // fill the payload payload->first = l; payload->second = s; } void print() { printf("%d-%d", min, max); } public: int min, max; }; /* Defines a client configuration, including sensible default * values.*/ struct config_t { public: config_t() : port(11211), clients(64), load(load_t()), keys(distr_t(8, 16)), values(distr_t(8, 128)), duration(10000000) { strcpy(host, "localhost"); } void print() { printf("[host: %s, port: %d, clients: %d, load: ", host, port, clients); load.print(); printf(", keys: "); keys.print(); printf(", values: "); values.print(); printf(" , duration: %ld]\n", duration); } public: char host[MAX_HOST]; int port; int clients; load_t load; distr_t keys; distr_t values; long duration; }; /* Usage */ void usage(const char *name) { // Create a default config config_t _d; // Print usage printf("Usage:\n"); printf("\t%s [OPTIONS]\n", name); printf("\nOptions:\n"); printf("\t-h, --host\n\t\tServer host to connect to. Defaults to [%s].\n", _d.host); printf("\t-p, --port\n\t\tServer port to connect to. Defaults to [%d].\n", _d.port); printf("\t-c, --clients\n\t\tNumber of concurrent clients. Defaults to [%d].\n", _d.clients); printf("\t-l, --load\n\t\tTarget load to generate. Expects a value in format D:U:I:R, where\n" \ "\t\t\tD - number of deletes\n" \ "\t\t\tU - number of updates\n" \ "\t\t\tI - number of inserts\n" \ "\t\t\tR - number of reads\n" \ "\t\tDefaults to ["); _d.load.print(); printf("]\n"); printf("\t-k, --keys\n\t\tKey distribution in DISTR format (see below). Defaults to ["); _d.keys.print(); printf("].\n"); printf("\t-v, --values\n\t\tValue distribution in DISTR format (see below). Defaults to ["); _d.values.print(); printf("].\n"); printf("\t-d, --duration\n\t\tDuration of the run specified in number of operations.\n" \ "\t\tDefaults to [%ld].\n", _d.duration); printf("\nAdditional information:\n"); printf("\t\tDISTR format describes a range and can be specified in as MIN-MAX\n"); exit(-1); } void* run_client(void* data) { // Grab the config config_t *config = (config_t*)data; // Connect to the server memcached_st memcached; memcached_create(&memcached); memcached_server_add(&memcached, config->host, config->port); // Store the keys so we can run updates and deletes. vector<payload_t> keys; // Perform the ops for(int i = 0; i < config->duration; i++) { // Generate the command load_t::load_op_t cmd = config->load.toss(); int _val; payload_t key, value; char *_value; size_t _value_length; uint32_t _flags; memcached_return_t _error; switch(cmd) { case load_t::delete_op: // Find the key if(keys.empty()) break; _val = random(0, keys.size() - 1); key = keys[_val]; // Delete it from the server _error = memcached_delete(&memcached, key.first, key.second, 0); if(_error != MEMCACHED_SUCCESS) { fprintf(stderr, "Error performing delete operation (%d)\n", _error); exit(-1); } // Our own bookkeeping free(key.first); keys[_val] = keys[keys.size() - 1]; keys.erase(keys.begin() + _val); break; case load_t::update_op: // Find the key and generate the payload if(keys.empty()) break; key = keys[random(0, keys.size() - 1)]; config->values.toss(&value); // Send it to server _error = memcached_set(&memcached, key.first, key.second, value.first, value.second, 0, 0); if(_error != MEMCACHED_SUCCESS) { fprintf(stderr, "Error performing update operation (%d)\n", _error); exit(-1); } // Free the value free(value.first); break; case load_t::insert_op: // Generate the payload config->keys.toss(&key); config->values.toss(&value); // Send it to server _error = memcached_set(&memcached, key.first, key.second, value.first, value.second, 0, 0); if(_error != MEMCACHED_SUCCESS) { fprintf(stderr, "Error performing insert operation (%d)\n", _error); exit(-1); } // Free the value and save the key free(value.first); keys.push_back(key); break; case load_t::read_op: // Find the key if(keys.empty()) break; key = keys[random(0, keys.size() - 1)]; // Read it from the server _value = memcached_get(&memcached, key.first, key.second, &_value_length, &_flags, &_error); if(_error != MEMCACHED_SUCCESS) { fprintf(stderr, "Error performing read operation (%d)\n", _error); exit(-1); } // Our own bookkeeping free(_value); break; }; } // Disconnect memcached_free(&memcached); // Free all the keys for(vector<payload_t>::iterator i = keys.begin(); i != keys.end(); i++) { free(i->first); } } int main(int argv, char *argc[]) { // Initialize randomness srand(time(NULL)); // Parse the arguments config_t config; int res; vector<pthread_t> threads(config.clients); // Create the threads for(int i = 0; i < config.clients; i++) { int res = pthread_create(&threads[i], NULL, run_client, &config); if(res != 0) { fprintf(stderr, "Can't create thread"); exit(-1); } } // Wait for the threads to finish for(int i = 0; i < config.clients; i++) { res = pthread_join(threads[i], NULL); if(res != 0) { fprintf(stderr, "Can't join on the thread"); exit(-1); } } return 0; } <commit_msg>Adding support for parsing<commit_after> #include <unistd.h> #include <getopt.h> #include <stdio.h> #include <vector> #include <time.h> #include <libmemcached/memcached.h> using namespace std; #define MAX_HOST 255 /* Returns random number between [min, max] */ size_t random(size_t min, size_t max) { return rand() % (max - min + 1) + min; } /* Helpful typedefs */ typedef pair<char*, size_t> payload_t; /* Defines a load in terms of ratio of deletes, updates, inserts, and * reads. */ struct load_t { public: load_t() : deletes(1), updates(4), inserts(8), reads(64) {} load_t(int d, int u, int i, int r) : deletes(d), updates(u), inserts(i), reads(r) {} enum load_op_t { delete_op, update_op, insert_op, read_op }; // Generates an operation to perform using the ratios as // probabilities. load_op_t toss() { int total = deletes + updates + inserts + reads; int rand_op = random(0, total - 1); int acc = 0; if(rand_op >= acc && rand_op < (acc += deletes)) return delete_op; if(rand_op >= acc && rand_op < (acc += updates)) return update_op; if(rand_op >= acc && rand_op < (acc += inserts)) return insert_op; if(rand_op >= acc && rand_op < (acc += reads)) return read_op; fprintf(stderr, "Something horrible has happened with the toss\n"); exit(-1); } void parse(char *str) { char *tok = strtok(str, "/"); int c = 0; while(tok != NULL) { switch(c) { case 0: deletes = atoi(tok); break; case 1: updates = atoi(tok); break; case 2: inserts = atoi(tok); break; case 3: reads = atoi(tok); break; default: fprintf(stderr, "Invalid load format (use D/U/I/R)\n"); exit(-1); break; } tok = strtok(NULL, "/"); c++; } if(c < 4) { fprintf(stderr, "Invalid load format (use D/U/I/R)\n"); exit(-1); } } void print() { printf("%d/%d/%d/%d", deletes, updates, inserts, reads); } public: int deletes; int updates; int inserts; int reads; }; /* Defines a distribution of values, from min to max. */ struct distr_t { public: distr_t(int _min, int _max) : min(_min), max(_max) {} distr_t() : min(8), max(16) {} // Generates a random payload within given bounds. It is the // user's responsibility to clean up the payload. void toss(payload_t *payload) { // generate the size int s = random(min, max); // malloc and fill memory char *l = (char*)malloc(s); for(int i = 0; i < s; i++) { l[i] = random(65, 90); } // fill the payload payload->first = l; payload->second = s; } void parse(char *str) { char *tok = strtok(str, "-"); int c = 0; while(tok != NULL) { switch(c) { case 0: min = atoi(tok); break; case 1: max = atoi(tok); break; default: fprintf(stderr, "Invalid distr format (use MIN-MAX)\n"); exit(-1); break; } tok = strtok(NULL, "-"); c++; } if(c < 2) { fprintf(stderr, "Invalid distr format (use MIN-MAX)\n"); exit(-1); } } void print() { printf("%d-%d", min, max); } public: int min, max; }; /* Defines a client configuration, including sensible default * values.*/ struct config_t { public: config_t() : port(11211), clients(64), load(load_t()), keys(distr_t(8, 16)), values(distr_t(8, 128)), duration(10000000L) { strcpy(host, "localhost"); } void print() { printf("[host: %s, port: %d, clients: %d, load: ", host, port, clients); load.print(); printf(", keys: "); keys.print(); printf(", values: "); values.print(); printf(" , duration: %ld]\n", duration); } public: char host[MAX_HOST]; int port; int clients; load_t load; distr_t keys; distr_t values; long duration; }; /* Usage */ void usage(const char *name) { // Create a default config config_t _d; // Print usage printf("Usage:\n"); printf("\t%s [OPTIONS]\n", name); printf("\nOptions:\n"); printf("\t-n, --host\n\t\tServer host to connect to. Defaults to [%s].\n", _d.host); printf("\t-p, --port\n\t\tServer port to connect to. Defaults to [%d].\n", _d.port); printf("\t-c, --clients\n\t\tNumber of concurrent clients. Defaults to [%d].\n", _d.clients); printf("\t-l, --load\n\t\tTarget load to generate. Expects a value in format D/U/I/R, where\n" \ "\t\t\tD - number of deletes\n" \ "\t\t\tU - number of updates\n" \ "\t\t\tI - number of inserts\n" \ "\t\t\tR - number of reads\n" \ "\t\tDefaults to ["); _d.load.print(); printf("]\n"); printf("\t-k, --keys\n\t\tKey distribution in DISTR format (see below). Defaults to ["); _d.keys.print(); printf("].\n"); printf("\t-v, --values\n\t\tValue distribution in DISTR format (see below). Defaults to ["); _d.values.print(); printf("].\n"); printf("\t-d, --duration\n\t\tDuration of the run specified in number of operations.\n" \ "\t\tDefaults to [%ld].\n", _d.duration); printf("\nAdditional information:\n"); printf("\t\tDISTR format describes a range and can be specified in as MIN-MAX\n"); exit(-1); } /* Parse the args */ void parse(config_t *config, int argc, char *argv[]) { optind = 1; // reinit getopt while(1) { int do_help = 0; struct option long_options[] = { {"host", required_argument, 0, 'n'}, {"port", required_argument, 0, 'p'}, {"clients", required_argument, 0, 'c'}, {"load", required_argument, 0, 'l'}, {"keys", required_argument, 0, 'k'}, {"values", required_argument, 0, 'v'}, {"duration", required_argument, 0, 'd'}, {"help", no_argument, &do_help, 1}, {0, 0, 0, 0} }; int option_index = 0; int c = getopt_long(argc, argv, "n:p:c:l:k:v:d:h", long_options, &option_index); if(do_help) c = 'h'; /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: break; case 'n': strncpy(config->host, optarg, MAX_HOST); break; case 'p': config->port = atoi(optarg); break; case 'c': config->clients = atoi(optarg); break; case 'l': config->load.parse(optarg); break; case 'k': config->keys.parse(optarg); break; case 'v': config->values.parse(optarg); break; case 'd': config->duration = atol(optarg); break; case 'h': usage(argv[0]); break; default: /* getopt_long already printed an error message. */ usage(argv[0]); } } } /* The function that does the work */ void* run_client(void* data) { // Grab the config config_t *config = (config_t*)data; // Connect to the server memcached_st memcached; memcached_create(&memcached); memcached_server_add(&memcached, config->host, config->port); // Store the keys so we can run updates and deletes. vector<payload_t> keys; // Perform the ops for(int i = 0; i < config->duration / config->clients; i++) { // Generate the command load_t::load_op_t cmd = config->load.toss(); int _val; payload_t key, value; char *_value; size_t _value_length; uint32_t _flags; memcached_return_t _error; switch(cmd) { case load_t::delete_op: // Find the key if(keys.empty()) break; _val = random(0, keys.size() - 1); key = keys[_val]; // Delete it from the server _error = memcached_delete(&memcached, key.first, key.second, 0); if(_error != MEMCACHED_SUCCESS) { fprintf(stderr, "Error performing delete operation (%d)\n", _error); exit(-1); } // Our own bookkeeping free(key.first); keys[_val] = keys[keys.size() - 1]; keys.erase(keys.begin() + _val); break; case load_t::update_op: // Find the key and generate the payload if(keys.empty()) break; key = keys[random(0, keys.size() - 1)]; config->values.toss(&value); // Send it to server _error = memcached_set(&memcached, key.first, key.second, value.first, value.second, 0, 0); if(_error != MEMCACHED_SUCCESS) { fprintf(stderr, "Error performing update operation (%d)\n", _error); exit(-1); } // Free the value free(value.first); break; case load_t::insert_op: // Generate the payload config->keys.toss(&key); config->values.toss(&value); // Send it to server _error = memcached_set(&memcached, key.first, key.second, value.first, value.second, 0, 0); if(_error != MEMCACHED_SUCCESS) { fprintf(stderr, "Error performing insert operation (%d)\n", _error); exit(-1); } // Free the value and save the key free(value.first); keys.push_back(key); break; case load_t::read_op: // Find the key if(keys.empty()) break; key = keys[random(0, keys.size() - 1)]; // Read it from the server _value = memcached_get(&memcached, key.first, key.second, &_value_length, &_flags, &_error); if(_error != MEMCACHED_SUCCESS) { fprintf(stderr, "Error performing read operation (%d)\n", _error); exit(-1); } // Our own bookkeeping free(_value); break; }; } // Disconnect memcached_free(&memcached); // Free all the keys for(vector<payload_t>::iterator i = keys.begin(); i != keys.end(); i++) { free(i->first); } } /* Tie it all together */ int main(int argc, char *argv[]) { // Initialize randomness srand(time(NULL)); // Parse the arguments config_t config; parse(&config, argc, argv); config.print(); // Let's rock 'n roll int res; vector<pthread_t> threads(config.clients); // Create the threads for(int i = 0; i < config.clients; i++) { int res = pthread_create(&threads[i], NULL, run_client, &config); if(res != 0) { fprintf(stderr, "Can't create thread"); exit(-1); } } // Wait for the threads to finish for(int i = 0; i < config.clients; i++) { res = pthread_join(threads[i], NULL); if(res != 0) { fprintf(stderr, "Can't join on the thread"); exit(-1); } } return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTrivialProducer.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkTrivialProducer.h" #include "vtkImageData.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkTrivialProducer, "1.12"); vtkStandardNewMacro(vtkTrivialProducer); // This compile-time switch determines whether the update extent is // checked. If so this algorithm will produce an error message when // the update extent is smaller than the whole extent which will // result in lost data. There are real cases in which this is a valid // thing so an error message should normally not be produced. However // there are hard-to-find bugs that can be revealed quickly if this // option is enabled. This should be enabled only for debugging // purposes in a working checkout of VTK. Do not commit a change that // turns on this switch! #define VTK_TRIVIAL_PRODUCER_CHECK_UPDATE_EXTENT 0 //---------------------------------------------------------------------------- vtkTrivialProducer::vtkTrivialProducer() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Output = 0; } //---------------------------------------------------------------------------- vtkTrivialProducer::~vtkTrivialProducer() { this->SetOutput(0); } //---------------------------------------------------------------------------- void vtkTrivialProducer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------------- void vtkTrivialProducer::SetOutput(vtkDataObject*newOutput) { vtkDataObject* oldOutput = this->Output; if(newOutput != oldOutput) { if(newOutput) { newOutput->Register(this); } this->Output = newOutput; this->GetExecutive()->SetOutputData(0, newOutput); if(oldOutput) { oldOutput->UnRegister(this); } this->Modified(); } } //---------------------------------------------------------------------------- unsigned long vtkTrivialProducer::GetMTime() { unsigned long mtime = this->Superclass::GetMTime(); if(this->Output) { unsigned long omtime = this->Output->GetMTime(); if(omtime > mtime) { mtime = omtime; } } return mtime; } //---------------------------------------------------------------------------- vtkExecutive* vtkTrivialProducer::CreateDefaultExecutive() { return vtkStreamingDemandDrivenPipeline::New(); } //---------------------------------------------------------------------------- int vtkTrivialProducer::FillInputPortInformation(int, vtkInformation*) { return 1; } //---------------------------------------------------------------------------- int vtkTrivialProducer::FillOutputPortInformation(int, vtkInformation*) { return 1; } //---------------------------------------------------------------------------- int vtkTrivialProducer::ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()) && this->Output) { vtkInformation* outputInfo = outputVector->GetInformationObject(0); vtkInformation* dataInfo = this->Output->GetInformation(); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_PIECES_EXTENT) { // There is no real source to change the output data, so we can // produce exactly one piece. outputInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); } else if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT) { // The whole extent is just the extent because the output has no // real source to change its data. int extent[6]; dataInfo->Get(vtkDataObject::DATA_EXTENT(), extent); outputInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent, 6); } else if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_TIME_EXTENT) { // The time extent is captured in TIME_STEPS and/or TIME_RANGE. double time = 0.0; if (dataInfo->Has(vtkDataObject::DATA_TIME_STEPS())) { time = dataInfo->Get(vtkDataObject::DATA_TIME_STEPS())[0]; } double timeRange[2]; timeRange[0] = timeRange[1] = time; outputInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), timeRange, 2); } } #if VTK_TRIVIAL_PRODUCER_CHECK_UPDATE_EXTENT if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT())) { // If an exact extent smaller than the whole extent has been // requested then warn. vtkInformation* outputInfo = outputVector->GetInformationObject(0); if(outputInfo->Get(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT())) { vtkInformation* dataInfo = this->Output->GetInformation(); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT) { // Compare the update extent to the whole extent. int updateExtent[6] = {0,-1,0,-1,0,-1}; int wholeExtent[6] = {0,-1,0,-1,0,-1}; outputInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wholeExtent); outputInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), updateExtent); if(updateExtent[0] != wholeExtent[0] || updateExtent[1] != wholeExtent[1] || updateExtent[2] != wholeExtent[2] || updateExtent[3] != wholeExtent[3] || updateExtent[4] != wholeExtent[4] || updateExtent[5] != wholeExtent[5]) { vtkErrorMacro("Request for exact extent " << updateExtent[0] << " " << updateExtent[1] << " " << updateExtent[2] << " " << updateExtent[3] << " " << updateExtent[4] << " " << updateExtent[5] << " will lose data because it is not the whole extent " << wholeExtent[0] << " " << wholeExtent[1] << " " << wholeExtent[2] << " " << wholeExtent[3] << " " << wholeExtent[4] << " " << wholeExtent[5] << "."); } } } } #endif if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_NOT_GENERATED())) { // We do not really generate the output. Do not let the executive // initialize it. vtkInformation* outputInfo = outputVector->GetInformationObject(0); outputInfo->Set(vtkDemandDrivenPipeline::DATA_NOT_GENERATED(), 1); } if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()) && this->Output) { // Pretend we generated the output. vtkInformation* outputInfo = outputVector->GetInformationObject(0); outputInfo->Remove(vtkDemandDrivenPipeline::DATA_NOT_GENERATED()); } return this->Superclass::ProcessRequest(request,inputVector,outputVector); } //---------------------------------------------------------------------------- void vtkTrivialProducer::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->Output, "Output"); } <commit_msg>BUG: The trivial producer should report an output data type<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTrivialProducer.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkTrivialProducer.h" #include "vtkImageData.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkTrivialProducer, "1.13"); vtkStandardNewMacro(vtkTrivialProducer); // This compile-time switch determines whether the update extent is // checked. If so this algorithm will produce an error message when // the update extent is smaller than the whole extent which will // result in lost data. There are real cases in which this is a valid // thing so an error message should normally not be produced. However // there are hard-to-find bugs that can be revealed quickly if this // option is enabled. This should be enabled only for debugging // purposes in a working checkout of VTK. Do not commit a change that // turns on this switch! #define VTK_TRIVIAL_PRODUCER_CHECK_UPDATE_EXTENT 0 //---------------------------------------------------------------------------- vtkTrivialProducer::vtkTrivialProducer() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Output = 0; } //---------------------------------------------------------------------------- vtkTrivialProducer::~vtkTrivialProducer() { this->SetOutput(0); } //---------------------------------------------------------------------------- void vtkTrivialProducer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------------- void vtkTrivialProducer::SetOutput(vtkDataObject*newOutput) { vtkDataObject* oldOutput = this->Output; if(newOutput != oldOutput) { if(newOutput) { newOutput->Register(this); } this->Output = newOutput; this->GetExecutive()->SetOutputData(0, newOutput); if(oldOutput) { oldOutput->UnRegister(this); } this->Modified(); } } //---------------------------------------------------------------------------- unsigned long vtkTrivialProducer::GetMTime() { unsigned long mtime = this->Superclass::GetMTime(); if(this->Output) { unsigned long omtime = this->Output->GetMTime(); if(omtime > mtime) { mtime = omtime; } } return mtime; } //---------------------------------------------------------------------------- vtkExecutive* vtkTrivialProducer::CreateDefaultExecutive() { return vtkStreamingDemandDrivenPipeline::New(); } //---------------------------------------------------------------------------- int vtkTrivialProducer::FillInputPortInformation(int, vtkInformation*) { return 1; } //---------------------------------------------------------------------------- int vtkTrivialProducer::FillOutputPortInformation(int, vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataObject"); return 1; } //---------------------------------------------------------------------------- int vtkTrivialProducer::ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()) && this->Output) { vtkInformation* outputInfo = outputVector->GetInformationObject(0); vtkInformation* dataInfo = this->Output->GetInformation(); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_PIECES_EXTENT) { // There is no real source to change the output data, so we can // produce exactly one piece. outputInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); } else if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT) { // The whole extent is just the extent because the output has no // real source to change its data. int extent[6]; dataInfo->Get(vtkDataObject::DATA_EXTENT(), extent); outputInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent, 6); } else if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_TIME_EXTENT) { // The time extent is captured in TIME_STEPS and/or TIME_RANGE. double time = 0.0; if (dataInfo->Has(vtkDataObject::DATA_TIME_STEPS())) { time = dataInfo->Get(vtkDataObject::DATA_TIME_STEPS())[0]; } double timeRange[2]; timeRange[0] = timeRange[1] = time; outputInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), timeRange, 2); } } #if VTK_TRIVIAL_PRODUCER_CHECK_UPDATE_EXTENT if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT())) { // If an exact extent smaller than the whole extent has been // requested then warn. vtkInformation* outputInfo = outputVector->GetInformationObject(0); if(outputInfo->Get(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT())) { vtkInformation* dataInfo = this->Output->GetInformation(); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT) { // Compare the update extent to the whole extent. int updateExtent[6] = {0,-1,0,-1,0,-1}; int wholeExtent[6] = {0,-1,0,-1,0,-1}; outputInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wholeExtent); outputInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), updateExtent); if(updateExtent[0] != wholeExtent[0] || updateExtent[1] != wholeExtent[1] || updateExtent[2] != wholeExtent[2] || updateExtent[3] != wholeExtent[3] || updateExtent[4] != wholeExtent[4] || updateExtent[5] != wholeExtent[5]) { vtkErrorMacro("Request for exact extent " << updateExtent[0] << " " << updateExtent[1] << " " << updateExtent[2] << " " << updateExtent[3] << " " << updateExtent[4] << " " << updateExtent[5] << " will lose data because it is not the whole extent " << wholeExtent[0] << " " << wholeExtent[1] << " " << wholeExtent[2] << " " << wholeExtent[3] << " " << wholeExtent[4] << " " << wholeExtent[5] << "."); } } } } #endif if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_NOT_GENERATED())) { // We do not really generate the output. Do not let the executive // initialize it. vtkInformation* outputInfo = outputVector->GetInformationObject(0); outputInfo->Set(vtkDemandDrivenPipeline::DATA_NOT_GENERATED(), 1); } if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()) && this->Output) { // Pretend we generated the output. vtkInformation* outputInfo = outputVector->GetInformationObject(0); outputInfo->Remove(vtkDemandDrivenPipeline::DATA_NOT_GENERATED()); } return this->Superclass::ProcessRequest(request,inputVector,outputVector); } //---------------------------------------------------------------------------- void vtkTrivialProducer::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->Output, "Output"); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTrivialProducer.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkTrivialProducer.h" #include "vtkImageData.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkTrivialProducer, "1.9"); vtkStandardNewMacro(vtkTrivialProducer); //---------------------------------------------------------------------------- vtkTrivialProducer::vtkTrivialProducer() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Output = 0; } //---------------------------------------------------------------------------- vtkTrivialProducer::~vtkTrivialProducer() { this->SetOutput(0); } //---------------------------------------------------------------------------- void vtkTrivialProducer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------------- void vtkTrivialProducer::SetOutput(vtkDataObject*newOutput) { vtkDataObject* oldOutput = this->Output; if(newOutput != oldOutput) { if(newOutput) { newOutput->Register(this); } this->Output = newOutput; this->GetExecutive()->SetOutputData(0, newOutput); if(oldOutput) { oldOutput->UnRegister(this); } this->Modified(); } } //---------------------------------------------------------------------------- unsigned long vtkTrivialProducer::GetMTime() { unsigned long mtime = this->Superclass::GetMTime(); if(this->Output) { unsigned long omtime = this->Output->GetMTime(); if(omtime > mtime) { mtime = omtime; } } return mtime; } //---------------------------------------------------------------------------- vtkExecutive* vtkTrivialProducer::CreateDefaultExecutive() { return vtkStreamingDemandDrivenPipeline::New(); } //---------------------------------------------------------------------------- int vtkTrivialProducer::FillInputPortInformation(int, vtkInformation*) { return 1; } //---------------------------------------------------------------------------- int vtkTrivialProducer::FillOutputPortInformation(int, vtkInformation*) { return 1; } //---------------------------------------------------------------------------- int vtkTrivialProducer::ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()) && this->Output) { vtkInformation* outputInfo = outputVector->GetInformationObject(0); vtkInformation* dataInfo = this->Output->GetInformation(); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_PIECES_EXTENT) { // There is no real source to change the output data, so we can // produce exactly one piece. outputInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), 1); } else if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT) { // The whole extent is just the extent because the output has no // real source to change its data. int extent[6]; dataInfo->Get(vtkDataObject::DATA_EXTENT(), extent); outputInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent, 6); } } if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_NOT_GENERATED())) { // We do not really generate the output. Do not let the executive // initialize it. vtkInformation* outputInfo = outputVector->GetInformationObject(0); outputInfo->Set(vtkDemandDrivenPipeline::DATA_NOT_GENERATED(), 1); } if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()) && this->Output) { // Pretend we generated the output. vtkInformation* outputInfo = outputVector->GetInformationObject(0); outputInfo->Remove(vtkDemandDrivenPipeline::DATA_NOT_GENERATED()); } return this->Superclass::ProcessRequest(request,inputVector,outputVector); } //---------------------------------------------------------------------------- void vtkTrivialProducer::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->Output, "Output"); } <commit_msg>ENH: Added compile-time switch to check the update extent to avoid data loss. This is for debugging purposes only and should never be enabled in a committed revision of this source.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTrivialProducer.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkTrivialProducer.h" #include "vtkImageData.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkTrivialProducer, "1.10"); vtkStandardNewMacro(vtkTrivialProducer); // This compile-time switch determines whether the update extent is // checked. If so this algorithm will produce an error message when // the update extent is smaller than the whole extent which will // result in lost data. There are real cases in which this is a valid // thing so an error message should normally not be produced. However // there are hard-to-find bugs that can be revealed quickly if this // option is enabled. This should be enabled only for debugging // purposes in a working checkout of VTK. Do not commit a change that // turns on this switch! #define VTK_TRIVIAL_PRODUCER_CHECK_UPDATE_EXTENT 0 //---------------------------------------------------------------------------- vtkTrivialProducer::vtkTrivialProducer() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Output = 0; } //---------------------------------------------------------------------------- vtkTrivialProducer::~vtkTrivialProducer() { this->SetOutput(0); } //---------------------------------------------------------------------------- void vtkTrivialProducer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------------- void vtkTrivialProducer::SetOutput(vtkDataObject*newOutput) { vtkDataObject* oldOutput = this->Output; if(newOutput != oldOutput) { if(newOutput) { newOutput->Register(this); } this->Output = newOutput; this->GetExecutive()->SetOutputData(0, newOutput); if(oldOutput) { oldOutput->UnRegister(this); } this->Modified(); } } //---------------------------------------------------------------------------- unsigned long vtkTrivialProducer::GetMTime() { unsigned long mtime = this->Superclass::GetMTime(); if(this->Output) { unsigned long omtime = this->Output->GetMTime(); if(omtime > mtime) { mtime = omtime; } } return mtime; } //---------------------------------------------------------------------------- vtkExecutive* vtkTrivialProducer::CreateDefaultExecutive() { return vtkStreamingDemandDrivenPipeline::New(); } //---------------------------------------------------------------------------- int vtkTrivialProducer::FillInputPortInformation(int, vtkInformation*) { return 1; } //---------------------------------------------------------------------------- int vtkTrivialProducer::FillOutputPortInformation(int, vtkInformation*) { return 1; } //---------------------------------------------------------------------------- int vtkTrivialProducer::ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()) && this->Output) { vtkInformation* outputInfo = outputVector->GetInformationObject(0); vtkInformation* dataInfo = this->Output->GetInformation(); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_PIECES_EXTENT) { // There is no real source to change the output data, so we can // produce exactly one piece. outputInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), 1); } else if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT) { // The whole extent is just the extent because the output has no // real source to change its data. int extent[6]; dataInfo->Get(vtkDataObject::DATA_EXTENT(), extent); outputInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent, 6); } } #if VTK_TRIVIAL_PRODUCER_CHECK_UPDATE_EXTENT if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT())) { // If an exact extent smaller than the whole extent has been // requested then warn. vtkInformation* outputInfo = outputVector->GetInformationObject(0); if(outputInfo->Get(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT())) { vtkInformation* dataInfo = this->Output->GetInformation(); if(dataInfo->Get(vtkDataObject::DATA_EXTENT_TYPE()) == VTK_3D_EXTENT) { // Compare the update extent to the whole extent. int updateExtent[6] = {0,-1,0,-1,0,-1}; int wholeExtent[6] = {0,-1,0,-1,0,-1}; outputInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wholeExtent); outputInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), updateExtent); if(updateExtent[0] != wholeExtent[0] || updateExtent[1] != wholeExtent[1] || updateExtent[2] != wholeExtent[2] || updateExtent[3] != wholeExtent[3] || updateExtent[4] != wholeExtent[4] || updateExtent[5] != wholeExtent[5]) { vtkErrorMacro("Request for exact extent " << updateExtent[0] << " " << updateExtent[1] << " " << updateExtent[2] << " " << updateExtent[3] << " " << updateExtent[4] << " " << updateExtent[5] << " will lose data because it is not the whole extent " << wholeExtent[0] << " " << wholeExtent[1] << " " << wholeExtent[2] << " " << wholeExtent[3] << " " << wholeExtent[4] << " " << wholeExtent[5] << "."); } } } } #endif if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_NOT_GENERATED())) { // We do not really generate the output. Do not let the executive // initialize it. vtkInformation* outputInfo = outputVector->GetInformationObject(0); outputInfo->Set(vtkDemandDrivenPipeline::DATA_NOT_GENERATED(), 1); } if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()) && this->Output) { // Pretend we generated the output. vtkInformation* outputInfo = outputVector->GetInformationObject(0); outputInfo->Remove(vtkDemandDrivenPipeline::DATA_NOT_GENERATED()); } return this->Superclass::ProcessRequest(request,inputVector,outputVector); } //---------------------------------------------------------------------------- void vtkTrivialProducer::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->Output, "Output"); } <|endoftext|>
<commit_before>#include <system/Locale.h> #if defined(HX_WINDOWS) #include <windows.h> #elif defined(HX_LINUX) #include <stdlib.h> #include <string.h> #include <clocale> #endif namespace lime { std::string* Locale::GetSystemLocale () { #if defined(HX_WINDOWS) char locale[8]; int length = GetLocaleInfo (GetSystemDefaultUILanguage (), LOCALE_SISO639LANGNAME, locale, sizeof (locale)); std::string* result = new std::string (locale); return result; #elif defined(HX_LINUX) const char* locale = getenv ("LANG"); if (!locale) { locale = setlocale (LC_ALL, ""); } if (locale) { std::string* result = new std::string (locale); return result; } return 0; #else return 0; #endif } }<commit_msg>Update locale handling on Windows<commit_after>#include <system/Locale.h> #if defined(HX_WINDOWS) #include <windows.h> #elif defined(HX_LINUX) #include <stdlib.h> #include <string.h> #include <clocale> #endif namespace lime { std::string* Locale::GetSystemLocale () { #if defined(HX_WINDOWS) char language[5] = {0}; char country[5] = {0}; GetLocaleInfoA (LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, language, sizeof (language) / sizeof (char)); GetLocaleInfoA (LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, sizeof (country) / sizeof (char)); std::string* locale = new std::string (std::string (language) + "_" + std::string (country)); return locale; #elif defined(HX_LINUX) const char* locale = getenv ("LANG"); if (!locale) { locale = setlocale (LC_ALL, ""); } if (locale) { std::string* result = new std::string (locale); return result; } return 0; #else return 0; #endif } }<|endoftext|>
<commit_before>/* * Copyright (c) 2013, Roland Bock * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "TabSample.h" #include <cassert> #include <sqlpp11/alias_provider.h> #include <sqlpp11/select.h> #include <sqlpp11/insert.h> #include <sqlpp11/update.h> #include <sqlpp11/remove.h> #include <sqlpp11/functions.h> #include <sqlpp11/transaction.h> #include <sqlpp11/multi_column.h> #include <sqlpp11/sqlite3/connection.h> #include <sqlite3.h> #include <iostream> #include <vector> SQLPP_ALIAS_PROVIDER(left); namespace sql = sqlpp::sqlite3; TabSample tab; void testSelectAll(sql::connection& db, size_t expectedRowCount) { std::cerr << "--------------------------------------" << std::endl; size_t i = 0; for(const auto& row : db(sqlpp::select(all_of(tab)).from(tab).where(true))) { ++i; std::cerr << ">>> row.alpha: " << row.alpha << ", row.beta: " << row.beta << ", row.gamma: " << row.gamma << std::endl; assert(row.alpha == i); }; assert(i == expectedRowCount); auto preparedSelectAll = db.prepare(sqlpp::select(all_of(tab)).from(tab).where(true)); i = 0; for(const auto& row : db(preparedSelectAll)) { ++i; std::cerr << ">>> row.alpha: " << row.alpha << ", row.beta: " << row.beta << ", row.gamma: " << row.gamma << std::endl; assert(row.alpha == i); }; assert(i == expectedRowCount); std::cerr << "--------------------------------------" << std::endl; } int main() { auto config = std::make_shared<sql::connection_config>(); config->path_to_database = ":memory:"; config->flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; config->debug = true; sql::connection db(config); db.execute(R"(CREATE TABLE tab_sample ( alpha INTEGER PRIMARY KEY, beta varchar(255) DEFAULT NULL, gamma bool DEFAULT NULL ))"); testSelectAll(db, 0); db(insert_into(tab).default_values()); testSelectAll(db, 1); db(insert_into(tab).set(tab.gamma = true, tab.beta = "cheesecake")); testSelectAll(db, 2); db(insert_into(tab).set(tab.gamma = true, tab.beta = "cheesecake")); testSelectAll(db, 3); // selecting two multicolumns for(const auto& row : db(select(multi_column(tab.alpha, tab.beta, tab.gamma).as(left), multi_column(all_of(tab)).as(tab)).from(tab).where(true))) { std::cerr << ">>> row.left.alpha: " << row.left.alpha << ", row.left.beta: " << row.left.beta << ", row.left.gamma: " << row.left.gamma << std::endl; std::cerr << ">>> row.tabSample.alpha: " << row.tabSample.alpha << ", row.tabSample.beta: " << row.tabSample.beta << ", row.tabSample.gamma: " << row.tabSample.gamma << std::endl; }; std::cerr << "--------------------------------------" << std::endl; // test functions and operators db(select(all_of(tab)).from(tab).where(tab.alpha.is_null())); db(select(all_of(tab)).from(tab).where(tab.alpha.is_not_null())); db(select(all_of(tab)).from(tab).where(tab.alpha.in(1, 2, 3))); db(select(all_of(tab)).from(tab).where(tab.alpha.in(sqlpp::value_list(std::vector<int>{1, 2, 3, 4})))); db(select(all_of(tab)).from(tab).where(tab.alpha.not_in(1, 2, 3))); db(select(all_of(tab)).from(tab).where(tab.alpha.not_in(sqlpp::value_list(std::vector<int>{1, 2, 3, 4})))); db(select(count(tab.alpha)).from(tab).where(true)); db(select(avg(tab.alpha)).from(tab).where(true)); db(select(max(tab.alpha)).from(tab).where(true)); db(select(min(tab.alpha)).from(tab).where(true)); db(select(exists(select(tab.alpha).from(tab).where(tab.alpha > 7))).from(tab).where(true)); //db(select(not_exists(select(tab.alpha).from(tab).where(tab.alpha > 7))).from(tab)); //db(select(all_of(tab)).from(tab).where(tab.alpha == any(select(tab.alpha).from(tab).where(tab.alpha < 3)))); db(select(all_of(tab)).from(tab).where((tab.alpha + tab.alpha) > 3)); db(select(all_of(tab)).from(tab).where((tab.beta + tab.beta) == "")); db(select(all_of(tab)).from(tab).where((tab.beta + tab.beta).like(R"(%'\"%)"))); // update db(update(tab).set(tab.gamma = false).where(tab.alpha.in(1))); db(update(tab).set(tab.gamma = false).where(tab.alpha.in(sqlpp::value_list(std::vector<int>{1, 2, 3, 4})))); // remove db(remove_from(tab).where(tab.alpha == tab.alpha + 3)); auto result = db(select(all_of(tab)).from(tab).where(true)); std::cerr << "Accessing a field directly from the result (using the current row): " << result.begin()->alpha << std::endl; std::cerr << "Can do that again, no problem: " << result.begin()->alpha << std::endl; std::cerr << "--------------------------------------" << std::endl; auto tx = start_transaction(db); if (const auto& row = *db(select(all_of(tab), select(max(tab.alpha)).from(tab)).from(tab).where(true)).begin()) { int x = row.alpha; int a = row.max; std::cout << ">>>" << x << ", " << a << std::endl; } tx.commit(); std::cerr << "--------------------------------------" << std::endl; return 0; } <commit_msg>Minor test adjustment<commit_after>/* * Copyright (c) 2013, Roland Bock * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "TabSample.h" #include <cassert> #include <sqlpp11/alias_provider.h> #include <sqlpp11/select.h> #include <sqlpp11/insert.h> #include <sqlpp11/update.h> #include <sqlpp11/remove.h> #include <sqlpp11/functions.h> #include <sqlpp11/transaction.h> #include <sqlpp11/multi_column.h> #include <sqlpp11/sqlite3/connection.h> #include <sqlite3.h> #include <iostream> #include <vector> SQLPP_ALIAS_PROVIDER(left); namespace sql = sqlpp::sqlite3; TabSample tab; void testSelectAll(sql::connection& db, size_t expectedRowCount) { std::cerr << "--------------------------------------" << std::endl; size_t i = 0; for(const auto& row : db(sqlpp::select(all_of(tab)).from(tab).where(true))) { ++i; std::cerr << ">>> row.alpha: " << row.alpha << ", row.beta: " << row.beta << ", row.gamma: " << row.gamma << std::endl; assert(row.alpha == i); }; assert(i == expectedRowCount); auto preparedSelectAll = db.prepare(sqlpp::select(all_of(tab)).from(tab).where(true)); i = 0; for(const auto& row : db(preparedSelectAll)) { ++i; std::cerr << ">>> row.alpha: " << row.alpha << ", row.beta: " << row.beta << ", row.gamma: " << row.gamma << std::endl; assert(row.alpha == i); }; assert(i == expectedRowCount); std::cerr << "--------------------------------------" << std::endl; } int main() { auto config = std::make_shared<sql::connection_config>(); config->path_to_database = ":memory:"; config->flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; config->debug = true; sql::connection db(config); db.execute(R"(CREATE TABLE tab_sample ( alpha INTEGER PRIMARY KEY, beta varchar(255) DEFAULT NULL, gamma bool DEFAULT NULL ))"); testSelectAll(db, 0); db(insert_into(tab).default_values()); testSelectAll(db, 1); db(insert_into(tab).set(tab.gamma = true, tab.beta = "cheesecake")); testSelectAll(db, 2); db(insert_into(tab).set(tab.gamma = true, tab.beta = "cheesecake")); testSelectAll(db, 3); // selecting two multicolumns for(const auto& row : db(select(tab.alpha, tab.beta, tab.gamma, multi_column(tab.alpha, tab.beta, tab.gamma).as(left), multi_column(all_of(tab)).as(tab)).from(tab).where(true))) { std::cerr << ">>> row.alpha: " << row.alpha << ", row.beta: " << row.beta << ", row.gamma: " << row.gamma << std::endl; std::cerr << ">>> row.left.alpha: " << row.left.alpha << ", row.left.beta: " << row.left.beta << ", row.left.gamma: " << row.left.gamma << std::endl; std::cerr << ">>> row.tabSample.alpha: " << row.tabSample.alpha << ", row.tabSample.beta: " << row.tabSample.beta << ", row.tabSample.gamma: " << row.tabSample.gamma << std::endl; }; std::cerr << "--------------------------------------" << std::endl; // test functions and operators db(select(all_of(tab)).from(tab).where(tab.alpha.is_null())); db(select(all_of(tab)).from(tab).where(tab.alpha.is_not_null())); db(select(all_of(tab)).from(tab).where(tab.alpha.in(1, 2, 3))); db(select(all_of(tab)).from(tab).where(tab.alpha.in(sqlpp::value_list(std::vector<int>{1, 2, 3, 4})))); db(select(all_of(tab)).from(tab).where(tab.alpha.not_in(1, 2, 3))); db(select(all_of(tab)).from(tab).where(tab.alpha.not_in(sqlpp::value_list(std::vector<int>{1, 2, 3, 4})))); db(select(count(tab.alpha)).from(tab).where(true)); db(select(avg(tab.alpha)).from(tab).where(true)); db(select(max(tab.alpha)).from(tab).where(true)); db(select(min(tab.alpha)).from(tab).where(true)); db(select(exists(select(tab.alpha).from(tab).where(tab.alpha > 7))).from(tab).where(true)); //db(select(not_exists(select(tab.alpha).from(tab).where(tab.alpha > 7))).from(tab)); //db(select(all_of(tab)).from(tab).where(tab.alpha == any(select(tab.alpha).from(tab).where(tab.alpha < 3)))); db(select(all_of(tab)).from(tab).where((tab.alpha + tab.alpha) > 3)); db(select(all_of(tab)).from(tab).where((tab.beta + tab.beta) == "")); db(select(all_of(tab)).from(tab).where((tab.beta + tab.beta).like(R"(%'\"%)"))); // update db(update(tab).set(tab.gamma = false).where(tab.alpha.in(1))); db(update(tab).set(tab.gamma = false).where(tab.alpha.in(sqlpp::value_list(std::vector<int>{1, 2, 3, 4})))); // remove db(remove_from(tab).where(tab.alpha == tab.alpha + 3)); auto result = db(select(all_of(tab)).from(tab).where(true)); std::cerr << "Accessing a field directly from the result (using the current row): " << result.begin()->alpha << std::endl; std::cerr << "Can do that again, no problem: " << result.begin()->alpha << std::endl; std::cerr << "--------------------------------------" << std::endl; auto tx = start_transaction(db); if (const auto& row = *db(select(all_of(tab), select(max(tab.alpha)).from(tab)).from(tab).where(true)).begin()) { int x = row.alpha; int a = row.max; std::cout << ">>>" << x << ", " << a << std::endl; } tx.commit(); std::cerr << "--------------------------------------" << std::endl; return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2012, University of Erlangen-Nuremberg // Copyright (c) 2012, Siemens AG // 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. // #ifndef __MASK_HPP__ #define __MASK_HPP__ #include "iterationspace.hpp" #include "types.hpp" namespace hipacc { class MaskBase { protected: const int size_x, size_y; const int offset_x, offset_y; uchar *domain_space; IterationSpaceBase iteration_space; public: MaskBase(int size_x, int size_y) : size_x(size_x), size_y(size_y), offset_x(-size_x/2), offset_y(-size_y/2), domain_space(new uchar[size_x*size_y]), iteration_space(size_x, size_y) { assert(size_x>0 && size_y>0 && "Size for Domain must be positive!"); // initialize full domain for (int i = 0; i < size_x*size_y; ++i) { domain_space[i] = 1; } } MaskBase(const MaskBase &mask) : MaskBase(mask.size_x, mask.size_y) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = mask.domain_space[y * size_x + x]; } } } ~MaskBase() { if (domain_space != NULL) { delete[] domain_space; domain_space = NULL; } } int getSizeX() const { return size_x; } int getSizeY() const { return size_y; } virtual int getX() = 0; virtual int getY() = 0; friend class Domain; template<typename> friend class Mask; }; class Domain : public MaskBase { public: class DomainIterator : public ElementIterator { private: uchar *domain_space; public: DomainIterator(int width=0, int height=0, int offsetx=0, int offsety=0, const IterationSpaceBase *iterspace=NULL, uchar *domain_space=NULL) : ElementIterator(width, height, offsetx, offsety, iterspace), domain_space(domain_space) { if (domain_space != NULL) { // set current coordinate before domain coord.x = min_x-1; coord.y = min_y; // use increment to search first non-zero value ++(*this); } } ~DomainIterator() {} // increment so we iterate over elements in a block DomainIterator &operator++() { do { if (iteration_space) { coord.x++; if (coord.x >= max_x) { coord.x = min_x; coord.y++; if (coord.y >= max_y) { iteration_space = NULL; } } } } while (NULL != iteration_space && (NULL == domain_space || 0 == domain_space[(coord.y-min_y) * (max_x-min_x) + (coord.x-min_x)])); return *this; } }; protected: DomainIterator *DI; public: Domain(int size_x, int size_y) : MaskBase(size_x, size_y), DI(NULL) {} Domain(const MaskBase &mask) : MaskBase(mask), DI(NULL) {} Domain(const Domain &domain) : MaskBase(domain), DI(domain.DI) {} ~Domain() {} int getX() { assert(DI && "DomainIterator for Domain not set!"); return DI->getX(); } int getY() { assert(DI && "DomainIterator for Domain not set!"); return DI->getY(); } uchar &operator()(unsigned int x, unsigned int y) { x += size_x >> 1; y += size_y >> 1; if ((int)x < size_x && (int)y < size_y) { return domain_space[y * size_x + x]; } else { return domain_space[0]; } } Domain &operator=(const uchar *other) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = other[y * size_x + x]; } } return *this; } void operator=(const Domain &dom) { assert(size_x==dom.getSizeX() && size_y==dom.getSizeY() && "Domain sizes must be equal."); for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = dom.domain_space[y * size_x + x]; } } } void operator=(const MaskBase &mask) { assert(size_x==mask.getSizeX() && size_y==mask.getSizeY() && "Domain and Mask size must be equal."); for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = mask.domain_space[y * size_x + x]; } } } void setDI(DomainIterator *di) { DI = di; } DomainIterator begin() const { return DomainIterator(size_x, size_y, offset_x, offset_y, &iteration_space, domain_space); } DomainIterator end() const { return DomainIterator(); } }; template<typename data_t> class Mask : public MaskBase { private: ElementIterator *EI; data_t *array; public: Mask(int size_x, int size_y) : MaskBase(size_x, size_y), EI(NULL), array(new data_t[size_x*size_y]) { assert(size_x>0 && size_y>0 && "size for Mask must be positive!"); } Mask(const Mask &mask) : MaskBase(mask.size_x, mask.size_y), array(new data_t[mask.size_x*mask.size_y]) { operator=(mask.array); } ~Mask() { if (array != NULL) { delete[] array; array = NULL; } } int getX() { assert(EI && "ElementIterator for Mask not set!"); return EI->getX(); } int getY() { assert(EI && "ElementIterator for Mask not set!"); return EI->getY(); } data_t &operator()(void) { assert(EI && "ElementIterator for Mask not set!"); return array[(EI->getY()-offset_y)*size_x + EI->getX()-offset_x]; } data_t &operator()(const int xf, const int yf) { return array[(yf-offset_y)*size_x + xf-offset_x]; } data_t &operator()(Domain &D) { assert(D.getSizeX()==size_x && D.getSizeY()==size_y && "Domain and Mask size must be equal."); return array[(D.getY()-offset_y)*size_x + D.getX()-offset_x]; } Mask &operator=(const data_t *other) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { array[y*size_x + x] = other[y*size_x + x]; // set holes in underlying domain_space if (other[y*size_x + x] == 0) { domain_space[y*size_x + x] = 0; } else { domain_space[y*size_x + x] = 1; } } } return *this; } void setEI(ElementIterator *ei) { EI = ei; } ElementIterator begin() const { return ElementIterator(size_x, size_y, offset_x, offset_y, &iteration_space); } ElementIterator end() const { return ElementIterator(); } }; template <typename data_t, typename Function> auto convolve(Mask<data_t> &mask, HipaccConvolutionMode mode, const Function& fun) -> decltype(fun()) { ElementIterator end = mask.end(); ElementIterator iter = mask.begin(); // register mask mask.setEI(&iter); // initialize result - calculate first iteration auto result = fun(); ++iter; // advance iterator and apply kernel to remaining iteration space while (iter != end) { switch (mode) { case HipaccSUM: result += fun(); break; case HipaccMIN: { auto tmp = fun(); result = hipacc::math::min(tmp, result); } break; case HipaccMAX: { auto tmp = fun(); result = hipacc::math::max(tmp, result); } break; case HipaccPROD: result *= fun(); break; case HipaccMEDIAN: assert(0 && "HipaccMEDIAN not implemented yet!"); break; } ++iter; } // de-register mask mask.setEI(NULL); return result; } template <typename Function> auto reduce(Domain &domain, HipaccConvolutionMode mode, const Function &fun) -> decltype(fun()) { Domain::DomainIterator end = domain.end(); Domain::DomainIterator iter = domain.begin(); // register domain domain.setDI(&iter); // initialize result - calculate first iteration auto result = fun(); ++iter; // advance iterator and apply kernel to remaining iteration space while (iter != end) { switch (mode) { case HipaccSUM: result += fun(); break; case HipaccMIN: { auto tmp = fun(); result = hipacc::math::min(tmp, result); } break; case HipaccMAX: { auto tmp = fun(); result = hipacc::math::max(tmp, result); } break; case HipaccPROD: result *= fun(); break; case HipaccMEDIAN: assert(0 && "HipaccMEDIAN not implemented yet!"); break; } ++iter; } // de-register domain domain.setDI(NULL); return result; } template <typename Function> void iterate(Domain &domain, const Function &fun) { Domain::DomainIterator end = domain.end(); Domain::DomainIterator iter = domain.begin(); // register domain domain.setDI(&iter); // advance iterator and apply kernel to iteration space while (iter != end) { fun(); ++iter; } // de-register domain domain.setDI(NULL); } } // end namespace hipacc #endif // __MASK_HPP__ <commit_msg>DSL: Removed delegating ctor to support ancient GCC 4.6<commit_after>// // Copyright (c) 2012, University of Erlangen-Nuremberg // Copyright (c) 2012, Siemens AG // 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. // #ifndef __MASK_HPP__ #define __MASK_HPP__ #include "iterationspace.hpp" #include "types.hpp" namespace hipacc { class MaskBase { protected: const int size_x, size_y; const int offset_x, offset_y; uchar *domain_space; IterationSpaceBase iteration_space; public: MaskBase(int size_x, int size_y) : size_x(size_x), size_y(size_y), offset_x(-size_x/2), offset_y(-size_y/2), domain_space(new uchar[size_x*size_y]), iteration_space(size_x, size_y) { assert(size_x>0 && size_y>0 && "Size for Domain must be positive!"); // initialize full domain for (int i = 0; i < size_x*size_y; ++i) { domain_space[i] = 1; } } MaskBase(const MaskBase &mask) : size_x(size_x), size_y(size_y), offset_x(-size_x/2), offset_y(-size_y/2), domain_space(new uchar[size_x*size_y]), iteration_space(size_x, size_y) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = mask.domain_space[y * size_x + x]; } } } ~MaskBase() { if (domain_space != NULL) { delete[] domain_space; domain_space = NULL; } } int getSizeX() const { return size_x; } int getSizeY() const { return size_y; } virtual int getX() = 0; virtual int getY() = 0; friend class Domain; template<typename> friend class Mask; }; class Domain : public MaskBase { public: class DomainIterator : public ElementIterator { private: uchar *domain_space; public: DomainIterator(int width=0, int height=0, int offsetx=0, int offsety=0, const IterationSpaceBase *iterspace=NULL, uchar *domain_space=NULL) : ElementIterator(width, height, offsetx, offsety, iterspace), domain_space(domain_space) { if (domain_space != NULL) { // set current coordinate before domain coord.x = min_x-1; coord.y = min_y; // use increment to search first non-zero value ++(*this); } } ~DomainIterator() {} // increment so we iterate over elements in a block DomainIterator &operator++() { do { if (iteration_space) { coord.x++; if (coord.x >= max_x) { coord.x = min_x; coord.y++; if (coord.y >= max_y) { iteration_space = NULL; } } } } while (NULL != iteration_space && (NULL == domain_space || 0 == domain_space[(coord.y-min_y) * (max_x-min_x) + (coord.x-min_x)])); return *this; } }; protected: DomainIterator *DI; public: Domain(int size_x, int size_y) : MaskBase(size_x, size_y), DI(NULL) {} Domain(const MaskBase &mask) : MaskBase(mask), DI(NULL) {} Domain(const Domain &domain) : MaskBase(domain), DI(domain.DI) {} ~Domain() {} int getX() { assert(DI && "DomainIterator for Domain not set!"); return DI->getX(); } int getY() { assert(DI && "DomainIterator for Domain not set!"); return DI->getY(); } uchar &operator()(unsigned int x, unsigned int y) { x += size_x >> 1; y += size_y >> 1; if ((int)x < size_x && (int)y < size_y) { return domain_space[y * size_x + x]; } else { return domain_space[0]; } } Domain &operator=(const uchar *other) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = other[y * size_x + x]; } } return *this; } void operator=(const Domain &dom) { assert(size_x==dom.getSizeX() && size_y==dom.getSizeY() && "Domain sizes must be equal."); for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = dom.domain_space[y * size_x + x]; } } } void operator=(const MaskBase &mask) { assert(size_x==mask.getSizeX() && size_y==mask.getSizeY() && "Domain and Mask size must be equal."); for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = mask.domain_space[y * size_x + x]; } } } void setDI(DomainIterator *di) { DI = di; } DomainIterator begin() const { return DomainIterator(size_x, size_y, offset_x, offset_y, &iteration_space, domain_space); } DomainIterator end() const { return DomainIterator(); } }; template<typename data_t> class Mask : public MaskBase { private: ElementIterator *EI; data_t *array; public: Mask(int size_x, int size_y) : MaskBase(size_x, size_y), EI(NULL), array(new data_t[size_x*size_y]) { assert(size_x>0 && size_y>0 && "size for Mask must be positive!"); } Mask(const Mask &mask) : MaskBase(mask.size_x, mask.size_y), array(new data_t[mask.size_x*mask.size_y]) { operator=(mask.array); } ~Mask() { if (array != NULL) { delete[] array; array = NULL; } } int getX() { assert(EI && "ElementIterator for Mask not set!"); return EI->getX(); } int getY() { assert(EI && "ElementIterator for Mask not set!"); return EI->getY(); } data_t &operator()(void) { assert(EI && "ElementIterator for Mask not set!"); return array[(EI->getY()-offset_y)*size_x + EI->getX()-offset_x]; } data_t &operator()(const int xf, const int yf) { return array[(yf-offset_y)*size_x + xf-offset_x]; } data_t &operator()(Domain &D) { assert(D.getSizeX()==size_x && D.getSizeY()==size_y && "Domain and Mask size must be equal."); return array[(D.getY()-offset_y)*size_x + D.getX()-offset_x]; } Mask &operator=(const data_t *other) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { array[y*size_x + x] = other[y*size_x + x]; // set holes in underlying domain_space if (other[y*size_x + x] == 0) { domain_space[y*size_x + x] = 0; } else { domain_space[y*size_x + x] = 1; } } } return *this; } void setEI(ElementIterator *ei) { EI = ei; } ElementIterator begin() const { return ElementIterator(size_x, size_y, offset_x, offset_y, &iteration_space); } ElementIterator end() const { return ElementIterator(); } }; template <typename data_t, typename Function> auto convolve(Mask<data_t> &mask, HipaccConvolutionMode mode, const Function& fun) -> decltype(fun()) { ElementIterator end = mask.end(); ElementIterator iter = mask.begin(); // register mask mask.setEI(&iter); // initialize result - calculate first iteration auto result = fun(); ++iter; // advance iterator and apply kernel to remaining iteration space while (iter != end) { switch (mode) { case HipaccSUM: result += fun(); break; case HipaccMIN: { auto tmp = fun(); result = hipacc::math::min(tmp, result); } break; case HipaccMAX: { auto tmp = fun(); result = hipacc::math::max(tmp, result); } break; case HipaccPROD: result *= fun(); break; case HipaccMEDIAN: assert(0 && "HipaccMEDIAN not implemented yet!"); break; } ++iter; } // de-register mask mask.setEI(NULL); return result; } template <typename Function> auto reduce(Domain &domain, HipaccConvolutionMode mode, const Function &fun) -> decltype(fun()) { Domain::DomainIterator end = domain.end(); Domain::DomainIterator iter = domain.begin(); // register domain domain.setDI(&iter); // initialize result - calculate first iteration auto result = fun(); ++iter; // advance iterator and apply kernel to remaining iteration space while (iter != end) { switch (mode) { case HipaccSUM: result += fun(); break; case HipaccMIN: { auto tmp = fun(); result = hipacc::math::min(tmp, result); } break; case HipaccMAX: { auto tmp = fun(); result = hipacc::math::max(tmp, result); } break; case HipaccPROD: result *= fun(); break; case HipaccMEDIAN: assert(0 && "HipaccMEDIAN not implemented yet!"); break; } ++iter; } // de-register domain domain.setDI(NULL); return result; } template <typename Function> void iterate(Domain &domain, const Function &fun) { Domain::DomainIterator end = domain.end(); Domain::DomainIterator iter = domain.begin(); // register domain domain.setDI(&iter); // advance iterator and apply kernel to iteration space while (iter != end) { fun(); ++iter; } // de-register domain domain.setDI(NULL); } } // end namespace hipacc #endif // __MASK_HPP__ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: CArray.hh Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ // .NAME vlCharArray - dynamic, self adjusting unssigned character array // .SECTION Description // vlCharArray is an array of unsigned character values. It provides methods // for insertion and retrieval of characters, and will automatically // resize itself to hold new data. #ifndef __vlCharArray_h #define __vlCharArray_h #include "Object.hh" class vlCharArray : public vlObject { public: vlCharArray():Array(NULL),Size(0),MaxId(-1),Extend(1000) {}; int Allocate(const int sz, const int ext=1000); void Initialize(); vlCharArray(const int sz, const int ext=1000); vlCharArray(const vlCharArray& ia); ~vlCharArray(); virtual char *GetClassName() {return "vlCharArray";}; void PrintSelf(ostream& os, vlIndent indent); // access/insertion methods unsigned char GetValue(const int id); vlCharArray &InsertValue(const int id, const unsigned char c); int InsertNextValue(const unsigned char c); unsigned char *GetPtr(const int id); unsigned char *WritePtr(const int id, const int number); // special operators vlCharArray &operator=(const vlCharArray& ia); void operator+=(const vlCharArray& ia); void operator+=(const unsigned char c); unsigned char& operator[](const int i); // miscellaneous methods void Squeeze(); int GetSize(); int GetMaxId(); void Reset(); private: unsigned char *Array; // pointer to data int Size; // allocated size of data int MaxId; // maximum index inserted thus far int Extend; // grow array by this point unsigned char *Resize(const int sz); // function to resize data }; // Description: // Get the data at a particular index. inline unsigned char vlCharArray::GetValue(const int id) {return this->Array[id];}; // Description: // Get the address of a particular data index. inline unsigned char *vlCharArray::GetPtr(const int id) {return this->Array + id;}; // Description: // Get the address of a particular data index. Make sure data is allocated // for the number of items requested. Set MaxId according to the number of // data values requested. inline unsigned char *vlCharArray::WritePtr(const int id, const int number) { if ( (id + number) > this->Size ) this->Resize(id+number); this->MaxId = id + number - 1; return this->Array + id; } // Description: // Insert data at a specified position in the array. inline vlCharArray& vlCharArray::InsertValue(const int id, const unsigned char c) { if ( id >= this->Size ) this->Resize(id); this->Array[id] = c; if ( id > this->MaxId ) this->MaxId = id; return *this; } // Description: // Insert data at the end of the array. Return its location in the array. inline int vlCharArray::InsertNextValue(const unsigned char c) { this->InsertValue (++this->MaxId,c); return this->MaxId; } inline void vlCharArray::operator+=(const unsigned char c) { this->InsertNextValue(c); } // Description: // Does insert or get (depending on location on lhs or rhs of statement). Does // not do automatic resizing - user's responsibility to range check. inline unsigned char& vlCharArray::operator[](const int i) { if (i > this->MaxId) this->MaxId = 1; return this->Array[i]; } // Description: // Resize object to just fit data requirement. Reclaims extra memory. inline void vlCharArray::Squeeze() {this->Resize (this->MaxId+1);}; // Description: // Get the allocated size of the object in terms of number of data items. inline int vlCharArray::GetSize() {return this->Size;}; // Description: // Returning the maximum index of data inserted so far. inline int vlCharArray::GetMaxId() {return this->MaxId;}; // Description: // Reuse the memory allocated by this object. Objects appears like // no data has been previously inserted. inline void vlCharArray::Reset() {this->MaxId = -1;}; #endif <commit_msg>*** empty log message ***<commit_after>/*========================================================================= Program: Visualization Library Module: CArray.hh Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ // .NAME vlCharArray - dynamic, self adjusting unssigned character array // .SECTION Description // vlCharArray is an array of unsigned character values. It provides methods // for insertion and retrieval of characters, and will automatically // resize itself to hold new data. #ifndef __vlCharArray_h #define __vlCharArray_h #include "Object.hh" class vlCharArray : public vlObject { public: vlCharArray():Array(NULL),Size(0),MaxId(-1),Extend(1000) {}; int Allocate(const int sz, const int ext=1000); void Initialize(); vlCharArray(const int sz, const int ext=1000); vlCharArray(const vlCharArray& ia); ~vlCharArray(); virtual char *GetClassName() {return "vlCharArray";}; void PrintSelf(ostream& os, vlIndent indent); // access/insertion methods unsigned char GetValue(const int id); vlCharArray &InsertValue(const int id, const unsigned char c); int InsertNextValue(const unsigned char c); unsigned char *GetPtr(const int id); unsigned char *WritePtr(const int id, const int number); // special operators vlCharArray &operator=(const vlCharArray& ia); void operator+=(const vlCharArray& ia); void operator+=(const unsigned char c); unsigned char& operator[](const int i); // miscellaneous methods void Squeeze(); int GetSize(); int GetMaxId(); void Reset(); private: unsigned char *Array; // pointer to data int Size; // allocated size of data int MaxId; // maximum index inserted thus far int Extend; // grow array by this point unsigned char *Resize(const int sz); // function to resize data }; // Description: // Get the data at a particular index. inline unsigned char vlCharArray::GetValue(const int id) {return this->Array[id];}; // Description: // Get the address of a particular data index. inline unsigned char *vlCharArray::GetPtr(const int id) {return this->Array + id;}; // Description: // Get the address of a particular data index. Make sure data is allocated // for the number of items requested. Set MaxId according to the number of // data values requested. inline unsigned char *vlCharArray::WritePtr(const int id, const int number) { if ( (id + number) > this->Size ) this->Resize(id+number); this->MaxId = id + number - 1; return this->Array + id; } // Description: // Insert data at a specified position in the array. inline vlCharArray& vlCharArray::InsertValue(const int id, const unsigned char c) { if ( id >= this->Size ) this->Resize(id); this->Array[id] = c; if ( id > this->MaxId ) this->MaxId = id; return *this; } // Description: // Insert data at the end of the array. Return its location in the array. inline int vlCharArray::InsertNextValue(const unsigned char c) { this->InsertValue (++this->MaxId,c); return this->MaxId; } inline void vlCharArray::operator+=(const unsigned char c) { this->InsertNextValue(c); } // Description: // Does insert or get (depending on location on lhs or rhs of statement). Does // not do automatic resizing - user's responsibility to range check. inline unsigned char& vlCharArray::operator[](const int i) { if (i > this->MaxId) this->MaxId = i; return this->Array[i]; } // Description: // Resize object to just fit data requirement. Reclaims extra memory. inline void vlCharArray::Squeeze() {this->Resize (this->MaxId+1);}; // Description: // Get the allocated size of the object in terms of number of data items. inline int vlCharArray::GetSize() {return this->Size;}; // Description: // Returning the maximum index of data inserted so far. inline int vlCharArray::GetMaxId() {return this->MaxId;}; // Description: // Reuse the memory allocated by this object. Objects appears like // no data has been previously inserted. inline void vlCharArray::Reset() {this->MaxId = -1;}; #endif <|endoftext|>
<commit_before>#include "stack.hpp" #ifndef STACK_CPP #define STACK_CPP template <typename T> stack<T>::stack() : count_(0), array_size_(1), array_(new T[array_size_]) /*strong*/ {} template <typename T> size_t stack<T> :: count() const /*noexcept*/ { return count_; } template <typename T> stack<T>::~stack() /*noexcept*/ { delete[] array_; } template <typename T> void stack <T> :: push(const T& b) /*strong*/ { if(count_==array_size_) { array_size_*=2; T*l=copy_new(array_,count_,array_size_); delete[] array_; array_=l; l=nullptr; } array_[count_]=b; count_++; } template <typename T> stack<T>::stack(const stack&c) : array_size_(c.array_size_),count_(c.count_), array_(copy_new(c.array_, c.count_, c.array_size_ )) /*strong*/ {}; /*template<typename T> T*stack<T>::copy_new(const T*arr,size_t count,size_t array_size) {T*l=new T[array_size]; std::copy(arr,arr+count,l); return;}*/ template <typename T> stack<T>& stack<T>::operator=(const stack &b) /*strong*/ { if (this != &b) { delete[] array_; array_size_ = b.array_size_; count_ = b.count_; array_ = copy_new(b.array_, count_, array_size_); } return *this; } template <typename T> T stack<T>::pop() /*strong*/ { if (!count_) { throw std::logic_error("Stack is empty!"); } return array_[--count_]; } template<typename T> const T& stack<T>::top() /*strong*/ { if (count_ == 0) { throw std::logic_error("Stack is empty!"); } return array_[count_-1]; } template<typename T> bool stack<T>::operator==(stack const & _s) /*noexcept*/ { if ((_s.count_ != count_) || (_s.array_size_ != array_size_)) { return false; } else { for (size_t i = 0; i < count_; i++) { if (_s.array_[i] != array_[i]) { return false; } } } return true; } template<typename T> bool stack<T>::empty() const noexcept { return (count_==0); } void stack<T>::swap(stack &v) { std::swap(v.array_size_,array_size_); std::swap(v.count_,count_); std::swap(v.array_,array_); } #endif <commit_msg>Update stack.cpp<commit_after>#include "stack.hpp" #ifndef STACK_CPP #define STACK_CPP template <typename T> stack<T>::stack() : count_(0), array_size_(1), array_(new T[array_size_]) /*strong*/ {} template <typename T> size_t stack<T> :: count() const /*noexcept*/ { return count_; } template <typename T> stack<T>::~stack() /*noexcept*/ { delete[] array_; } template <typename T> void stack <T> :: push(const T& b) /*strong*/ { if(count_==array_size_) { array_size_*=2; T*l=copy_new(array_,count_,array_size_); delete[] array_; array_=l; l=nullptr; } array_[count_]=b; count_++; } template <typename T> stack<T>::stack(const stack&c) : array_size_(c.array_size_),count_(c.count_), array_(copy_new(c.array_, c.count_, c.array_size_ )) /*strong*/ {}; /*template<typename T> T*stack<T>::copy_new(const T*arr,size_t count,size_t array_size) {T*l=new T[array_size]; std::copy(arr,arr+count,l); return;}*/ template <typename T> stack<T>& stack<T>::operator=(const stack &b) /*strong*/ { if (this != &b) { delete[] array_; array_size_ = b.array_size_; count_ = b.count_; array_ = copy_new(b.array_, count_, array_size_); } return *this; } template <typename T> void stack<T>::pop() /*strong*/ { if (!count_) { throw std::logic_error("Stack is empty!"); } --count_; } template<typename T> const T& stack<T>::top() /*strong*/ { if (count_ == 0) { throw std::logic_error("Stack is empty!"); } return array_[count_-1]; } template<typename T> bool stack<T>::operator==(stack const & _s) /*noexcept*/ { if ((_s.count_ != count_) || (_s.array_size_ != array_size_)) { return false; } else { for (size_t i = 0; i < count_; i++) { if (_s.array_[i] != array_[i]) { return false; } } } return true; } template<typename T> bool stack<T>::empty() const noexcept { return (count_==0); } void stack<T>::swap(stack &v) { std::swap(v.array_size_,array_size_); std::swap(v.count_,count_); std::swap(v.array_,array_); } #endif <|endoftext|>
<commit_before>#include <iostream> using namespace std; template <typename T> class stack { public: stack(); stack(const stack<T> &); size_t count() const; void print()const; void push(T const &); void swap(const stack<T>&); T pop(); stack<T>& operator=(const stack<T> &); ~stack(); private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr } {} template<class T> stack<T>::~stack() { count_ = 0; array_size_ = 0; delete[] array_; } template <typename T> stack<T>::stack(const stack<T>& copy) { array_size_ = copy.array_size_; count_ = copy.count_; array_ = new T*[array_size_]; for (int i = 0; i < array_size_; i++) array_[array_size_] = copy.array_[array_size_]; } template<class T> size_t stack<T>::count() const { return count_; } template<typename T> void stack<T>::swap(const stack& x) { std::swap(x.array_size_, array_size_); std::swap(count_, x.count_); std::swap(x.array_, array_); } template <typename T> void stack<T>::push(T const &value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_]; } else if (array_size_ == count_) { array_size_ = array_size_ * 2; T *s1 = new T[array_size_]; std::copy(array_, array_ + count_, s1; //for (int i = 0; i < count_; i++) //std::copy(int i = 0; i < count; i++) // s1[i] = array_[i]; delete[] array_; array_ = s1; } array_[count_] = value; count_++; } template <typename T> T stack<T>::pop() { if (count_ == 0) throw "Stack is empty" ; count_--; T x = array_[count_]; swap(); return x; } template <typename T> void stack<T>::print() const { for (int i = 0; i < array_size_; i++) cout << array_[i]; } template<typename T> stack<T>& stack<T>::operator=(const stack<T> & tmp) { if (this != &tmp) { delete[] array_; } if (array_size_ != 0) { array_size_ = tmp.array_size_; count_ = tmp.count_; array_=new T[count_]; std::copy(tmp.array_, tmp.array_ + tmp.count_, array_); } return *this; } <commit_msg>Update stack.hpp<commit_after>#include <iostream> using namespace std; template <typename T> class stack { public: stack(); stack(const stack<T> &); size_t count() const; void print()const; void push(T const &); void swap(const stack<T>&); T pop(); stack<T>& operator=(const stack<T> &); ~stack(); private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr } {} template<class T> stack<T>::~stack() { count_ = 0; array_size_ = 0; delete[] array_; } template <typename T> stack<T>::stack(const stack<T>& copy) { array_size_ = copy.array_size_; count_ = copy.count_; array_ = new T*[array_size_]; for (int i = 0; i < array_size_; i++) array_[array_size_] = copy.array_[array_size_]; } template<class T> size_t stack<T>::count() const { return count_; } template<typename T> void stack<T>::swap(const stack& x) { std::swap(x.array_size_, array_size_); std::swap(count_, x.count_); std::swap(x.array_, array_); } template <typename T> void stack<T>::push(T const &value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_]; } else if (array_size_ == count_) { array_size_ = array_size_ * 2; T *s1 = new T[array_size_]; std::copy(array_, array_ + count_, s1); //for (int i = 0; i < count_; i++) //std::copy(int i = 0; i < count; i++) // s1[i] = array_[i]; delete[] array_; array_ = s1; } array_[count_] = value; count_++; } template <typename T> T stack<T>::pop() { if (count_ == 0) throw "Stack is empty" ; count_--; T x = array_[count_]; swap(); return x; } template <typename T> void stack<T>::print() const { for (int i = 0; i < array_size_; i++) cout << array_[i]; } template<typename T> stack<T>& stack<T>::operator=(const stack<T> & tmp) { if (this != &tmp) { delete[] array_; } if (array_size_ != 0) { array_size_ = tmp.array_size_; count_ = tmp.count_; array_=new T[count_]; std::copy(tmp.array_, tmp.array_ + tmp.count_, array_); } return *this; } <|endoftext|>
<commit_before>#include <iostream> using namespace std; template <typename T> class stack { public: stack();/*noexept*/ stack(const stack<T> &);/*strong*/ size_t count() const; /*noexcept*/ void print()const;/*noexcept*/ void push(T const &); /*strong*/ void swap(stack<T>&); /*noexcept*/ void pop(); /*strong*/ T top(); /*strong*/ bool empty() const; /*noexcept*/ stack<T>& operator=(stack<T> &); /*noexcept*/ ~stack();/*noexcept*/ private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr } {} template<class T> stack<T>::~stack() { count_ = 0; array_size_ = 0; delete[] array_; } template <typename T> stack<T>::stack(const stack<T>& copy) { if (count_ > 0) { array_size_ = copy.array_size_; count_ = copy.count_; array_ = new T[count_]; std::copy(copy.array_, copy.array_ + copy.count_, array_); } } template<class T> size_t stack<T>::count() const { return count_; } template <typename T> bool stack<T>::empty() const { return (count_ == 0); } template<typename T> void stack<T>::swap(stack& x) { std::swap(x.array_size_, array_size_); std::swap(count_, x.count_); std::swap(x.array_, array_); } template <typename T> T stack<T>::top() { if (empty()) { throw "Stack is empty!"; } return array_[count_ - 1]; } template <typename T> void stack<T>::push(T const &value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_]; } else if (array_size_ == count_) { if (array_size_ > 0) { array_size_ = array_size_ * 2; T *s1 = new T[array_size_]; std::copy(array_, array_ + count_, s1); delete[] array_; array_ = s1; } } array_[count_] = value; count_++; } template <typename T> void stack<T>::pop() { if (empty()) throw "Stack is empty" ; count_--; } template <typename T> void stack<T>::print() const { for (int i = 0; i < array_size_; i++) cout << array_[i]; } template<typename T> stack<T>& stack<T>::operator=(stack<T> & tmp) { if (this != &tmp) { stack<T> other(tmp); other.swap(*this); } return *this; } <commit_msg>Update stack.hpp<commit_after>#include <iostream> using namespace std; template <typename T> class stack { public: stack();/*noexept*/ stack(const stack<T> &);/*strong*/ size_t count() const; /*noexcept*/ void print()const;/*noexcept*/ void push(T const &); /*strong*/ void swap(stack<T>&); /*noexcept*/ void pop(); /*strong*/ T top(); /*strong*/ bool empty() const; /*noexcept*/ stack<T>& operator=(stack<T> &); /*noexcept*/ ~stack();/*noexcept*/ private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr } {} template<class T> stack<T>::~stack() { count_ = 0; array_size_ = 0; delete[] array_; } template <typename T> stack<T>::stack(const stack<T>& copy) { if (count_ > 0) { array_size_ = copy.array_size_; count_ = copy.count_; array_ = new T[count_]; std::copy(copy.array_, copy.array_ + copy.count_, array_); }else{ array_ = nullptr; } template<class T> size_t stack<T>::count() const { return count_; } template <typename T> bool stack<T>::empty() const { return (count_ == 0); } template<typename T> void stack<T>::swap(stack& x) { std::swap(x.array_size_, array_size_); std::swap(count_, x.count_); std::swap(x.array_, array_); } template <typename T> T stack<T>::top() { if (empty()) { throw "Stack is empty!"; } return array_[count_ - 1]; } template <typename T> void stack<T>::push(T const &value) { if (array_size_ == 0) { array_size_ = 1; array_ = new T[array_size_]; } else if (array_size_ == count_) { if (array_size_ > 0) { array_size_ = array_size_ * 2; T *s1 = new T[array_size_]; std::copy(array_, array_ + count_, s1); delete[] array_; array_ = s1; } } array_[count_] = value; count_++; } template <typename T> void stack<T>::pop() { if (empty()) throw "Stack is empty" ; count_--; } template <typename T> void stack<T>::print() const { for (int i = 0; i < array_size_; i++) cout << array_[i]; } template<typename T> stack<T>& stack<T>::operator=(stack<T> & other) { if (this != &other) { stack<T> tmp(other); tmp.swap(*this); } return *this; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2015-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef WORD_SPOTTER_UTILS_HPP #define WORD_SPOTTER_UTILS_HPP #include <vector> #include <string> #include "etl/etl.hpp" #include "config.hpp" #include "dataset.hpp" template <typename T> std::ostream& operator<<(std::ostream& stream, const std::vector<T>& vec) { std::string comma = ""; stream << "["; for (auto& v : vec) { stream << comma << v; comma = ", "; } stream << "]"; return stream; } template <typename T> std::string keyword_to_string(const std::vector<T>& vec) { std::string comma = ""; std::string result; result += "["; for (auto& v : vec) { result += comma; result += v; comma = ", "; } result += "]"; return result; } etl::dyn_matrix<weight, 3> mat_for_patches(const config& conf, const cv::Mat& image); template <typename DBN> typename DBN::template layer_type<0>::input_one_t holistic_mat(const config& conf, const cv::Mat& image) { using image_t = typename DBN::template layer_type<0>::input_one_t; image_t training_image; #ifndef OPENCV_23 cv::Mat normalized(cv::Size(WIDTH, HEIGHT), CV_8U); normalized = cv::Scalar(255); image.copyTo(normalized(cv::Rect((WIDTH - image.size().width) / 2, 0, image.size().width, HEIGHT))); cv::Mat scaled_normalized(cv::Size(std::max(1UL, WIDTH), std::max(1UL, HEIGHT / conf.downscale)), CV_8U); cv::resize(normalized, scaled_normalized, scaled_normalized.size(), cv::INTER_AREA); cv::adaptiveThreshold(scaled_normalized, normalized, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 7, 2); for (std::size_t y = 0; y < static_cast<std::size_t>(normalized.size().height); ++y) { for (std::size_t x = 0; x < static_cast<std::size_t>(normalized.size().width); ++x) { auto pixel = normalized.at<uint8_t>(cv::Point(x, y)); training_image(0, y, x) = pixel == 0 ? 0.0 : 1.0; if (pixel != 0 && pixel != 255) { std::cout << "The normalized input image is not binary! pixel:" << static_cast<int>(pixel) << std::endl; } } } #else cpp_unused(conf); cpp_unused(image); #endif return training_image; } template <typename DBN> std::vector<typename DBN::template layer_type<0>::input_one_t> mat_to_patches(const config& conf, const cv::Mat& image, bool train) { using image_t = typename DBN::template layer_type<0>::input_one_t; cv::Mat buffer_image; if (conf.downscale > 1) { cv::Mat scaled_normalized( cv::Size(std::max(1UL, image.size().width / conf.downscale), std::max(1UL, image.size().height / conf.downscale)), CV_8U); cv::resize(image, scaled_normalized, scaled_normalized.size(), cv::INTER_AREA); cv::adaptiveThreshold(scaled_normalized, buffer_image, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 7, 2); } const cv::Mat& clean_image = conf.downscale > 1 ? buffer_image : image; std::vector<image_t> patches; const auto context = conf.patch_width / 2; const auto patch_stride = train ? conf.train_stride : conf.test_stride; for (std::size_t i = 0; i < static_cast<std::size_t>(clean_image.size().width); i += patch_stride) { patches.emplace_back(); auto& patch = patches.back(); for (std::size_t y = 0; y < static_cast<std::size_t>(clean_image.size().height); ++y) { for (int x = i - context; x < static_cast<int>(i + context); ++x) { uint8_t pixel = 1; if (x >= 0 && x < clean_image.size().width) { pixel = clean_image.at<uint8_t>(y, x); } patch(0, y, x - i + context) = pixel == 0 ? 0.0 : 1.0; } } } return patches; } #endif <commit_msg>Revert stupidity<commit_after>//======================================================================= // Copyright Baptiste Wicht 2015-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef WORD_SPOTTER_UTILS_HPP #define WORD_SPOTTER_UTILS_HPP #include <vector> #include <string> #include "etl/etl.hpp" #include "config.hpp" #include "dataset.hpp" template <typename T> std::ostream& operator<<(std::ostream& stream, const std::vector<T>& vec) { std::string comma = ""; stream << "["; for (auto& v : vec) { stream << comma << v; comma = ", "; } stream << "]"; return stream; } template <typename T> std::string keyword_to_string(const std::vector<T>& vec) { std::string comma = ""; std::string result; result += "["; for (auto& v : vec) { result += comma; result += v; comma = ", "; } result += "]"; return result; } etl::dyn_matrix<weight, 3> mat_for_patches(const config& conf, const cv::Mat& image); template <typename DBN> typename DBN::template layer_type<0>::input_one_t holistic_mat(const config& conf, const cv::Mat& image) { using image_t = typename DBN::template layer_type<0>::input_one_t; image_t training_image; #ifndef OPENCV_23 cv::Mat normalized(cv::Size(WIDTH, HEIGHT), CV_8U); normalized = cv::Scalar(255); image.copyTo(normalized(cv::Rect((WIDTH - image.size().width) / 2, 0, image.size().width, HEIGHT))); cv::Mat scaled_normalized(cv::Size(std::max(1UL, WIDTH / conf.downscale), std::max(1UL, HEIGHT / conf.downscale)), CV_8U); cv::resize(normalized, scaled_normalized, scaled_normalized.size(), cv::INTER_AREA); cv::adaptiveThreshold(scaled_normalized, normalized, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 7, 2); for (std::size_t y = 0; y < static_cast<std::size_t>(normalized.size().height); ++y) { for (std::size_t x = 0; x < static_cast<std::size_t>(normalized.size().width); ++x) { auto pixel = normalized.at<uint8_t>(cv::Point(x, y)); training_image(0, y, x) = pixel == 0 ? 0.0 : 1.0; if (pixel != 0 && pixel != 255) { std::cout << "The normalized input image is not binary! pixel:" << static_cast<int>(pixel) << std::endl; } } } #else cpp_unused(conf); cpp_unused(image); #endif return training_image; } template <typename DBN> std::vector<typename DBN::template layer_type<0>::input_one_t> mat_to_patches(const config& conf, const cv::Mat& image, bool train) { using image_t = typename DBN::template layer_type<0>::input_one_t; cv::Mat buffer_image; if (conf.downscale > 1) { cv::Mat scaled_normalized( cv::Size(std::max(1UL, static_cast<size_t>(image.size().width)), std::max(1UL, image.size().height / conf.downscale)), CV_8U); cv::resize(image, scaled_normalized, scaled_normalized.size(), cv::INTER_AREA); cv::adaptiveThreshold(scaled_normalized, buffer_image, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 7, 2); } const cv::Mat& clean_image = conf.downscale > 1 ? buffer_image : image; std::vector<image_t> patches; const auto context = conf.patch_width / 2; const auto patch_stride = train ? conf.train_stride : conf.test_stride; for (std::size_t i = 0; i < static_cast<std::size_t>(clean_image.size().width); i += patch_stride) { patches.emplace_back(); auto& patch = patches.back(); for (std::size_t y = 0; y < static_cast<std::size_t>(clean_image.size().height); ++y) { for (int x = i - context; x < static_cast<int>(i + context); ++x) { uint8_t pixel = 1; if (x >= 0 && x < clean_image.size().width) { pixel = clean_image.at<uint8_t>(y, x); } patch(0, y, x - i + context) = pixel == 0 ? 0.0 : 1.0; } } } return patches; } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2015, Wator Vapor 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 wator nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <wator/net.hpp> #include <wator/layer.hpp> #include <wator/layer_image.hpp> <commit_msg>Update wator.hpp<commit_after>/* Copyright (c) 2015, Wator Vapor 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 wator nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <wator/net.hpp> #include <wator/layer.hpp> #include <wator/blob.hpp> #include <wator/layer_image.hpp> <|endoftext|>
<commit_before>#include "Representations/Infrastructure/AccelerometerData.h" #include "Messages/Framework-Representations.pb.h" #include <google/protobuf/io/zero_copy_stream_impl.h> using namespace naoth; using namespace std; Vector3d AccelerometerData::getAcceleration() const { Vector3d acc(data); acc.z += Math::g; return acc; } void AccelerometerData::print(ostream& stream) const { stream << "x = " << data.x << endl; stream << "y = " << data.y << endl; stream << "z = " << data.z << endl; stream << getAcceleration() <<endl; } void Serializer<AccelerometerData>::serialize(const AccelerometerData& representation, std::ostream& stream) { naothmessages::AccelerometerData msg; msg.mutable_data()->set_x(representation.data.x); msg.mutable_data()->set_y(representation.data.y); msg.mutable_data()->set_z(representation.data.z); msg.mutable_rawdata()->set_x(representation.rawData.x); msg.mutable_rawdata()->set_y(representation.rawData.y); msg.mutable_rawdata()->set_z(representation.rawData.z); ::google::protobuf::io::OstreamOutputStream buf(&stream); msg.SerializeToZeroCopyStream(&buf); } void Serializer<AccelerometerData>::deserialize(std::istream& stream, AccelerometerData& representation) { naothmessages::AccelerometerData msg; ::google::protobuf::io::IstreamInputStream buf(&stream); msg.ParseFromZeroCopyStream(&buf); // allow us to parse old log files if(msg.legacypackeddata_size() == 4) { for(int i=0; i<2; i++) { representation.data[i] = msg.legacypackeddata(i*2); representation.rawData[i] = msg.legacypackeddata(i*2+1); } } // always use the non-deprecated fields if possible if(msg.has_data()) { representation.data.x = msg.data().x(); representation.data.y = msg.data().y(); representation.data.z = msg.data().z(); } if(msg.has_rawdata()) { representation.rawData.x = msg.rawdata().x(); representation.rawData.y = msg.rawdata().y(); representation.rawData.z = msg.rawdata().z(); } } <commit_msg>Finish gyro_accel_proto<commit_after>#include "Representations/Infrastructure/AccelerometerData.h" #include "Messages/Framework-Representations.pb.h" #include <google/protobuf/io/zero_copy_stream_impl.h> using namespace naoth; using namespace std; Vector3d AccelerometerData::getAcceleration() const { Vector3d acc(data); acc.z += Math::g; return acc; } void AccelerometerData::print(ostream& stream) const { stream << "x = " << data.x << endl; stream << "y = " << data.y << endl; stream << "z = " << data.z << endl; stream << getAcceleration() <<endl; } void Serializer<AccelerometerData>::serialize(const AccelerometerData& representation, std::ostream& stream) { naothmessages::AccelerometerData msg; msg.mutable_data()->set_x(representation.data.x); msg.mutable_data()->set_y(representation.data.y); msg.mutable_data()->set_z(representation.data.z); msg.mutable_rawdata()->set_x(representation.rawData.x); msg.mutable_rawdata()->set_y(representation.rawData.y); msg.mutable_rawdata()->set_z(representation.rawData.z); ::google::protobuf::io::OstreamOutputStream buf(&stream); msg.SerializeToZeroCopyStream(&buf); } void Serializer<AccelerometerData>::deserialize(std::istream& stream, AccelerometerData& representation) { naothmessages::AccelerometerData msg; ::google::protobuf::io::IstreamInputStream buf(&stream); msg.ParseFromZeroCopyStream(&buf); // allow us to parse old log files if(msg.legacypackeddata_size() == 6) { for(int i=0; i<3; i++) { representation.data[i] = msg.legacypackeddata(i*2); representation.rawData[i] = msg.legacypackeddata(i*2+1); } } // always use the non-deprecated fields if possible if(msg.has_data()) { representation.data.x = msg.data().x(); representation.data.y = msg.data().y(); representation.data.z = msg.data().z(); } if(msg.has_rawdata()) { representation.rawData.x = msg.rawdata().x(); representation.rawData.y = msg.rawdata().y(); representation.rawData.z = msg.rawdata().z(); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSpanTreeLayoutStrategy.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ // File: vtkSpanTreeLayoutStrategy.cxx // Graph visualization library for VTK // (c) 2003 D.J. Duke #include "vtkSpanTreeLayoutStrategy.h" #include "vtkConeLayoutStrategy.h" #include "vtkObjectFactory.h" #include "vtkMutableDirectedGraph.h" #include "vtkTree.h" #include "vtkEdgeListIterator.h" #include "vtkInEdgeIterator.h" #include "vtkOutEdgeIterator.h" #include "vtkGraphLayout.h" #include "vtkGraph.h" #include "vtkPoints.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" #include "vtkDataSetAttributes.h" #include "vtkSmartPointer.h" //-------------------------------------------------------------------------- vtkStandardNewMacro(vtkSpanTreeLayoutStrategy); vtkCxxRevisionMacro(vtkSpanTreeLayoutStrategy, "1.0"); vtkSpanTreeLayoutStrategy::vtkSpanTreeLayoutStrategy() { this->TreeLayout = vtkConeLayoutStrategy::New(); this->DepthFirstSpanningTree = false; } vtkSpanTreeLayoutStrategy::~vtkSpanTreeLayoutStrategy() { if (this->TreeLayout) { this->TreeLayout->Delete(); this->TreeLayout = NULL; } } // Edges that cross levels more than one level of the layout // will have edge-points inserted to match the structure of // the rest of the graph. However, in order to compute the // position of these points, we first need to lay out a // graph in which these edge points are represented by real // vertices. This struct is used to keep trach of the // relationship between the proxy nodes in the graph used // to compute the layout, and edges in the original graph. struct _vtkBridge_s { vtkEdgeType edge; vtkIdType delta; vtkIdType anchor[2]; }; void vtkSpanTreeLayoutStrategy::Layout() { vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkMutableDirectedGraph> spanningDAG = vtkSmartPointer<vtkMutableDirectedGraph>::New(); vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); vtkSmartPointer<vtkGraphLayout> layoutWorker = vtkSmartPointer<vtkGraphLayout>::New(); vtkSmartPointer<vtkOutEdgeIterator> outEdges = vtkSmartPointer<vtkOutEdgeIterator>::New(); vtkSmartPointer<vtkInEdgeIterator> inEdges = vtkSmartPointer<vtkInEdgeIterator>::New(); // Auxiliary structures used for building a spanning tree int *level; int *marks; vtkIdType *queue; vtkIdType front, back; // Handle for the layout computed for the spanning tree vtkPoints *layout; // Auxiliary structures for placing bends into edges. _vtkBridge_s *editlist; _vtkBridge_s link; link.delta = 0; link.anchor[1] = 0; vtkIdType editsize; vtkEdgeType edge; vtkIdType i, nrNodes, nrEdges; double pointS[3], pointT[3], pointA[3]; double edgePoints[6]; // ---------------------------------------------------------- vtkDebugMacro(<<"vtkSpanTreeLayoutStrategy executing."); // Ensure that all required inputs are available. nrNodes = this->Graph->GetNumberOfVertices(); nrEdges = this->Graph->GetNumberOfEdges(); if (nrNodes == 0 || nrEdges == 0 || !this->TreeLayout) { if (nrNodes == 0) { vtkErrorMacro(<< "Cannot execute - no nodes in input." ); } if (nrEdges == 0) { vtkErrorMacro(<< "Cannot execute - no edges in input." ); } if (!this->TreeLayout) { vtkErrorMacro(<< "Cannot execute - no tree layout strategy." ); } return; } // Compute a spanning tree from the graph. This is done inline here // rather than via a Boost class so we can offer a choice of spanning // tree. Graph traversal is supported by a queue, and during // traversal the (tree)level is calculated for each vertex. level = new int [nrNodes]; marks = new int [nrNodes]; queue = new vtkIdType [nrNodes]; // Initialize spanning tree with all vertices of the graph. for (vtkIdType v = 0; v < nrNodes; v++) { spanningDAG->AddVertex(); marks[v] = 0; } // Strategy: iterate over the vertices of the graph. // As each unvisited vertex is found, we perform a traversal starting // from that vertex. The result is technically a spanning forest. for (vtkIdType v = 0; v < nrNodes; v++) { if (!marks[v]) // not visited { front = back = 0; queue[back++] = v; // push node v level[v] = 0; marks[v] = 1; // mark as visited while (back != front) { vtkIdType src; if (this->DepthFirstSpanningTree) { src = queue[--back]; // stack discipline = depth-first traversal } else { src = queue[front++]; // queue discipline = breadth-first traversal } // Look at outgoing edges from this node, // adding any unseen targets to the queue, // and edges to the spanning tree. this->Graph->GetOutEdges(src, outEdges); while (outEdges->HasNext()) { vtkIdType dst = outEdges->Next().Target; if (marks[dst] == 0) // not seen or done { level[dst] = level[src]+1; queue[back++] = dst; spanningDAG->AddGraphEdge(src,dst); marks[dst] = 1; //seen } } // Look at incoming edges: as per outgoing edges. this->Graph->GetInEdges(src, inEdges); while (inEdges->HasNext()) { vtkIdType origin = inEdges->Next().Source; if (marks[origin] == 0) // not seen or done { level[origin] = level[src]+1; queue[back++] = origin; spanningDAG->AddGraphEdge(src,origin); marks[origin] = 1; //seen } } } // while back != front } // if !marks[v] } // for each vertex // Check each edge to see if it spans more than one level of // the tree. If it does, the edge will be drawn using edge-points, // and before we lay out the tree, we need to insert proxy nodes // to compute the position for those points. editsize = 0; editlist = new _vtkBridge_s[nrEdges]; this->Graph->GetEdges(edges); while (edges->HasNext()) { link.edge = edges->Next(); // Loop ... if (link.edge.Source == link.edge.Target) { link.anchor[0] = spanningDAG->AddVertex(); spanningDAG->AddEdge(link.edge.Source,link.anchor[0]); editlist[editsize++] = link; continue; } // If the difference in level between the start and end nodes // is greater than one, this edge, by definition, is not // present in the layout tree. link.delta = level[link.edge.Target] - level[link.edge.Source]; if (abs(link.delta) > 1) { link.anchor[0] = spanningDAG->AddVertex(); spanningDAG->AddEdge(link.delta > 0 ? link.edge.Source : link.edge.Target, link.anchor[0]); if (abs(link.delta) > 2) { link.anchor[1] = spanningDAG->AddVertex(); spanningDAG->AddEdge(link.anchor[0], link.anchor[1]); } editlist[editsize++] = link; } } // Layout the tree using the layout filter provided. layoutWorker->SetLayoutStrategy(this->TreeLayout); layoutWorker->SetInput(spanningDAG); layoutWorker->Update(); layout = layoutWorker->GetOutput()->GetPoints(); // Copy the node positions for nodes in the original // graph from the layout tree to the output positions. points->SetNumberOfPoints(nrNodes); for (i = 0; i < nrNodes; i++) { points->SetPoint(i, layout->GetPoint(i)); } // Now run through the edit list, computing the position for // each of the edge points for (i = 0; i < editsize; i++) { link = editlist[i]; if (link.delta == 0) { // Loop: Each loop is drawn as an edge with 2 edge points. The x & y // coordinates have been fixed by the layout. The z coordinates are // scaled to that the edge points are 1/3 of the distance between // levels, above and below the node. layout->GetPoint(link.edge.Source, pointS); layout->GetPoint(link.anchor[0], pointA); edgePoints[0] = edgePoints[3] = pointA[0]; edgePoints[1] = edgePoints[4] = pointA[1]; edgePoints[2] = pointS[2] + (pointA[2]-pointS[2])/3.0; edgePoints[5] = pointS[2] - (pointA[2]-pointS[2])/3.0; this->Graph->SetEdgePoints(link.edge.Id, 2, edgePoints); } else if (link.delta > 1) { layout->GetPoint(link.edge.Source, pointS); layout->GetPoint(link.edge.Target, pointT); layout->GetPoint(link.anchor[0], pointA); edgePoints[0] = pointA[0]; edgePoints[1] = pointA[1]; edgePoints[2] = pointS[2] + (pointT[2] - pointS[2])/link.delta; if (link.delta > 2) { layout->GetPoint(link.anchor[1], pointA); edgePoints[3] = edgePoints[0]; edgePoints[4] = edgePoints[1]; edgePoints[5] = pointS[2] + (link.delta-1)*(pointT[2] - pointS[2])/link.delta; this->Graph->SetEdgePoints(link.edge.Id, 2, edgePoints); } else { this->Graph->SetEdgePoints(link.edge.Id, 1, edgePoints); } } else if (link.delta < -1) { int delta = -link.delta; layout->GetPoint(link.edge.Source, pointS); layout->GetPoint(link.edge.Target, pointT); layout->GetPoint(link.anchor[0], pointA); edgePoints[0] = pointA[0]; edgePoints[1] = pointA[1]; edgePoints[2] = pointS[2] + (pointT[2] - pointS[2])/delta; if (link.delta < -2) { layout->GetPoint(link.anchor[1], pointA); edgePoints[3] = edgePoints[0]; edgePoints[4] = edgePoints[1]; edgePoints[5] = pointS[2] + (delta-1)*(pointT[2] - pointS[2])/delta; this->Graph->SetEdgePoints(link.edge.Id, 2, edgePoints); } else { this->Graph->SetEdgePoints(link.edge.Id, 1, edgePoints); } } } // Clean up temporary storage. delete [] editlist; delete [] level; delete [] marks; this->Graph->SetPoints(points); vtkDebugMacro(<<"SpanTreeLayoutStrategy complete."); } void vtkSpanTreeLayoutStrategy::PrintSelf(ostream& os, vtkIndent indent) { vtkGraphLayoutStrategy::PrintSelf(os,indent); os << indent << "TreeLayout: " << (this->TreeLayout ? "" : "(none)") << endl; if (this->TreeLayout) { this->TreeLayout->PrintSelf(os, indent.GetNextIndent()); } os << indent << "DepthFirstSpanningTree: " << (this->DepthFirstSpanningTree ? "On" : "Off") << endl; } <commit_msg>COMP: Avoid the dreaded ambiguous abs.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSpanTreeLayoutStrategy.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ // File: vtkSpanTreeLayoutStrategy.cxx // Graph visualization library for VTK // (c) 2003 D.J. Duke #include "vtkSpanTreeLayoutStrategy.h" #include "vtkConeLayoutStrategy.h" #include "vtkObjectFactory.h" #include "vtkMutableDirectedGraph.h" #include "vtkTree.h" #include "vtkEdgeListIterator.h" #include "vtkInEdgeIterator.h" #include "vtkOutEdgeIterator.h" #include "vtkGraphLayout.h" #include "vtkGraph.h" #include "vtkPoints.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" #include "vtkDataSetAttributes.h" #include "vtkSmartPointer.h" //-------------------------------------------------------------------------- vtkStandardNewMacro(vtkSpanTreeLayoutStrategy); vtkCxxRevisionMacro(vtkSpanTreeLayoutStrategy, "1.0"); vtkSpanTreeLayoutStrategy::vtkSpanTreeLayoutStrategy() { this->TreeLayout = vtkConeLayoutStrategy::New(); this->DepthFirstSpanningTree = false; } vtkSpanTreeLayoutStrategy::~vtkSpanTreeLayoutStrategy() { if (this->TreeLayout) { this->TreeLayout->Delete(); this->TreeLayout = NULL; } } // Edges that cross levels more than one level of the layout // will have edge-points inserted to match the structure of // the rest of the graph. However, in order to compute the // position of these points, we first need to lay out a // graph in which these edge points are represented by real // vertices. This struct is used to keep trach of the // relationship between the proxy nodes in the graph used // to compute the layout, and edges in the original graph. struct _vtkBridge_s { vtkEdgeType edge; vtkIdType delta; vtkIdType anchor[2]; }; void vtkSpanTreeLayoutStrategy::Layout() { vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkMutableDirectedGraph> spanningDAG = vtkSmartPointer<vtkMutableDirectedGraph>::New(); vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); vtkSmartPointer<vtkGraphLayout> layoutWorker = vtkSmartPointer<vtkGraphLayout>::New(); vtkSmartPointer<vtkOutEdgeIterator> outEdges = vtkSmartPointer<vtkOutEdgeIterator>::New(); vtkSmartPointer<vtkInEdgeIterator> inEdges = vtkSmartPointer<vtkInEdgeIterator>::New(); // Auxiliary structures used for building a spanning tree int *level; int *marks; vtkIdType *queue; vtkIdType front, back; // Handle for the layout computed for the spanning tree vtkPoints *layout; // Auxiliary structures for placing bends into edges. _vtkBridge_s *editlist; _vtkBridge_s link; link.delta = 0; link.anchor[1] = 0; vtkIdType editsize; vtkEdgeType edge; vtkIdType i, nrNodes, nrEdges; double pointS[3], pointT[3], pointA[3]; double edgePoints[6]; // ---------------------------------------------------------- vtkDebugMacro(<<"vtkSpanTreeLayoutStrategy executing."); // Ensure that all required inputs are available. nrNodes = this->Graph->GetNumberOfVertices(); nrEdges = this->Graph->GetNumberOfEdges(); if (nrNodes == 0 || nrEdges == 0 || !this->TreeLayout) { if (nrNodes == 0) { vtkErrorMacro(<< "Cannot execute - no nodes in input." ); } if (nrEdges == 0) { vtkErrorMacro(<< "Cannot execute - no edges in input." ); } if (!this->TreeLayout) { vtkErrorMacro(<< "Cannot execute - no tree layout strategy." ); } return; } // Compute a spanning tree from the graph. This is done inline here // rather than via a Boost class so we can offer a choice of spanning // tree. Graph traversal is supported by a queue, and during // traversal the (tree)level is calculated for each vertex. level = new int [nrNodes]; marks = new int [nrNodes]; queue = new vtkIdType [nrNodes]; // Initialize spanning tree with all vertices of the graph. for (vtkIdType v = 0; v < nrNodes; v++) { spanningDAG->AddVertex(); marks[v] = 0; } // Strategy: iterate over the vertices of the graph. // As each unvisited vertex is found, we perform a traversal starting // from that vertex. The result is technically a spanning forest. for (vtkIdType v = 0; v < nrNodes; v++) { if (!marks[v]) // not visited { front = back = 0; queue[back++] = v; // push node v level[v] = 0; marks[v] = 1; // mark as visited while (back != front) { vtkIdType src; if (this->DepthFirstSpanningTree) { src = queue[--back]; // stack discipline = depth-first traversal } else { src = queue[front++]; // queue discipline = breadth-first traversal } // Look at outgoing edges from this node, // adding any unseen targets to the queue, // and edges to the spanning tree. this->Graph->GetOutEdges(src, outEdges); while (outEdges->HasNext()) { vtkIdType dst = outEdges->Next().Target; if (marks[dst] == 0) // not seen or done { level[dst] = level[src]+1; queue[back++] = dst; spanningDAG->AddGraphEdge(src,dst); marks[dst] = 1; //seen } } // Look at incoming edges: as per outgoing edges. this->Graph->GetInEdges(src, inEdges); while (inEdges->HasNext()) { vtkIdType origin = inEdges->Next().Source; if (marks[origin] == 0) // not seen or done { level[origin] = level[src]+1; queue[back++] = origin; spanningDAG->AddGraphEdge(src,origin); marks[origin] = 1; //seen } } } // while back != front } // if !marks[v] } // for each vertex // Check each edge to see if it spans more than one level of // the tree. If it does, the edge will be drawn using edge-points, // and before we lay out the tree, we need to insert proxy nodes // to compute the position for those points. editsize = 0; editlist = new _vtkBridge_s[nrEdges]; this->Graph->GetEdges(edges); while (edges->HasNext()) { link.edge = edges->Next(); // Loop ... if (link.edge.Source == link.edge.Target) { link.anchor[0] = spanningDAG->AddVertex(); spanningDAG->AddEdge(link.edge.Source,link.anchor[0]); editlist[editsize++] = link; continue; } // If the difference in level between the start and end nodes // is greater than one, this edge, by definition, is not // present in the layout tree. link.delta = level[link.edge.Target] - level[link.edge.Source]; if (abs(static_cast<double>(link.delta)) > 1) { link.anchor[0] = spanningDAG->AddVertex(); spanningDAG->AddEdge(link.delta > 0 ? link.edge.Source : link.edge.Target, link.anchor[0]); if (abs(static_cast<double>(link.delta)) > 2) { link.anchor[1] = spanningDAG->AddVertex(); spanningDAG->AddEdge(link.anchor[0], link.anchor[1]); } editlist[editsize++] = link; } } // Layout the tree using the layout filter provided. layoutWorker->SetLayoutStrategy(this->TreeLayout); layoutWorker->SetInput(spanningDAG); layoutWorker->Update(); layout = layoutWorker->GetOutput()->GetPoints(); // Copy the node positions for nodes in the original // graph from the layout tree to the output positions. points->SetNumberOfPoints(nrNodes); for (i = 0; i < nrNodes; i++) { points->SetPoint(i, layout->GetPoint(i)); } // Now run through the edit list, computing the position for // each of the edge points for (i = 0; i < editsize; i++) { link = editlist[i]; if (link.delta == 0) { // Loop: Each loop is drawn as an edge with 2 edge points. The x & y // coordinates have been fixed by the layout. The z coordinates are // scaled to that the edge points are 1/3 of the distance between // levels, above and below the node. layout->GetPoint(link.edge.Source, pointS); layout->GetPoint(link.anchor[0], pointA); edgePoints[0] = edgePoints[3] = pointA[0]; edgePoints[1] = edgePoints[4] = pointA[1]; edgePoints[2] = pointS[2] + (pointA[2]-pointS[2])/3.0; edgePoints[5] = pointS[2] - (pointA[2]-pointS[2])/3.0; this->Graph->SetEdgePoints(link.edge.Id, 2, edgePoints); } else if (link.delta > 1) { layout->GetPoint(link.edge.Source, pointS); layout->GetPoint(link.edge.Target, pointT); layout->GetPoint(link.anchor[0], pointA); edgePoints[0] = pointA[0]; edgePoints[1] = pointA[1]; edgePoints[2] = pointS[2] + (pointT[2] - pointS[2])/link.delta; if (link.delta > 2) { layout->GetPoint(link.anchor[1], pointA); edgePoints[3] = edgePoints[0]; edgePoints[4] = edgePoints[1]; edgePoints[5] = pointS[2] + (link.delta-1)*(pointT[2] - pointS[2])/link.delta; this->Graph->SetEdgePoints(link.edge.Id, 2, edgePoints); } else { this->Graph->SetEdgePoints(link.edge.Id, 1, edgePoints); } } else if (link.delta < -1) { int delta = -link.delta; layout->GetPoint(link.edge.Source, pointS); layout->GetPoint(link.edge.Target, pointT); layout->GetPoint(link.anchor[0], pointA); edgePoints[0] = pointA[0]; edgePoints[1] = pointA[1]; edgePoints[2] = pointS[2] + (pointT[2] - pointS[2])/delta; if (link.delta < -2) { layout->GetPoint(link.anchor[1], pointA); edgePoints[3] = edgePoints[0]; edgePoints[4] = edgePoints[1]; edgePoints[5] = pointS[2] + (delta-1)*(pointT[2] - pointS[2])/delta; this->Graph->SetEdgePoints(link.edge.Id, 2, edgePoints); } else { this->Graph->SetEdgePoints(link.edge.Id, 1, edgePoints); } } } // Clean up temporary storage. delete [] editlist; delete [] level; delete [] marks; this->Graph->SetPoints(points); vtkDebugMacro(<<"SpanTreeLayoutStrategy complete."); } void vtkSpanTreeLayoutStrategy::PrintSelf(ostream& os, vtkIndent indent) { vtkGraphLayoutStrategy::PrintSelf(os,indent); os << indent << "TreeLayout: " << (this->TreeLayout ? "" : "(none)") << endl; if (this->TreeLayout) { this->TreeLayout->PrintSelf(os, indent.GetNextIndent()); } os << indent << "DepthFirstSpanningTree: " << (this->DepthFirstSpanningTree ? "On" : "Off") << endl; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //! File : MasterController.cpp //! Author : Jens Krueger //! SCI Institute //! University of Utah //! Date : September 2008 // //! Copyright (C) 2008 SCI Institute #include "MasterController.h" #include "../DebugOut/TextfileOut.h" #include "../DebugOut/MultiplexOut.h" MasterController::MasterController(AbstrDebugOut* pDebugOut) : m_pDebugOut(pDebugOut == NULL ? new ConsoleOut() : pDebugOut), m_bDeleteDebugOutOnExit(true) { m_pSystemInfo = new SystemInfo(); m_pIOManager = new IOManager(this); m_pGPUMemMan = new GPUMemMan(this); m_pScriptEngine = new Scripting(this); RegisterCalls(m_pScriptEngine); } MasterController::~MasterController() { for (AbstrRendererListIter i = m_vVolumeRenderer.begin(); i<m_vVolumeRenderer.end(); ++i) delete (*i); m_vVolumeRenderer.resize(0); delete m_pSystemInfo; delete m_pIOManager; delete m_pGPUMemMan; if (m_bDeleteDebugOutOnExit) delete m_pDebugOut; } void MasterController::SetDebugOut(AbstrDebugOut* debugOut, bool bDeleteOnExit) { if (debugOut != NULL) { m_pDebugOut->Message("MasterController::SetDebugOut", "Disconnecting from this debug out"); if (m_bDeleteDebugOutOnExit ) delete m_pDebugOut; m_bDeleteDebugOutOnExit = bDeleteOnExit; m_pDebugOut = debugOut; m_pDebugOut->Message("MasterController::SetDebugOut", "Connected to this debug out"); } else { m_pDebugOut->Warning("MasterController::SetDebugOut", "New debug is a NULL pointer, keeping old debug out"); } } void MasterController::RemoveDebugOut(AbstrDebugOut* debugOut) { if (debugOut == m_pDebugOut) { m_pDebugOut->Message("MasterController::RemoveDebugOut", "Disconnecting from this debug out"); if (m_bDeleteDebugOutOnExit) delete m_pDebugOut; m_pDebugOut = new ConsoleOut(); m_bDeleteDebugOutOnExit = true; m_pDebugOut->Message("MasterController::RemoveDebugOut", "Connected to this debug out"); } else { m_pDebugOut->Message("MasterController::RemoveDebugOut", "Not Connected the debug out in question (anymore), doing nothing"); } } AbstrRenderer* MasterController:: RequestNewVolumerenderer(EVolumeRendererType eRendererType, bool bUseOnlyPowerOfTwo, bool bDownSampleTo8Bits, bool bDisableBorder) { switch (eRendererType) { case OPENGL_SBVR : m_pDebugOut->Message("MasterController::RequestNewVolumerenderer","Starting up new renderer (API=OpenGL, Method=Slice Based Volume Rendering)"); m_vVolumeRenderer.push_back(new GLSBVR(this, bUseOnlyPowerOfTwo, bDownSampleTo8Bits, bDisableBorder)); return m_vVolumeRenderer[m_vVolumeRenderer.size()-1]; case OPENGL_RAYCASTER : m_pDebugOut->Message("MasterController::RequestNewVolumerenderer","Starting up new renderer (API=OpenGL, Method=Raycaster)"); m_vVolumeRenderer.push_back(new GLRaycaster(this, bUseOnlyPowerOfTwo, bDownSampleTo8Bits, bDisableBorder)); return m_vVolumeRenderer[m_vVolumeRenderer.size()-1]; case DIRECTX_SBVR : case DIRECTX_RAYCASTER : m_pDebugOut->Error("MasterController::RequestNewVolumerenderer","DirectX 10 volume renderer not yet implemented. Please select OpenGL as the render API in the settings dialog."); return NULL; default : m_pDebugOut->Error("MasterController::RequestNewVolumerenderer","Unsupported Volume renderer requested"); return NULL; }; } void MasterController::ReleaseVolumerenderer(AbstrRenderer* pVolumeRenderer) { for (AbstrRendererListIter i = m_vVolumeRenderer.begin(); i<m_vVolumeRenderer.end(); ++i) { if (*i == pVolumeRenderer) { m_pDebugOut->Message("MasterController::ReleaseVolumerenderer", "Deleting volume renderer"); delete pVolumeRenderer; m_vVolumeRenderer.erase(i); return; } } m_pDebugOut->Warning("MasterController::ReleaseVolumerenderer", "requested volume renderer not found"); } void MasterController::Filter( std::string , UINT32 , void*, void *, void *, void * ) { }; void MasterController::RegisterCalls(Scripting* pScriptEngine) { pScriptEngine->RegisterCommand(this, "seterrorlog", "on/off", "toggle recording of errors"); pScriptEngine->RegisterCommand(this, "setwarninglog", "on/off", "toggle recording of warnings"); pScriptEngine->RegisterCommand(this, "setemessagelog", "on/off", "toggle recording of messages"); pScriptEngine->RegisterCommand(this, "printerrorlog", "", "print recorded errors"); pScriptEngine->RegisterCommand(this, "printwarninglog", "", "print recorded errwarningsors"); pScriptEngine->RegisterCommand(this, "printmessagelog", "", "print recorded messages"); pScriptEngine->RegisterCommand(this, "clearerrorlog", "", "clear recorded errors"); pScriptEngine->RegisterCommand(this, "clearwarninglog", "", "clear recorded warnings"); pScriptEngine->RegisterCommand(this, "clearmessagelog", "", "clear recorded messages"); pScriptEngine->RegisterCommand(this, "fileoutput", "filename","write debug output to 'filename'"); pScriptEngine->RegisterCommand(this, "toggleoutput", "on/off on/off on/off on/off","toggle messages, warning, errors, and other output"); } bool MasterController::Execute(const std::string& strCommand, const std::vector< std::string >& strParams, std::string& strMessage) { strMessage = ""; if (strCommand == "seterrorlog") { m_pDebugOut->SetListRecordingErrors(strParams[0] == "on"); if (m_pDebugOut->GetListRecordingErrors()) m_pDebugOut->printf("current state: true"); else m_pDebugOut->printf("current state: false"); return true; } if (strCommand == "setwarninglog") { m_pDebugOut->SetListRecordingWarnings(strParams[0] == "on"); if (m_pDebugOut->GetListRecordingWarnings()) m_pDebugOut->printf("current state: true"); else m_pDebugOut->printf("current state: false"); return true; } if (strCommand == "setmessagelog") { m_pDebugOut->SetListRecordingMessages(strParams[0] == "on"); if (m_pDebugOut->GetListRecordingMessages()) m_pDebugOut->printf("current state: true"); else m_pDebugOut->printf("current state: false"); return true; } if (strCommand == "printerrorlog") { m_pDebugOut->PrintErrorList(); return true; } if (strCommand == "printwarninglog") { m_pDebugOut->PrintWarningList(); return true; } if (strCommand == "printmessagelog") { m_pDebugOut->PrintMessageList(); return true; } if (strCommand == "clearerrorlog") { m_pDebugOut->ClearErrorList(); return true; } if (strCommand == "clearwarninglog") { m_pDebugOut->ClearWarningList(); return true; } if (strCommand == "clearmessagelog") { m_pDebugOut->ClearMessageList(); return true; } if (strCommand == "toggleoutput") { m_pDebugOut->SetOutput(strParams[0] == "on", strParams[1] == "on", strParams[2] == "on", strParams[3] == "on"); return true; } if (strCommand == "fileoutput") { TextfileOut* textout = new TextfileOut(strParams[0]); textout->SetShowErrors(m_pDebugOut->ShowErrors()); textout->SetShowWarnings(m_pDebugOut->ShowWarnings()); textout->SetShowMessages(m_pDebugOut->ShowMessages()); textout->SetShowOther(m_pDebugOut->ShowOther()); AbstrDebugOut* pOldDebug = DebugOut(); bool bDeleteOldDebug = DoDeleteDebugOut(); MultiplexOut* pMultiOut = new MultiplexOut(); pMultiOut->SetOutput(true,true,true,true); SetDebugOut(pMultiOut, true); pMultiOut->AddDebugOut(textout, true); pMultiOut->AddDebugOut(pOldDebug, bDeleteOldDebug); return true; } return false; } <commit_msg>Don't use double-deleted DebugOuts.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //! File : MasterController.cpp //! Author : Jens Krueger //! SCI Institute //! University of Utah //! Date : September 2008 // //! Copyright (C) 2008 SCI Institute #include "MasterController.h" #include "../DebugOut/TextfileOut.h" #include "../DebugOut/MultiplexOut.h" MasterController::MasterController(AbstrDebugOut* pDebugOut) : m_pDebugOut(pDebugOut == NULL ? new ConsoleOut() : pDebugOut), m_bDeleteDebugOutOnExit(true) { m_pSystemInfo = new SystemInfo(); m_pIOManager = new IOManager(this); m_pGPUMemMan = new GPUMemMan(this); m_pScriptEngine = new Scripting(this); RegisterCalls(m_pScriptEngine); } MasterController::~MasterController() { for (AbstrRendererListIter i = m_vVolumeRenderer.begin(); i<m_vVolumeRenderer.end(); ++i) delete (*i); m_vVolumeRenderer.resize(0); delete m_pSystemInfo; delete m_pIOManager; delete m_pGPUMemMan; if (m_bDeleteDebugOutOnExit) delete m_pDebugOut; } void MasterController::SetDebugOut(AbstrDebugOut* debugOut, bool bDeleteOnExit) { if (debugOut != NULL) { m_pDebugOut->Message("MasterController::SetDebugOut", "Disconnecting from this debug out"); if (m_bDeleteDebugOutOnExit ) delete m_pDebugOut; m_bDeleteDebugOutOnExit = bDeleteOnExit; m_pDebugOut = debugOut; m_pDebugOut->Message("MasterController::SetDebugOut", "Connected to this debug out"); } else { m_pDebugOut->Warning("MasterController::SetDebugOut", "New debug is a NULL pointer, keeping old debug out"); } } void MasterController::RemoveDebugOut(AbstrDebugOut* debugOut) { if (debugOut == m_pDebugOut) { m_pDebugOut->Message("MasterController::RemoveDebugOut", "Disconnecting from this debug out"); if (m_bDeleteDebugOutOnExit) delete m_pDebugOut; m_pDebugOut = new ConsoleOut(); m_bDeleteDebugOutOnExit = true; m_pDebugOut->Message("MasterController::RemoveDebugOut", "Connected to this debug out"); } else { m_pDebugOut->Message("MasterController::RemoveDebugOut", "Not Connected the debug out in question (anymore), doing nothing"); } } AbstrRenderer* MasterController:: RequestNewVolumerenderer(EVolumeRendererType eRendererType, bool bUseOnlyPowerOfTwo, bool bDownSampleTo8Bits, bool bDisableBorder) { switch (eRendererType) { case OPENGL_SBVR : m_pDebugOut->Message("MasterController::RequestNewVolumerenderer","Starting up new renderer (API=OpenGL, Method=Slice Based Volume Rendering)"); m_vVolumeRenderer.push_back(new GLSBVR(this, bUseOnlyPowerOfTwo, bDownSampleTo8Bits, bDisableBorder)); return m_vVolumeRenderer[m_vVolumeRenderer.size()-1]; case OPENGL_RAYCASTER : m_pDebugOut->Message("MasterController::RequestNewVolumerenderer","Starting up new renderer (API=OpenGL, Method=Raycaster)"); m_vVolumeRenderer.push_back(new GLRaycaster(this, bUseOnlyPowerOfTwo, bDownSampleTo8Bits, bDisableBorder)); return m_vVolumeRenderer[m_vVolumeRenderer.size()-1]; case DIRECTX_SBVR : case DIRECTX_RAYCASTER : m_pDebugOut->Error("MasterController::RequestNewVolumerenderer","DirectX 10 volume renderer not yet implemented. Please select OpenGL as the render API in the settings dialog."); return NULL; default : m_pDebugOut->Error("MasterController::RequestNewVolumerenderer","Unsupported Volume renderer requested"); return NULL; }; } void MasterController::ReleaseVolumerenderer(AbstrRenderer* pVolumeRenderer) { for (AbstrRendererListIter i = m_vVolumeRenderer.begin(); i<m_vVolumeRenderer.end(); ++i) { if (*i == pVolumeRenderer) { m_pDebugOut->Message("MasterController::ReleaseVolumerenderer", "Deleting volume renderer"); delete pVolumeRenderer; m_vVolumeRenderer.erase(i); return; } } m_pDebugOut->Warning("MasterController::ReleaseVolumerenderer", "requested volume renderer not found"); } void MasterController::Filter( std::string , UINT32 , void*, void *, void *, void * ) { }; void MasterController::RegisterCalls(Scripting* pScriptEngine) { pScriptEngine->RegisterCommand(this, "seterrorlog", "on/off", "toggle recording of errors"); pScriptEngine->RegisterCommand(this, "setwarninglog", "on/off", "toggle recording of warnings"); pScriptEngine->RegisterCommand(this, "setemessagelog", "on/off", "toggle recording of messages"); pScriptEngine->RegisterCommand(this, "printerrorlog", "", "print recorded errors"); pScriptEngine->RegisterCommand(this, "printwarninglog", "", "print recorded errwarningsors"); pScriptEngine->RegisterCommand(this, "printmessagelog", "", "print recorded messages"); pScriptEngine->RegisterCommand(this, "clearerrorlog", "", "clear recorded errors"); pScriptEngine->RegisterCommand(this, "clearwarninglog", "", "clear recorded warnings"); pScriptEngine->RegisterCommand(this, "clearmessagelog", "", "clear recorded messages"); pScriptEngine->RegisterCommand(this, "fileoutput", "filename","write debug output to 'filename'"); pScriptEngine->RegisterCommand(this, "toggleoutput", "on/off on/off on/off on/off","toggle messages, warning, errors, and other output"); } bool MasterController::Execute(const std::string& strCommand, const std::vector< std::string >& strParams, std::string& strMessage) { strMessage = ""; if (strCommand == "seterrorlog") { m_pDebugOut->SetListRecordingErrors(strParams[0] == "on"); if (m_pDebugOut->GetListRecordingErrors()) m_pDebugOut->printf("current state: true"); else m_pDebugOut->printf("current state: false"); return true; } if (strCommand == "setwarninglog") { m_pDebugOut->SetListRecordingWarnings(strParams[0] == "on"); if (m_pDebugOut->GetListRecordingWarnings()) m_pDebugOut->printf("current state: true"); else m_pDebugOut->printf("current state: false"); return true; } if (strCommand == "setmessagelog") { m_pDebugOut->SetListRecordingMessages(strParams[0] == "on"); if (m_pDebugOut->GetListRecordingMessages()) m_pDebugOut->printf("current state: true"); else m_pDebugOut->printf("current state: false"); return true; } if (strCommand == "printerrorlog") { m_pDebugOut->PrintErrorList(); return true; } if (strCommand == "printwarninglog") { m_pDebugOut->PrintWarningList(); return true; } if (strCommand == "printmessagelog") { m_pDebugOut->PrintMessageList(); return true; } if (strCommand == "clearerrorlog") { m_pDebugOut->ClearErrorList(); return true; } if (strCommand == "clearwarninglog") { m_pDebugOut->ClearWarningList(); return true; } if (strCommand == "clearmessagelog") { m_pDebugOut->ClearMessageList(); return true; } if (strCommand == "toggleoutput") { m_pDebugOut->SetOutput(strParams[0] == "on", strParams[1] == "on", strParams[2] == "on", strParams[3] == "on"); return true; } if (strCommand == "fileoutput") { TextfileOut* textout = new TextfileOut(strParams[0]); textout->SetShowErrors(m_pDebugOut->ShowErrors()); textout->SetShowWarnings(m_pDebugOut->ShowWarnings()); textout->SetShowMessages(m_pDebugOut->ShowMessages()); textout->SetShowOther(m_pDebugOut->ShowOther()); AbstrDebugOut* pOldDebug = DebugOut(); bool bDeleteOldDebug = DoDeleteDebugOut(); SetDeleteDebugOut(false); MultiplexOut* pMultiOut = new MultiplexOut(); pMultiOut->SetOutput(true,true,true,true); SetDebugOut(pMultiOut, true); pMultiOut->AddDebugOut(textout, true); pMultiOut->AddDebugOut(pOldDebug, bDeleteOldDebug); return true; } return false; } <|endoftext|>
<commit_before>// // DebugOptions.cpp // TimGameLib // // Created by Tim Brier on 05/10/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "DebugOptions.hpp" #include "SystemUtilities.hpp" namespace DebugOptions { // ============================================================================= // Namespace globals // ----------------------------------------------------------------------------- bool showFramerate = true; bool drawBounds = false; bool drawOrigins = false; bool drawShapePoints = false; bool drawShapeNormals = false; bool useSlowMotion = false; bool showMouseCoords = false; } // namespace DebugOptions // ============================================================================= // CDebugHelper constructor/destructor // ----------------------------------------------------------------------------- CDebugHelper::CDebugHelper() { SystemUtilities::SubscribeToEvents(this); } CDebugHelper::~CDebugHelper() { } // ============================================================================= // CDebugHelper::ReactToEvent // ----------------------------------------------------------------------------- void CDebugHelper::ReactToEvent(CEvent *theEvent) { // Toggle debug options on key presses, only when alt is held if (CKeyboard::isKeyPressed(CKeyboard::LAlt) && theEvent->type == CEvent::KeyPressed) { TOGGLE_DEBUG_OPTION(F, DebugOptions::showFramerate); TOGGLE_DEBUG_OPTION(B, DebugOptions::drawBounds); TOGGLE_DEBUG_OPTION(O, DebugOptions::drawOrigins); TOGGLE_DEBUG_OPTION(P, DebugOptions::drawShapePoints); TOGGLE_DEBUG_OPTION(N, DebugOptions::drawShapeNormals); TOGGLE_DEBUG_OPTION(S, DebugOptions::useSlowMotion); TOGGLE_DEBUG_OPTION(M, DebugOptions::showMouseCoords); } } // ============================================================================= // CDebugHelper::Draw // ----------------------------------------------------------------------------- void CDebugHelper::Draw(CWindow *theWindow) { FOR_EACH_IN_LIST(CConvexShape*, mShapes) { theWindow->draw(*(*it)); } FOR_EACH_IN_LIST(CLine, mLines) { theWindow->DrawLine((*it), CColour::Red); } if (DebugOptions::showMouseCoords) { CVector2f coords = SystemUtilities::GetMousePosition(); char txt[32]; sprintf(txt, "(%f, %f)", coords.x, coords.y); theWindow->DrawTextAt(txt, coords.x, coords.y - 15, CColour::Red); } } // ============================================================================= // CDebugHelper::AddShape // ----------------------------------------------------------------------------- void CDebugHelper::AddShape(CConvexShape *theShape) { mShapes.push_back(theShape); } // ============================================================================= // CDebugHelper::RemoveShape // ----------------------------------------------------------------------------- void CDebugHelper::RemoveShape(CConvexShape *theShape) { mShapes.remove(theShape); } // ============================================================================= // CDebugHelper::AddLine // ----------------------------------------------------------------------------- void CDebugHelper::AddLine(CLine theLine) { mLines.push_back(theLine); } // ============================================================================= // CDebugHelper::RemoveLine // ----------------------------------------------------------------------------- void CDebugHelper::RemoveLine(CLine theLine) { mLines.remove(theLine); }<commit_msg>Make sure to unsubscribe from events<commit_after>// // DebugOptions.cpp // TimGameLib // // Created by Tim Brier on 05/10/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "DebugOptions.hpp" #include "SystemUtilities.hpp" namespace DebugOptions { // ============================================================================= // Namespace globals // ----------------------------------------------------------------------------- bool showFramerate = true; bool drawBounds = false; bool drawOrigins = false; bool drawShapePoints = false; bool drawShapeNormals = false; bool useSlowMotion = false; bool showMouseCoords = false; } // namespace DebugOptions // ============================================================================= // CDebugHelper constructor/destructor // ----------------------------------------------------------------------------- CDebugHelper::CDebugHelper() { SystemUtilities::SubscribeToEvents(this); } CDebugHelper::~CDebugHelper() { SystemUtilities::UnsubscribeToEvents(this); } // ============================================================================= // CDebugHelper::ReactToEvent // ----------------------------------------------------------------------------- void CDebugHelper::ReactToEvent(CEvent *theEvent) { // Toggle debug options on key presses, only when alt is held if (CKeyboard::isKeyPressed(CKeyboard::LAlt) && theEvent->type == CEvent::KeyPressed) { TOGGLE_DEBUG_OPTION(F, DebugOptions::showFramerate); TOGGLE_DEBUG_OPTION(B, DebugOptions::drawBounds); TOGGLE_DEBUG_OPTION(O, DebugOptions::drawOrigins); TOGGLE_DEBUG_OPTION(P, DebugOptions::drawShapePoints); TOGGLE_DEBUG_OPTION(N, DebugOptions::drawShapeNormals); TOGGLE_DEBUG_OPTION(S, DebugOptions::useSlowMotion); TOGGLE_DEBUG_OPTION(M, DebugOptions::showMouseCoords); } } // ============================================================================= // CDebugHelper::Draw // ----------------------------------------------------------------------------- void CDebugHelper::Draw(CWindow *theWindow) { FOR_EACH_IN_LIST(CConvexShape*, mShapes) { theWindow->draw(*(*it)); } FOR_EACH_IN_LIST(CLine, mLines) { theWindow->DrawLine((*it), CColour::Red); } if (DebugOptions::showMouseCoords) { CVector2f coords = SystemUtilities::GetMousePosition(); char txt[32]; sprintf(txt, "(%f, %f)", coords.x, coords.y); theWindow->DrawTextAt(txt, coords.x, coords.y - 15, CColour::Red); } } // ============================================================================= // CDebugHelper::AddShape // ----------------------------------------------------------------------------- void CDebugHelper::AddShape(CConvexShape *theShape) { mShapes.push_back(theShape); } // ============================================================================= // CDebugHelper::RemoveShape // ----------------------------------------------------------------------------- void CDebugHelper::RemoveShape(CConvexShape *theShape) { mShapes.remove(theShape); } // ============================================================================= // CDebugHelper::AddLine // ----------------------------------------------------------------------------- void CDebugHelper::AddLine(CLine theLine) { mLines.push_back(theLine); } // ============================================================================= // CDebugHelper::RemoveLine // ----------------------------------------------------------------------------- void CDebugHelper::RemoveLine(CLine theLine) { mLines.remove(theLine); }<|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright Daniel Adamitskiy. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "Sort.h" #include <ctime> #include <functional> #include <vector> #include <algorithm> bool AscendingOrderPredicate(int a, int b) { return a < b; } void RandomizeContainer(std::vector<int>& container) { std::random_shuffle(container.begin(), container.end()); } void PrintContainerContents(const std::vector<int>& container) { for each (int i in container) { printf("%i,", i); } printf("\n\n"); } int main(int argc, const char** argv) { // Seed random srand(static_cast<unsigned int>(time(0))); // Create a container with random items std::vector<int> container; for (int i = 0; i < 25; ++i) { container.push_back(static_cast<int>(3.14f * (rand() % 100))); } RandomizeContainer(container); const unsigned int containerSize = static_cast<unsigned int>(container.size()); // Debug output printf("Unsorted container:\n"); PrintContainerContents(container); // Sort with a lambda DA::Sort::BubbleSort<std::vector<int>>(container, containerSize, [](int a, int b) { return a < b; }); // Debug output printf("Sorted container via bubble sort:\n"); PrintContainerContents(container); RandomizeContainer(container); printf("Unsorted container:\n"); PrintContainerContents(container); // Sort with a function pointer DA::Sort::InsertionSort<std::vector<int>>(container, containerSize, AscendingOrderPredicate); // Debug output printf("Sorted container via insertion sort:\n"); PrintContainerContents(container); RandomizeContainer(container); printf("Unsorted container:\n"); PrintContainerContents(container); // Sort with std::function std::function<bool(int, int)> LessThanFunc = &AscendingOrderPredicate; DA::Sort::SelectionSort<std::vector<int>>(container, containerSize, LessThanFunc); // Debug output printf("Sorted container via selection sort:\n"); PrintContainerContents(container); return 0; } <commit_msg>Removed MSVC specific for loop.<commit_after>/** * The MIT License (MIT) * * Copyright Daniel Adamitskiy. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "Sort.h" #include <ctime> #include <functional> #include <vector> #include <algorithm> bool AscendingOrderPredicate(int a, int b) { return a < b; } void RandomizeContainer(std::vector<int>& container) { std::random_shuffle(container.begin(), container.end()); } void PrintContainerContents(const std::vector<int>& container) { for (int i = 0; i < container.size(); ++i) { printf("%i,", container[i]); } printf("\n\n"); } int main(int argc, const char** argv) { // Seed random srand(static_cast<unsigned int>(time(0))); // Create a container with random items std::vector<int> container; for (int i = 0; i < 25; ++i) { container.push_back(static_cast<int>(3.14f * (rand() % 100))); } RandomizeContainer(container); const unsigned int containerSize = static_cast<unsigned int>(container.size()); // Debug output printf("Unsorted container:\n"); PrintContainerContents(container); // Sort with a lambda DA::Sort::BubbleSort<std::vector<int>>(container, containerSize, [](int a, int b) { return a < b; }); // Debug output printf("Sorted container via bubble sort:\n"); PrintContainerContents(container); RandomizeContainer(container); printf("Unsorted container:\n"); PrintContainerContents(container); // Sort with a function pointer DA::Sort::InsertionSort<std::vector<int>>(container, containerSize, AscendingOrderPredicate); // Debug output printf("Sorted container via insertion sort:\n"); PrintContainerContents(container); RandomizeContainer(container); printf("Unsorted container:\n"); PrintContainerContents(container); // Sort with std::function std::function<bool(int, int)> LessThanFunc = &AscendingOrderPredicate; DA::Sort::SelectionSort<std::vector<int>>(container, containerSize, LessThanFunc); // Debug output printf("Sorted container via selection sort:\n"); PrintContainerContents(container); return 0; } <|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ // Disable "'this': used in base member initializer list" #ifdef _MSC_VER # pragma warning( push ) # pragma warning(disable: 4355) #endif #include <iostream> #include <cstring> #include <map> #ifdef ANDROID #include <linux/in.h> // for IPPROTO_TCP #endif #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include "tcptransportsocket.hpp" #include "transportsocket_p.hpp" #include "message_p.hpp" #include <qi/log.hpp> #include <qi/types.hpp> #include <qimessaging/session.hpp> #include <qimessaging/message.hpp> #include <qi/buffer.hpp> #include <qi/eventloop.hpp> #define MAX_LINE 16384 qiLogCategory("qimessaging.transportsocket"); namespace qi { TcpTransportSocket::TcpTransportSocket(EventLoop* eventLoop, bool ssl) : TransportSocketPrivate(this, eventLoop) , TransportSocket(this) , _ssl(ssl) , _sslHandshake(false) #ifdef WITH_SSL , _sslContext(boost::asio::ssl::context::sslv23) #endif , _readHdr(true) , _msg(0) , _connecting(false) , _sending(false) { #ifdef WITH_SSL if (_ssl) { _sslContext.set_verify_mode(boost::asio::ssl::verify_none); } _socket = (new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>((*(boost::asio::io_service*)eventLoop->nativeHandle()), _sslContext)); #else _socket = new boost::asio::ip::tcp::socket(*(boost::asio::io_service*)eventLoop->nativeHandle()); #endif assert(eventLoop); _disconnectPromise.setValue(0); // not connected, so we are finished disconnecting _abort = boost::shared_ptr<bool>(new bool(false)); } TcpTransportSocket::TcpTransportSocket(void* s, EventLoop* eventLoop, bool ssl) : TransportSocketPrivate(this, eventLoop) , TransportSocket(this) , _ssl(ssl) , _sslHandshake(false) #ifdef WITH_SSL , _sslContext(boost::asio::ssl::context::sslv23) , _socket((boost::asio::ssl::stream<boost::asio::ip::tcp::socket>*) s) #else , _socket((boost::asio::ip::tcp::socket*) s) #endif , _readHdr(true) , _msg(0) , _connecting(false) , _sending(false) { assert(eventLoop); _status = qi::TransportSocket::Status_Connected; _abort = boost::shared_ptr<bool>(new bool(false)); // Transmit each Message without delay const boost::asio::ip::tcp::no_delay option( true ); _socket->set_option(option); } TcpTransportSocket::~TcpTransportSocket() { disconnect(); delete _msg; delete _socket; _p = 0; qiLogVerbose() << "deleted " << this; } void TcpTransportSocket::startReading() { _msg = new qi::Message(); #ifdef WITH_SSL if (_ssl) { if (!_sslHandshake) { _socket->async_handshake(boost::asio::ssl::stream_base::server, boost::bind(&TcpTransportSocket::handshake, this, _1)); return; } boost::asio::async_read(*_socket, boost::asio::buffer(_msg->_p->getHeader(), sizeof(MessagePrivate::MessageHeader)), boost::bind(&TcpTransportSocket::onReadHeader, this, _1, _2)); } else { boost::asio::async_read(_socket->next_layer(), boost::asio::buffer(_msg->_p->getHeader(), sizeof(MessagePrivate::MessageHeader)), boost::bind(&TcpTransportSocket::onReadHeader, this, _1, _2)); } #else boost::asio::async_read(*_socket, boost::asio::buffer(_msg->_p->getHeader(), sizeof(MessagePrivate::MessageHeader)), boost::bind(&TcpTransportSocket::onReadHeader, this, _1, _2)); #endif } void TcpTransportSocket::onReadHeader(const boost::system::error_code& erc, std::size_t len) { if (erc) { error(erc); return; } size_t payload = _msg->_p->header.size; if (payload) { void* ptr = _msg->_p->buffer.reserve(payload); #ifdef WITH_SSL if (_ssl) { boost::asio::async_read(*_socket, boost::asio::buffer(ptr, payload), boost::bind(&TcpTransportSocket::onReadData, this, _1, _2)); } else { boost::asio::async_read(_socket->next_layer(), boost::asio::buffer(ptr, payload), boost::bind(&TcpTransportSocket::onReadData, this, _1, _2)); } #else boost::asio::async_read(*_socket, boost::asio::buffer(ptr, payload), boost::bind(&TcpTransportSocket::onReadData, this, _1, _2)); #endif } else onReadData(boost::system::error_code(), 0); } void TcpTransportSocket::onReadData(const boost::system::error_code& erc, std::size_t len) { if (erc) { error(erc); return; } qiLogDebug() << _self << " Recv (" << _msg->type() << "):" << _msg->address(); static int usWarnThreshold = os::getenv("QIMESSAGING_SOCKET_DISPATCH_TIME_WARN_THRESHOLD").empty()?0:strtol(os::getenv("QIMESSAGING_SOCKET_DISPATCH_TIME_WARN_THRESHOLD").c_str(),0,0); qi::int64_t start = 0; if (usWarnThreshold) start = os::ustime(); // call might be not that cheap _self->messageReady(*_msg); _dispatcher.dispatch(*_msg); if (usWarnThreshold) { qi::int64_t duration = os::ustime() - start; if (duration > usWarnThreshold) qiLogWarning() << "Dispatch to user took " << duration << "us"; } delete _msg; startReading(); } void TcpTransportSocket::error(const boost::system::error_code& erc) { _status = qi::TransportSocket::Status_Disconnected; _self->disconnected(erc.value()); if (_connecting) { _connecting = false; _connectPromise.setError(std::string("Connection error: ") + erc.message()); } { boost::mutex::scoped_lock l(_sendQueueMutex); boost::system::error_code er; if (_socket->lowest_layer().is_open()) _socket->lowest_layer().close(er); } _disconnectPromise.setValue(0); } qi::FutureSync<void> TcpTransportSocket::connect(const qi::Url &url) { if (_status == qi::TransportSocket::Status_Connected || _connecting) { const char* s = "connection already in progress"; qiLogError() << s; return makeFutureError<void>(s); } _url = url; _connectPromise.reset(); _disconnectPromise.reset(); _status = qi::TransportSocket::Status_Connecting; _connecting = true; _err = 0; if (_url.port() == 0) { qiLogError() << "Error try to connect to a bad address: " << _url.str(); _connectPromise.setError("Bad address " + _url.str()); _status = qi::TransportSocket::Status_Disconnected; _connecting = false; _disconnectPromise.setValue(0); return _connectPromise.future(); } qiLogVerbose() << "Trying to connect to " << _url.host() << ":" << _url.port(); using namespace boost::asio; // Resolve url ip::tcp::resolver r(_socket->get_io_service()); ip::tcp::resolver::query q(_url.host(), boost::lexical_cast<std::string>(_url.port())); // Synchronous resolution try { ip::tcp::resolver::iterator it = r.resolve(q); // asynchronous connect _socket->lowest_layer().async_connect(*it, boost::bind(&TcpTransportSocket::connected, this, _1)); return _connectPromise.future(); } catch (const std::exception& e) { const char* s = e.what(); qiLogError() << s; _connectPromise.setError(s); return _connectPromise.future(); } } void TcpTransportSocket::handshake(const boost::system::error_code& erc) { if (erc) { qiLogWarning() << "connect: " << erc.message(); _status = qi::TransportSocket::Status_Disconnected; _connectPromise.setError(erc.message()); _disconnectPromise.setValue(0); //FIXME: ?? _connectPromise.setError(erc.message()); } else { _status = qi::TransportSocket::Status_Connected; _connectPromise.setValue(0); _self->connected(); _sslHandshake = true; // Transmit each Message without delay const boost::asio::ip::tcp::no_delay option( true ); _socket->set_option(option); startReading(); } } void TcpTransportSocket::connected(const boost::system::error_code& erc) { _connecting = false; if (erc) { qiLogWarning("qimessaging.TransportSocketLibEvent") << "connect: " << erc.message(); _status = qi::TransportSocket::Status_Disconnected; _connectPromise.setError(erc.message()); _disconnectPromise.setValue(0); } else { if (_ssl) { #ifdef WITH_SSL _socket->async_handshake(boost::asio::ssl::stream_base::client, boost::bind(&TcpTransportSocket::handshake, this, _1)); #endif } else { _status = qi::TransportSocket::Status_Connected; _connectPromise.setValue(0); _self->connected(); // Transmit each Message without delay const boost::asio::ip::tcp::no_delay option( true ); _socket->set_option(option); startReading(); } } } qi::FutureSync<void> TcpTransportSocket::disconnect() { *_abort = true; // Notify send callback sendCont that it must silently terminate { boost::mutex::scoped_lock l(_sendQueueMutex); if (_socket->lowest_layer().is_open()) { boost::system::error_code erc; _socket->lowest_layer().close(erc); // will invoke read callback with error set } // Do not set disconnectPromise here, it will/has been set // by error(), called by read callback, and we must wait for it // to terminate. } return _disconnectPromise.future(); } bool TcpTransportSocket::send(const qi::Message &msg) { qiLogDebug() << _self << " Send (" << msg.type() << "):" << msg.address(); boost::mutex::scoped_lock lock(_sendQueueMutex); if (!_sending) { _sending = true; send_(new Message(msg)); } else _sendQueue.push_back(msg); return true; } void TcpTransportSocket::send_(qi::Message* msg) { using boost::asio::buffer; std::vector<boost::asio::const_buffer> b; msg->_p->complete(); // Send header b.push_back(buffer(msg->_p->getHeader(), sizeof(qi::MessagePrivate::MessageHeader))); const qi::Buffer& buf = msg->buffer(); size_t sz = buf.size(); const std::vector<std::pair<size_t, Buffer> >& subs = buf.subBuffers(); size_t pos = 0; // Handle subbuffers for (unsigned i=0; i< subs.size(); ++i) { // Send parent buffer between pos and start of sub size_t end = subs[i].first+4; if (end != pos) b.push_back(buffer((const char*)buf.data() + pos, end-pos)); pos = end; // Send subbuffer b.push_back(buffer(subs[i].second.data(), subs[i].second.size())); } b.push_back(buffer((const char*)buf.data() + pos, sz - pos)); _dispatcher.sent(*msg); #ifdef WITH_SSL if (_ssl) { boost::asio::async_write(*_socket, b, boost::bind(&TcpTransportSocket::sendCont, this, _1, msg, _abort)); } else { boost::asio::async_write(_socket->next_layer(), b, boost::bind(&TcpTransportSocket::sendCont, this, _1, msg, _abort)); } #else boost::asio::async_write(*_socket, b, boost::bind(&TcpTransportSocket::sendCont, this, _1, msg, _abort)); #endif } void TcpTransportSocket::sendCont(const boost::system::error_code& erc, Message* msg, boost::shared_ptr<bool> abort) { delete msg; // The class does not wait for us to terminate, but it will set abort to true. // So do not use this before checking abort. if (erc || *abort) return; // read-callback will also get the error, avoid dup and ignore it boost::mutex::scoped_lock lock(_sendQueueMutex); if (_sendQueue.empty()) _sending = false; else { msg = new Message(_sendQueue.front()); _sendQueue.pop_front(); send_(msg); } } } <commit_msg>Fix tcp no delay with SSL sockets<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ // Disable "'this': used in base member initializer list" #ifdef _MSC_VER # pragma warning( push ) # pragma warning(disable: 4355) #endif #include <iostream> #include <cstring> #include <map> #ifdef ANDROID #include <linux/in.h> // for IPPROTO_TCP #endif #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include "tcptransportsocket.hpp" #include "transportsocket_p.hpp" #include "message_p.hpp" #include <qi/log.hpp> #include <qi/types.hpp> #include <qimessaging/session.hpp> #include <qimessaging/message.hpp> #include <qi/buffer.hpp> #include <qi/eventloop.hpp> #define MAX_LINE 16384 qiLogCategory("qimessaging.transportsocket"); namespace qi { TcpTransportSocket::TcpTransportSocket(EventLoop* eventLoop, bool ssl) : TransportSocketPrivate(this, eventLoop) , TransportSocket(this) , _ssl(ssl) , _sslHandshake(false) #ifdef WITH_SSL , _sslContext(boost::asio::ssl::context::sslv23) #endif , _readHdr(true) , _msg(0) , _connecting(false) , _sending(false) { #ifdef WITH_SSL if (_ssl) { _sslContext.set_verify_mode(boost::asio::ssl::verify_none); } _socket = (new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>((*(boost::asio::io_service*)eventLoop->nativeHandle()), _sslContext)); #else _socket = new boost::asio::ip::tcp::socket(*(boost::asio::io_service*)eventLoop->nativeHandle()); #endif assert(eventLoop); _disconnectPromise.setValue(0); // not connected, so we are finished disconnecting _abort = boost::shared_ptr<bool>(new bool(false)); } TcpTransportSocket::TcpTransportSocket(void* s, EventLoop* eventLoop, bool ssl) : TransportSocketPrivate(this, eventLoop) , TransportSocket(this) , _ssl(ssl) , _sslHandshake(false) #ifdef WITH_SSL , _sslContext(boost::asio::ssl::context::sslv23) , _socket((boost::asio::ssl::stream<boost::asio::ip::tcp::socket>*) s) #else , _socket((boost::asio::ip::tcp::socket*) s) #endif , _readHdr(true) , _msg(0) , _connecting(false) , _sending(false) { assert(eventLoop); _status = qi::TransportSocket::Status_Connected; _abort = boost::shared_ptr<bool>(new bool(false)); // Transmit each Message without delay const boost::asio::ip::tcp::no_delay option( true ); _socket->lowest_layer().set_option(option); } TcpTransportSocket::~TcpTransportSocket() { disconnect(); delete _msg; delete _socket; _p = 0; qiLogVerbose() << "deleted " << this; } void TcpTransportSocket::startReading() { _msg = new qi::Message(); #ifdef WITH_SSL if (_ssl) { if (!_sslHandshake) { _socket->async_handshake(boost::asio::ssl::stream_base::server, boost::bind(&TcpTransportSocket::handshake, this, _1)); return; } boost::asio::async_read(*_socket, boost::asio::buffer(_msg->_p->getHeader(), sizeof(MessagePrivate::MessageHeader)), boost::bind(&TcpTransportSocket::onReadHeader, this, _1, _2)); } else { boost::asio::async_read(_socket->next_layer(), boost::asio::buffer(_msg->_p->getHeader(), sizeof(MessagePrivate::MessageHeader)), boost::bind(&TcpTransportSocket::onReadHeader, this, _1, _2)); } #else boost::asio::async_read(*_socket, boost::asio::buffer(_msg->_p->getHeader(), sizeof(MessagePrivate::MessageHeader)), boost::bind(&TcpTransportSocket::onReadHeader, this, _1, _2)); #endif } void TcpTransportSocket::onReadHeader(const boost::system::error_code& erc, std::size_t len) { if (erc) { error(erc); return; } size_t payload = _msg->_p->header.size; if (payload) { void* ptr = _msg->_p->buffer.reserve(payload); #ifdef WITH_SSL if (_ssl) { boost::asio::async_read(*_socket, boost::asio::buffer(ptr, payload), boost::bind(&TcpTransportSocket::onReadData, this, _1, _2)); } else { boost::asio::async_read(_socket->next_layer(), boost::asio::buffer(ptr, payload), boost::bind(&TcpTransportSocket::onReadData, this, _1, _2)); } #else boost::asio::async_read(*_socket, boost::asio::buffer(ptr, payload), boost::bind(&TcpTransportSocket::onReadData, this, _1, _2)); #endif } else onReadData(boost::system::error_code(), 0); } void TcpTransportSocket::onReadData(const boost::system::error_code& erc, std::size_t len) { if (erc) { error(erc); return; } qiLogDebug() << _self << " Recv (" << _msg->type() << "):" << _msg->address(); static int usWarnThreshold = os::getenv("QIMESSAGING_SOCKET_DISPATCH_TIME_WARN_THRESHOLD").empty()?0:strtol(os::getenv("QIMESSAGING_SOCKET_DISPATCH_TIME_WARN_THRESHOLD").c_str(),0,0); qi::int64_t start = 0; if (usWarnThreshold) start = os::ustime(); // call might be not that cheap _self->messageReady(*_msg); _dispatcher.dispatch(*_msg); if (usWarnThreshold) { qi::int64_t duration = os::ustime() - start; if (duration > usWarnThreshold) qiLogWarning() << "Dispatch to user took " << duration << "us"; } delete _msg; startReading(); } void TcpTransportSocket::error(const boost::system::error_code& erc) { _status = qi::TransportSocket::Status_Disconnected; _self->disconnected(erc.value()); if (_connecting) { _connecting = false; _connectPromise.setError(std::string("Connection error: ") + erc.message()); } { boost::mutex::scoped_lock l(_sendQueueMutex); boost::system::error_code er; if (_socket->lowest_layer().is_open()) _socket->lowest_layer().close(er); } _disconnectPromise.setValue(0); } qi::FutureSync<void> TcpTransportSocket::connect(const qi::Url &url) { if (_status == qi::TransportSocket::Status_Connected || _connecting) { const char* s = "connection already in progress"; qiLogError() << s; return makeFutureError<void>(s); } _url = url; _connectPromise.reset(); _disconnectPromise.reset(); _status = qi::TransportSocket::Status_Connecting; _connecting = true; _err = 0; if (_url.port() == 0) { qiLogError() << "Error try to connect to a bad address: " << _url.str(); _connectPromise.setError("Bad address " + _url.str()); _status = qi::TransportSocket::Status_Disconnected; _connecting = false; _disconnectPromise.setValue(0); return _connectPromise.future(); } qiLogVerbose() << "Trying to connect to " << _url.host() << ":" << _url.port(); using namespace boost::asio; // Resolve url ip::tcp::resolver r(_socket->get_io_service()); ip::tcp::resolver::query q(_url.host(), boost::lexical_cast<std::string>(_url.port())); // Synchronous resolution try { ip::tcp::resolver::iterator it = r.resolve(q); // asynchronous connect _socket->lowest_layer().async_connect(*it, boost::bind(&TcpTransportSocket::connected, this, _1)); return _connectPromise.future(); } catch (const std::exception& e) { const char* s = e.what(); qiLogError() << s; _connectPromise.setError(s); return _connectPromise.future(); } } void TcpTransportSocket::handshake(const boost::system::error_code& erc) { if (erc) { qiLogWarning() << "connect: " << erc.message(); _status = qi::TransportSocket::Status_Disconnected; _connectPromise.setError(erc.message()); _disconnectPromise.setValue(0); //FIXME: ?? _connectPromise.setError(erc.message()); } else { _status = qi::TransportSocket::Status_Connected; _connectPromise.setValue(0); _self->connected(); _sslHandshake = true; // Transmit each Message without delay const boost::asio::ip::tcp::no_delay option( true ); _socket->lowest_layer().set_option(option); startReading(); } } void TcpTransportSocket::connected(const boost::system::error_code& erc) { _connecting = false; if (erc) { qiLogWarning("qimessaging.TransportSocketLibEvent") << "connect: " << erc.message(); _status = qi::TransportSocket::Status_Disconnected; _connectPromise.setError(erc.message()); _disconnectPromise.setValue(0); } else { if (_ssl) { #ifdef WITH_SSL _socket->async_handshake(boost::asio::ssl::stream_base::client, boost::bind(&TcpTransportSocket::handshake, this, _1)); #endif } else { _status = qi::TransportSocket::Status_Connected; _connectPromise.setValue(0); _self->connected(); // Transmit each Message without delay const boost::asio::ip::tcp::no_delay option( true ); _socket->lowest_layer().set_option(option); startReading(); } } } qi::FutureSync<void> TcpTransportSocket::disconnect() { *_abort = true; // Notify send callback sendCont that it must silently terminate { boost::mutex::scoped_lock l(_sendQueueMutex); if (_socket->lowest_layer().is_open()) { boost::system::error_code erc; _socket->lowest_layer().close(erc); // will invoke read callback with error set } // Do not set disconnectPromise here, it will/has been set // by error(), called by read callback, and we must wait for it // to terminate. } return _disconnectPromise.future(); } bool TcpTransportSocket::send(const qi::Message &msg) { qiLogDebug() << _self << " Send (" << msg.type() << "):" << msg.address(); boost::mutex::scoped_lock lock(_sendQueueMutex); if (!_sending) { _sending = true; send_(new Message(msg)); } else _sendQueue.push_back(msg); return true; } void TcpTransportSocket::send_(qi::Message* msg) { using boost::asio::buffer; std::vector<boost::asio::const_buffer> b; msg->_p->complete(); // Send header b.push_back(buffer(msg->_p->getHeader(), sizeof(qi::MessagePrivate::MessageHeader))); const qi::Buffer& buf = msg->buffer(); size_t sz = buf.size(); const std::vector<std::pair<size_t, Buffer> >& subs = buf.subBuffers(); size_t pos = 0; // Handle subbuffers for (unsigned i=0; i< subs.size(); ++i) { // Send parent buffer between pos and start of sub size_t end = subs[i].first+4; if (end != pos) b.push_back(buffer((const char*)buf.data() + pos, end-pos)); pos = end; // Send subbuffer b.push_back(buffer(subs[i].second.data(), subs[i].second.size())); } b.push_back(buffer((const char*)buf.data() + pos, sz - pos)); _dispatcher.sent(*msg); #ifdef WITH_SSL if (_ssl) { boost::asio::async_write(*_socket, b, boost::bind(&TcpTransportSocket::sendCont, this, _1, msg, _abort)); } else { boost::asio::async_write(_socket->next_layer(), b, boost::bind(&TcpTransportSocket::sendCont, this, _1, msg, _abort)); } #else boost::asio::async_write(*_socket, b, boost::bind(&TcpTransportSocket::sendCont, this, _1, msg, _abort)); #endif } void TcpTransportSocket::sendCont(const boost::system::error_code& erc, Message* msg, boost::shared_ptr<bool> abort) { delete msg; // The class does not wait for us to terminate, but it will set abort to true. // So do not use this before checking abort. if (erc || *abort) return; // read-callback will also get the error, avoid dup and ignore it boost::mutex::scoped_lock lock(_sendQueueMutex); if (_sendQueue.empty()) _sending = false; else { msg = new Message(_sendQueue.front()); _sendQueue.pop_front(); send_(msg); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unoapi.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:47:11 $ * * 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 _SVX_UNOAPI_HXX_ #define _SVX_UNOAPI_HXX_ #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _GRFMGR_HXX #include <goodies/grfmgr.hxx> #endif #ifndef _SFXPOOLITEM_HXX #include <svtools/poolitem.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SvxShape; class SdrObject; class SvxNumBulletItem; class SfxItemPool; class String; /** creates a StarOffice API wrapper with the given type and inventor Deprecated: This will be replaced with a function returning XShape. */ SVX_DLLPUBLIC SvxShape* CreateSvxShapeByTypeAndInventor( sal_uInt16 nType, sal_uInt32 nInventor ) throw(); /** returns a StarOffice API wrapper for the given SdrObject */ SVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > GetXShapeForSdrObject( SdrObject* pObj ) throw (); /** returns the SdrObject from the given StarOffice API wrapper */ SVX_DLLPUBLIC SdrObject* GetSdrObjectFromXShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ) throw() ; /** returns a GraphicObject for this URL */ SVX_DLLPUBLIC GraphicObject CreateGraphicObjectFromURL( const ::rtl::OUString &rURL ) throw() ; /** returns the SvxNumBulletItem with the given name from the pool or a null if there is no item with that name */ SvxNumBulletItem* SvxGetNumBulletItemByName( SfxItemPool* pPool, const ::rtl::OUString& aName ) throw(); /** maps the API constant MeasureUnit to a vcl MapUnit enum. Returns false if conversion is not supported. @cl: for warnings01 I found out that this method never worked so I thin it is not used at all sal_Bool SvxMeasureUnitToMapUnit( const short eApi, short& nVcl ) throw(); */ /** maps the vcl MapUnit enum to a API constant MeasureUnit. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxMapUnitToMeasureUnit( const short nVcl, short& eApi ) throw(); /** maps the API constant MeasureUnit to a vcl MapUnit enum. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxMeasureUnitToFieldUnit( const short eApi, short& nVcl ) throw(); /** maps the vcl MapUnit enum to a API constant MeasureUnit. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxFieldUnitToMeasureUnit( const short nVcl, short& eApi ) throw(); /** if the given name is a predefined name for the current language it is replaced by the corresponding api name. */ void SvxUnogetApiNameForItem( const sal_Int16 nWhich, const String& rInternalName, rtl::OUString& rApiName ) throw(); /** if the given name is a predefined api name it is replaced by the predefined name for the current language. */ void SvxUnogetInternalNameForItem( const sal_Int16 nWhich, const rtl::OUString& rApiName, String& rInternalName ) throw(); /** converts the given any with a metric to 100th/mm if needed */ void SvxUnoConvertToMM( const SfxMapUnit eSourceMapUnit, com::sun::star::uno::Any & rMetric ) throw(); /** converts the given any with a metric from 100th/mm to the given metric if needed */ void SvxUnoConvertFromMM( const SfxMapUnit eDestinationMapUnit, com::sun::star::uno::Any & rMetric ) throw(); #endif // _SVX_UNOAPI_HXX_ <commit_msg>INTEGRATION: CWS chart2mst3 (1.6.168); FILE MERGED 2006/10/19 03:57:31 bm 1.6.168.5: RESYNC: (1.8-1.9); FILE MERGED 2005/10/08 19:59:10 bm 1.6.168.4: RESYNC: (1.7-1.8); FILE MERGED 2005/03/21 13:37:39 bm 1.6.168.3: some more symbols need an export specifier SVX_DLLPUBLIC 2005/03/17 21:19:26 bm 1.6.168.2: RESYNC: (1.6-1.7); FILE MERGED 2004/06/04 07:42:01 bm 1.6.168.1: +SvxUnoGetWhichIdForNamedProperty to get which ids for properties like FillGradientName (using the map for shapes SVXMAP_SHAPE)<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unoapi.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: vg $ $Date: 2007-05-22 15:14:53 $ * * 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 _SVX_UNOAPI_HXX_ #define _SVX_UNOAPI_HXX_ #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _GRFMGR_HXX #include <goodies/grfmgr.hxx> #endif #ifndef _SFXPOOLITEM_HXX #include <svtools/poolitem.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SvxShape; class SdrObject; class SvxNumBulletItem; class SfxItemPool; class String; /** creates a StarOffice API wrapper with the given type and inventor Deprecated: This will be replaced with a function returning XShape. */ SVX_DLLPUBLIC SvxShape* CreateSvxShapeByTypeAndInventor( sal_uInt16 nType, sal_uInt32 nInventor ) throw(); /** returns a StarOffice API wrapper for the given SdrObject */ SVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > GetXShapeForSdrObject( SdrObject* pObj ) throw (); /** returns the SdrObject from the given StarOffice API wrapper */ SVX_DLLPUBLIC SdrObject* GetSdrObjectFromXShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ) throw() ; /** returns a GraphicObject for this URL */ SVX_DLLPUBLIC GraphicObject CreateGraphicObjectFromURL( const ::rtl::OUString &rURL ) throw() ; /** returns the SvxNumBulletItem with the given name from the pool or a null if there is no item with that name */ SvxNumBulletItem* SvxGetNumBulletItemByName( SfxItemPool* pPool, const ::rtl::OUString& aName ) throw(); /** maps the API constant MeasureUnit to a vcl MapUnit enum. Returns false if conversion is not supported. @cl: for warnings01 I found out that this method never worked so I thin it is not used at all sal_Bool SvxMeasureUnitToMapUnit( const short eApi, short& nVcl ) throw(); */ /** maps the vcl MapUnit enum to a API constant MeasureUnit. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxMapUnitToMeasureUnit( const short nVcl, short& eApi ) throw(); /** maps the API constant MeasureUnit to a vcl MapUnit enum. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxMeasureUnitToFieldUnit( const short eApi, short& nVcl ) throw(); /** maps the vcl MapUnit enum to a API constant MeasureUnit. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxFieldUnitToMeasureUnit( const short nVcl, short& eApi ) throw(); /** if the given name is a predefined name for the current language it is replaced by the corresponding api name. */ void SvxUnogetApiNameForItem( const sal_Int16 nWhich, const String& rInternalName, rtl::OUString& rApiName ) throw(); /** if the given name is a predefined api name it is replaced by the predefined name for the current language. */ void SvxUnogetInternalNameForItem( const sal_Int16 nWhich, const rtl::OUString& rApiName, String& rInternalName ) throw(); /** returns the which id for the given property name. This only works for properties of shapes (map SVXMAP_SHAPE is used for searching) Note: As this function has no access to SvxItemPropertySet but only to SfxItemPropertyMap, the search in the map is not done via bsearch, but by linear search. */ SVX_DLLPUBLIC sal_Int16 SvxUnoGetWhichIdForNamedProperty( const ::rtl::OUString & rPropName ); /** converts the given any with a metric to 100th/mm if needed */ void SvxUnoConvertToMM( const SfxMapUnit eSourceMapUnit, com::sun::star::uno::Any & rMetric ) throw(); /** converts the given any with a metric from 100th/mm to the given metric if needed */ void SvxUnoConvertFromMM( const SfxMapUnit eDestinationMapUnit, com::sun::star::uno::Any & rMetric ) throw(); #endif // _SVX_UNOAPI_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unoapi.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2005-01-21 15:42:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_UNOAPI_HXX_ #define _SVX_UNOAPI_HXX_ #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _GRFMGR_HXX #include <goodies/grfmgr.hxx> #endif #ifndef _SFXPOOLITEM_HXX #include <svtools/poolitem.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SvxShape; class SdrObject; class SvxNumBulletItem; class SfxItemPool; class String; /** creates a StarOffice API wrapper with the given type and inventor Deprecated: This will be replaced with a function returning XShape. */ SVX_DLLPUBLIC SvxShape* CreateSvxShapeByTypeAndInventor( sal_uInt16 nType, sal_uInt32 nInventor ) throw(); /** returns a StarOffice API wrapper for the given SdrObject */ SVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > GetXShapeForSdrObject( SdrObject* pObj ) throw (); /** returns the SdrObject from the given StarOffice API wrapper */ SVX_DLLPUBLIC SdrObject* GetSdrObjectFromXShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ) throw() ; /** returns a GraphicObject for this URL */ SVX_DLLPUBLIC GraphicObject CreateGraphicObjectFromURL( const ::rtl::OUString &rURL ) throw() ; /** returns the SvxNumBulletItem with the given name from the pool or a null if there is no item with that name */ SvxNumBulletItem* SvxGetNumBulletItemByName( SfxItemPool* pPool, const ::rtl::OUString& aName ) throw(); /** maps the API constant MeasureUnit to a vcl MapUnit enum. Returns false if conversion is not supported. */ sal_Bool SvxMeasureUnitToMapUnit( const short eApi, short& nVcl ) throw(); /** maps the vcl MapUnit enum to a API constant MeasureUnit. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxMapUnitToMeasureUnit( const short nVcl, short& eApi ) throw(); /** maps the API constant MeasureUnit to a vcl MapUnit enum. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxMeasureUnitToFieldUnit( const short eApi, short& nVcl ) throw(); /** maps the vcl MapUnit enum to a API constant MeasureUnit. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxFieldUnitToMeasureUnit( const short nVcl, short& eApi ) throw(); /** if the given name is a predefined name for the current language it is replaced by the corresponding api name. */ void SvxUnogetApiNameForItem( const sal_Int16 nWhich, const String& rInternalName, rtl::OUString& rApiName ) throw(); /** if the given name is a predefined api name it is replaced by the predefined name for the current language. */ void SvxUnogetInternalNameForItem( const sal_Int16 nWhich, const rtl::OUString& rApiName, String& rInternalName ) throw(); /** converts the given any with a metric to 100th/mm if needed */ void SvxUnoConvertToMM( const SfxMapUnit eSourceMapUnit, com::sun::star::uno::Any & rMetric ) throw(); /** converts the given any with a metric from 100th/mm to the given metric if needed */ void SvxUnoConvertFromMM( const SfxMapUnit eDestinationMapUnit, com::sun::star::uno::Any & rMetric ) throw(); #endif // _SVX_UNOAPI_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.7.428); FILE MERGED 2005/09/05 14:16:56 rt 1.7.428.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unoapi.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:23:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_UNOAPI_HXX_ #define _SVX_UNOAPI_HXX_ #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _GRFMGR_HXX #include <goodies/grfmgr.hxx> #endif #ifndef _SFXPOOLITEM_HXX #include <svtools/poolitem.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SvxShape; class SdrObject; class SvxNumBulletItem; class SfxItemPool; class String; /** creates a StarOffice API wrapper with the given type and inventor Deprecated: This will be replaced with a function returning XShape. */ SVX_DLLPUBLIC SvxShape* CreateSvxShapeByTypeAndInventor( sal_uInt16 nType, sal_uInt32 nInventor ) throw(); /** returns a StarOffice API wrapper for the given SdrObject */ SVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > GetXShapeForSdrObject( SdrObject* pObj ) throw (); /** returns the SdrObject from the given StarOffice API wrapper */ SVX_DLLPUBLIC SdrObject* GetSdrObjectFromXShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ) throw() ; /** returns a GraphicObject for this URL */ SVX_DLLPUBLIC GraphicObject CreateGraphicObjectFromURL( const ::rtl::OUString &rURL ) throw() ; /** returns the SvxNumBulletItem with the given name from the pool or a null if there is no item with that name */ SvxNumBulletItem* SvxGetNumBulletItemByName( SfxItemPool* pPool, const ::rtl::OUString& aName ) throw(); /** maps the API constant MeasureUnit to a vcl MapUnit enum. Returns false if conversion is not supported. */ sal_Bool SvxMeasureUnitToMapUnit( const short eApi, short& nVcl ) throw(); /** maps the vcl MapUnit enum to a API constant MeasureUnit. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxMapUnitToMeasureUnit( const short nVcl, short& eApi ) throw(); /** maps the API constant MeasureUnit to a vcl MapUnit enum. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxMeasureUnitToFieldUnit( const short eApi, short& nVcl ) throw(); /** maps the vcl MapUnit enum to a API constant MeasureUnit. Returns false if conversion is not supported. */ SVX_DLLPUBLIC sal_Bool SvxFieldUnitToMeasureUnit( const short nVcl, short& eApi ) throw(); /** if the given name is a predefined name for the current language it is replaced by the corresponding api name. */ void SvxUnogetApiNameForItem( const sal_Int16 nWhich, const String& rInternalName, rtl::OUString& rApiName ) throw(); /** if the given name is a predefined api name it is replaced by the predefined name for the current language. */ void SvxUnogetInternalNameForItem( const sal_Int16 nWhich, const rtl::OUString& rApiName, String& rInternalName ) throw(); /** converts the given any with a metric to 100th/mm if needed */ void SvxUnoConvertToMM( const SfxMapUnit eSourceMapUnit, com::sun::star::uno::Any & rMetric ) throw(); /** converts the given any with a metric from 100th/mm to the given metric if needed */ void SvxUnoConvertFromMM( const SfxMapUnit eDestinationMapUnit, com::sun::star::uno::Any & rMetric ) throw(); #endif // _SVX_UNOAPI_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fchrfmt.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:45:04 $ * * 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 _FCHRFMT_HXX #define _FCHRFMT_HXX #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _CALBCK_HXX //autogen #include <calbck.hxx> #endif #ifndef _FORMAT_HXX //autogen #include <format.hxx> #endif class SwCharFmt; class SwTxtCharFmt; class IntlWrapper; // ATT_CHARFMT ********************************************* class SwFmtCharFmt: public SfxPoolItem, public SwClient { friend class SwTxtCharFmt; SwTxtCharFmt* pTxtAttr; // mein TextAttribut public: SwFmtCharFmt() : pTxtAttr(0) {} // single argument ctors shall be explicit. explicit SwFmtCharFmt( SwCharFmt *pFmt ); virtual ~SwFmtCharFmt(); // @@@ public copy ctor, but no copy assignment? SwFmtCharFmt( const SwFmtCharFmt& rAttr ); private: // @@@ public copy ctor, but no copy assignment? SwFmtCharFmt & operator= (const SwFmtCharFmt &); public: TYPEINFO(); // "pure virtual Methoden" vom SfxPoolItem virtual int operator==( const SfxPoolItem& ) const; virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper* pIntl = 0 ) const; virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const; virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ); // an das SwTxtCharFmt weiterleiten (vom SwClient) virtual void Modify( SfxPoolItem*, SfxPoolItem* ); virtual BOOL GetInfo( SfxPoolItem& rInfo ) const; void SetCharFmt( SwFmt* pFmt ) { pFmt->Add(this); } SwCharFmt* GetCharFmt() const { return (SwCharFmt*)GetRegisteredIn(); } }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.8.1200); FILE MERGED 2008/04/01 15:56:10 thb 1.8.1200.3: #i85898# Stripping all external header guards 2008/04/01 12:53:28 thb 1.8.1200.2: #i85898# Stripping all external header guards 2008/03/31 16:52:36 rt 1.8.1200.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fchrfmt.hxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _FCHRFMT_HXX #define _FCHRFMT_HXX #include <svtools/poolitem.hxx> #include <calbck.hxx> #include <format.hxx> class SwCharFmt; class SwTxtCharFmt; class IntlWrapper; // ATT_CHARFMT ********************************************* class SwFmtCharFmt: public SfxPoolItem, public SwClient { friend class SwTxtCharFmt; SwTxtCharFmt* pTxtAttr; // mein TextAttribut public: SwFmtCharFmt() : pTxtAttr(0) {} // single argument ctors shall be explicit. explicit SwFmtCharFmt( SwCharFmt *pFmt ); virtual ~SwFmtCharFmt(); // @@@ public copy ctor, but no copy assignment? SwFmtCharFmt( const SwFmtCharFmt& rAttr ); private: // @@@ public copy ctor, but no copy assignment? SwFmtCharFmt & operator= (const SwFmtCharFmt &); public: TYPEINFO(); // "pure virtual Methoden" vom SfxPoolItem virtual int operator==( const SfxPoolItem& ) const; virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper* pIntl = 0 ) const; virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const; virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ); // an das SwTxtCharFmt weiterleiten (vom SwClient) virtual void Modify( SfxPoolItem*, SfxPoolItem* ); virtual BOOL GetInfo( SfxPoolItem& rInfo ) const; void SetCharFmt( SwFmt* pFmt ) { pFmt->Add(this); } SwCharFmt* GetCharFmt() const { return (SwCharFmt*)GetRegisteredIn(); } }; #endif <|endoftext|>
<commit_before>template<class T> struct StarrySkyTree { using int_type = T; vector<T> data; vector<T> lazy; int N; StarrySkyTree(int n) { N=1; while(N<n) N<<=1; data.assign(2*N-1, 0); lazy.assign(2*N-1, 0); } // [a,b) void add(int a,int b, int_type val) { add(a,b,val,0,0,N); } int_type get(int a,int b) { return get(a,b,0,0,N); } void add(int a,int b,int_type val, int k,int l,int r) { if(r<=a || b<=l) return; if(a<=l && r<=b) { lazy[k]+=val; return; } add(a,b,val,k*2+1,l,(l+r)/2); add(a,b,val,k*2+2,(l+r)/2,r); data[k]=max(data[k*2+1]+lazy[k*2+1], data[k*2+2]+lazy[k*2+2]); } int_type get(int a,int b, int k,int l, int r) { if(r<=a || b<=l) return -INF; if(a<=l && r<=b) return data[k]+lazy[k]; int_type lval = get(a,b,k*2+1,l,(l+r)/2); int_type rval = get(a,b,k*2+2,(l+r)/2,r); return max(lval, rval)+lazy[k]; } }; <commit_msg>Fix StarrySkyTree<commit_after>// Verified // http://code-festival-2015-final-open.contest.atcoder.jp/tasks/codefestival_2015_final_d // http://judge.u-aizu.ac.jp/onlinejudge/cdescription.jsp?cid=RitsCamp16Day3&pid=F template<class T> struct StarrySkyTree { using int_type = T; vector<T> data; vector<T> lazy; int N; StarrySkyTree(int n) { N=1; while(N<n) N<<=1; data.assign(2*N-1, 0); lazy.assign(2*N-1, 0); } // [a,b) void add(int a,int b, int_type val) { add(a,b,val,0,0,N); } int_type get(int a,int b) { return get(a,b,0,0,N); } void add(int a,int b,int_type val, int k,int l,int r) { if(r<=a || b<=l) return; if(a<=l && r<=b) { lazy[k]+=val; return; } add(a,b,val,k*2+1,l,(l+r)/2); add(a,b,val,k*2+2,(l+r)/2,r); data[k]=max(data[k*2+1]+lazy[k*2+1], data[k*2+2]+lazy[k*2+2]); } int_type get(int a,int b, int k,int l, int r) { if(r<=a || b<=l) return -INF; if(a<=l && r<=b) return data[k]+lazy[k]; auto lval = get(a,b,k*2+1,l,(l+r)/2); auto rval = get(a,b,k*2+2,(l+r)/2,r); return max(lval, rval)+lazy[k]; } }; <|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * 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. * * @file JPetTaskExecutor.cpp */ #include "JPetTaskExecutor.h" #include <cassert> #include "../JPetTaskInterface/JPetTaskInterface.h" #include "../JPetScopeLoader/JPetScopeLoader.h" #include "../JPetTaskLoader/JPetTaskLoader.h" #include "../JPetParamGetterAscii/JPetParamGetterAscii.h" #include "../JPetParamGetterAscii/JPetParamSaverAscii.h" #include "../JPetLoggerInclude.h" JPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) : fProcessedFile(processedFileId), ftaskGeneratorChain(taskGeneratorChain), fOptions(opt) { if (fOptions.isLocalDB()) { fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB())); } else { fParamManager = new JPetParamManager(); } if (taskGeneratorChain) { for (auto taskGenerator : *ftaskGeneratorChain) { auto task = taskGenerator(); task->setParamManager(fParamManager); // maybe that should not be here fTasks.push_back(task); } } else { ERROR("taskGeneratorChain is null while constructing JPetTaskExecutor"); } } bool JPetTaskExecutor::process() { if(!processFromCmdLineArgs(fProcessedFile)) { ERROR("Error in processFromCmdLineArgs"); return false; } for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) { // ignore the event range options for all but the first processed task if (currentTask != fTasks.begin()) { fOptions.resetEventRange(); } INFO(Form("Starting task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName())); (*currentTask)->init(fOptions.getOptions()); (*currentTask)->exec(); (*currentTask)->terminate(); INFO(Form("Finished task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName())); } return true; } void* JPetTaskExecutor::processProxy(void* runner) { assert(runner); static_cast<JPetTaskExecutor*>(runner)->process(); return 0; } TThread* JPetTaskExecutor::run() { TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this); assert(thread); thread->Run(); return thread; } bool JPetTaskExecutor::processFromCmdLineArgs(int) { auto runNum = fOptions.getRunNumber(); if (runNum >= 0) { try { fParamManager->fillParameterBank(runNum); } catch (...) { ERROR("Param bank was not generated correctly.\n The run number used:" + JPetCommonTools::intToString(runNum)); return false; } if (fOptions.isLocalDBCreate()) { JPetParamSaverAscii saver; saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate()); } } auto inputFileType = fOptions.getInputFileType(); auto inputFile = fOptions.getInputFile(); if (inputFileType == JPetOptions::kScope) { createScopeTaskAndAddToTaskList(); } else if (inputFileType == JPetOptions::kHld) { long long nevents = fOptions.getTotalEvents(); if (nevents > 0) { fUnpacker.setParams(fOptions.getInputFile(), nevents); WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file.")); } else { fUnpacker.setParams(fOptions.getInputFile()); } unpackFile(); } return true; } void JPetTaskExecutor::createScopeTaskAndAddToTaskList() { JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask("JPetScopeReader", "Process Oscilloscope ASCII data into JPetRecoSignal structures.")); assert(module); module->setParamManager(fParamManager); auto scopeFile = fOptions.getScopeConfigFile(); if (!fParamManager->getParametersFromScopeConfig(scopeFile)) { ERROR("Unable to generate Param Bank from Scope Config"); } fTasks.push_front(module); } void JPetTaskExecutor::unpackFile() { if (fOptions.getInputFileType() == JPetOptions::kHld) { fUnpacker.exec(); } else { WARNING("Input file is not hld and unpacker was supposed to be called!"); } } JPetTaskExecutor::~JPetTaskExecutor() { for (auto & task : fTasks) { if (task) { delete task; task = 0; } } } <commit_msg>Add logic that for the tasks that are not first changes the output paths options correctly<commit_after>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * 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. * * @file JPetTaskExecutor.cpp */ #include "JPetTaskExecutor.h" #include <cassert> #include "../JPetTaskInterface/JPetTaskInterface.h" #include "../JPetScopeLoader/JPetScopeLoader.h" #include "../JPetTaskLoader/JPetTaskLoader.h" #include "../JPetParamGetterAscii/JPetParamGetterAscii.h" #include "../JPetParamGetterAscii/JPetParamSaverAscii.h" #include "../JPetLoggerInclude.h" JPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) : fProcessedFile(processedFileId), ftaskGeneratorChain(taskGeneratorChain), fOptions(opt) { if (fOptions.isLocalDB()) { fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB())); } else { fParamManager = new JPetParamManager(); } if (taskGeneratorChain) { for (auto taskGenerator : *ftaskGeneratorChain) { auto task = taskGenerator(); task->setParamManager(fParamManager); // maybe that should not be here fTasks.push_back(task); } } else { ERROR("taskGeneratorChain is null while constructing JPetTaskExecutor"); } } bool JPetTaskExecutor::process() { if(!processFromCmdLineArgs(fProcessedFile)) { ERROR("Error in processFromCmdLineArgs"); return false; } for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) { JPetOptions::Options currOpts = fOptions.getOptions(); if (currentTask != fTasks.begin()) { /// Ignore the event range options for all but the first task. currOpts = JPetOptions::resetEventRange(currOpts); /// For all but the first task, /// the input path must be changed if /// the output path argument -o was given, because the input /// data for them will lay in the location defined by -o. auto outPath = currOpts.at("outputPath"); if (!outPath.empty()) { currOpts.at("inputFile") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at("inputFile")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at("inputFile")); } } INFO(Form("Starting task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName())); (*currentTask)->init(currOpts); (*currentTask)->exec(); (*currentTask)->terminate(); INFO(Form("Finished task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName())); } return true; } void* JPetTaskExecutor::processProxy(void* runner) { assert(runner); static_cast<JPetTaskExecutor*>(runner)->process(); return 0; } TThread* JPetTaskExecutor::run() { TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this); assert(thread); thread->Run(); return thread; } bool JPetTaskExecutor::processFromCmdLineArgs(int) { auto runNum = fOptions.getRunNumber(); if (runNum >= 0) { try { fParamManager->fillParameterBank(runNum); } catch (...) { ERROR("Param bank was not generated correctly.\n The run number used:" + JPetCommonTools::intToString(runNum)); return false; } if (fOptions.isLocalDBCreate()) { JPetParamSaverAscii saver; saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate()); } } auto inputFileType = fOptions.getInputFileType(); auto inputFile = fOptions.getInputFile(); if (inputFileType == JPetOptions::kScope) { createScopeTaskAndAddToTaskList(); } else if (inputFileType == JPetOptions::kHld) { long long nevents = fOptions.getTotalEvents(); if (nevents > 0) { fUnpacker.setParams(fOptions.getInputFile(), nevents); WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file.")); } else { fUnpacker.setParams(fOptions.getInputFile()); } unpackFile(); } return true; } void JPetTaskExecutor::createScopeTaskAndAddToTaskList() { JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask("JPetScopeReader", "Process Oscilloscope ASCII data into JPetRecoSignal structures.")); assert(module); module->setParamManager(fParamManager); auto scopeFile = fOptions.getScopeConfigFile(); if (!fParamManager->getParametersFromScopeConfig(scopeFile)) { ERROR("Unable to generate Param Bank from Scope Config"); } fTasks.push_front(module); } void JPetTaskExecutor::unpackFile() { if (fOptions.getInputFileType() == JPetOptions::kHld) { fUnpacker.exec(); } else { WARNING("Input file is not hld and unpacker was supposed to be called!"); } } JPetTaskExecutor::~JPetTaskExecutor() { for (auto & task : fTasks) { if (task) { delete task; task = 0; } } } <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include <catch.hpp> // #include <glm/glm.hpp> // #include <glm/gtx/intersect.hpp> #include "sphere.hpp" #include "box.hpp" #include "material.hpp" #include "light.hpp" #include "camera.hpp" #include "sdfloader.hpp" #include "renderer.hpp" TEST_CASE("test material", "[test material]") { std::cout << std::endl << "Material Tests: " << std::endl; std::cout << "(Default-Konstructor)" <<std::endl; Material mat1; std::string s1 = "defaultmaterial"; Color col1{}; REQUIRE(mat1.name() == s1); REQUIRE(mat1.ka() == col1); REQUIRE(mat1.kd() == col1); REQUIRE(mat1.ks() == col1); REQUIRE(mat1.m() == 0); std::cout << mat1; std::cout << std::endl << "(Konstructor)" << std::endl; std::string s2 = "mat2"; Color col2{1.0f,0.0f,1.0f}; Material mat2{s2,col2,col2,col2,1}; REQUIRE(mat2.name() == s2); REQUIRE(mat2.ka() == col2); REQUIRE(mat2.kd() == col2); REQUIRE(mat2.ks() == col2); REQUIRE(mat2.m() == 1); std::cout << mat2; } TEST_CASE("test box", "[test box]") { std::cout << std::endl << "Box Tests: " << std::endl; Box box1; glm::vec3 vec3{}; REQUIRE(box1.min() == vec3); REQUIRE(box1.max() == vec3); Box box2{glm::vec3{1.0,1.0,1.0},glm::vec3{3.0,4.0,5.0}}; glm::vec3 p1{1.0,1.0,1.0}; glm::vec3 p2{3.0,4.0,5.0}; REQUIRE(box2.min() == p1); REQUIRE(box2.max() == p2); REQUIRE(box2.area() == Approx(52.0)); REQUIRE(box2.volume() == Approx(24.0)); std::cout << std::endl; std::string b = "Box3"; Material mat{}; Box box3{glm::vec3{1.0,1.0,1.0}, glm::vec3{2.0,2.0,2.0}, b, mat}; REQUIRE(box3.name() == b); REQUIRE(box3.material() == mat); std::cout << box3; } TEST_CASE("test sphere", "[test sphere]") { std::cout << std::endl << "Sphere Tests: " << std::endl; Sphere sphere0; glm::vec3 vec0{}; std::string a = "defaultshape"; Material mat{}; REQUIRE(sphere0.radius() == Approx(0.0)); REQUIRE(sphere0.center() == vec0); REQUIRE(sphere0.name() == a); REQUIRE(sphere0.material() == mat); std::cout << sphere0; glm::vec3 vec1{1.0,1.0,1.0}; std::string b = "sphere1"; Sphere sphere1{vec1, 1.0, b, mat}; REQUIRE(sphere1.radius() == Approx(1.0)); REQUIRE(sphere1.center() == vec1); REQUIRE(sphere1.name() == b); REQUIRE(sphere1.material() == mat); REQUIRE(sphere1.area() == Approx(12.5664)); REQUIRE(sphere1.volume() == Approx(4.18879f)); std::cout << sphere1; } /*TEST_CASE("test intersectRaySphere", "[test intersectRaySphere]") { std::cout << std::endl << "Intersect-Ray-Sphere Tests: " << std::endl; glm::vec3 ray_origin1(0.0,0.0,0.0); glm::vec3 ray_direction1(0.0,0.0,1.0); Ray ray1{ray_origin1,ray_direction1}; glm::vec3 ray_origin2(2.0,1.0,3.0); glm::vec3 ray_direction2(4.0,2.0,6.0); Ray ray2{ray_origin2,ray_direction2}; float sphere_radius(1.0); Material mat{}; glm::vec3 sphere_center0(0.0,0.0,5.0); std::string a = "sphere0"; Sphere sphere0{sphere_center0, sphere_radius, a, mat}; glm::vec3 sphere_center1(3.0,1.5,4.5); std::string b = "sphere1"; Sphere sphere1{sphere_center1, sphere_radius, b, mat}; glm::vec3 sphere_center2(7.0,7.0,7.0); std::string c = "sphere2"; Sphere sphere2{sphere_center2, sphere_radius, c, mat}; float distance(0.0); REQUIRE(sphere0.intersect(ray1, distance) == true); REQUIRE(distance == Approx(4.0f)); REQUIRE(sphere1.intersect(ray2, distance) == true); REQUIRE(sphere2.intersect(ray2, distance) == false); }*/ TEST_CASE("test intersectRayBox", "[test intersectRayBox]") { std::cout << std::endl << "Intersect-Ray-Box Tests: " << std::endl; glm::vec3 ray_origin1(0.0,0.0,0.0); glm::vec3 ray_direction1(1.0,1.0,1.0); Ray ray1{ray_origin1,ray_direction1}; glm::vec3 ray_origin2(3.0,1.5,4.5); glm::vec3 ray_direction2(-1.0,-1.0,-1.0); Ray ray2{ray_origin2,ray_direction2}; std::string a = "box0"; Material mat{}; glm::vec3 box_min0(2.0,2.0,2.0); glm::vec3 box_max0(4.0,4.0,4.0); Box box0{box_min0, box_max0, a, mat}; std::string b = "box1"; glm::vec3 box_min1(3.0,1.5,4.5); glm::vec3 box_max1(1.0,1.0,1.0); Box box1{box_min1, box_max1, b, mat}; std::string c = "box2"; glm::vec3 box_min2(7.0,7.0,7.0); glm::vec3 box_max2(6.0,8.0,6.0); Box box2{box_min2, box_max2, c, mat}; /*Hit temp; REQUIRE(box0.intersect(ray1) == temp); REQUIRE(box1.intersect(ray2) == temp); REQUIRE(box2.intersect(ray2) == temp);*/ } TEST_CASE("test light", "[test light]"){ std::cout << std::endl << "Light Tests: " << std::endl; std::cout << "(Default-Konstructor)" <<std::endl; Light light1; std::string s1 = "defaultlight"; glm::vec3 pos0(0.0,0.0,0.0); Color c0; REQUIRE(light1.name() == s1); REQUIRE(light1.pos() == pos0); REQUIRE(light1.dl() == c0); std::cout << light1; } TEST_CASE("test camera", "[test camera]"){ std::cout << "Camera Tests: " << std::endl; std::cout << "(Default-Konstructor)" <<std::endl; Camera cam1; std::string s1 = "defaultcam"; glm::vec3 pos0(0.0,0.0,0.0); float fovx = 60.0f; REQUIRE(cam1.name() == s1); REQUIRE(cam1.pos() == pos0); REQUIRE(cam1.fovx() == fovx); std::cout << cam1; glm::vec3 d(1.0,1.0,1.0); //std::cout << cam1.castray(d) << std::endl; } TEST_CASE("sdfloader_material", "[sdfloader]"){ Sdfloader loader{"./materials.txt"}; std::shared_ptr<Scene> s = loader.loadscene("./materials.txt"); } TEST_CASE("sdfloader Test", "[sdfloader test]"){ Sdfloader loader{"./test.txt"}; std::shared_ptr<Scene> sptr = loader.loadscene("./test.txt"); Scene s = *sptr; std::cout << "\n" ; std::cout << "Ambientes Licht: \n" << s.amblight << std::endl; std::cout << "Background-Color: \n" << s.background << std::endl; std::cout << *s.materials["red"] << std::endl; std::cout << *s.materials["blue"] << std::endl; std::cout << *s.shapes_ptr[0]; std::cout << *s.shapes_ptr[1]; std::cout << s.camera; std::cout << *s.lights[0]; } TEST_CASE("renderer Test", "[renderer test]"){ Sdfloader loader{"./test.txt"}; std::shared_ptr<Scene> s = loader.loadscene("./test.txt"); Renderer renderer(s); //Renderer renderer(scene); } // AUFGABENBLATT 6 /*TEST_CASE("statischer Typ/dynamischer Typ Variable", "[6.7]") { std::cout << std::endl << "6.7:" << std::endl; Color rot(255,0,0); Material red("ton" ,rot,rot,rot,7.1f); glm::vec3 position(0,0,0); std::shared_ptr<Sphere> s1 = std::make_shared<Sphere>( position, 1.2, "sphere0", red ); std::shared_ptr<Shape> s2 = std::make_shared<Sphere>( position, 1.2, "sphere1", red ); s1->print(std::cout); s2->print(std::cout); //C++ ist eine statisch typisierte Sprache. //In C++ können Variablen einer Basisklasse Objekte einer abgeleiteten Klasse referenzieren. //Da hier im Beispiel die Pointer von verschiedenen Typen sind, kann man sehen, dass diese trotzdem auf das gleiche Objekt zeigen können. //Der erste erzeugte Sphere-Pointer zeigt auf eine Sphere, hier sind statische und dynamische Klasse die selbe. //Der zweite erzeugte Shape-Pointer zeigt auf eine Sphere, hier ist Shape die statische und Sphere ist die dynamische Klasse. } TEST_CASE("destructor", "[6.8]") { std::cout << std::endl << "6.8:" << std::endl; Material red("red",Color {255,0,0}, 0.0); glm::vec3 position(0,0,0); Sphere* s1 = new Sphere(position, 1.2f, "sphere0", red); Shape* s2 = new Sphere(position, 1.2f, "sphere1", red); s1->print(std::cout); s2->print(std::cout); delete s1; delete s2; //Ohne virtual wird beim Shape-Pointer der Destruktor der Sphere nicht aufgerufen, da hier nur der Destruktor von der Klasse aufgerufen wird auf den der Pointer zeigt. //Bei dem Sphere-Pointer werden zwei Destruktoren aufgerufen, da wenn der Destruktor der Sphere aufgerufen wird, auf welche der Pointer zeigt, automatisch auch noch der Destruktor der Basisklasse aufgerufen wird. //Wenn man virtual verwendet wird auch für den Shape-Pointer der Destruktor der Sphere-Klasse aufgerufen, da der Destruktor des Pointers virtual und Sphere die abgeleitete Klasse der Basisklasse Shape ist. }*/ int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } <commit_msg>testing box intersect<commit_after>#define CATCH_CONFIG_RUNNER #include <catch.hpp> // #include <glm/glm.hpp> // #include <glm/gtx/intersect.hpp> #include "sphere.hpp" #include "box.hpp" #include "material.hpp" #include "light.hpp" #include "camera.hpp" #include "sdfloader.hpp" #include "renderer.hpp" TEST_CASE("test material", "[test material]") { std::cout << std::endl << "Material Tests: " << std::endl; std::cout << "(Default-Konstructor)" <<std::endl; Material mat1; std::string s1 = "defaultmaterial"; Color col1{}; REQUIRE(mat1.name() == s1); REQUIRE(mat1.ka() == col1); REQUIRE(mat1.kd() == col1); REQUIRE(mat1.ks() == col1); REQUIRE(mat1.m() == 0); std::cout << mat1; std::cout << std::endl << "(Konstructor)" << std::endl; std::string s2 = "mat2"; Color col2{1.0f,0.0f,1.0f}; Material mat2{s2,col2,col2,col2,1}; REQUIRE(mat2.name() == s2); REQUIRE(mat2.ka() == col2); REQUIRE(mat2.kd() == col2); REQUIRE(mat2.ks() == col2); REQUIRE(mat2.m() == 1); std::cout << mat2; } TEST_CASE("test box", "[test box]") { std::cout << std::endl << "Box Tests: " << std::endl; Box box1; glm::vec3 vec3{}; REQUIRE(box1.min() == vec3); REQUIRE(box1.max() == vec3); Box box2{glm::vec3{1.0,1.0,1.0},glm::vec3{3.0,4.0,5.0}}; glm::vec3 p1{1.0,1.0,1.0}; glm::vec3 p2{3.0,4.0,5.0}; REQUIRE(box2.min() == p1); REQUIRE(box2.max() == p2); REQUIRE(box2.area() == Approx(52.0)); REQUIRE(box2.volume() == Approx(24.0)); std::cout << std::endl; std::string b = "Box3"; Material mat{}; Box box3{glm::vec3{1.0,1.0,1.0}, glm::vec3{2.0,2.0,2.0}, b, mat}; REQUIRE(box3.name() == b); REQUIRE(box3.material() == mat); std::cout << box3; } TEST_CASE("test sphere", "[test sphere]") { std::cout << std::endl << "Sphere Tests: " << std::endl; Sphere sphere0; glm::vec3 vec0{}; std::string a = "defaultshape"; Material mat{}; REQUIRE(sphere0.radius() == Approx(0.0)); REQUIRE(sphere0.center() == vec0); REQUIRE(sphere0.name() == a); REQUIRE(sphere0.material() == mat); std::cout << sphere0; glm::vec3 vec1{1.0,1.0,1.0}; std::string b = "sphere1"; Sphere sphere1{vec1, 1.0, b, mat}; REQUIRE(sphere1.radius() == Approx(1.0)); REQUIRE(sphere1.center() == vec1); REQUIRE(sphere1.name() == b); REQUIRE(sphere1.material() == mat); REQUIRE(sphere1.area() == Approx(12.5664)); REQUIRE(sphere1.volume() == Approx(4.18879f)); std::cout << sphere1; } /*TEST_CASE("test intersectRaySphere", "[test intersectRaySphere]") { std::cout << std::endl << "Intersect-Ray-Sphere Tests: " << std::endl; glm::vec3 ray_origin1(0.0,0.0,0.0); glm::vec3 ray_direction1(0.0,0.0,1.0); Ray ray1{ray_origin1,ray_direction1}; glm::vec3 ray_origin2(2.0,1.0,3.0); glm::vec3 ray_direction2(4.0,2.0,6.0); Ray ray2{ray_origin2,ray_direction2}; float sphere_radius(1.0); Material mat{}; glm::vec3 sphere_center0(0.0,0.0,5.0); std::string a = "sphere0"; Sphere sphere0{sphere_center0, sphere_radius, a, mat}; glm::vec3 sphere_center1(3.0,1.5,4.5); std::string b = "sphere1"; Sphere sphere1{sphere_center1, sphere_radius, b, mat}; glm::vec3 sphere_center2(7.0,7.0,7.0); std::string c = "sphere2"; Sphere sphere2{sphere_center2, sphere_radius, c, mat}; float distance(0.0); REQUIRE(sphere0.intersect(ray1, distance) == true); REQUIRE(distance == Approx(4.0f)); REQUIRE(sphere1.intersect(ray2, distance) == true); REQUIRE(sphere2.intersect(ray2, distance) == false); }*/ TEST_CASE("test intersectRayBox", "[test intersectRayBox]") { std::cout << std::endl << "Intersect-Ray-Box Tests: " << std::endl; glm::vec3 ray_origin0(0.0,0.0,0.0); glm::vec3 ray_direction0(1.0,1.0,1.0); Ray ray0{ray_origin0,ray_direction0}; glm::vec3 ray_origin1(3.0,1.5,4.5); glm::vec3 ray_direction1(-1.0,-1.0,-1.0); Ray ray1{ray_origin1,ray_direction1}; std::string a = "box0"; Material mat{}; glm::vec3 box_min0(2.0,2.0,2.0); glm::vec3 box_max0(4.0,4.0,4.0); Box box0{box_min0, box_max0, a, mat}; std::string b = "box1"; glm::vec3 box_min1(3.0,1.5,4.5); glm::vec3 box_max1(1.0,1.0,1.0); Box box1{box_min1, box_max1, b, mat}; std::string c = "box2"; glm::vec3 box_min2(7.0,7.0,7.0); glm::vec3 box_max2(6.0,8.0,6.0); Box box2{box_min2, box_max2, c, mat}; Hit hit0 = box0.intersect(ray0); std::cout << hit0; Hit hit1 = box0.intersect(ray1); std::cout << hit1; // REQUIRE(box2.intersect(ray1) == temp); // REQUIRE(box0.intersect(ray0) == temp); // REQUIRE(box1.intersect(ray1) == temp); } TEST_CASE("test light", "[test light]"){ std::cout << std::endl << "Light Tests: " << std::endl; std::cout << "(Default-Konstructor)" <<std::endl; Light light1; std::string s1 = "defaultlight"; glm::vec3 pos0(0.0,0.0,0.0); Color c0; REQUIRE(light1.name() == s1); REQUIRE(light1.pos() == pos0); REQUIRE(light1.dl() == c0); std::cout << light1; } TEST_CASE("test camera", "[test camera]"){ std::cout << "Camera Tests: " << std::endl; std::cout << "(Default-Konstructor)" <<std::endl; Camera cam1; std::string s1 = "defaultcam"; glm::vec3 pos0(0.0,0.0,0.0); float fovx = 60.0f; REQUIRE(cam1.name() == s1); REQUIRE(cam1.pos() == pos0); REQUIRE(cam1.fovx() == fovx); std::cout << cam1; glm::vec3 d(1.0,1.0,1.0); //std::cout << cam1.castray(d) << std::endl; } TEST_CASE("sdfloader_material", "[sdfloader]"){ Sdfloader loader{"./materials.txt"}; std::shared_ptr<Scene> s = loader.loadscene("./materials.txt"); } TEST_CASE("sdfloader Test", "[sdfloader test]"){ Sdfloader loader{"./test.txt"}; std::shared_ptr<Scene> sptr = loader.loadscene("./test.txt"); Scene s = *sptr; std::cout << "\n" ; std::cout << "Ambientes Licht: \n" << s.amblight << std::endl; std::cout << "Background-Color: \n" << s.background << std::endl; std::cout << *s.materials["red"] << std::endl; std::cout << *s.materials["blue"] << std::endl; std::cout << *s.shapes_ptr[0]; std::cout << *s.shapes_ptr[1]; std::cout << s.camera; std::cout << *s.lights[0]; } TEST_CASE("renderer Test", "[renderer test]"){ Sdfloader loader{"./test.txt"}; std::shared_ptr<Scene> s = loader.loadscene("./test.txt"); Renderer renderer(s); //Renderer renderer(scene); } // AUFGABENBLATT 6 /*TEST_CASE("statischer Typ/dynamischer Typ Variable", "[6.7]") { std::cout << std::endl << "6.7:" << std::endl; Color rot(255,0,0); Material red("ton" ,rot,rot,rot,7.1f); glm::vec3 position(0,0,0); std::shared_ptr<Sphere> s1 = std::make_shared<Sphere>( position, 1.2, "sphere0", red ); std::shared_ptr<Shape> s2 = std::make_shared<Sphere>( position, 1.2, "sphere1", red ); s1->print(std::cout); s2->print(std::cout); //C++ ist eine statisch typisierte Sprache. //In C++ können Variablen einer Basisklasse Objekte einer abgeleiteten Klasse referenzieren. //Da hier im Beispiel die Pointer von verschiedenen Typen sind, kann man sehen, dass diese trotzdem auf das gleiche Objekt zeigen können. //Der erste erzeugte Sphere-Pointer zeigt auf eine Sphere, hier sind statische und dynamische Klasse die selbe. //Der zweite erzeugte Shape-Pointer zeigt auf eine Sphere, hier ist Shape die statische und Sphere ist die dynamische Klasse. } TEST_CASE("destructor", "[6.8]") { std::cout << std::endl << "6.8:" << std::endl; Material red("red",Color {255,0,0}, 0.0); glm::vec3 position(0,0,0); Sphere* s1 = new Sphere(position, 1.2f, "sphere0", red); Shape* s2 = new Sphere(position, 1.2f, "sphere1", red); s1->print(std::cout); s2->print(std::cout); delete s1; delete s2; //Ohne virtual wird beim Shape-Pointer der Destruktor der Sphere nicht aufgerufen, da hier nur der Destruktor von der Klasse aufgerufen wird auf den der Pointer zeigt. //Bei dem Sphere-Pointer werden zwei Destruktoren aufgerufen, da wenn der Destruktor der Sphere aufgerufen wird, auf welche der Pointer zeigt, automatisch auch noch der Destruktor der Basisklasse aufgerufen wird. //Wenn man virtual verwendet wird auch für den Shape-Pointer der Destruktor der Sphere-Klasse aufgerufen, da der Destruktor des Pointers virtual und Sphere die abgeleitete Klasse der Basisklasse Shape ist. }*/ int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include <sphere.hpp> #include <box.hpp> #include <fstream> #include <iostream> #include <glm/glm.hpp> #include <glm/gtx/intersect.hpp> /* SDF Test */ TEST_CASE("SDFRead","[SDF]") { std::string line; std::ifstream sdf("../sdf/test.txt"); if(sdf.is_open()) { while(std::getline(sdf,line)) { std::cout << line << '\n'; } sdf.close(); } else { std::cout << "Unable to open file"; } } /* Sphere tests */ TEST_CASE("sphereDefaultConstructor","[Sphere]") { Sphere s = Sphere{}; REQUIRE(s.center() == glm::vec3{0}); REQUIRE(s.radius() == 0); REQUIRE(s.name() == "untitled_sphere"); REQUIRE(s.color() == Color{0.0}); } TEST_CASE("sphereCenterConstructor","[Sphere]") { glm::vec3 center{2}; Sphere s = Sphere{center}; REQUIRE(s.center() == center); REQUIRE(s.radius() == 0); REQUIRE(s.name() == "untitled_sphere"); REQUIRE(s.color() == Color{0.0}); } TEST_CASE("sphereRadiusConstructor","[Sphere]") { Sphere s = Sphere{2}; REQUIRE(s.center() == glm::vec3{0}); REQUIRE(s.radius() == 2); REQUIRE(s.name() == "untitled_sphere"); REQUIRE(s.color() == Color{0.0}); } TEST_CASE("sphereConstructor","[Sphere]") { glm::vec3 center{2}; Sphere s = Sphere{center, 3.5,"test",Color{1.0}}; REQUIRE(s.center() == center); REQUIRE(s.radius() == 3.5); REQUIRE(s.name() == "test"); REQUIRE(s.color() == Color{1.0}); } TEST_CASE("sphereGetter","[Sphere]") { Sphere s = Sphere{}; glm::vec3 center{0}; REQUIRE(s.center() == center); REQUIRE(s.radius() == 0); REQUIRE(s.name() == "untitled_sphere"); REQUIRE(s.color() == Color{0.0}); } TEST_CASE("sphereArea","[Sphere]") { glm::vec3 center{2}; Sphere s = Sphere{center, 2}; REQUIRE(s.area() == Approx(50.2655)); } TEST_CASE("sphereVolume","[Sphere]") { glm::vec3 center{2}; Sphere s = Sphere{center, 2}; REQUIRE(s.volume() == Approx(33.5103)); } /* Box tests */ TEST_CASE("boxDefaultConstructor","[Box]") { Box b = Box{}; REQUIRE(b.min() == glm::vec3{0}); REQUIRE(b.max() == glm::vec3{0}); REQUIRE(b.name() == "untitled_box"); REQUIRE(b.color() == Color{0.0}); } TEST_CASE("boxConstructor","[Box]") { Box b = Box{glm::vec3{0},glm::vec3{1},"test",Color{1.0}}; REQUIRE(b.min() == glm::vec3{0}); REQUIRE(b.max() == glm::vec3{1}); REQUIRE(b.name() == "test"); REQUIRE(b.color() == Color{1.0}); } TEST_CASE("boxGetter","[Box]") { Box b = Box{glm::vec3{0},glm::vec3{1}}; REQUIRE(b.min() == glm::vec3{0}); REQUIRE(b.max() == glm::vec3{1}); REQUIRE(b.name() == "untitled_box"); REQUIRE(b.color() == Color{0.0}); } TEST_CASE("boxArea","[Box]") { Box b = Box{glm::vec3{0},glm::vec3{1}}; REQUIRE(b.area() == 6); } TEST_CASE("boxVolume","[Box]") { Box b = Box{glm::vec3{0},glm::vec3{1}}; REQUIRE(b.volume() == 1); } TEST_CASE("printShape","[Shape]") { Box b = Box{}; Sphere s = Sphere{}; std::cout << b; std::cout << s; } /* Ray tests */ TEST_CASE("rayDefaultConstructor", "[ray]") { Ray r = Ray{}; REQUIRE(r.origin == glm::vec3{0}); REQUIRE(r.direction == glm::vec3{0}); } TEST_CASE("rayCustomConstructor", "[ray]") { Ray r = Ray{glm::vec3{1}, glm::vec3{5}}; REQUIRE(r.origin == glm::vec3{1}); REQUIRE(r.direction == glm::vec3{5}); } /* Intersect tests */ TEST_CASE("intersectRaySphere","[intersect]") { //Ray glm::vec3 ray_origin(0.0,0.0,0.0); glm::vec3 ray_direction(0.0,0.0,1.0); //Sphere glm::vec3 sphere_center(0.0,0.0,5.0); float sphere_radius(1.0); float distance(0.0); auto result = glm::intersectRaySphere( ray_origin,ray_direction, sphere_center,sphere_radius, distance); REQUIRE(distance==Approx(4.0f)); } TEST_CASE("customIntersectRaySphere","[intersect]") { Ray ray{glm::vec3{6.0,6.0,6.0},glm::vec3{-1.0,-1.0,-1.0}}; Sphere sphere{glm::vec3{0.0,0.0,0.0}, 7.0}; float d; REQUIRE(sphere.intersect(ray,d)); } /* Virtual destructor test */ TEST_CASE("virtualDestructor","[destruct]") { std::cout << "============================================\n"; Color red{255,0,0}; glm::vec3 position{0.0}; Sphere* s1 = new Sphere{position , 1.2 ,"sphere0" ,red}; Shape* s2 = new Sphere{position , 1.2 , "sphere1" , red}; //std::cout << s1 << "\n"; //std::cout << s2; s1->print(std::cout); s2->print(std::cout); delete s1 ; delete s2 ; } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } <commit_msg>Added TestCases for SceneObject transformations<commit_after>#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include <sphere.hpp> #include <box.hpp> #include <fstream> #include <iostream> #include <glm/glm.hpp> #include <glm/matrix.hpp> #include <glm/vec4.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/intersect.hpp> /* SceneObject tests */ //Matrix initalisation for further SceneObject tests glm::vec4 col0 = glm::vec4{1.0f,2.0f,3.0f,4.0f}; glm::vec4 col1 = glm::vec4{2.0f,3.0f,4.0f,5.0f}; glm::vec4 col2 = glm::vec4{3.0f,4.0f,5.0f,6.0f}; glm::vec4 col3 = glm::vec4{4.0f,5.0f,6.0f,7.0f}; glm::mat4 mat = glm::mat4{col0,col1,col2,col3}; TEST_CASE("sceneObjectDefaultConstructor","[SceneObject]") { SceneObject so = SceneObject{}; REQUIRE(so.transformMatrix() == glm::mat4{0.0}); } TEST_CASE("sceneObjectMatrixConstructor","[SceneObject]") { SceneObject so = SceneObject{mat}; REQUIRE(so.transformMatrix() == mat); }; TEST_CASE("sceneObjectInverseMatrix","[SceneObject]"){ SceneObject so = SceneObject{mat}; REQUIRE(so.inverseTransformMatrix() == glm::inverse(mat)); }; TEST_CASE("sceneObjectTranslateMatrix","[SceneObject]"){ SceneObject so = SceneObject{mat}; REQUIRE(so.inverseTransformMatrix() == glm::translate(mat,glm::vec3(1,2,3))); }; TEST_CASE("sceneObjectRotateMatrix","[SceneObject]"){ SceneObject so = SceneObject{mat}; REQUIRE(so.rotate(glm::vec3(1.0f,2.0f,3.0f),45) == glm::rotate(mat,45.0f,glm::vec3(1,2,3))); }; TEST_CASE("sceneObjectScaleMatrix","[SceneObject]"){ SceneObject so = SceneObject{mat}; REQUIRE(so.inverseTransformMatrix() == glm::scale(mat,glm::vec3(1,2,3))); }; /* Sphere tests */ TEST_CASE("sphereDefaultConstructor","[Sphere]") { Sphere s = Sphere{}; REQUIRE(s.center() == glm::vec3{0}); REQUIRE(s.radius() == 0); REQUIRE(s.name() == "untitled_sphere"); REQUIRE(s.color() == Color{0.0}); } TEST_CASE("sphereCenterConstructor","[Sphere]") { glm::vec3 center{2}; Sphere s = Sphere{center}; REQUIRE(s.center() == center); REQUIRE(s.radius() == 0); REQUIRE(s.name() == "untitled_sphere"); REQUIRE(s.color() == Color{0.0}); } TEST_CASE("sphereRadiusConstructor","[Sphere]") { Sphere s = Sphere{2}; REQUIRE(s.center() == glm::vec3{0}); REQUIRE(s.radius() == 2); REQUIRE(s.name() == "untitled_sphere"); REQUIRE(s.color() == Color{0.0}); } TEST_CASE("sphereConstructor","[Sphere]") { glm::vec3 center{2}; Sphere s = Sphere{center, 3.5,"test",Color{1.0}}; REQUIRE(s.center() == center); REQUIRE(s.radius() == 3.5); REQUIRE(s.name() == "test"); REQUIRE(s.color() == Color{1.0}); } TEST_CASE("sphereGetter","[Sphere]") { Sphere s = Sphere{}; glm::vec3 center{0}; REQUIRE(s.center() == center); REQUIRE(s.radius() == 0); REQUIRE(s.name() == "untitled_sphere"); REQUIRE(s.color() == Color{0.0}); } TEST_CASE("sphereArea","[Sphere]") { glm::vec3 center{2}; Sphere s = Sphere{center, 2}; REQUIRE(s.area() == Approx(50.2655)); } TEST_CASE("sphereVolume","[Sphere]") { glm::vec3 center{2}; Sphere s = Sphere{center, 2}; REQUIRE(s.volume() == Approx(33.5103)); } /* Box tests */ TEST_CASE("boxDefaultConstructor","[Box]") { Box b = Box{}; REQUIRE(b.min() == glm::vec3{0}); REQUIRE(b.max() == glm::vec3{0}); REQUIRE(b.name() == "untitled_box"); REQUIRE(b.color() == Color{0.0}); } TEST_CASE("boxConstructor","[Box]") { Box b = Box{glm::vec3{0},glm::vec3{1},"test",Color{1.0}}; REQUIRE(b.min() == glm::vec3{0}); REQUIRE(b.max() == glm::vec3{1}); REQUIRE(b.name() == "test"); REQUIRE(b.color() == Color{1.0}); } TEST_CASE("boxGetter","[Box]") { Box b = Box{glm::vec3{0},glm::vec3{1}}; REQUIRE(b.min() == glm::vec3{0}); REQUIRE(b.max() == glm::vec3{1}); REQUIRE(b.name() == "untitled_box"); REQUIRE(b.color() == Color{0.0}); } TEST_CASE("boxArea","[Box]") { Box b = Box{glm::vec3{0},glm::vec3{1}}; REQUIRE(b.area() == 6); } TEST_CASE("boxVolume","[Box]") { Box b = Box{glm::vec3{0},glm::vec3{1}}; REQUIRE(b.volume() == 1); } TEST_CASE("printShape","[Shape]") { Box b = Box{}; Sphere s = Sphere{}; std::cout << b; std::cout << s; } /* Ray tests */ TEST_CASE("rayDefaultConstructor", "[ray]") { Ray r = Ray{}; REQUIRE(r.origin == glm::vec3{0}); REQUIRE(r.direction == glm::vec3{0}); } TEST_CASE("rayCustomConstructor", "[ray]") { Ray r = Ray{glm::vec3{1}, glm::vec3{5}}; REQUIRE(r.origin == glm::vec3{1}); REQUIRE(r.direction == glm::vec3{5}); } /* Intersect tests */ TEST_CASE("intersectRaySphere","[intersect]") { //Ray glm::vec3 ray_origin(0.0,0.0,0.0); glm::vec3 ray_direction(0.0,0.0,1.0); //Sphere glm::vec3 sphere_center(0.0,0.0,5.0); float sphere_radius(1.0); float distance(0.0); auto result = glm::intersectRaySphere( ray_origin,ray_direction, sphere_center,sphere_radius, distance); REQUIRE(distance==Approx(4.0f)); } TEST_CASE("customIntersectRaySphere","[intersect]") { Ray ray{glm::vec3{6.0,6.0,6.0},glm::vec3{-1.0,-1.0,-1.0}}; Sphere sphere{glm::vec3{0.0,0.0,0.0}, 7.0}; float d; REQUIRE(sphere.intersect(ray,d)); } /* Virtual destructor test */ TEST_CASE("virtualDestructor","[destruct]") { std::cout << "============================================\n"; Color red{255,0,0}; glm::vec3 position{0.0}; Sphere* s1 = new Sphere{position , 1.2 ,"sphere0" ,red}; Shape* s2 = new Sphere{position , 1.2 , "sphere1" , red}; //std::cout << s1 << "\n"; //std::cout << s2; s1->print(std::cout); s2->print(std::cout); delete s1 ; delete s2 ; } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } <|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2009 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Vc. If not, see <http://www.gnu.org/licenses/>. */ #include <Vc/Vc> #include "unittest.h" #include <iostream> #include "vectormemoryhelper.h" #include <cmath> using namespace Vc; template<typename Vec> void testInc() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); COMPARE(aa(m)++, a); COMPARE(aa, b); COMPARE(++a(m), b); COMPARE(a, b); } } template<typename Vec> void testDec() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 1); data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); COMPARE(aa(m)--, a); COMPARE(--a(m), b); COMPARE(a, b); COMPARE(aa, b); } } template<typename Vec> void testPlusEq() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 1); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) += static_cast<T>(2), b); COMPARE(a, b); } } template<typename Vec> void testMinusEq() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 2); data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) -= static_cast<T>(2), b); COMPARE(a, b); } } template<typename Vec> void testTimesEq() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) *= static_cast<T>(2), b); COMPARE(a, b); } } template<typename Vec> void testDivEq() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(5 * i); data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) /= static_cast<T>(3), b); COMPARE(a, b); } } template<typename Vec> void testAssign() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) = b, b); COMPARE(a, b); } } template<typename Vec> void testZero() { typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; typedef typename Vec::IndexType I; for (int cut = 0; cut < Vec::Size; ++cut) { const Mask mask(I(Vc::IndexesFromZero) < cut); //std::cout << mask << std::endl; const T aa = 4; Vec a(aa); Vec b(Vc::Zero); b(!mask) = a; a.setZero(mask); COMPARE(a, b); } } template<typename Vec> void testCount() { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; typedef typename Vec::Mask M; for (int cut = 0; cut <= Vec::Size; ++cut) { const M mask(I(Vc::IndexesFromZero) < cut); //std::cout << mask << std::endl; COMPARE(mask.count(), cut); } } template<typename Vec> void testFirstOne() { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; typedef typename Vec::Mask M; for (int i = 0; i < Vec::Size; ++i) { const M mask(I(Vc::IndexesFromZero) == i); COMPARE(mask.firstOne(), i); } } #ifdef VC_IMPL_SSE void testFloat8GatherMask() { Memory<short_v, short_v::Size * 256> data; short_v::Memory andMemory; for (int i = 0; i < short_v::Size; ++i) { andMemory[i] = 1 << i; } const short_v andMask(andMemory); for (unsigned int i = 0; i < data.vectorsCount(); ++i) { data.vector(i) = andMask & i; } for (unsigned int i = 0; i < data.vectorsCount(); ++i) { const short_m mask = data.vector(i) == short_v::Zero(); SSE::Float8GatherMask gatherMaskA(mask), gatherMaskB(static_cast<sfloat_m>(mask)); COMPARE(gatherMaskA.toInt(), gatherMaskB.toInt()); } } #endif int main() { runTest(testInc<int_v>); runTest(testInc<uint_v>); runTest(testInc<float_v>); runTest(testInc<double_v>); runTest(testInc<short_v>); runTest(testInc<ushort_v>); runTest(testInc<sfloat_v>); runTest(testDec<int_v>); runTest(testDec<uint_v>); runTest(testDec<float_v>); runTest(testDec<double_v>); runTest(testDec<short_v>); runTest(testDec<ushort_v>); runTest(testDec<sfloat_v>); runTest(testPlusEq<int_v>); runTest(testPlusEq<uint_v>); runTest(testPlusEq<float_v>); runTest(testPlusEq<double_v>); runTest(testPlusEq<short_v>); runTest(testPlusEq<ushort_v>); runTest(testPlusEq<sfloat_v>); runTest(testMinusEq<int_v>); runTest(testMinusEq<uint_v>); runTest(testMinusEq<float_v>); runTest(testMinusEq<double_v>); runTest(testMinusEq<short_v>); runTest(testMinusEq<ushort_v>); runTest(testMinusEq<sfloat_v>); runTest(testTimesEq<int_v>); runTest(testTimesEq<uint_v>); runTest(testTimesEq<float_v>); runTest(testTimesEq<double_v>); runTest(testTimesEq<short_v>); runTest(testTimesEq<ushort_v>); runTest(testTimesEq<sfloat_v>); runTest(testDivEq<int_v>); runTest(testDivEq<uint_v>); runTest(testDivEq<float_v>); runTest(testDivEq<double_v>); runTest(testDivEq<short_v>); runTest(testDivEq<ushort_v>); runTest(testDivEq<sfloat_v>); runTest(testAssign<int_v>); runTest(testAssign<uint_v>); runTest(testAssign<float_v>); runTest(testAssign<double_v>); runTest(testAssign<short_v>); runTest(testAssign<ushort_v>); runTest(testAssign<sfloat_v>); runTest(testZero<int_v>); runTest(testZero<uint_v>); runTest(testZero<float_v>); runTest(testZero<double_v>); runTest(testZero<short_v>); runTest(testZero<ushort_v>); runTest(testZero<sfloat_v>); runTest(testCount<int_v>); runTest(testCount<uint_v>); runTest(testCount<float_v>); runTest(testCount<double_v>); runTest(testCount<short_v>); runTest(testCount<ushort_v>); runTest(testCount<sfloat_v>); runTest(testFirstOne<int_v>); runTest(testFirstOne<uint_v>); runTest(testFirstOne<float_v>); runTest(testFirstOne<double_v>); runTest(testFirstOne<short_v>); runTest(testFirstOne<ushort_v>); runTest(testFirstOne<sfloat_v>); #ifdef VC_IMPL_SSE runTest(testFloat8GatherMask); #endif return 0; } <commit_msg>simplify mask main a bit<commit_after>/* This file is part of the Vc library. Copyright (C) 2009 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Vc. If not, see <http://www.gnu.org/licenses/>. */ #include <Vc/Vc> #include "unittest.h" #include <iostream> #include "vectormemoryhelper.h" #include <cmath> using namespace Vc; template<typename Vec> void testInc() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); COMPARE(aa(m)++, a); COMPARE(aa, b); COMPARE(++a(m), b); COMPARE(a, b); } } template<typename Vec> void testDec() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 1); data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); COMPARE(aa(m)--, a); COMPARE(--a(m), b); COMPARE(a, b); COMPARE(aa, b); } } template<typename Vec> void testPlusEq() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 1); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) += static_cast<T>(2), b); COMPARE(a, b); } } template<typename Vec> void testMinusEq() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 2); data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) -= static_cast<T>(2), b); COMPARE(a, b); } } template<typename Vec> void testTimesEq() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) *= static_cast<T>(2), b); COMPARE(a, b); } } template<typename Vec> void testDivEq() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(5 * i); data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) /= static_cast<T>(3), b); COMPARE(a, b); } } template<typename Vec> void testAssign() { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; COMPARE(a(m) = b, b); COMPARE(a, b); } } template<typename Vec> void testZero() { typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; typedef typename Vec::IndexType I; for (int cut = 0; cut < Vec::Size; ++cut) { const Mask mask(I(Vc::IndexesFromZero) < cut); //std::cout << mask << std::endl; const T aa = 4; Vec a(aa); Vec b(Vc::Zero); b(!mask) = a; a.setZero(mask); COMPARE(a, b); } } template<typename Vec> void testCount() { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; typedef typename Vec::Mask M; for (int cut = 0; cut <= Vec::Size; ++cut) { const M mask(I(Vc::IndexesFromZero) < cut); //std::cout << mask << std::endl; COMPARE(mask.count(), cut); } } template<typename Vec> void testFirstOne() { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; typedef typename Vec::Mask M; for (int i = 0; i < Vec::Size; ++i) { const M mask(I(Vc::IndexesFromZero) == i); COMPARE(mask.firstOne(), i); } } #ifdef VC_IMPL_SSE void testFloat8GatherMask() { Memory<short_v, short_v::Size * 256> data; short_v::Memory andMemory; for (int i = 0; i < short_v::Size; ++i) { andMemory[i] = 1 << i; } const short_v andMask(andMemory); for (unsigned int i = 0; i < data.vectorsCount(); ++i) { data.vector(i) = andMask & i; } for (unsigned int i = 0; i < data.vectorsCount(); ++i) { const short_m mask = data.vector(i) == short_v::Zero(); SSE::Float8GatherMask gatherMaskA(mask), gatherMaskB(static_cast<sfloat_m>(mask)); COMPARE(gatherMaskA.toInt(), gatherMaskB.toInt()); } } #endif int main(int argc, char **argv) { initTest(argc, argv); testAllTypes(testInc); testAllTypes(testDec); testAllTypes(testPlusEq); testAllTypes(testMinusEq); testAllTypes(testTimesEq); testAllTypes(testDivEq); testAllTypes(testAssign); testAllTypes(testZero); testAllTypes(testCount); testAllTypes(testFirstOne); #ifdef VC_IMPL_SSE runTest(testFloat8GatherMask); #endif return 0; } <|endoftext|>
<commit_before>/* This file is part of the Vc library. {{{ Copyright (C) 2009-2013 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Vc. If not, see <http://www.gnu.org/licenses/>. }}}*/ #include "unittest.h" #include <iostream> #include "vectormemoryhelper.h" #include <cmath> using Vc::float_v; using Vc::double_v; using Vc::sfloat_v; using Vc::int_v; using Vc::uint_v; using Vc::short_v; using Vc::ushort_v; template<typename T> T two() { return T(2); } template<typename T> T three() { return T(3); } template<typename Vec> void testInc()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) {/*{{{*/ const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); COMPARE(aa(m)++, a) << ", border: " << border << ", m: " << m; COMPARE(aa, b) << ", border: " << border << ", m: " << m; COMPARE(++a(m), b) << ", border: " << border << ", m: " << m; COMPARE(a, b) << ", border: " << border << ", m: " << m; } /*}}}*/ for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); where(m)(aa)++; COMPARE(aa, b) << ", border: " << border << ", m: " << m; ++where(m)(a); COMPARE(a, b) << ", border: " << border << ", m: " << m; } } /*}}}*/ template<typename Vec> void testDec()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 1); data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); COMPARE(aa(m)--, a); COMPARE(aa, b); aa = a; where(m)(aa)--; COMPARE(aa, b); aa = a; --where(m)(aa); COMPARE(aa, b); COMPARE(--a(m), b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testPlusEq()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 1); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Vec c = a; Mask m = a < border; COMPARE(a(m) += two<T>(), b); COMPARE(a, b); where(m) | c += two<T>(); COMPARE(c, b); } } /*}}}*/ template<typename Vec> void testMinusEq()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 2); data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec c = a; where(m) | c -= two<T>(); COMPARE(c, b); COMPARE(a(m) -= two<T>(), b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testTimesEq()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec c = a; where(m) | c *= two<T>(); COMPARE(c, b); COMPARE(a(m) *= two<T>(), b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testDivEq()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(5 * i); data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec c = a; where(m) | c /= three<T>(); COMPARE(c, b); COMPARE(a(m) /= three<T>(), b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testAssign()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec c = a; where(m) | c = b; COMPARE(c, b); COMPARE(a(m) = b, b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testZero()/*{{{*/ { typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; typedef typename Vec::IndexType I; for (int cut = 0; cut < Vec::Size; ++cut) { const Mask mask(I(Vc::IndexesFromZero) < cut); //std::cout << mask << std::endl; const T aa = 4; Vec a(aa); Vec b(Vc::Zero); where(!mask) | b = a; a.setZero(mask); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testCount()/*{{{*/ { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; typedef typename Vec::Mask M; for_all_masks(Vec, m) { unsigned int count = 0; for (int i = 0; i < Vec::Size; ++i) { if (m[i]) { ++count; } } COMPARE(m.count(), count) << ", m = " << m; } } /*}}}*/ template<typename Vec> void testFirstOne()/*{{{*/ { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; typedef typename Vec::Mask M; for (unsigned int i = 0; i < Vec::Size; ++i) { const M mask(I(Vc::IndexesFromZero) == i); COMPARE(mask.firstOne(), i); } } /*}}}*/ #ifdef VC_IMPL_SSE void testFloat8GatherMask()/*{{{*/ { Vc::Memory<short_v, short_v::Size * 256> data; short_v::Memory andMemory; for (int i = 0; i < short_v::Size; ++i) { andMemory[i] = 1 << i; } const short_v andMask(andMemory); for (unsigned int i = 0; i < data.vectorsCount(); ++i) { data.vector(i) = andMask & i; } for (unsigned int i = 0; i < data.vectorsCount(); ++i) { const Vc::short_m mask = data.vector(i) == short_v::Zero(); Vc::SSE::Float8GatherMask gatherMaskA(mask), gatherMaskB(static_cast<Vc::sfloat_m>(mask)); COMPARE(gatherMaskA.toInt(), gatherMaskB.toInt()); } }/*}}}*/ #endif template<typename V> void maskInit()/*{{{*/ { typedef typename V::Mask M; COMPARE(M(Vc::One), M(true)); COMPARE(M(Vc::Zero), M(false)); } /*}}}*/ int main(int argc, char **argv)/*{{{*/ { initTest(argc, argv); testAllTypes(maskInit); testAllTypes(testInc); testAllTypes(testDec); testAllTypes(testPlusEq); testAllTypes(testMinusEq); testAllTypes(testTimesEq); testAllTypes(testDivEq); testAllTypes(testAssign); testAllTypes(testZero); testAllTypes(testCount); testAllTypes(testFirstOne); #ifdef VC_IMPL_SSE runTest(testFloat8GatherMask); #endif return 0; }/*}}}*/ // vim: foldmethod=marker <commit_msg>test all_of, any_of, none_of<commit_after>/* This file is part of the Vc library. {{{ Copyright (C) 2009-2013 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Vc. If not, see <http://www.gnu.org/licenses/>. }}}*/ #include "unittest.h" #include <iostream> #include "vectormemoryhelper.h" #include <cmath> using Vc::float_v; using Vc::double_v; using Vc::sfloat_v; using Vc::int_v; using Vc::uint_v; using Vc::short_v; using Vc::ushort_v; template<typename T> T two() { return T(2); } template<typename T> T three() { return T(3); } template<typename Vec> void testInc()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) {/*{{{*/ const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); COMPARE(aa(m)++, a) << ", border: " << border << ", m: " << m; COMPARE(aa, b) << ", border: " << border << ", m: " << m; COMPARE(++a(m), b) << ", border: " << border << ", m: " << m; COMPARE(a, b) << ", border: " << border << ", m: " << m; } /*}}}*/ for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); where(m)(aa)++; COMPARE(aa, b) << ", border: " << border << ", m: " << m; ++where(m)(a); COMPARE(a, b) << ", border: " << border << ", m: " << m; } } /*}}}*/ template<typename Vec> void testDec()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 1); data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec aa(a); COMPARE(aa(m)--, a); COMPARE(aa, b); aa = a; where(m)(aa)--; COMPARE(aa, b); aa = a; --where(m)(aa); COMPARE(aa, b); COMPARE(--a(m), b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testPlusEq()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 1); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Vec c = a; Mask m = a < border; COMPARE(a(m) += two<T>(), b); COMPARE(a, b); where(m) | c += two<T>(); COMPARE(c, b); } } /*}}}*/ template<typename Vec> void testMinusEq()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i + 2); data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec c = a; where(m) | c -= two<T>(); COMPARE(c, b); COMPARE(a(m) -= two<T>(), b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testTimesEq()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec c = a; where(m) | c *= two<T>(); COMPARE(c, b); COMPARE(a(m) *= two<T>(), b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testDivEq()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(5 * i); data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec c = a; where(m) | c /= three<T>(); COMPARE(c, b); COMPARE(a(m) /= three<T>(), b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testAssign()/*{{{*/ { VectorMemoryHelper<Vec> mem(2); typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; T *data = mem; for (int borderI = 0; borderI < Vec::Size; ++borderI) { const T border = static_cast<T>(borderI); for (int i = 0; i < Vec::Size; ++i) { data[i] = static_cast<T>(i); data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0); } Vec a(&data[0]); Vec b(&data[Vec::Size]); Mask m = a < border; Vec c = a; where(m) | c = b; COMPARE(c, b); COMPARE(a(m) = b, b); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testZero()/*{{{*/ { typedef typename Vec::EntryType T; typedef typename Vec::Mask Mask; typedef typename Vec::IndexType I; for (int cut = 0; cut < Vec::Size; ++cut) { const Mask mask(I(Vc::IndexesFromZero) < cut); //std::cout << mask << std::endl; const T aa = 4; Vec a(aa); Vec b(Vc::Zero); where(!mask) | b = a; a.setZero(mask); COMPARE(a, b); } } /*}}}*/ template<typename Vec> void testCount()/*{{{*/ { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; typedef typename Vec::Mask M; for_all_masks(Vec, m) { unsigned int count = 0; for (int i = 0; i < Vec::Size; ++i) { if (m[i]) { ++count; } } COMPARE(m.count(), count) << ", m = " << m; } } /*}}}*/ template<typename Vec> void testFirstOne()/*{{{*/ { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; typedef typename Vec::Mask M; for (unsigned int i = 0; i < Vec::Size; ++i) { const M mask(I(Vc::IndexesFromZero) == i); COMPARE(mask.firstOne(), i); } } /*}}}*/ #ifdef VC_IMPL_SSE void testFloat8GatherMask()/*{{{*/ { Vc::Memory<short_v, short_v::Size * 256> data; short_v::Memory andMemory; for (int i = 0; i < short_v::Size; ++i) { andMemory[i] = 1 << i; } const short_v andMask(andMemory); for (unsigned int i = 0; i < data.vectorsCount(); ++i) { data.vector(i) = andMask & i; } for (unsigned int i = 0; i < data.vectorsCount(); ++i) { const Vc::short_m mask = data.vector(i) == short_v::Zero(); Vc::SSE::Float8GatherMask gatherMaskA(mask), gatherMaskB(static_cast<Vc::sfloat_m>(mask)); COMPARE(gatherMaskA.toInt(), gatherMaskB.toInt()); } }/*}}}*/ #endif template<typename V> void maskReductions() { for_all_masks(V, mask) { COMPARE(all_of(mask), mask.count() == V::Size); if (mask.count() > 0) { VERIFY(any_of(mask)); VERIFY(!none_of(mask)); } else { VERIFY(!any_of(mask)); VERIFY(none_of(mask)); } } } template<typename V> void maskInit()/*{{{*/ { typedef typename V::Mask M; COMPARE(M(Vc::One), M(true)); COMPARE(M(Vc::Zero), M(false)); } /*}}}*/ int main(int argc, char **argv)/*{{{*/ { initTest(argc, argv); testAllTypes(maskInit); testAllTypes(testInc); testAllTypes(testDec); testAllTypes(testPlusEq); testAllTypes(testMinusEq); testAllTypes(testTimesEq); testAllTypes(testDivEq); testAllTypes(testAssign); testAllTypes(testZero); testAllTypes(testCount); testAllTypes(testFirstOne); testAllTypes(maskReductions); #ifdef VC_IMPL_SSE runTest(testFloat8GatherMask); #endif return 0; }/*}}}*/ // vim: foldmethod=marker <|endoftext|>
<commit_before>/* Used to calculate the m-dimension submatrices used in the Four Russians algorithm. Each submatrix is calculated like a Wagner-Fischer edit matrix with cells as follows: - (i-1, j-1) to (i, j) with +1 score added if the characters at (i, j) match, 0 otherwise - (i-1, j) to (i, j) with -1 score added - (i, j-1) to (i, j) with -1 score added Notes: The strings start with a space because the (0, x) and (x, 0) fields refer to one string being empty. The scores are not directly stored, they're converted to step vectors as per the Four Russians algorithm. */ #include <cstdio> #include <iostream> #include <vector> #include <map> #include <cmath> using namespace std; class SubmatrixCalculator{ public: SubmatrixCalculator(int _dimension, int _alphabet){ this->dimension = _dimension; this->alphabet = _alphabet; this->initialSteps.reserve(pow(3, _dimension)); this->initialStrings.reserve(pow(_alphabet, _dimension)); } map<string, string> calculate(){ generateInitialSteps(0, ""); generateInitialStrings(0, " "); // all possible initial steps and strings combinations for (int strA = 0; strA < initialStrings.size(); strA++){ for (int strB = 0; strB < initialStrings.size(); strB++){ for (int stepC = 0; stepC < initialSteps.size(); stepC++){ for (int stepD = 0; stepD < initialSteps.size(); stepD++){ // TODO calculate results } } } } return this->results; } x finalSteps(string, string, string, string){ } string stepsToString(vector<int> steps){ string ret = ""; ret.reserve(steps.size()); for (int i = 0; i < steps.size(); i++) ret += steps[i] + '1'; return ret; } string stepsToPrettyString(string steps){ string ret = ""; for (int i = 0; i < steps.size(); i++){ if (steps[i] == '0') ret += "-1 "; else if (steps[i] == '2') ret += "+1 "; else ret += "0 "; } return ret; } // DEBUG void printDebug(){ for (int i=0; i<initialSteps.size(); i++) cout << stepsToPrettyString(initialSteps[i]) << endl; for (int i=0; i<initialStrings.size(); i++) cout << initialStrings[i] << endl; } private: // TODO: first step has to be 0? void generateInitialSteps(int pos, string currStep){ if (pos == this->dimension){ initialSteps.push_back(currStep); return; } for (int i=-1; i<=1; i++){ string tmp = currStep; tmp.push_back('1' + i); generateInitialSteps(pos + 1, tmp); } } void generateInitialStrings(int pos, string currString){ if (pos == this->dimension){ initialStrings.push_back(currString); return; } for (int i=0; i<this->alphabet; i++){ string tmp = currString; tmp.push_back('a' + i); generateInitialStrings(pos + 1, tmp); } } int dimension; int alphabet; // ['a', 'a' + alphabet> vector<string> initialSteps; vector<string> initialStrings; map<string, string> results; }; int main() { SubmatrixCalculator calc(4, 4); calc.calculate(); //calc.printDebug(); return 0; } <commit_msg>Added vector/string handling, unfinished matrix calculation<commit_after>/* Used to calculate the m-dimension submatrices used in the Four Russians algorithm. Each submatrix is calculated like a Wagner-Fischer edit matrix with cells as follows: - (i-1, j-1) to (i, j) with +1 score added if the characters at (i, j) match, 0 otherwise - (i-1, j) to (i, j) with -1 score added - (i, j-1) to (i, j) with -1 score added Notes: The strings start with a space because the (0, x) and (x, 0) fields refer to one string being empty. The scores are not directly stored, they're converted to step vectors as per the Four Russians algorithm. */ #include <cstdio> #include <iostream> #include <vector> #include <map> #include <cmath> using namespace std; class SubmatrixCalculator { public: SubmatrixCalculator(int _dimension, int _alphabet) { this->dimension = _dimension; this->alphabet = _alphabet; this->initialSteps.reserve(pow(3, _dimension)); this->initialStrings.reserve(pow(_alphabet, _dimension)); } void calculate() { printf("Clearing the submatrix data...\n"); results.clear(); generateInitialSteps(0, ""); generateInitialStrings(0, " "); // all possible initial steps and strings combinations for (int strA = 0; strA < initialStrings.size(); strA++) { for (int strB = 0; strB < initialStrings.size(); strB++) { for (int stepC = 0; stepC < initialSteps.size(); stepC++) { for (int stepD = 0; stepD < initialSteps.size(); stepD++) { pair<string, string> finalSteps = calculateFinalSteps(initialStrings[strA], initialStrings[strB], initialSteps[stepC], initialSteps[stepD]); results[initialStrings[strA] + initialStrings[strB] + initialSteps[stepC] + initialSteps[stepD]] = finalSteps.first + finalSteps.second; } } } } } vector<int, int> calculateSubmatrix(string strLeft, string strTop, string stepLeft, string stepTop){ vector<int> leftSteps = stepsToVector(stepLeft); vector<int> topSteps = stepsToVector(stepTop); //TODO } /* Args: left string, top string, left steps, top steps Returns: bottom steps, right steps */ pair<string, string> getFinalSteps(string strLeft, string strTop, string stepLeft, string stepTop) { string resultingSteps = results[strLeft + strTop + stepLeft + stepTop]; return make_pair( resultingSteps.substr(0, resultingSteps.size() / 2), resultingSteps.substr(resultingSteps.size() / 2, npos)); } static string stepsToString(vector<int> steps) { string ret = ""; ret.reserve(steps.size()); for (int i = 0; i < steps.size(); i++) ret += steps[i] + '1'; return ret; } static vector<int> stepsToVector(string steps){ vector<int> ret; ret.reserve(steps.size()); for (int i = 0; i < steps.size(); i++) ret.push_back(steps[i] - '1'); return ret; } static string stepsToPrettyString(string steps) { string ret = ""; for (int i = 0; i < steps.size(); i++) { if (steps[i] == '0') ret += "-1 "; else if (steps[i] == '2') ret += "+1 "; else ret += "0 "; } return ret; } private: pair<string, string> calculateFinalSteps(string strLeft, string strTop, string stepLeft, string stepTop) { vector<int, int> stepMatrix = calculateSubmatrix(strLeft, strTop, stepLeft, stepTop); vector<int> stepBot; stepBot.reserve(this->dimension); for (int i = 0; i < this->dimension; i++) stepBot.push_back(stepMatrix[this->dimension - 1][i]); vector<int> stepRight; stepRight.reserve(this->dimension); for (int i = 0; i < this->dimension; i++) stepRight.push_back(stepMatrix[i][this->dimension - 1]); return make_pair(stepsToString(stepBot), stepsToString(stepRight)); } // TODO: first step has to be 0? void generateInitialSteps(int pos, string currStep) { if (pos == this->dimension) { initialSteps.push_back(currStep); return; } for (int i = -1; i <= 1; i++) { string tmp = currStep; tmp.push_back('1' + i); generateInitialSteps(pos + 1, tmp); } } void generateInitialStrings(int pos, string currString) { if (pos == this->dimension) { initialStrings.push_back(currString); return; } for (int i = 0; i < this->alphabet; i++) { string tmp = currString; tmp.push_back('a' + i); generateInitialStrings(pos + 1, tmp); } } // DEBUG void printDebug() { for (int i = 0; i < initialSteps.size(); i++) cout << stepsToPrettyString(initialSteps[i]) << endl; for (int i = 0; i < initialStrings.size(); i++) cout << initialStrings[i] << endl; } int dimension; int alphabet; // ['a', 'a' + alphabet> vector<string> initialSteps; vector<string> initialStrings; map<string, string> results; }; int main() { SubmatrixCalculator calc(4, 4); calc.calculate(); //calc.printDebug(); return 0; } <|endoftext|>
<commit_before>#include "cnn/hsm-builder.h" #include <fstream> #include <iostream> using namespace std; namespace cnn { using namespace expr; HierarchicalSoftmaxBuilder::HierarchicalSoftmaxBuilder(unsigned rep_dim, const std::string& cluster_file, Dict* word_dict, Model* model) { ReadClusterFile(cluster_file, word_dict); const unsigned num_clusters = cdict.size(); p_r2c = model->add_parameters({num_clusters, rep_dim}); p_cbias = model->add_parameters({num_clusters}); p_rc2ws.resize(num_clusters); p_rcwbiases.resize(num_clusters); for (unsigned i = 0; i < num_clusters; ++i) { auto& words = cidx2words[i]; // vector of word ids const unsigned num_words_in_cluster = words.size(); p_rc2ws[i] = model->add_parameters({num_words_in_cluster, rep_dim}); p_rcwbiases[i] = model->add_parameters({num_words_in_cluster}); } } void HierarchicalSoftmaxBuilder::new_graph(ComputationGraph& cg) { pcg = &cg; const unsigned num_clusters = cdict.size(); r2c = parameter(cg, p_r2c); cbias = parameter(cg, p_cbias); rc2ws.clear(); rc2biases.clear(); rc2ws.resize(num_clusters); rc2biases.resize(num_clusters); } Expression HierarchicalSoftmaxBuilder::neg_log_softmax(const Expression& rep, unsigned wordidx) { int clusteridx = widx2cidx[wordidx]; assert(clusteridx >= 0); // if this fails, wordid is missing from clusters Expression cscores = affine_transform({cbias, r2c, rep}); Expression cnlp = pickneglogsoftmax(cscores, clusteridx); if (singleton_cluster[clusteridx]) return cnlp; // if there is only one word in the cluster, just return -log p(class | rep) // otherwise predict word too unsigned wordrow = widx2cwidx[wordidx]; Expression& cwbias = get_rc2wbias(clusteridx); Expression& r2cw = get_rc2w(clusteridx); Expression wscores = affine_transform({cwbias, r2cw, rep}); Expression wnlp = pickneglogsoftmax(wscores, wordrow); return cnlp + wnlp; } inline bool is_ws(char x) { return (x == ' ' || x == '\t'); } inline bool not_ws(char x) { return (x != ' ' && x != '\t'); } void HierarchicalSoftmaxBuilder::ReadClusterFile(const std::string& cluster_file, Dict* word_dict) { cerr << "Reading clusters from " << cluster_file << " ...\n"; ifstream in(cluster_file); assert(in); int wc = 0; string line; while(getline(in, line)) { ++wc; const unsigned len = line.size(); unsigned startc = 0; while (is_ws(line[startc]) && startc < len) { ++startc; } unsigned endc = startc; while (not_ws(line[endc]) && endc < len) { ++endc; } unsigned startw = endc; while (is_ws(line[startw]) && startw < len) { ++startw; } unsigned endw = startw; while (not_ws(line[endw]) && endw < len) { ++endw; } assert(endc > startc); assert(startw > endc); assert(endw > startw); unsigned c = cdict.Convert(line.substr(startc, endc - startc)); unsigned word = word_dict->Convert(line.substr(startw, endw - startw)); if (word >= widx2cidx.size()) { widx2cidx.resize(word + 1, -1); widx2cwidx.resize(word + 1); } widx2cidx[word] = c; if (c >= cidx2words.size()) cidx2words.resize(c + 1); auto& clusterwords = cidx2words[c]; widx2cwidx[word] = clusterwords.size(); clusterwords.push_back(word); } singleton_cluster.resize(cidx2words.size()); int scs = 0; for (unsigned i = 0; i < cidx2words.size(); ++i) { bool sc = cidx2words[i].size() <= 1; if (sc) scs++; singleton_cluster[i] = sc; } cerr << "Read " << wc << " words in " << cdict.size() << " clusters (" << scs << " singleton clusters)\n"; } } // namespace cnn <commit_msg>only create necessary params<commit_after>#include "cnn/hsm-builder.h" #include <fstream> #include <iostream> using namespace std; namespace cnn { using namespace expr; HierarchicalSoftmaxBuilder::HierarchicalSoftmaxBuilder(unsigned rep_dim, const std::string& cluster_file, Dict* word_dict, Model* model) { ReadClusterFile(cluster_file, word_dict); const unsigned num_clusters = cdict.size(); p_r2c = model->add_parameters({num_clusters, rep_dim}); p_cbias = model->add_parameters({num_clusters}); p_rc2ws.resize(num_clusters); p_rcwbiases.resize(num_clusters); for (unsigned i = 0; i < num_clusters; ++i) { auto& words = cidx2words[i]; // vector of word ids const unsigned num_words_in_cluster = words.size(); if (num_words_in_cluster > 1) { // for singleton clusters, we don't need these parameters, so // we don't create them p_rc2ws[i] = model->add_parameters({num_words_in_cluster, rep_dim}); p_rcwbiases[i] = model->add_parameters({num_words_in_cluster}); } } } void HierarchicalSoftmaxBuilder::new_graph(ComputationGraph& cg) { pcg = &cg; const unsigned num_clusters = cdict.size(); r2c = parameter(cg, p_r2c); cbias = parameter(cg, p_cbias); rc2ws.clear(); rc2biases.clear(); rc2ws.resize(num_clusters); rc2biases.resize(num_clusters); } Expression HierarchicalSoftmaxBuilder::neg_log_softmax(const Expression& rep, unsigned wordidx) { int clusteridx = widx2cidx[wordidx]; assert(clusteridx >= 0); // if this fails, wordid is missing from clusters Expression cscores = affine_transform({cbias, r2c, rep}); Expression cnlp = pickneglogsoftmax(cscores, clusteridx); if (singleton_cluster[clusteridx]) return cnlp; // if there is only one word in the cluster, just return -log p(class | rep) // otherwise predict word too unsigned wordrow = widx2cwidx[wordidx]; Expression& cwbias = get_rc2wbias(clusteridx); Expression& r2cw = get_rc2w(clusteridx); Expression wscores = affine_transform({cwbias, r2cw, rep}); Expression wnlp = pickneglogsoftmax(wscores, wordrow); return cnlp + wnlp; } inline bool is_ws(char x) { return (x == ' ' || x == '\t'); } inline bool not_ws(char x) { return (x != ' ' && x != '\t'); } void HierarchicalSoftmaxBuilder::ReadClusterFile(const std::string& cluster_file, Dict* word_dict) { cerr << "Reading clusters from " << cluster_file << " ...\n"; ifstream in(cluster_file); assert(in); int wc = 0; string line; while(getline(in, line)) { ++wc; const unsigned len = line.size(); unsigned startc = 0; while (is_ws(line[startc]) && startc < len) { ++startc; } unsigned endc = startc; while (not_ws(line[endc]) && endc < len) { ++endc; } unsigned startw = endc; while (is_ws(line[startw]) && startw < len) { ++startw; } unsigned endw = startw; while (not_ws(line[endw]) && endw < len) { ++endw; } assert(endc > startc); assert(startw > endc); assert(endw > startw); unsigned c = cdict.Convert(line.substr(startc, endc - startc)); unsigned word = word_dict->Convert(line.substr(startw, endw - startw)); if (word >= widx2cidx.size()) { widx2cidx.resize(word + 1, -1); widx2cwidx.resize(word + 1); } widx2cidx[word] = c; if (c >= cidx2words.size()) cidx2words.resize(c + 1); auto& clusterwords = cidx2words[c]; widx2cwidx[word] = clusterwords.size(); clusterwords.push_back(word); } singleton_cluster.resize(cidx2words.size()); int scs = 0; for (unsigned i = 0; i < cidx2words.size(); ++i) { bool sc = cidx2words[i].size() <= 1; if (sc) scs++; singleton_cluster[i] = sc; } cerr << "Read " << wc << " words in " << cdict.size() << " clusters (" << scs << " singleton clusters)\n"; } } // namespace cnn <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /////////////////////////////////////////////////////////////////////////////// // // // class for T0 calibration TM-AC-AM_6-02-2006 // equalize time shift for each time CFD channel // // /////////////////////////////////////////////////////////////////////////////// #include "AliT0CalibTimeEq.h" #include "AliLog.h" #include <TFile.h> #include <TMath.h> #include <TF1.h> #include <TSpectrum.h> #include <TProfile.h> #include <iostream> ClassImp(AliT0CalibTimeEq) //________________________________________________________________ AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(), fMeanVertex(0), fRmsVertex(0) { // } //________________________________________________________________ AliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(), fMeanVertex(0), fRmsVertex(0) { //constructor TString namst = "Calib_"; namst += name; SetName(namst.Data()); SetTitle(namst.Data()); } //________________________________________________________________ AliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda), fMeanVertex(0), fRmsVertex(0) { // copy constructor SetName(calibda.GetName()); SetTitle(calibda.GetName()); } //________________________________________________________________ AliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda) { // assignment operator SetName(calibda.GetName()); SetTitle(calibda.GetName()); return *this; } //________________________________________________________________ AliT0CalibTimeEq::~AliT0CalibTimeEq() { // // destrictor } //________________________________________________________________ void AliT0CalibTimeEq::Reset() { //reset values memset(fCFDvalue,0,120*sizeof(Float_t)); memset(fTimeEq,1,24*sizeof(Float_t)); } //________________________________________________________________ void AliT0CalibTimeEq::Print(Option_t*) const { // print time values printf("\n ---- PM Arrays ----\n\n"); printf(" Time delay CFD \n"); for (Int_t i=0; i<24; i++) printf(" CFD %f ",fTimeEq[i]); printf("\n Mean Vertex %f \n", fMeanVertex); } //________________________________________________________________ Bool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys) { // compute online equalized time Float_t meandiff, sigmadiff, meanver, meancfdtime, sigmacfdtime; meandiff = sigmadiff = meanver = meancfdtime = sigmacfdtime =0; // Double_t rms=0, rmscfd=0; Double_t rmsver=0; Int_t nent=0; Bool_t ok=false; gFile = TFile::Open(filePhys); if(!gFile) { AliError("No input PHYS data found "); } else { // gFile->ls(); ok=true; for (Int_t i=0; i<24; i++) { TH1F *cfd = (TH1F*) gFile->Get(Form("CFD1minCFD%d",i+1)); TH1F *cfdtime = (TH1F*) gFile->Get(Form("CFD%d",i+1)); if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i)); // printf(" i = %d buf1 = %s\n", i, buf1); if(cfd) { GetMeanAndSigma(cfd, meandiff, sigmadiff); nent=cfd->GetEntries(); if(nent<500 || cfd->GetRMS()>20. ) { ok=false; AliWarning(Form("Data is not good enouph in PMT %i - mean %f rsm %f nentries %i", i,meandiff,sigmadiff , nent)); } else { ok=false; AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i)); } if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i)); } // printf(" i = %d buf1 = %s\n", i, buf1); if(cfdtime) { GetMeanAndSigma(cfdtime,meancfdtime, sigmacfdtime); nent=cfdtime->GetEntries(); if(nent<500 || sigmacfdtime>30. ) { ok=false; AliWarning(Form("Data is not good enouph in PMT %i CFD data - meancfdtime %f rsm %f nentries %i", i,meancfdtime, sigmacfdtime, nent)); } } else { ok=false; AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i)); } SetTimeEq(i,meandiff); SetTimeEqRms(i,sigmadiff); SetCFDvalue(i,0,meancfdtime); SetCFDvalue(i,0,sigmacfdtime); if (cfd) delete cfd; if (cfdtime) delete cfdtime; } TH1F *ver = (TH1F*) gFile->Get("hVertex"); if(!ver) AliWarning("no T0 histogram collected by PHYS DA "); if(ver) { meanver = ver->GetMean(); rmsver = ver->GetRMS(); } SetMeanVertex(meanver); SetRmsVertex(rmsver); gFile->Close(); delete gFile; } return ok; } //________________________________________________________________ Bool_t AliT0CalibTimeEq::ComputeOfflineParams(const char* filePhys) { // compute online equalized time Float_t meandiff, sigmadiff, meanver, meancfdtime, sigmacfdtime; meandiff = sigmadiff = meanver = meancfdtime = sigmacfdtime =0; // Double_t rms=0, rmscfd=0; Double_t rmsver=0; Int_t nent=0; Bool_t ok=false; gFile = TFile::Open(filePhys); if(!gFile) { AliError("No input PHYS data found "); } else { // gFile->ls(); ok=true; TObjArray * TzeroObj = (TObjArray*) gFile->Get("fTzeroObject"); for (Int_t i=0; i<24; i++) { TH1F *cfddiff = (TH1F*)TzeroObj->At(i); TH1F *cfdtime = (TH1F*)TzeroObj->At(i+24); if(!cfddiff) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i)); // printf(" i = %d buf1 = %s\n", i, buf1); if(cfddiff) { GetMeanAndSigma(cfddiff,meandiff, sigmadiff); nent=cfddiff->GetEntries(); if(nent<500 || cfddiff->GetRMS()>20. ) { ok=false; AliWarning(Form("Data is not good enouph in PMT %i - mean %f rsm %f nentries %i", i,meandiff,sigmadiff, nent)); } else { ok=false; AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i)); } if(!cfdtime) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i)); // printf(" i = %d buf1 = %s\n", i, buf1); if(cfdtime) { GetMeanAndSigma(cfdtime,meancfdtime, sigmacfdtime); nent=cfdtime->GetEntries(); if(nent<500 || cfdtime->GetRMS()>30. ) { ok=false; AliWarning(Form("Data is not good enouph in PMT %i CFD data - mean %f rsm %f nentries %i", i,meancfdtime, sigmacfdtime, nent)); } } else { ok=false; AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i)); } } SetTimeEq(i,meandiff); SetTimeEqRms(i,sigmadiff); SetCFDvalue(i,0,meancfdtime); SetCFDvalue(i,0,sigmacfdtime); if (cfddiff) delete cfddiff; if (cfdtime) delete cfdtime; } TH1F *ver = (TH1F*) gFile->Get("hVertex"); if(!ver) AliWarning("no T0 histogram collected by PHYS DA "); if(ver) { meanver = ver->GetMean(); rmsver = ver->GetRMS(); } SetMeanVertex(meanver); SetRmsVertex(rmsver); gFile->Close(); delete gFile; } return ok; } //________________________________________________________________________ void AliT0CalibTimeEq::GetMeanAndSigma(TH1F* hist, Float_t &mean, Float_t &sigma) { const double window = 5.; //fit window double norm = hist->Integral(); // normalize to one count hist->Scale(1./norm); double meanEstimate, sigmaEstimate; int maxBin; maxBin = hist->GetMaximumBin(); //position of maximum meanEstimate = hist->GetBinCenter( maxBin); // mean of gaussian sitting in maximum sigmaEstimate = hist->GetRMS(); TF1* fit= new TF1("fit","gaus", meanEstimate - window*sigmaEstimate, meanEstimate + window*sigmaEstimate); fit->SetParameters(hist->GetBinContent(maxBin), meanEstimate, sigmaEstimate); hist->Fit("fit","R"); mean = (Float_t) fit->GetParameter(1); sigma = (Float_t) fit->GetParameter(2); delete fit; } <commit_msg>coverity warning fixed<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /////////////////////////////////////////////////////////////////////////////// // // // class for T0 calibration TM-AC-AM_6-02-2006 // equalize time shift for each time CFD channel // // /////////////////////////////////////////////////////////////////////////////// #include "AliT0CalibTimeEq.h" #include "AliLog.h" #include <TFile.h> #include <TMath.h> #include <TF1.h> #include <TSpectrum.h> #include <TProfile.h> #include <iostream> ClassImp(AliT0CalibTimeEq) //________________________________________________________________ AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(), fMeanVertex(0), fRmsVertex(0) { // } //________________________________________________________________ AliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(), fMeanVertex(0), fRmsVertex(0) { //constructor TString namst = "Calib_"; namst += name; SetName(namst.Data()); SetTitle(namst.Data()); } //________________________________________________________________ AliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda), fMeanVertex(0), fRmsVertex(0) { // copy constructor SetName(calibda.GetName()); SetTitle(calibda.GetName()); } //________________________________________________________________ AliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda) { // assignment operator SetName(calibda.GetName()); SetTitle(calibda.GetName()); return *this; } //________________________________________________________________ AliT0CalibTimeEq::~AliT0CalibTimeEq() { // // destrictor } //________________________________________________________________ void AliT0CalibTimeEq::Reset() { //reset values memset(fCFDvalue,0,120*sizeof(Float_t)); memset(fTimeEq,1,24*sizeof(Float_t)); } //________________________________________________________________ void AliT0CalibTimeEq::Print(Option_t*) const { // print time values printf("\n ---- PM Arrays ----\n\n"); printf(" Time delay CFD \n"); for (Int_t i=0; i<24; i++) printf(" CFD %f ",fTimeEq[i]); printf("\n Mean Vertex %f \n", fMeanVertex); } //________________________________________________________________ Bool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys) { // compute online equalized time Float_t meandiff, sigmadiff, meanver, meancfdtime, sigmacfdtime; meandiff = sigmadiff = meanver = meancfdtime = sigmacfdtime =0; // Double_t rms=0, rmscfd=0; Double_t rmsver=0; Int_t nent=0; Bool_t ok=false; gFile = TFile::Open(filePhys); if(!gFile) { AliError("No input PHYS data found "); } else { // gFile->ls(); ok=true; for (Int_t i=0; i<24; i++) { TH1F *cfd = (TH1F*) gFile->Get(Form("CFD1minCFD%d",i+1)); TH1F *cfdtime = (TH1F*) gFile->Get(Form("CFD%d",i+1)); if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i)); // printf(" i = %d buf1 = %s\n", i, buf1); if(cfd) { GetMeanAndSigma(cfd, meandiff, sigmadiff); nent = Int_t(cfd->GetEntries()); if(nent<500 || cfd->GetRMS()>20. ) { ok=false; AliWarning(Form("Data is not good enouph in PMT %i - mean %f rsm %f nentries %i", i,meandiff,sigmadiff , nent)); } else { ok=false; AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i)); } if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i)); } // printf(" i = %d buf1 = %s\n", i, buf1); if(cfdtime) { GetMeanAndSigma(cfdtime,meancfdtime, sigmacfdtime); nent = Int_t(cfdtime->GetEntries()); if(nent<500 || sigmacfdtime>30. ) { ok=false; AliWarning(Form("Data is not good enouph in PMT %i CFD data - meancfdtime %f rsm %f nentries %i", i,meancfdtime, sigmacfdtime, nent)); } } else { ok=false; AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i)); } SetTimeEq(i,meandiff); SetTimeEqRms(i,sigmadiff); SetCFDvalue(i,0,meancfdtime); SetCFDvalue(i,0,sigmacfdtime); if (cfd) delete cfd; if (cfdtime) delete cfdtime; } TH1F *ver = (TH1F*) gFile->Get("hVertex"); if(!ver) AliWarning("no T0 histogram collected by PHYS DA "); if(ver) { meanver = ver->GetMean(); rmsver = ver->GetRMS(); } SetMeanVertex(meanver); SetRmsVertex(rmsver); gFile->Close(); delete gFile; } return ok; } //________________________________________________________________ Bool_t AliT0CalibTimeEq::ComputeOfflineParams(const char* filePhys) { // compute online equalized time Float_t meandiff, sigmadiff, meanver, meancfdtime, sigmacfdtime; meandiff = sigmadiff = meanver = meancfdtime = sigmacfdtime =0; // Double_t rms=0, rmscfd=0; Double_t rmsver=0; Int_t nent=0; Bool_t ok=false; gFile = TFile::Open(filePhys); if(!gFile) { AliError("No input PHYS data found "); } else { // gFile->ls(); ok=true; TObjArray * TzeroObj = (TObjArray*) gFile->Get("fTzeroObject"); for (Int_t i=0; i<24; i++) { TH1F *cfddiff = (TH1F*)TzeroObj->At(i); TH1F *cfdtime = (TH1F*)TzeroObj->At(i+24); if(!cfddiff) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i)); // printf(" i = %d buf1 = %s\n", i, buf1); if(cfddiff) { GetMeanAndSigma(cfddiff,meandiff, sigmadiff); nent = Int_t(cfddiff->GetEntries()); if(nent<500 || cfddiff->GetRMS()>20. ) { ok=false; AliWarning(Form("Data is not good enouph in PMT %i - mean %f rsm %f nentries %i", i,meandiff,sigmadiff, nent)); } else { ok=false; AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i)); } if(!cfdtime) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i)); // printf(" i = %d buf1 = %s\n", i, buf1); if(cfdtime) { GetMeanAndSigma(cfdtime,meancfdtime, sigmacfdtime); nent = Int_t(cfdtime->GetEntries()); if(nent<500 || cfdtime->GetRMS()>30. ) { ok=false; AliWarning(Form("Data is not good enouph in PMT %i CFD data - mean %f rsm %f nentries %i", i,meancfdtime, sigmacfdtime, nent)); } } else { ok=false; AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i)); } } SetTimeEq(i,meandiff); SetTimeEqRms(i,sigmadiff); SetCFDvalue(i,0,meancfdtime); SetCFDvalue(i,0,sigmacfdtime); if (cfddiff) delete cfddiff; if (cfdtime) delete cfdtime; } TH1F *ver = (TH1F*) gFile->Get("hVertex"); if(!ver) AliWarning("no T0 histogram collected by PHYS DA "); if(ver) { meanver = ver->GetMean(); rmsver = ver->GetRMS(); } SetMeanVertex(meanver); SetRmsVertex(rmsver); gFile->Close(); delete gFile; } return ok; } //________________________________________________________________________ void AliT0CalibTimeEq::GetMeanAndSigma(TH1F* hist, Float_t &mean, Float_t &sigma) { const double window = 5.; //fit window double norm = hist->Integral(); // normalize to one count hist->Scale(1./norm); double meanEstimate, sigmaEstimate; int maxBin; maxBin = hist->GetMaximumBin(); //position of maximum meanEstimate = hist->GetBinCenter( maxBin); // mean of gaussian sitting in maximum sigmaEstimate = hist->GetRMS(); TF1* fit= new TF1("fit","gaus", meanEstimate - window*sigmaEstimate, meanEstimate + window*sigmaEstimate); fit->SetParameters(hist->GetBinContent(maxBin), meanEstimate, sigmaEstimate); hist->Fit("fit","R"); mean = (Float_t) fit->GetParameter(1); sigma = (Float_t) fit->GetParameter(2); delete fit; } <|endoftext|>
<commit_before>/* We rely on wrapped syscalls */ #include "libEpollFuzzer/epoll_fuzzer.h" #include "App.h" /* We keep this one for teardown later on */ struct us_listen_socket_t *listen_socket; struct us_socket_t *client; /* This test is run by libEpollFuzzer */ void test() { /* ws->getUserData returns one of these */ struct PerSocketData { /* Fill with user data */ }; { /* Keep in mind that uWS::SSLApp({options}) is the same as uWS::App() when compiled without SSL support. * You may swap to using uWS:App() if you don't need SSL */ auto app = uWS::App({ /* There are example certificates in uWebSockets.js repo */ .key_file_name = "../misc/key.pem", .cert_file_name = "../misc/cert.pem", .passphrase = "1234" }).ws<PerSocketData>("/*", { /* Settings */ .compression = uWS::SHARED_COMPRESSOR, .maxPayloadLength = 16 * 1024, .idleTimeout = 10, .maxBackpressure = 1 * 1024 * 1024, /* Handlers */ .open = [](auto *ws) { /* Open event here, you may access ws->getUserData() which points to a PerSocketData struct */ ws->getNativeHandle(); ws->getRemoteAddressAsText(); us_poll_ext((struct us_poll_t *) ws); }, .message = [](auto *ws, std::string_view message, uWS::OpCode opCode) { ws->send(message, opCode, true); }, .drain = [](auto *ws) { /* Check ws->getBufferedAmount() here */ }, .ping = [](auto *ws) { /* We use this to trigger the async/wakeup feature */ uWS::Loop::get()->defer([]() { /* Do nothing */ }); }, .pong = [](auto *ws) { /* Not implemented yet */ }, .close = [](auto *ws, int code, std::string_view message) { /* You may access ws->getUserData() here */ } }).listen(9001, [](auto *listenSocket) { listen_socket = listenSocket; }); /* Here we want to stress the connect feature, since nothing else stresses it */ struct us_loop_t *loop = (struct us_loop_t *) uWS::Loop::get(); /* This function is stupid */ us_loop_iteration_number(loop); struct us_socket_context_t *client_context = us_create_socket_context(0, loop, 0, {}); client = us_socket_context_connect(0, client_context, "hostname", 5000, "localhost", 0, 0); us_socket_context_on_connect_error(0, client_context, [](struct us_socket_t *s, int code) { client = nullptr; return s; }); us_socket_context_on_open(0, client_context, [](struct us_socket_t *s, int is_client, char *ip, int ip_length) { us_socket_flush(0, s); return s; }); us_socket_context_on_end(0, client_context, [](struct us_socket_t *s) { return s; }); us_socket_context_on_data(0, client_context, [](struct us_socket_t *s, char *data, int length) { return s; }); us_socket_context_on_writable(0, client_context, [](struct us_socket_t *s) { return s; }); us_socket_context_on_close(0, client_context, [](struct us_socket_t *s, int code, void *reason) { client = NULL; return s; }); /* Trigger some context functions */ app.addServerName("", {}); app.removeServerName(""); app.missingServerName(nullptr); app.getNativeHandle(); app.run(); /* After done we also free the client context */ us_socket_context_free(0, client_context); } uWS::Loop::get()->free(); } /* Thus function should shutdown the event-loop and let the test fall through */ void teardown() { /* If we are called twice there's a bug (it potentially could if * all open sockets cannot be error-closed in one epoll_wait call). * But we only allow 1k FDs and we have a buffer of 1024 from epoll_wait */ if (!listen_socket && !client) { exit(-1); } if (client) { us_socket_close(0, client, 0, 0); client = NULL; } /* We might have open sockets still, and these will be error-closed by epoll_wait */ // us_socket_context_close - close all open sockets created with this socket context if (listen_socket) { us_listen_socket_close(0, listen_socket); listen_socket = NULL; } } <commit_msg>Update EpollHelloWorld.cpp<commit_after>/* We rely on wrapped syscalls */ #include "libEpollFuzzer/epoll_fuzzer.h" #include "App.h" /* We keep this one for teardown later on */ struct us_listen_socket_t *listen_socket; struct us_socket_t *client; /* This test is run by libEpollFuzzer */ void test() { /* ws->getUserData returns one of these */ struct PerSocketData { /* Fill with user data */ }; { /* Keep in mind that uWS::SSLApp({options}) is the same as uWS::App() when compiled without SSL support. * You may swap to using uWS:App() if you don't need SSL */ auto app = uWS::App({ /* There are example certificates in uWebSockets.js repo */ .key_file_name = "../misc/key.pem", .cert_file_name = "../misc/cert.pem", .passphrase = "1234" }).ws<PerSocketData>("/*", { /* Settings */ .compression = uWS::SHARED_COMPRESSOR, .maxPayloadLength = 16 * 1024, .idleTimeout = 12, .maxBackpressure = 1024, /* Handlers */ .open = [](auto *ws) { /* Open event here, you may access ws->getUserData() which points to a PerSocketData struct */ ws->getNativeHandle(); ws->getRemoteAddressAsText(); us_poll_ext((struct us_poll_t *) ws); }, .message = [](auto *ws, std::string_view message, uWS::OpCode opCode) { ws->send(message, opCode, true); }, .drain = [](auto *ws) { /* Check ws->getBufferedAmount() here */ }, .ping = [](auto *ws) { /* We use this to trigger the async/wakeup feature */ uWS::Loop::get()->defer([]() { /* Do nothing */ }); }, .pong = [](auto *ws) { /* Not implemented yet */ }, .close = [](auto *ws, int code, std::string_view message) { /* You may access ws->getUserData() here */ } }).listen(9001, [](auto *listenSocket) { listen_socket = listenSocket; }); /* Here we want to stress the connect feature, since nothing else stresses it */ struct us_loop_t *loop = (struct us_loop_t *) uWS::Loop::get(); /* This function is stupid */ us_loop_iteration_number(loop); struct us_socket_context_t *client_context = us_create_socket_context(0, loop, 0, {}); client = us_socket_context_connect(0, client_context, "hostname", 5000, "localhost", 0, 0); us_socket_context_on_connect_error(0, client_context, [](struct us_socket_t *s, int code) { client = nullptr; return s; }); us_socket_context_on_open(0, client_context, [](struct us_socket_t *s, int is_client, char *ip, int ip_length) { us_socket_flush(0, s); return s; }); us_socket_context_on_end(0, client_context, [](struct us_socket_t *s) { return s; }); us_socket_context_on_data(0, client_context, [](struct us_socket_t *s, char *data, int length) { return s; }); us_socket_context_on_writable(0, client_context, [](struct us_socket_t *s) { return s; }); us_socket_context_on_close(0, client_context, [](struct us_socket_t *s, int code, void *reason) { client = NULL; return s; }); /* Trigger some context functions */ app.addServerName("", {}); app.removeServerName(""); app.missingServerName(nullptr); app.getNativeHandle(); app.run(); /* After done we also free the client context */ us_socket_context_free(0, client_context); } uWS::Loop::get()->free(); } /* Thus function should shutdown the event-loop and let the test fall through */ void teardown() { /* If we are called twice there's a bug (it potentially could if * all open sockets cannot be error-closed in one epoll_wait call). * But we only allow 1k FDs and we have a buffer of 1024 from epoll_wait */ if (!listen_socket && !client) { exit(-1); } if (client) { us_socket_close(0, client, 0, 0); client = NULL; } /* We might have open sockets still, and these will be error-closed by epoll_wait */ // us_socket_context_close - close all open sockets created with this socket context if (listen_socket) { us_listen_socket_close(0, listen_socket); listen_socket = NULL; } } <|endoftext|>
<commit_before>/* This file is part of Akregator. Copyright (C) 2004 Sashmit Bhaduri <smt@vfemail.net> 2005 Frank Osterfeld <frank.osterfeld at kdemail.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 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 "akregatorconfig.h" #include "akregator_run.h" #include "feediconmanager.h" #include "pageviewer.h" #include "viewer.h" #include <kaction.h> #include <kapplication.h> #include <kbookmark.h> #include <kbookmarkmanager.h> #include <kconfig.h> #include <kglobalsettings.h> #include <khtml_settings.h> #include <khtmlview.h> #include <kiconloader.h> #include <klocale.h> #include <kpopupmenu.h> #include <kstandarddirs.h> #include <kparts/browserinterface.h> #include <qclipboard.h> #include <qcstring.h> #include <qdatastream.h> #include <qdatetime.h> #include <qfile.h> #include <qmetaobject.h> #include <qscrollview.h> #include <qstring.h> #include <qvaluelist.h> #include <private/qucomextra_p.h> #include <cstdlib> using std::abs; namespace Akregator { // taken from KDevelop class PageViewer::HistoryEntry { public: KURL url; QString title; QByteArray state; int id; HistoryEntry() {} HistoryEntry(const KURL& u, const QString& t=QString::null): url(u), title(t) { id = abs( QTime::currentTime().msecsTo( QTime() ) ); // nasty, but should provide a reasonably unique number } }; class PageViewer::PageViewerPrivate { public: QValueList<HistoryEntry> history; QValueList<HistoryEntry>::Iterator current; KToolBarPopupAction* backAction; KToolBarPopupAction* forwardAction; KAction* reloadAction; KAction* stopAction; QString caption; }; PageViewer::PageViewer(QWidget *parent, const char *name) : Viewer(parent, name), d(new PageViewerPrivate) { // this hack is necessary since the part looks for []HTML Settings] in // KGlobal::config() by default, which is wrong when running in Kontact KHTMLSettings* s = const_cast<KHTMLSettings*> (settings()); s->init(Settings::self()->config()); setXMLFile(locate("data", "akregator/pageviewer.rc"), true); d->backAction = new KToolBarPopupAction(i18n("Back"), "back", "Alt+Left", this, SLOT(slotBack()), actionCollection(), "pageviewer_back"); connect(d->backAction->popupMenu(), SIGNAL(aboutToShow()), this, SLOT(slotBackAboutToShow())); connect(d->backAction->popupMenu(), SIGNAL(activated(int)), this, SLOT(slotPopupActivated(int))); d->forwardAction = new KToolBarPopupAction(i18n("Forward"), "forward", "Alt+Right", this, SLOT(slotForward()), actionCollection(), "pageviewer_forward"); connect(d->forwardAction->popupMenu(), SIGNAL(aboutToShow()), this, SLOT(slotForwardAboutToShow())); connect(d->forwardAction->popupMenu(), SIGNAL(activated(int)), this, SLOT(slotPopupActivated(int))); d->reloadAction = new KAction(i18n("Reload"), "reload", 0, this, SLOT(slotReload()), actionCollection(), "pageviewer_reload"); d->stopAction = new KAction(i18n("Stop"), "stop", 0, this, SLOT(slotStop()), actionCollection(), "pageviewer_stop"); //connect( this, SIGNAL(popupMenu(const QString &, const QPoint &)), this, SLOT(slotPopupMenu(const QString &, const QPoint &))); d->backAction->setEnabled(false); d->forwardAction->setEnabled(false); d->stopAction->setEnabled(false); connect( this, SIGNAL(setWindowCaption (const QString &)), this, SLOT(slotSetCaption (const QString &)) ); connect(this, SIGNAL(started(KIO::Job *)), this, SLOT(slotStarted(KIO::Job* ))); connect(this, SIGNAL(completed()), this, SLOT(slotCompleted())); connect(this, SIGNAL(canceled(const QString &)), this, SLOT(slotCancelled(const QString &))); d->current = d->history.end(); // uncomment this to load konq plugins (doesn't work properly and clutters the GUI) //loadPlugins( partObject(), this, instance() ); } PageViewer::~PageViewer() { delete d; d = 0; } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotBack() { if ( d->current != d->history.begin() ) { QValueList<HistoryEntry>::Iterator tmp = d->current; --tmp; restoreHistoryEntry(tmp); } } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotForward() { if ( d->current != d->history.fromLast() ) { QValueList<HistoryEntry>::Iterator tmp = d->current; ++tmp; restoreHistoryEntry(tmp); } } void PageViewer::slotBackAboutToShow() { KPopupMenu *popup = d->backAction->popupMenu(); popup->clear(); if ( d->current == d->history.begin() ) return; QValueList<HistoryEntry>::Iterator it = d->current; --it; int i = 0; while( i < 10 ) { if ( it == d->history.begin() ) { popup->insertItem( (*it).title, (*it).id ); return; } popup->insertItem( (*it).title, (*it).id ); ++i; --it; } } void PageViewer::slotForwardAboutToShow() { KPopupMenu *popup = d->forwardAction->popupMenu(); popup->clear(); if ( d->current == d->history.fromLast() ) return; QValueList<HistoryEntry>::Iterator it = d->current; ++it; int i = 0; while( i < 10 ) { if ( it == d->history.fromLast() ) { popup->insertItem( (*it).title, (*it).id ); return; } popup->insertItem( (*it).title, (*it).id ); ++i; ++it; } } void PageViewer::slotReload() { openURL( url() ); } void PageViewer::slotStop() { closeURL(); } bool PageViewer::openURL(const KURL& url) { updateHistoryEntry(); // update old history entry before switching to the new one emit started(0); bool val = KHTMLPart::openURL(url); addHistoryEntry(url); // add new URL to history d->backAction->setEnabled( d->current != d->history.begin() ); d->forwardAction->setEnabled( d->current != d->history.fromLast() ); QString favicon = FeedIconManager::self()->iconLocation(url); if (!favicon.isEmpty()) emit setTabIcon(QPixmap(KGlobal::dirs()->findResource("cache", favicon+".png"))); else emit setTabIcon(SmallIcon("html")); return val; } void PageViewer::slotOpenURLRequest(const KURL& url, const KParts::URLArgs& args) { updateHistoryEntry(); if (args.doPost()) { browserExtension()->setURLArgs(args); openURL(url); } } void PageViewer::slotPopupActivated( int id ) { QValueList<HistoryEntry>::Iterator it = d->history.begin(); while( it != d->history.end() ) { if ( (*it).id == id ) { restoreHistoryEntry(it); return; } ++it; } } void PageViewer::updateHistoryEntry() { (*d->current).title = d->caption; (*d->current).state = QByteArray(); // Start with empty buffer. QDataStream stream( (*d->current).state, IO_WriteOnly); browserExtension()->saveState(stream); } void PageViewer::restoreHistoryEntry(const QValueList<HistoryEntry>::Iterator& entry) { updateHistoryEntry(); QDataStream stream( (*entry).state, IO_ReadOnly ); browserExtension()->restoreState( stream ); d->current = entry; d->backAction->setEnabled( d->current != d->history.begin() ); d->forwardAction->setEnabled( d->current != d->history.fromLast() ); //openURL( entry.url ); // TODO read state } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::addHistoryEntry(const KURL& url) { QValueList<HistoryEntry>::Iterator it = d->current; // if We're not already the last entry, we truncate the list here before adding an entry if ( it != d->history.end() && it != d->history.fromLast() ) { d->history.erase( ++it, d->history.end() ); } HistoryEntry newEntry( url, url.url() ); // Only save the new entry if it is different from the last if ( newEntry.url != (*d->current).url ) { d->history.append( newEntry ); d->current = d->history.fromLast(); } updateHistoryEntry(); } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotStarted( KIO::Job * ) { d->stopAction->setEnabled(true); } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotCompleted( ) { d->stopAction->setEnabled(false); } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotCancelled( const QString & /*errMsg*/ ) { d->stopAction->setEnabled(false); } void PageViewer::urlSelected(const QString &url, int button, int state, const QString &_target, KParts::URLArgs args) { if (button == LeftButton) { m_url = completeURL(url); browserExtension()->setURLArgs(args); slotOpenLinkInThisTab(); } else { Viewer::urlSelected(url,button,state,_target,args); } } void PageViewer::slotSetCaption(const QString& cap) { d->caption = cap; (*d->current).title = cap; } void PageViewer::slotPaletteOrFontChanged() { kdDebug() << "PageViewer::slotPaletteOrFontChanged()" << endl; // taken from KonqView (kdebase/konqueror/konq_view.cc) QObject *obj = KParts::BrowserExtension::childObject(this); if ( !obj ) // not all views have a browser extension ! return; int id = obj->metaObject()->findSlot("reparseConfiguration()"); if (id == -1) return; QUObject o[1]; obj->qt_invoke(id, o); // this hack is necessary since the part looks for []HTML Settings] in // KGlobal::config() by default, which is wrong when running in Kontact // NOTE: when running in Kontact, immediate updating doesn't work KHTMLSettings* s = const_cast<KHTMLSettings*> (settings()); s->init(Settings::self()->config()); } void PageViewer::slotGlobalBookmarkArticle() { KBookmarkManager *mgr = KBookmarkManager::userBookmarksManager(); KBookmarkGroup grp = mgr->root(); grp.addBookmark(mgr, d->caption, toplevelURL()); mgr->emitChanged(grp); mgr->save(); } void PageViewer::slotPopupMenu(KXMLGUIClient*, const QPoint& p, const KURL& kurl, const KParts::URLArgs&, KParts::BrowserExtension::PopupFlags kpf, mode_t) { m_url = kurl; QString url = kurl.url(); // maximal url confusion const bool isLink = (kpf & KParts::BrowserExtension::ShowNavigationItems) == 0; KPopupMenu popup(this->widget()); int idNewWindow = -2; if (isLink) { idNewWindow = popup.insertItem(SmallIcon("tab_new"),i18n("Open Link in New &Tab"), this, SLOT(slotOpenLinkInForegroundTab())); popup.setWhatsThis(idNewWindow, i18n("<b>Open Link in New Tab</b><p>Opens current link in a new tab.")); popup.insertItem(SmallIcon("window_new"), i18n("Open Link in External &Browser"), this, SLOT(slotOpenLinkInBrowser())); popup.insertSeparator(); action("savelinkas")->plug(&popup); KAction* copylinkaddress = action("copylinkaddress"); if (copylinkaddress) { copylinkaddress->plug( &popup); //popup.insertSeparator(); } } else // we are not on a link { d->backAction->plug( &popup ); d->forwardAction->plug( &popup ); d->reloadAction->plug(&popup); d->stopAction->plug(&popup); popup.insertSeparator(); action("viewer_copy")->plug(&popup); popup.insertSeparator(); KAction* incFontAction = this->action("incFontSizes"); KAction* decFontAction = this->action("decFontSizes"); if ( incFontAction && decFontAction ) { incFontAction->plug( &popup ); decFontAction->plug( &popup ); popup.insertSeparator(); } popup.insertItem(SmallIcon("window_new"), i18n("Open Page in External Browser"), this, SLOT(slotOpenLinkInBrowser())); action("viewer_print")->plug(&popup); popup.insertSeparator(); KAction *ac = action("setEncoding"); if (ac) ac->plug(&popup); popup.insertItem(SmallIcon("bookmark_add"),i18n("Add to Konqueror Bookmarks"), this, SLOT(slotGlobalBookmarkArticle())); } int r = popup.exec(p); if (r == idNewWindow) { KURL kurl; if (!KURL(url).path().startsWith("/")) { kdDebug() << "processing relative url: " << url << endl; if (url.startsWith("#")) { kurl = KURL(PageViewer::url()); kurl.setRef(url.mid(1)); } else kurl = KURL(PageViewer::url().upURL().url(true)+url); } else kurl = KURL(url); // kurl.addPath(url); if (kurl.isValid()) { //slotOpenInNewWindow(kurl); } // ( kurl ); } } } // namespace Akregator #include "pageviewer.moc" <commit_msg>Changes the guitems/shortcuts of back/forward/stop buttons for the page viewer to their KDE "standard" counterparts<commit_after>/* This file is part of Akregator. Copyright (C) 2004 Sashmit Bhaduri <smt@vfemail.net> 2005 Frank Osterfeld <frank.osterfeld at kdemail.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 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 "akregatorconfig.h" #include "akregator_run.h" #include "feediconmanager.h" #include "pageviewer.h" #include "viewer.h" #include <kaction.h> #include <kapplication.h> #include <kbookmark.h> #include <kbookmarkmanager.h> #include <kconfig.h> #include <kglobalsettings.h> #include <khtml_settings.h> #include <khtmlview.h> #include <kiconloader.h> #include <klocale.h> #include <kpopupmenu.h> #include <kstandarddirs.h> #include <kstdaccel.h> #include <kparts/browserinterface.h> #include <qclipboard.h> #include <qcstring.h> #include <qdatastream.h> #include <qdatetime.h> #include <qfile.h> #include <qmetaobject.h> #include <qscrollview.h> #include <qstring.h> #include <qvaluelist.h> #include <private/qucomextra_p.h> #include <cstdlib> using std::abs; namespace Akregator { // taken from KDevelop class PageViewer::HistoryEntry { public: KURL url; QString title; QByteArray state; int id; HistoryEntry() {} HistoryEntry(const KURL& u, const QString& t=QString::null): url(u), title(t) { id = abs( QTime::currentTime().msecsTo( QTime() ) ); // nasty, but should provide a reasonably unique number } }; class PageViewer::PageViewerPrivate { public: QValueList<HistoryEntry> history; QValueList<HistoryEntry>::Iterator current; KToolBarPopupAction* backAction; KToolBarPopupAction* forwardAction; KAction* reloadAction; KAction* stopAction; QString caption; }; PageViewer::PageViewer(QWidget *parent, const char *name) : Viewer(parent, name), d(new PageViewerPrivate) { // this hack is necessary since the part looks for []HTML Settings] in // KGlobal::config() by default, which is wrong when running in Kontact KHTMLSettings* s = const_cast<KHTMLSettings*> (settings()); s->init(Settings::self()->config()); setXMLFile(locate("data", "akregator/pageviewer.rc"), true); QPair< KGuiItem, KGuiItem > backForward = KStdGuiItem::backAndForward(); d->backAction = new KToolBarPopupAction(backForward.first, KStdAccel::shortcut(KStdAccel::Back), this, SLOT(slotBack()), actionCollection(), "pageviewer_back"); connect(d->backAction->popupMenu(), SIGNAL(aboutToShow()), this, SLOT(slotBackAboutToShow())); connect(d->backAction->popupMenu(), SIGNAL(activated(int)), this, SLOT(slotPopupActivated(int))); d->forwardAction = new KToolBarPopupAction(backForward.second, KStdAccel::shortcut(KStdAccel::Forward),this, SLOT(slotForward()), actionCollection(), "pageviewer_forward"); connect(d->forwardAction->popupMenu(), SIGNAL(aboutToShow()), this, SLOT(slotForwardAboutToShow())); connect(d->forwardAction->popupMenu(), SIGNAL(activated(int)), this, SLOT(slotPopupActivated(int))); d->reloadAction = new KAction(i18n("Reload"), "reload", 0, this, SLOT(slotReload()), actionCollection(), "pageviewer_reload"); d->stopAction = new KAction(KStdGuiItem::guiItem(KStdGuiItem::Stop), 0, this, SLOT(slotStop()), actionCollection(), "pageviewer_stop"); //connect( this, SIGNAL(popupMenu(const QString &, const QPoint &)), this, SLOT(slotPopupMenu(const QString &, const QPoint &))); d->backAction->setEnabled(false); d->forwardAction->setEnabled(false); d->stopAction->setEnabled(false); connect( this, SIGNAL(setWindowCaption (const QString &)), this, SLOT(slotSetCaption (const QString &)) ); connect(this, SIGNAL(started(KIO::Job *)), this, SLOT(slotStarted(KIO::Job* ))); connect(this, SIGNAL(completed()), this, SLOT(slotCompleted())); connect(this, SIGNAL(canceled(const QString &)), this, SLOT(slotCancelled(const QString &))); d->current = d->history.end(); // uncomment this to load konq plugins (doesn't work properly and clutters the GUI) //loadPlugins( partObject(), this, instance() ); } PageViewer::~PageViewer() { delete d; d = 0; } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotBack() { if ( d->current != d->history.begin() ) { QValueList<HistoryEntry>::Iterator tmp = d->current; --tmp; restoreHistoryEntry(tmp); } } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotForward() { if ( d->current != d->history.fromLast() ) { QValueList<HistoryEntry>::Iterator tmp = d->current; ++tmp; restoreHistoryEntry(tmp); } } void PageViewer::slotBackAboutToShow() { KPopupMenu *popup = d->backAction->popupMenu(); popup->clear(); if ( d->current == d->history.begin() ) return; QValueList<HistoryEntry>::Iterator it = d->current; --it; int i = 0; while( i < 10 ) { if ( it == d->history.begin() ) { popup->insertItem( (*it).title, (*it).id ); return; } popup->insertItem( (*it).title, (*it).id ); ++i; --it; } } void PageViewer::slotForwardAboutToShow() { KPopupMenu *popup = d->forwardAction->popupMenu(); popup->clear(); if ( d->current == d->history.fromLast() ) return; QValueList<HistoryEntry>::Iterator it = d->current; ++it; int i = 0; while( i < 10 ) { if ( it == d->history.fromLast() ) { popup->insertItem( (*it).title, (*it).id ); return; } popup->insertItem( (*it).title, (*it).id ); ++i; ++it; } } void PageViewer::slotReload() { openURL( url() ); } void PageViewer::slotStop() { closeURL(); } bool PageViewer::openURL(const KURL& url) { updateHistoryEntry(); // update old history entry before switching to the new one emit started(0); bool val = KHTMLPart::openURL(url); addHistoryEntry(url); // add new URL to history d->backAction->setEnabled( d->current != d->history.begin() ); d->forwardAction->setEnabled( d->current != d->history.fromLast() ); QString favicon = FeedIconManager::self()->iconLocation(url); if (!favicon.isEmpty()) emit setTabIcon(QPixmap(KGlobal::dirs()->findResource("cache", favicon+".png"))); else emit setTabIcon(SmallIcon("html")); return val; } void PageViewer::slotOpenURLRequest(const KURL& url, const KParts::URLArgs& args) { updateHistoryEntry(); if (args.doPost()) { browserExtension()->setURLArgs(args); openURL(url); } } void PageViewer::slotPopupActivated( int id ) { QValueList<HistoryEntry>::Iterator it = d->history.begin(); while( it != d->history.end() ) { if ( (*it).id == id ) { restoreHistoryEntry(it); return; } ++it; } } void PageViewer::updateHistoryEntry() { (*d->current).title = d->caption; (*d->current).state = QByteArray(); // Start with empty buffer. QDataStream stream( (*d->current).state, IO_WriteOnly); browserExtension()->saveState(stream); } void PageViewer::restoreHistoryEntry(const QValueList<HistoryEntry>::Iterator& entry) { updateHistoryEntry(); QDataStream stream( (*entry).state, IO_ReadOnly ); browserExtension()->restoreState( stream ); d->current = entry; d->backAction->setEnabled( d->current != d->history.begin() ); d->forwardAction->setEnabled( d->current != d->history.fromLast() ); //openURL( entry.url ); // TODO read state } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::addHistoryEntry(const KURL& url) { QValueList<HistoryEntry>::Iterator it = d->current; // if We're not already the last entry, we truncate the list here before adding an entry if ( it != d->history.end() && it != d->history.fromLast() ) { d->history.erase( ++it, d->history.end() ); } HistoryEntry newEntry( url, url.url() ); // Only save the new entry if it is different from the last if ( newEntry.url != (*d->current).url ) { d->history.append( newEntry ); d->current = d->history.fromLast(); } updateHistoryEntry(); } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotStarted( KIO::Job * ) { d->stopAction->setEnabled(true); } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotCompleted( ) { d->stopAction->setEnabled(false); } // Taken from KDevelop (lib/widgets/kdevhtmlpart.cpp) void PageViewer::slotCancelled( const QString & /*errMsg*/ ) { d->stopAction->setEnabled(false); } void PageViewer::urlSelected(const QString &url, int button, int state, const QString &_target, KParts::URLArgs args) { if (button == LeftButton) { m_url = completeURL(url); browserExtension()->setURLArgs(args); slotOpenLinkInThisTab(); } else { Viewer::urlSelected(url,button,state,_target,args); } } void PageViewer::slotSetCaption(const QString& cap) { d->caption = cap; (*d->current).title = cap; } void PageViewer::slotPaletteOrFontChanged() { kdDebug() << "PageViewer::slotPaletteOrFontChanged()" << endl; // taken from KonqView (kdebase/konqueror/konq_view.cc) QObject *obj = KParts::BrowserExtension::childObject(this); if ( !obj ) // not all views have a browser extension ! return; int id = obj->metaObject()->findSlot("reparseConfiguration()"); if (id == -1) return; QUObject o[1]; obj->qt_invoke(id, o); // this hack is necessary since the part looks for []HTML Settings] in // KGlobal::config() by default, which is wrong when running in Kontact // NOTE: when running in Kontact, immediate updating doesn't work KHTMLSettings* s = const_cast<KHTMLSettings*> (settings()); s->init(Settings::self()->config()); } void PageViewer::slotGlobalBookmarkArticle() { KBookmarkManager *mgr = KBookmarkManager::userBookmarksManager(); KBookmarkGroup grp = mgr->root(); grp.addBookmark(mgr, d->caption, toplevelURL()); mgr->emitChanged(grp); mgr->save(); } void PageViewer::slotPopupMenu(KXMLGUIClient*, const QPoint& p, const KURL& kurl, const KParts::URLArgs&, KParts::BrowserExtension::PopupFlags kpf, mode_t) { m_url = kurl; QString url = kurl.url(); // maximal url confusion const bool isLink = (kpf & KParts::BrowserExtension::ShowNavigationItems) == 0; KPopupMenu popup(this->widget()); int idNewWindow = -2; if (isLink) { idNewWindow = popup.insertItem(SmallIcon("tab_new"),i18n("Open Link in New &Tab"), this, SLOT(slotOpenLinkInForegroundTab())); popup.setWhatsThis(idNewWindow, i18n("<b>Open Link in New Tab</b><p>Opens current link in a new tab.")); popup.insertItem(SmallIcon("window_new"), i18n("Open Link in External &Browser"), this, SLOT(slotOpenLinkInBrowser())); popup.insertSeparator(); action("savelinkas")->plug(&popup); KAction* copylinkaddress = action("copylinkaddress"); if (copylinkaddress) { copylinkaddress->plug( &popup); //popup.insertSeparator(); } } else // we are not on a link { d->backAction->plug( &popup ); d->forwardAction->plug( &popup ); d->reloadAction->plug(&popup); d->stopAction->plug(&popup); popup.insertSeparator(); action("viewer_copy")->plug(&popup); popup.insertSeparator(); KAction* incFontAction = this->action("incFontSizes"); KAction* decFontAction = this->action("decFontSizes"); if ( incFontAction && decFontAction ) { incFontAction->plug( &popup ); decFontAction->plug( &popup ); popup.insertSeparator(); } popup.insertItem(SmallIcon("window_new"), i18n("Open Page in External Browser"), this, SLOT(slotOpenLinkInBrowser())); action("viewer_print")->plug(&popup); popup.insertSeparator(); KAction *ac = action("setEncoding"); if (ac) ac->plug(&popup); popup.insertItem(SmallIcon("bookmark_add"),i18n("Add to Konqueror Bookmarks"), this, SLOT(slotGlobalBookmarkArticle())); } int r = popup.exec(p); if (r == idNewWindow) { KURL kurl; if (!KURL(url).path().startsWith("/")) { kdDebug() << "processing relative url: " << url << endl; if (url.startsWith("#")) { kurl = KURL(PageViewer::url()); kurl.setRef(url.mid(1)); } else kurl = KURL(PageViewer::url().upURL().url(true)+url); } else kurl = KURL(url); // kurl.addPath(url); if (kurl.isValid()) { //slotOpenInNewWindow(kurl); } // ( kurl ); } } } // namespace Akregator #include "pageviewer.moc" <|endoftext|>
<commit_before>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" #include "Engine.h" #include "App.h" #include "Engine.h" #include "App.h" #include "Input.h" #include "ObjectGui.h" #include "WidgetLabel.h" //解决跨平台字符集兼容问题 #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //角色要初始化,着色器要初始化, virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。 virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //设置是否显示鼠标 virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。 virtual void SetControlMode(ControlMode mode); //控制模式 virtual ControlMode GetControlMode() const; //获取控制模式 private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //控制游戏中移动 CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //控制模式 int m_nOldMouseX; //上一个鼠标坐标X int m_nOldMouseY; //上一个鼠标坐标Y CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); SetControlMode(CONTROL_KEYBORAD_MOUSE); m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/"); m_pTest3DUI->SetMouseShow(0); m_pTest3DUI->SetBackground(1); m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f)); m_pTest3DUI->SetScreenSize(800, 400); m_pTest3DUI->SetControlDistance(1000.0f); m_pTest3DUI->CreateMaterial("gui_base"); //show in game m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f))); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel->SetFontSize(80); //设置字体大小 m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓 m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船"); void CSysControlLocal::Update(float ifps) { Update_Mouse(ifps); Update_Keyboard(ifps); Update_XPad360(ifps); } m_nOldMouseX = 0; m_nOldMouseY = 0; } void CSysControlLocal::Shutdown() { g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); delete m_pControlsApp; m_pControlsApp = NULL; delete m_pControlsXPad360; m_pControlsXPad360 = NULL; delete m_pTestMessageLabel; m_pTestMessageLabel = NULL; delete m_pTest3DUI; m_pTest3DUI = NULL; } int CSysControlLocal::GetState(int state) { return m_pControlsApp->GetState(state); } int CSysControlLocal::ClearState(int state) { return m_pControlsApp->ClearState(state); } float CSysControlLocal::GetMouseDX() { return m_pControlsApp->GetMouseDX(); } float CSysControlLocal::GetMouseDY() { return m_pControlsApp->GetMouseDY(); } void CSysControlLocal::SetMouseGrab(int g) { g_Engine.pApp->SetMouseGrab(g); g_Engine.pGui->SetMouseShow(!g); } int CSysControlLocal::GetMouseGrab() { return g_Engine.pApp->GetMouseGrab(); } void CSysControlLocal::SetControlMode(ControlMode mode) { m_nControlMode = mode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } void CSysControlLocal::Update_Mouse(float ifps) { float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快 float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢 m_pControlsApp->SetMouseDX(dx); m_pControlsApp->SetMouseDY(dy); if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive()) { g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2); } m_nOldMouseX = g_Engine.pApp->GetMouseX(); m_nOldMouseY = g_Engine.pApp->GetMouseY(); } void CSysControlLocal::Update_Keyboard(float ifps) //键盘按键响应wsad { if (g_Engine.pInput->IsKeyDown('w')) m_pControlsApp->SetState(CControls::STATE_FORWARD, 1); if (g_Engine.pInput->IsKeyDown('s')) m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1); if (g_Engine.pInput->IsKeyDown('a')) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1); if (g_Engine.pInput->IsKeyDown('d')) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1); if (g_Engine.pInput->IsKeyUp('w')) m_pControlsApp->SetState(CControls::STATE_FORWARD, 0); else if (g_Engine.pInput->IsKeyUp('s')) m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0); if (g_Engine.pInput->IsKeyUp('a')) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0); else if (g_Engine.pInput->IsKeyUp('d')) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0); if (g_Engine.pInput->IsKeyDown(' ')) //空格跳跃 m_pControlsApp->SetState(CControls::STATE_JUMP, 1); else m_pControlsApp->SetState(CControls::STATE_JUMP, 0); } void CSysControlLocal::Update_XPad360(float ifps) { m_pControlsXPad360->UpdateEvents(); CUtilStr strMessage; strMessage = CUtilStr("测试3D UI\n"), strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n"; strMessage += CUtilStr::Format("\n手柄测试\n"); strMessage += CUtilStr::Format("LeftX: %5.2f\n", m_pControlsXPad360->GetLeftX()); strMessage += CUtilStr::Format("LeftY: %5.2f\n", m_pControlsXPad360->GetLeftY()); strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX()); strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY()); strMessage += "\nTriggers:\n"; strMessage += CUtilStr::Format("Left: %5.2f\n", m_pControlsXPad360->GetLeftTrigger()); strMessage += CUtilStr::Format("Right: %5.2f\n", m_pControlsXPad360->GetRightTrigger()); strMessage += CUtilStr::Format("\nButtons:\n"); for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i) { strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i)); } m_pTestMessageLabel->SetText(strMessage.Get()); }<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" #include "Engine.h" #include "App.h" #include "Engine.h" #include "App.h" #include "Input.h" #include "ObjectGui.h" #include "WidgetLabel.h" //解决跨平台字符集兼容问题 #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //角色要初始化,着色器要初始化, virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。 virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //设置是否显示鼠标 virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。 virtual void SetControlMode(ControlMode mode); //控制模式 virtual ControlMode GetControlMode() const; //获取控制模式 private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //控制游戏中移动 CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //控制模式 int m_nOldMouseX; //上一个鼠标坐标X int m_nOldMouseY; //上一个鼠标坐标Y CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); SetControlMode(CONTROL_KEYBORAD_MOUSE); m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/"); m_pTest3DUI->SetMouseShow(0); m_pTest3DUI->SetBackground(1); m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f)); m_pTest3DUI->SetScreenSize(800, 400); m_pTest3DUI->SetControlDistance(1000.0f); m_pTest3DUI->CreateMaterial("gui_base"); //show in game m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f))); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel->SetFontSize(80); //设置字体大小 m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓 m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船"); void CSysControlLocal::Update(float ifps) { Update_Mouse(ifps); Update_Keyboard(ifps); Update_XPad360(ifps); } m_nOldMouseX = 0; m_nOldMouseY = 0; } void CSysControlLocal::Shutdown() { g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); delete m_pControlsApp; m_pControlsApp = NULL; delete m_pControlsXPad360; m_pControlsXPad360 = NULL; delete m_pTestMessageLabel; m_pTestMessageLabel = NULL; delete m_pTest3DUI; m_pTest3DUI = NULL; } int CSysControlLocal::GetState(int state) { return m_pControlsApp->GetState(state); } int CSysControlLocal::ClearState(int state) { return m_pControlsApp->ClearState(state); } float CSysControlLocal::GetMouseDX() { return m_pControlsApp->GetMouseDX(); } float CSysControlLocal::GetMouseDY() { return m_pControlsApp->GetMouseDY(); } void CSysControlLocal::SetMouseGrab(int g) { g_Engine.pApp->SetMouseGrab(g); g_Engine.pGui->SetMouseShow(!g); } int CSysControlLocal::GetMouseGrab() { return g_Engine.pApp->GetMouseGrab(); } void CSysControlLocal::SetControlMode(ControlMode mode) { m_nControlMode = mode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } void CSysControlLocal::Update_Mouse(float ifps) { float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快 float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢 m_pControlsApp->SetMouseDX(dx); m_pControlsApp->SetMouseDY(dy); if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive()) { g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2); } m_nOldMouseX = g_Engine.pApp->GetMouseX(); m_nOldMouseY = g_Engine.pApp->GetMouseY(); } void CSysControlLocal::Update_Keyboard(float ifps) //键盘按键响应wsad { if (g_Engine.pInput->IsKeyDown('w')) m_pControlsApp->SetState(CControls::STATE_FORWARD, 1); if (g_Engine.pInput->IsKeyDown('s')) m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1); if (g_Engine.pInput->IsKeyDown('a')) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1); if (g_Engine.pInput->IsKeyDown('d')) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1); if (g_Engine.pInput->IsKeyUp('w')) m_pControlsApp->SetState(CControls::STATE_FORWARD, 0); else if (g_Engine.pInput->IsKeyUp('s')) m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0); if (g_Engine.pInput->IsKeyUp('a')) m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0); else if (g_Engine.pInput->IsKeyUp('d')) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0); if (g_Engine.pInput->IsKeyDown(' ')) //空格跳跃 m_pControlsApp->SetState(CControls::STATE_JUMP, 1); else m_pControlsApp->SetState(CControls::STATE_JUMP, 0); } void CSysControlLocal::Update_XPad360(float ifps) { m_pControlsXPad360->UpdateEvents(); CUtilStr strMessage; strMessage = CUtilStr("测试3D UI\n"), strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n"; strMessage += CUtilStr::Format("\n手柄测试\n"); strMessage += CUtilStr::Format("LeftX: %5.2f\n", m_pControlsXPad360->GetLeftX()); strMessage += CUtilStr::Format("LeftY: %5.2f\n", m_pControlsXPad360->GetLeftY()); strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX()); strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY()); strMessage += "\nTriggers:\n"; strMessage += CUtilStr::Format("Left: %5.2f\n", m_pControlsXPad360->GetLeftTrigger()); strMessage += CUtilStr::Format("Right: %5.2f\n", m_pControlsXPad360->GetRightTrigger()); strMessage += CUtilStr::Format("\nButtons:\n"); for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i) { strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i)); } m_pTestMessageLabel->SetText(strMessage.Get()); const float fPadThreshold = 0.5f; if (m_pControlsXPad360->GetLeftX() > fPadThreshold) m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1); }<|endoftext|>
<commit_before>#include "mc2lib/codegen/ops/armv7.hpp" #include "mc2lib/codegen/rit.hpp" #include "mc2lib/memconsistency/cats.hpp" #include <gtest/gtest.h> using namespace mc2lib; using namespace mc2lib::codegen; using namespace mc2lib::memconsistency; TEST(CodeGen, ARMv7) { std::default_random_engine urng(1238); cats::ExecWitness ew; cats::Arch_ARMv7 arch; armv7::RandomFactory factory(0, 1, 0xccc0, 0xccc5); RandInstTest<std::default_random_engine, armv7::RandomFactory> rit( urng, &factory, 150); auto threads = [&rit]() { auto result = rit.threads(); EXPECT_EQ(result.size(), 2); EXPECT_EQ(threads_size(result), rit.Get().size()); return result; }; Compiler<armv7::Operation, armv7::Backend> compiler( std::unique_ptr<EvtStateCats>(new EvtStateCats(&ew, &arch)), threads()); constexpr std::size_t MAX_CODE_SIZE = 1024 / sizeof(std::uint16_t); std::uint16_t code0[MAX_CODE_SIZE]; std::uint16_t code1[MAX_CODE_SIZE]; std::size_t emit_len = compiler.Emit(0, 0xffff, code0, sizeof(code0)); ASSERT_NE(emit_len, 0); emit_len = compiler.Emit(1, 0, code1, sizeof(code1)); ASSERT_NE(emit_len, 0); #if 1 auto checker = arch.MakeChecker(&arch, &ew); ew.po.set_props(mc::EventRel::kTransitiveClosure); ew.co.set_props(mc::EventRel::kTransitiveClosure); types::WriteID wid = 0; ASSERT_TRUE(compiler.UpdateObs(0x2a, 0, 0xccc3, &wid, 1)); // write 0xccc3 ASSERT_TRUE(compiler.UpdateObs(0x68, 0, 0xccc3, &wid, 1)); // read 0xccc3 ASSERT_FALSE(checker->sc_per_location()); wid = 0x29; // check replacement/update works ASSERT_TRUE(compiler.UpdateObs(0x68, 0, 0xccc3, &wid, 1)); // read 0xccc3 ASSERT_TRUE(checker->sc_per_location()); #endif #ifdef OUTPUT_BIN_TO_TMP std::fill(code1 + (emit_len / sizeof(std::uint16_t)), code1 + MAX_CODE_SIZE, 0xbf00); auto f = fopen("/tmp/mc2lib-armv7-test.bin", "wb"); fwrite(code1, sizeof(code1), 1, f); fclose(f); #endif } // Should be able to handle exhausting write-ids gracefully. TEST(CodeGen, ARMv7_Exhaust) { std::default_random_engine urng(42); cats::ExecWitness ew; cats::Arch_ARMv7 arch; armv7::RandomFactory factory(0, 1, 0xbeef, 0xfeed); RandInstTest<std::default_random_engine, armv7::RandomFactory> rit( urng, &factory, 1234); Compiler<armv7::Operation, armv7::Backend> compiler( std::unique_ptr<EvtStateCats>(new EvtStateCats(&ew, &arch)), rit.threads()); constexpr std::size_t MAX_CODE_SIZE = 4096*2; char code[MAX_CODE_SIZE]; ASSERT_NE(0, compiler.Emit(0, 0, code, sizeof(code))); ASSERT_NE(0, compiler.Emit(1, MAX_CODE_SIZE << 1, code, sizeof(code))); } <commit_msg>test: armv7: Factor out SC_PER_LOCATION test<commit_after>#include "mc2lib/codegen/ops/armv7.hpp" #include "mc2lib/codegen/rit.hpp" #include "mc2lib/memconsistency/cats.hpp" #include <gtest/gtest.h> using namespace mc2lib; using namespace mc2lib::codegen; using namespace mc2lib::memconsistency; TEST(CodeGen, ARMv7_Short) { std::default_random_engine urng(42); cats::ExecWitness ew; cats::Arch_ARMv7 arch; armv7::RandomFactory factory(0, 1, 0xccc0, 0xccca); RandInstTest<std::default_random_engine, armv7::RandomFactory> rit( urng, &factory, 150); auto threads = [&rit]() { auto result = rit.threads(); EXPECT_EQ(result.size(), 2); EXPECT_EQ(threads_size(result), rit.Get().size()); return result; }; Compiler<armv7::Operation, armv7::Backend> compiler( std::unique_ptr<EvtStateCats>(new EvtStateCats(&ew, &arch)), threads()); constexpr std::size_t MAX_CODE_SIZE = 1024 / sizeof(std::uint16_t); std::uint16_t code0[MAX_CODE_SIZE]; std::uint16_t code1[MAX_CODE_SIZE]; std::size_t emit_len = compiler.Emit(0, 0xffff, code0, sizeof(code0)); ASSERT_NE(emit_len, 0); emit_len = compiler.Emit(1, 0, code1, sizeof(code1)); ASSERT_NE(emit_len, 0); #ifdef OUTPUT_BIN_TO_TMP std::fill(code1 + (emit_len / sizeof(std::uint16_t)), code1 + MAX_CODE_SIZE, 0xbf00); auto f = fopen("/tmp/mc2lib-armv7-test.bin", "wb"); fwrite(code1, sizeof(code1), 1, f); fclose(f); #endif } // Should be able to handle exhausting write-ids gracefully. TEST(CodeGen, ARMv7_Exhaust) { std::default_random_engine urng(42); cats::ExecWitness ew; cats::Arch_ARMv7 arch; armv7::RandomFactory factory(0, 1, 0xbeef, 0xfeed); RandInstTest<std::default_random_engine, armv7::RandomFactory> rit( urng, &factory, 1234); Compiler<armv7::Operation, armv7::Backend> compiler( std::unique_ptr<EvtStateCats>(new EvtStateCats(&ew, &arch)), rit.threads()); constexpr std::size_t MAX_CODE_SIZE = 4096*2; char code[MAX_CODE_SIZE]; ASSERT_NE(0, compiler.Emit(0, 0, code, sizeof(code))); ASSERT_NE(0, compiler.Emit(1, MAX_CODE_SIZE << 1, code, sizeof(code))); } TEST(CodeGen, ARMv7_SC_PER_LOCATION) { std::vector<codegen::armv7::Operation::Ptr> threads = { // p0 std::make_shared<armv7::Write>(0xf0, 0), // @0x0a std::make_shared<armv7::Read>(0xf0, armv7::Backend::r1, 0), // @0x14 std::make_shared<armv7::Read>(0xf0, armv7::Backend::r2, 0), // @0x1e std::make_shared<armv7::Read>(0xf1, armv7::Backend::r3, 0), // @0x28 std::make_shared<armv7::Read>(0xf1, armv7::Backend::r4, 0), // @0x32 // p1 std::make_shared<armv7::Write>(0xf1, 1), }; cats::ExecWitness ew; cats::Arch_ARMv7 arch; Compiler<armv7::Operation, armv7::Backend> compiler( std::unique_ptr<EvtStateCats>(new EvtStateCats(&ew, &arch)), ExtractThreads(&threads)); char* code[128]; ASSERT_NE(0, compiler.Emit(0, 0, code, sizeof(code))); ASSERT_NE(0, compiler.Emit(1, 0xffff, code, sizeof(code))); auto checker = arch.MakeChecker(&arch, &ew); ew.po.set_props(mc::EventRel::kTransitiveClosure); ew.co.set_props(mc::EventRel::kTransitiveClosure); types::WriteID wid = 0; ASSERT_TRUE(compiler.UpdateObs(0x0a, 0, 0xf0, &wid, 1)); ASSERT_TRUE(compiler.UpdateObs(0x14, 0, 0xf0, &wid, 1)); ASSERT_FALSE(checker->sc_per_location()); // Check update works. wid = 1; ASSERT_TRUE(compiler.UpdateObs(0x14, 0, 0xf0, &wid, 1)); ASSERT_TRUE(checker->sc_per_location()); // Read-from external wid = 0; ASSERT_TRUE(compiler.UpdateObs(0xffff+0x0a, 0, 0xf1, &wid, 1)); wid = 2; ASSERT_TRUE(compiler.UpdateObs(0x28, 0, 0xf1, &wid, 1)); wid = 0; ASSERT_TRUE(compiler.UpdateObs(0x32, 0, 0xf1, &wid, 1)); ASSERT_FALSE(checker->sc_per_location()); // update wid = 2; ASSERT_TRUE(compiler.UpdateObs(0x32, 0, 0xf1, &wid, 1)); ASSERT_TRUE(checker->sc_per_location()); } <|endoftext|>
<commit_before>// Copyright 2008 Paul Hodge #include "common_headers.h" #include "branch.h" #include "builtins.h" #include "debug.h" #include "introspection.h" #include "parser.h" #include "runtime.h" #include "term.h" #include "testing.h" #include "type.h" #include "values.h" namespace circa { namespace branch_tests { void test_duplicate() { Branch original; Term* term1 = apply_function(original, VAR_INT, ReferenceList()); Term* term2 = apply_function(original, VAR_STRING, ReferenceList()); as_int(term1) = 5; as_string(term2) = "yarn"; original.bindName(term1, "term1"); original.bindName(term2, "term two"); Branch duplicate; duplicate_branch(&original, &duplicate); Term* term1_duplicate = duplicate.getNamed("term1"); test_assert(term1_duplicate != NULL); Term* term2_duplicate = duplicate.getNamed("term two"); test_assert(as_int(term1_duplicate) == 5); test_assert(as_string(term2_duplicate) == "yarn"); // make sure 'duplicate' uses different terms as_int(term1) = 8; test_assert(as_int(term1_duplicate) == 5); assert(sanity_check_term(term1)); assert(sanity_check_term(term2)); assert(sanity_check_term(term1_duplicate)); assert(sanity_check_term(term2_duplicate)); } void external_pointers() { Branch branch; Term* inner_branch = create_value(&branch, BRANCH_TYPE); test_equals(list_all_pointers(inner_branch), ReferenceList(inner_branch->function, inner_branch->type)); Term* inner_int = create_value(&as_branch(inner_branch), INT_TYPE); Term* inner_add = apply_function(as_branch(inner_branch), ADD_FUNC, ReferenceList(inner_int, inner_int)); // make sure that the pointer from inner_add to inner_int does // not show up in list_all_pointers. /* fixme test_equals(list_all_pointers(inner_branch), ReferenceList( inner_branch->function, inner_branch->type, inner_int->function, FLOAT_TYPE, INT_TYPE, ADD_FUNC, FLOAT_TYPE)); ReferenceMap myRemap; myRemap[ADD_FUNC] = MULT_FUNC; remap_pointers(inner_branch, myRemap); test_equals(list_all_pointers(inner_branch), ReferenceList( inner_branch->function, inner_branch->type, inner_int->function, FLOAT_TYPE, INT_TYPE, MULT_FUNC, FLOAT_TYPE)); test_assert(inner_add->function == MULT_FUNC); */ } void test_owning_term() { Branch branch; Term* b = branch.eval("Branch()"); alloc_value(b); test_assert(b->type == BRANCH_TYPE); test_assert(as_branch(b).owningTerm == b); Term* b2 = branch.eval("Branch()"); steal_value(b, b2); test_assert(as_branch(b2).owningTerm == b2); duplicate_value(b2, b); test_assert(as_branch(b).owningTerm == b); } void find_name_in_outer_branch() { Branch branch; Term* outer_branch = branch.eval("Branch()"); alloc_value(outer_branch); Term* a = as_branch(outer_branch).eval("a = 1"); Term* inner_branch = as_branch(outer_branch).eval("Branch()"); alloc_value(inner_branch); as_branch(inner_branch).outerScope = outer_branch; test_assert(as_branch(inner_branch).findNamed("a") == a); } } // namespace branch_tests void register_branch_tests() { REGISTER_TEST_CASE(branch_tests::test_duplicate); REGISTER_TEST_CASE(branch_tests::external_pointers); REGISTER_TEST_CASE(branch_tests::test_owning_term); REGISTER_TEST_CASE(branch_tests::find_name_in_outer_branch); } } // namespace circa <commit_msg>Add test_startBranch (currently fails)<commit_after>// Copyright 2008 Paul Hodge #include "common_headers.h" #include "branch.h" #include "builtins.h" #include "debug.h" #include "introspection.h" #include "parser.h" #include "runtime.h" #include "term.h" #include "testing.h" #include "type.h" #include "values.h" namespace circa { namespace branch_tests { void test_duplicate() { Branch original; Term* term1 = apply_function(original, VAR_INT, ReferenceList()); Term* term2 = apply_function(original, VAR_STRING, ReferenceList()); as_int(term1) = 5; as_string(term2) = "yarn"; original.bindName(term1, "term1"); original.bindName(term2, "term two"); Branch duplicate; duplicate_branch(&original, &duplicate); Term* term1_duplicate = duplicate.getNamed("term1"); test_assert(term1_duplicate != NULL); Term* term2_duplicate = duplicate.getNamed("term two"); test_assert(as_int(term1_duplicate) == 5); test_assert(as_string(term2_duplicate) == "yarn"); // make sure 'duplicate' uses different terms as_int(term1) = 8; test_assert(as_int(term1_duplicate) == 5); assert(sanity_check_term(term1)); assert(sanity_check_term(term2)); assert(sanity_check_term(term1_duplicate)); assert(sanity_check_term(term2_duplicate)); } void external_pointers() { Branch branch; Term* inner_branch = create_value(&branch, BRANCH_TYPE); test_equals(list_all_pointers(inner_branch), ReferenceList(inner_branch->function, inner_branch->type)); Term* inner_int = create_value(&as_branch(inner_branch), INT_TYPE); Term* inner_add = apply_function(as_branch(inner_branch), ADD_FUNC, ReferenceList(inner_int, inner_int)); // make sure that the pointer from inner_add to inner_int does // not show up in list_all_pointers. /* fixme test_equals(list_all_pointers(inner_branch), ReferenceList( inner_branch->function, inner_branch->type, inner_int->function, FLOAT_TYPE, INT_TYPE, ADD_FUNC, FLOAT_TYPE)); ReferenceMap myRemap; myRemap[ADD_FUNC] = MULT_FUNC; remap_pointers(inner_branch, myRemap); test_equals(list_all_pointers(inner_branch), ReferenceList( inner_branch->function, inner_branch->type, inner_int->function, FLOAT_TYPE, INT_TYPE, MULT_FUNC, FLOAT_TYPE)); test_assert(inner_add->function == MULT_FUNC); */ } void test_owning_term() { Branch branch; Term* b = branch.eval("Branch()"); alloc_value(b); test_assert(b->type == BRANCH_TYPE); test_assert(as_branch(b).owningTerm == b); Term* b2 = branch.eval("Branch()"); steal_value(b, b2); test_assert(as_branch(b2).owningTerm == b2); duplicate_value(b2, b); test_assert(as_branch(b).owningTerm == b); } void find_name_in_outer_branch() { Branch branch; Term* outer_branch = branch.eval("Branch()"); alloc_value(outer_branch); Term* a = as_branch(outer_branch).eval("a = 1"); Term* inner_branch = as_branch(outer_branch).eval("Branch()"); alloc_value(inner_branch); as_branch(inner_branch).outerScope = outer_branch; test_assert(as_branch(inner_branch).findNamed("a") == a); } void test_startBranch() { Branch branch; Term* a = branch.eval("a = 1"); Branch& sub = branch.startBranch("sub"); test_assert(sub.findNamed("a") == a); } } // namespace branch_tests void register_branch_tests() { REGISTER_TEST_CASE(branch_tests::test_duplicate); REGISTER_TEST_CASE(branch_tests::external_pointers); REGISTER_TEST_CASE(branch_tests::test_owning_term); REGISTER_TEST_CASE(branch_tests::find_name_in_outer_branch); REGISTER_TEST_CASE(branch_tests::test_startBranch); } } // namespace circa <|endoftext|>
<commit_before>#include "UT4WebAdmin.h" #include "Base64.h" #define UT4WA_PLUGIN_FOLDER "UT4WebAdmin" #define UT4WA_HTML_FOLDER "www" #define LISTENING_PORT "8080" int WelcomeHandler(struct mg_connection *conn, void *cbdata) { mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "close\r\n\r\n"); mg_printf(conn, "<html><body>"); mg_printf(conn, "<h2>Welcome to UT4 Web Admin !</h2>"); mg_printf(conn, "</body></html>\n"); return 1; } UUT4WebAdmin::UUT4WebAdmin(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { #if defined(USE_CIVETWEB) ctx = nullptr; #endif GameMode = nullptr; } void UUT4WebAdmin::Init() { // Don't garbage collect me SetFlags(RF_MarkAsRootSet); if (Port == 0) { Port = 8080; } // Set the document root FString DocumentRoot = FPaths::GamePluginsDir() / UT4WA_PLUGIN_FOLDER / UT4WA_HTML_FOLDER; // Set listening port FString PortStr = FString::FromInt(Port); #if defined(USE_CIVETWEB) StartCivetWeb(DocumentRoot, PortStr); #endif } #if defined(USE_CIVETWEB) void UUT4WebAdmin::StartCivetWeb(FString &DocumentRoot, FString &PortStr) { /* Initialize the library */ mg_init_library(0); const char *options[] = { "document_root", TCHAR_TO_ANSI(*DocumentRoot), "listening_ports", TCHAR_TO_ANSI(*PortStr), 0 }; /* Start the server */ ctx = mg_start(NULL, 0, options); if (ctx) { UE_LOG(UT4WebAdmin, Log, TEXT("==================")); UE_LOG(UT4WebAdmin, Log, TEXT("UT4WebAdmin Started:")); UE_LOG(UT4WebAdmin, Log, TEXT(" * Port : %i"), Port); UE_LOG(UT4WebAdmin, Log, TEXT(" * Root Web Folder: %s"), *DocumentRoot); UE_LOG(UT4WebAdmin, Log, TEXT("==================")); /* Add some handler */ mg_set_request_handler(ctx, "/", WelcomeHandler, "Hello world"); } else { UE_LOG(UT4WebAdmin, Log, TEXT("==================")); UE_LOG(UT4WebAdmin, Log, TEXT("UT4WebAdmin could not be started")); UE_LOG(UT4WebAdmin, Log, TEXT("==================")); } } void UUT4WebAdmin::StopCivetWeb() { if (ctx) { /* Stop the server */ mg_stop(ctx); UE_LOG(UT4WebAdmin, Log, TEXT("UT4WebAdmin Stopped")); /* Un-initialize the library */ mg_exit_library(); } } #endif void UUT4WebAdmin::Stop() { #if defined(USE_CIVETWEB) StopCivetWeb(); #endif } void UUT4WebAdmin::Tick(float DeltaTime) { //poll(MGServer, 1); // TODO } TStatId UUT4WebAdmin::GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(UUT4WebAdmin, STATGROUP_Tickables); } <commit_msg>Warning log if http server could not be started<commit_after>#include "UT4WebAdmin.h" #include "Base64.h" #define UT4WA_PLUGIN_FOLDER "UT4WebAdmin" #define UT4WA_HTML_FOLDER "www" #define LISTENING_PORT "8080" int WelcomeHandler(struct mg_connection *conn, void *cbdata) { mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "close\r\n\r\n"); mg_printf(conn, "<html><body>"); mg_printf(conn, "<h2>Welcome to UT4 Web Admin !</h2>"); mg_printf(conn, "</body></html>\n"); return 1; } UUT4WebAdmin::UUT4WebAdmin(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { #if defined(USE_CIVETWEB) ctx = nullptr; #endif GameMode = nullptr; } void UUT4WebAdmin::Init() { // Don't garbage collect me SetFlags(RF_MarkAsRootSet); if (Port == 0) { Port = 8080; } // Set the document root FString DocumentRoot = FPaths::GamePluginsDir() / UT4WA_PLUGIN_FOLDER / UT4WA_HTML_FOLDER; // Set listening port FString PortStr = FString::FromInt(Port); #if defined(USE_CIVETWEB) StartCivetWeb(DocumentRoot, PortStr); #endif } #if defined(USE_CIVETWEB) void UUT4WebAdmin::StartCivetWeb(FString &DocumentRoot, FString &PortStr) { /* Initialize the library */ mg_init_library(0); const char *options[] = { "document_root", TCHAR_TO_ANSI(*DocumentRoot), "listening_ports", TCHAR_TO_ANSI(*PortStr), 0 }; /* Start the server */ ctx = mg_start(NULL, 0, options); if (ctx) { UE_LOG(UT4WebAdmin, Log, TEXT("==================")); UE_LOG(UT4WebAdmin, Log, TEXT("UT4WebAdmin Started:")); UE_LOG(UT4WebAdmin, Log, TEXT(" * Port : %i"), Port); UE_LOG(UT4WebAdmin, Log, TEXT(" * Root Web Folder: %s"), *DocumentRoot); UE_LOG(UT4WebAdmin, Log, TEXT("==================")); /* Add some handler */ mg_set_request_handler(ctx, "/", WelcomeHandler, "Hello world"); } else { UE_LOG(UT4WebAdmin, Warning, TEXT("==================")); UE_LOG(UT4WebAdmin, Warning, TEXT("UT4WebAdmin could not be started")); UE_LOG(UT4WebAdmin, Warning, TEXT("==================")); } } void UUT4WebAdmin::StopCivetWeb() { if (ctx) { /* Stop the server */ mg_stop(ctx); UE_LOG(UT4WebAdmin, Log, TEXT("UT4WebAdmin Stopped")); /* Un-initialize the library */ mg_exit_library(); } } #endif void UUT4WebAdmin::Stop() { #if defined(USE_CIVETWEB) StopCivetWeb(); #endif } void UUT4WebAdmin::Tick(float DeltaTime) { //poll(MGServer, 1); // TODO } TStatId UUT4WebAdmin::GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(UUT4WebAdmin, STATGROUP_Tickables); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Testing #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include <mitkTestingMacros.h> // std includes #include <string> #include <cmath> #include <iomanip> #include <tinyxml.h> // MITK includes #include <mitkNumericTypes.h> #include "mitkStringProperty.h" //itksys #include <itksys/SystemTools.hxx> // VTK includes #include <vtkDebugLeaks.h> //vnl includes #include <vnl/vnl_vector_fixed.hxx> class mitkTinyXMLTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkTinyXMLTestSuite); MITK_TEST(TestingFunctionSetupWorks_Success); MITK_TEST(TestingReadValueFromSetupDocument_Success); MITK_TEST(TestingReadOutValueWorks_Success); MITK_TEST(TestDoubleValueWriteOut_Success); MITK_TEST(TestDoubleValueWriteOutManyDecimalPlaces_Success); CPPUNIT_TEST_SUITE_END(); private: const std::string filename = itksys::SystemTools::GetCurrentWorkingDirectory() + "/TinyXMLTest.txt"; const std::string elementToStoreAttributeName = "DoubleTest"; const std::string attributeToStoreName = "CommaValue"; double calcPrecision(const unsigned int requiredDecimalPlaces) { return pow(10.0, -1.0 * ((double)requiredDecimalPlaces)); } bool Setup(double valueToWrite) { // 1. create simple document TiXmlDocument document; auto decl = new TiXmlDeclaration("1.0", "", ""); // TODO what to write here? encoding? etc.... document.LinkEndChild(decl); auto version = new TiXmlElement("Version"); version->SetAttribute("Writer", __FILE__); version->SetAttribute("CVSRevision", "$Revision: 17055 $"); version->SetAttribute("FileVersion", 1); document.LinkEndChild(version); // 2. store one element containing a double value with potentially many after comma digits. auto vElement = new TiXmlElement(elementToStoreAttributeName); vElement->SetDoubleAttribute(attributeToStoreName, valueToWrite); document.LinkEndChild(vElement); // 3. store in file. return document.SaveFile(filename); } public: void setUp() { double valueToWrite=0; TiXmlDocument document; auto decl = new TiXmlDeclaration("1.0", "", ""); auto version = new TiXmlElement("Version"); auto vElement = new TiXmlElement(elementToStoreAttributeName); } void tearDown() { } void TestingFunctionSetupWorks_Success() { CPPUNIT_ASSERT_MESSAGE("Test if setup and teardown correctly writes data to file", Setup(1.0)); } int readValueFromSetupDocument(double &readOutValue) { TiXmlDocument document; if (!document.LoadFile(filename)) { CPPUNIT_ASSERT_MESSAGE("Test Setup failed, could not open file", false); return TIXML_NO_ATTRIBUTE; } else { TiXmlElement *doubleTest = document.FirstChildElement(elementToStoreAttributeName); return doubleTest->QueryDoubleAttribute(attributeToStoreName, &readOutValue); } } void TestingReadValueFromSetupDocument_Success() { TiXmlDocument document; if (!document.LoadFile(filename)) { CPPUNIT_ASSERT_MESSAGE("Test Setup failed, could not open file", !document.LoadFile(filename)); } else { TiXmlElement *doubleTest = document.FirstChildElement(elementToStoreAttributeName); CPPUNIT_ASSERT_MESSAGE("Test Setup could open file", doubleTest != nullptr); } } /** * this first test ensures we can correctly readout values from the * TinyXMLDocument. */ void TestingReadOutValueWorks_Success() { double readValue; CPPUNIT_ASSERT_MESSAGE("checking if readout mechanism works.", TIXML_SUCCESS == readValueFromSetupDocument(readValue)); } void TestDoubleValueWriteOut_Success() { const double valueToWrite = -1.123456; const int validDigitsAfterComma = 6; // indicates the number of valid digits after comma of valueToWrite const double neededPrecision = calcPrecision(validDigitsAfterComma + 1); double readValue; Setup(valueToWrite); readValueFromSetupDocument(readValue); CPPUNIT_ASSERT_MESSAGE("Testing if value valueToWrite equals readValue which was retrieved from TinyXML document", mitk::Equal(valueToWrite, readValue, neededPrecision)); } void TestDoubleValueWriteOutManyDecimalPlaces_Success() { const double valueToWrite = -1.12345678910111; const int validDigitsAfterComma = 14; // indicates the number of valid digits after comma of valueToWrite const double neededPrecision = calcPrecision(validDigitsAfterComma + 1); double readValue; Setup(valueToWrite); readValueFromSetupDocument(readValue); CPPUNIT_ASSERT_MESSAGE("Testing if value valueToWrite equals readValue which was retrieved from TinyXML document", mitk::Equal(valueToWrite, readValue, neededPrecision)); } }; MITK_TEST_SUITE_REGISTRATION(mitkTinyXML) <commit_msg>Port mitk Tiny XML test, add setUp and tearDown<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Testing #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include <mitkTestingMacros.h> // std includes #include <string> #include <cmath> #include <iomanip> #include <tinyxml.h> // MITK includes #include <mitkNumericTypes.h> #include "mitkStringProperty.h" //itksys #include <itksys/SystemTools.hxx> // VTK includes #include <vtkDebugLeaks.h> //vnl includes #include <vnl/vnl_vector_fixed.hxx> class mitkTinyXMLTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkTinyXMLTestSuite); MITK_TEST(TestingFunctionSetupWorks_Success); MITK_TEST(TestingReadValueFromSetupDocument_Success); MITK_TEST(TestingReadOutValueWorks_Success); MITK_TEST(TestDoubleValueWriteOut_Success); MITK_TEST(TestDoubleValueWriteOutManyDecimalPlaces_Success); CPPUNIT_TEST_SUITE_END(); private: const std::string m_filename = itksys::SystemTools::GetCurrentWorkingDirectory() + "/TinyXMLTest.txt"; const std::string m_elementToStoreAttributeName = "DoubleTest"; const std::string m_attributeToStoreName = "CommaValue"; TiXmlDocument m_document; TiXmlElement *m_doubleTest; double calcPrecision(const unsigned int requiredDecimalPlaces) { return pow(10.0, -1.0 * ((double)requiredDecimalPlaces)); } bool Setup(double valueToWrite) { // 1. create simple document auto decl = new TiXmlDeclaration("1.0", "", ""); // TODO what to write here? encoding? etc.... m_document.LinkEndChild(decl); auto version = new TiXmlElement("Version"); version->SetAttribute("Writer", __FILE__); version->SetAttribute("CVSRevision", "$Revision: 17055 $"); version->SetAttribute("FileVersion", 1); m_document.LinkEndChild(version); // 2. store one element containing a double value with potentially many after comma digits. auto vElement = new TiXmlElement(m_elementToStoreAttributeName); vElement->SetDoubleAttribute(m_attributeToStoreName, valueToWrite); m_document.LinkEndChild(vElement); // 3. store in file. return m_document.SaveFile(m_filename); } public: void setUp() { TiXmlDocument m_document; } void tearDown() { } void TestingFunctionSetupWorks_Success() { CPPUNIT_ASSERT_MESSAGE("Test if setup and teardown correctly writes data to file", Setup(1.0)); } int readValueFromSetupDocument(double &readOutValue) { if (!m_document.LoadFile(m_filename)) { CPPUNIT_ASSERT_MESSAGE("Test Setup failed, could not open file", false); return TIXML_NO_ATTRIBUTE; } else { m_doubleTest = m_document.FirstChildElement(m_elementToStoreAttributeName); return m_doubleTest->QueryDoubleAttribute(m_attributeToStoreName, &readOutValue); } } void TestingReadValueFromSetupDocument_Success() { if (!m_document.LoadFile(m_filename)) { CPPUNIT_ASSERT_MESSAGE("Test Setup failed, could not open file", !m_document.LoadFile(m_filename)); } else { m_doubleTest = m_document.FirstChildElement(m_elementToStoreAttributeName); CPPUNIT_ASSERT_MESSAGE("Test Setup could open file", m_doubleTest != nullptr); } } /** * this first test ensures we can correctly readout values from the * TinyXMLDocument. */ void TestingReadOutValueWorks_Success() { double readValue; CPPUNIT_ASSERT_MESSAGE("checking if readout mechanism works.", TIXML_SUCCESS == readValueFromSetupDocument(readValue)); } void TestDoubleValueWriteOut_Success() { const double valueToWrite = -1.123456; const int validDigitsAfterComma = 6; // indicates the number of valid digits after comma of valueToWrite const double neededPrecision = calcPrecision(validDigitsAfterComma + 1); double readValue; Setup(valueToWrite); readValueFromSetupDocument(readValue); CPPUNIT_ASSERT_MESSAGE("Testing if value valueToWrite equals readValue which was retrieved from TinyXML document", mitk::Equal(valueToWrite, readValue, neededPrecision)); } void TestDoubleValueWriteOutManyDecimalPlaces_Success() { const double valueToWrite = -1.12345678910111; const int validDigitsAfterComma = 14; // indicates the number of valid digits after comma of valueToWrite const double neededPrecision = calcPrecision(validDigitsAfterComma + 1); double readValue; Setup(valueToWrite); readValueFromSetupDocument(readValue); CPPUNIT_ASSERT_MESSAGE("Testing if value valueToWrite equals readValue which was retrieved from TinyXML document", mitk::Equal(valueToWrite, readValue, neededPrecision)); } }; MITK_TEST_SUITE_REGISTRATION(mitkTinyXML) <|endoftext|>
<commit_before>#include <stdio.h> #include "../SynCommonLib/RelationsIterator.h" #include "../common/SyntaxHolder.h" void GetAnanlytForms(const CSentence& Sentence, string& Res) { for( int WordNo = 0; WordNo<Sentence.m_Words.size(); WordNo++ ) { const CSynWord& W = Sentence.m_Words[WordNo]; if (!W.m_MainVerbs.empty()) { Res += string("\t<analyt> ")+ W.m_strWord.c_str(); for (size_t i=0; i< W.m_MainVerbs.size(); i++) { Res += string(" ") + Sentence.m_Words[W.m_MainVerbs[i]].m_strWord; const CSynWord& W_1 = Sentence.m_Words[W.m_MainVerbs[i]]; for (size_t j=0; j< W_1.m_MainVerbs.size(); j++) Res += string(" ") + Sentence.m_Words[W_1.m_MainVerbs[j]].m_strWord; }; Res += "</analyt>\n"; } } } string GetWords(const CSentence& Sentence, const CPeriod& P) { string S; for (int WordNo = P.m_iFirstWord; WordNo <= P.m_iLastWord; WordNo++) { S += Sentence.m_Words[WordNo].m_strWord; if (WordNo < P.m_iLastWord) S += " "; }; return S; } void GetGroups(const CSentence& Sentence, const CAgramtab& A, string& Res) { int nClausesCount = Sentence.GetClausesCount(); for( int ClauseNo = 0; ClauseNo<nClausesCount; ClauseNo++ ) { const CClause& Clause = Sentence.GetClause(ClauseNo); int nCvar = Clause.m_SynVariants.size(); if (Clause.m_SynVariants.empty()) continue; int nVmax = Clause.m_SynVariants.begin()->m_iWeight; for( CSVI pSynVar=Clause.m_SynVariants.begin(); pSynVar != Clause.m_SynVariants.end(); pSynVar++ ) { if( pSynVar->m_iWeight < nVmax ) break; const CMorphVariant& V = *pSynVar; Res += Format("\t<synvar>\n"); // print the clause { int ClauseType = (V.m_ClauseTypeNo == -1) ? UnknownSyntaxElement : Clause.m_vectorTypes[V.m_ClauseTypeNo].m_Type;; string Type; if (ClauseType != UnknownSyntaxElement) Type = (const char*)A.GetClauseNameByType(ClauseType); else Type = "EMPTY"; Res += Format("\t\t<clause type=\"%s\">%s</clause>\n", Type.c_str(), GetWords(Sentence, Clause).c_str()); } for (int GroupNo = 0; GroupNo < V.m_vectorGroups.GetGroups().size(); GroupNo++) { const CGroup& G = V.m_vectorGroups.GetGroups()[GroupNo]; Res += Format("\t\t<group type=\"%s\">%s</group>\n", Sentence.GetOpt()->GetGroupNameByIndex(G.m_GroupType), GetWords(Sentence, G).c_str()); }; Res += Format("\t</synvar>\n"); } } } string GetNodeStr(const CSentence& Sentence, const CRelationsIterator& RelIt, int GroupNo, int WordNo) { if (GroupNo != -1) return GetWords(Sentence, RelIt.GetFirmGroups()[GroupNo]); else return Sentence.m_Words[WordNo].m_strWord; } void GetRelations(const CSentence& Sentence, string& Result) { CRelationsIterator RelIt; RelIt.SetSentence(&Sentence); for( int i = 0; i<Sentence.m_vectorPrClauseNo.size(); i++ ) RelIt.AddClauseNoAndVariantNo(Sentence.m_vectorPrClauseNo[i], 0); RelIt.BuildRelations(); for(long RelNo = 0 ; RelNo < RelIt.GetRelations().size() ; RelNo++ ) { const CSynOutputRelation& piRel = RelIt.GetRelations()[RelNo]; string RelName = Sentence.GetOpt()->GetGroupNameByIndex(piRel.m_Relation.type); string Src = GetNodeStr(Sentence, RelIt,piRel.m_iSourceGroup, piRel.m_Relation.m_iFirstWord); string Trg = GetNodeStr(Sentence, RelIt,piRel.m_iTargetGroup, piRel.m_Relation.m_iLastWord); Result += Format("\t<rel name=\"%s\"> %s -> %s </rel>\n", RelName.c_str(), Src.c_str(), Trg.c_str() ); } } string GetStringBySyntax(const CSentencesCollection& SC, const CAgramtab& A, string input) { string Result; Result += Format("<chunk>\n"); Result += Format("<input>%s</input>\n",input.c_str()); for (size_t nSent=0; nSent < SC.m_vectorSents.size(); nSent++) { const CSentence& Sentence = *SC.m_vectorSents[nSent]; int iWord=0,iClau=0,iCvar=0; Result += "<sent>\n"; GetAnanlytForms(Sentence, Result); GetGroups(Sentence, A, Result); GetRelations(Sentence, Result); Result += "</sent>\n"; } Result += Format("</chunk>\n"); fprintf (stderr, "sentences count: %i\n", SC.m_vectorSents.size()); return Result; }; void PrintUsage() { printf ("Dialing DWDS Command Line Syntax Parser(www.aot.ru, www.dwds.de)\n"); printf ("Usage: TestSynan (RUSSIAN|GERMAN) [filename.txt] - \n"); printf ("Example: TestSynan Russian\n"); exit(1); }; int main(int argc, char* argv[]) { try { MorphLanguageEnum langua = morphUnknown; string FileName; for (size_t i=1; i<argc; i++) { string s = argv[i]; EngMakeLower(s); if ( (s == "-help") || (s == "--help") || (s == "/?") ) PrintUsage(); else { if (langua == morphUnknown) { if (!GetLanguageByString(s, langua)) PrintUsage(); } else { FileName = s; if (!FileExists(FileName.c_str())) { fprintf (stderr, "cannot open file %s\n", FileName.c_str()); exit(1); } } } } if ((langua == morphUnknown)) PrintUsage(); CSyntaxHolder H; if (!H.LoadSyntax(langua)) { fprintf (stderr, "initialization error\n"); return 1; }; fprintf (stderr, "ok\n"); if (!FileName.empty()) { vector<string> Files; if ((FileName.length() > 4) && FileName.substr(FileName.length() -4) == ".lst") { FILE* fp = fopen(FileName.c_str(), "r"); if (!fp) { fprintf( stderr, "cannot open %s\n", FileName.c_str()); return 1; } char buffer[1024]; while (fgets (buffer, 1024, fp)) { rtrim (buffer); Files.push_back(buffer); } fclose (fp); } else Files.push_back(FileName); for (size_t i=0; i < Files.size(); i++) { fprintf( stderr, "File %s\n", Files[i].c_str()); fflush (stderr); H.m_bTimeStatis = true; H.GetSentencesFromSynAn(Files[i], true); string s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, Files[i].c_str()); printf ("%s\n\n", s.c_str()); } return 0; } // =============== WORKING =============== char buffer[10000] ; while (fgets(buffer, 10000, stdin)) { string s = buffer; Trim(s); if (s.empty()) continue; H.GetSentencesFromSynAn(s, false); s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, s); printf ("%s", s.c_str()); fflush(stdout); }; } catch(...) { fprintf (stderr, "an exception occurred!\n"); return 1; }; return 0; }; <commit_msg>bug fix<commit_after>#include <stdio.h> #include "../SynCommonLib/RelationsIterator.h" #include "../common/SyntaxHolder.h" void GetAnanlytForms(const CSentence& Sentence, string& Res) { for( int WordNo = 0; WordNo<Sentence.m_Words.size(); WordNo++ ) { const CSynWord& W = Sentence.m_Words[WordNo]; if (!W.m_MainVerbs.empty()) { Res += string("\t<analyt> ")+ W.m_strWord.c_str(); for (size_t i=0; i< W.m_MainVerbs.size(); i++) { Res += string(" ") + Sentence.m_Words[W.m_MainVerbs[i]].m_strWord; const CSynWord& W_1 = Sentence.m_Words[W.m_MainVerbs[i]]; for (size_t j=0; j< W_1.m_MainVerbs.size(); j++) Res += string(" ") + Sentence.m_Words[W_1.m_MainVerbs[j]].m_strWord; }; Res += "</analyt>\n"; } } } string GetWords(const CSentence& Sentence, const CPeriod& P) { string S; for (int WordNo = P.m_iFirstWord; WordNo <= P.m_iLastWord; WordNo++) { S += Sentence.m_Words[WordNo].m_strWord; if (WordNo < P.m_iLastWord) S += " "; }; return S; } void GetGroups(const CSentence& Sentence, const CAgramtab& A, string& Res) { int nClausesCount = Sentence.GetClausesCount(); for( int ClauseNo = 0; ClauseNo<nClausesCount; ClauseNo++ ) { const CClause& Clause = Sentence.GetClause(ClauseNo); int nCvar = Clause.m_SynVariants.size(); if (Clause.m_SynVariants.empty()) continue; int nVmax = Clause.m_SynVariants.begin()->m_iWeight; for( CSVI pSynVar=Clause.m_SynVariants.begin(); pSynVar != Clause.m_SynVariants.end(); pSynVar++ ) { if( pSynVar->m_iWeight < nVmax ) break; const CMorphVariant& V = *pSynVar; Res += Format("\t<synvar>\n"); // print the clause { int ClauseType = (V.m_ClauseTypeNo == -1) ? UnknownSyntaxElement : Clause.m_vectorTypes[V.m_ClauseTypeNo].m_Type;; string Type; if (ClauseType != UnknownSyntaxElement) Type = (const char*)A.GetClauseNameByType(ClauseType); else Type = "EMPTY"; Res += Format("\t\t<clause type=\"%s\">%s</clause>\n", Type.c_str(), GetWords(Sentence, Clause).c_str()); } for (int GroupNo = 0; GroupNo < V.m_vectorGroups.GetGroups().size(); GroupNo++) { const CGroup& G = V.m_vectorGroups.GetGroups()[GroupNo]; Res += Format("\t\t<group type=\"%s\">%s</group>\n", Sentence.GetOpt()->GetGroupNameByIndex(G.m_GroupType), GetWords(Sentence, G).c_str()); }; Res += Format("\t</synvar>\n"); } } } string GetNodeStr(const CSentence& Sentence, const CRelationsIterator& RelIt, int GroupNo, int WordNo) { if (GroupNo != -1) return GetWords(Sentence, RelIt.GetFirmGroups()[GroupNo]); else return Sentence.m_Words[WordNo].m_strWord; } void GetRelations(const CSentence& Sentence, string& Result) { CRelationsIterator RelIt; RelIt.SetSentence(&Sentence); for( int i = 0; i<Sentence.m_vectorPrClauseNo.size(); i++ ) RelIt.AddClauseNoAndVariantNo(Sentence.m_vectorPrClauseNo[i], 0); RelIt.BuildRelations(); for(long RelNo = 0 ; RelNo < RelIt.GetRelations().size() ; RelNo++ ) { const CSynOutputRelation& piRel = RelIt.GetRelations()[RelNo]; string RelName = Sentence.GetOpt()->GetGroupNameByIndex(piRel.m_Relation.type); string Src = GetNodeStr(Sentence, RelIt,piRel.m_iSourceGroup, piRel.m_Relation.m_iFirstWord); string Trg = GetNodeStr(Sentence, RelIt,piRel.m_iTargetGroup, piRel.m_Relation.m_iLastWord); Result += Format("\t<rel name=\"%s\"> %s -> %s </rel>\n", RelName.c_str(), Src.c_str(), Trg.c_str() ); } } string GetStringBySyntax(const CSentencesCollection& SC, const CAgramtab& A, string input) { string Result; Result += Format("<chunk>\n"); Result += Format("<input>%s</input>\n",input.c_str()); for (size_t nSent=0; nSent < SC.m_vectorSents.size(); nSent++) { const CSentence& Sentence = *SC.m_vectorSents[nSent]; int iWord=0,iClau=0,iCvar=0; Result += "<sent>\n"; GetAnanlytForms(Sentence, Result); GetGroups(Sentence, A, Result); GetRelations(Sentence, Result); Result += "</sent>\n"; } Result += Format("</chunk>\n"); fprintf (stderr, "sentences count: %i\n", SC.m_vectorSents.size()); return Result; }; void PrintUsage() { printf ("Dialing DWDS Command Line Syntax Parser(www.aot.ru, www.dwds.de)\n"); printf ("Usage: TestSynan (RUSSIAN|GERMAN) [filename.txt] - \n"); printf ("Example: TestSynan Russian\n"); exit(1); }; int main(int argc, char* argv[]) { try { MorphLanguageEnum langua = morphUnknown; string FileName; for (size_t i=1; i<argc; i++) { string s = argv[i]; EngMakeLower(s); if ( (s == "-help") || (s == "--help") || (s == "/?") ) PrintUsage(); else { if (langua == morphUnknown) { if (!GetLanguageByString(s, langua)) PrintUsage(); } else { FileName = argv[i]; if (!FileExists(FileName.c_str())) { fprintf (stderr, "cannot open file %s\n", FileName.c_str()); exit(1); } } } } if ((langua == morphUnknown)) PrintUsage(); CSyntaxHolder H; if (!H.LoadSyntax(langua)) { fprintf (stderr, "initialization error\n"); return 1; }; fprintf (stderr, "ok\n"); if (!FileName.empty()) { vector<string> Files; if ((FileName.length() > 4) && FileName.substr(FileName.length() -4) == ".lst") { FILE* fp = fopen(FileName.c_str(), "r"); if (!fp) { fprintf( stderr, "cannot open %s\n", FileName.c_str()); return 1; } char buffer[1024]; while (fgets (buffer, 1024, fp)) { rtrim (buffer); Files.push_back(buffer); } fclose (fp); } else Files.push_back(FileName); for (size_t i=0; i < Files.size(); i++) { fprintf( stderr, "File %s\n", Files[i].c_str()); fflush (stderr); H.m_bTimeStatis = true; H.GetSentencesFromSynAn(Files[i], true); string s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, Files[i].c_str()); printf ("%s\n\n", s.c_str()); } return 0; } // =============== WORKING =============== char buffer[10000] ; while (fgets(buffer, 10000, stdin)) { string s = buffer; Trim(s); if (s.empty()) continue; H.GetSentencesFromSynAn(s, false); s = GetStringBySyntax(H.m_Synan, *H.m_pGramTab, s); printf ("%s", s.c_str()); fflush(stdout); }; } catch(...) { fprintf (stderr, "an exception occurred!\n"); return 1; }; return 0; }; <|endoftext|>
<commit_before><commit_msg>First iteration of creating udp sink.<commit_after>#include "Mocks.hpp" #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> namespace asio = boost::asio; namespace blackhole { namespace sink { class socket_t { asio::io_service io_service; asio::ip::udp::endpoint endpoint; std::unique_ptr<asio::ip::udp::socket> socket; public: socket_t(const std::string& host, std::uint16_t port) { asio::ip::udp::resolver resolver(io_service); asio::ip::udp::resolver::query query(host, boost::lexical_cast<std::string>(port)); asio::ip::udp::resolver::iterator it = resolver.resolve(query); //!@todo: May throw! asio::ip::udp::resolver::iterator end; std::vector<asio::ip::udp::endpoint> endpoints(it, end); for (auto it = endpoints.begin(); it != endpoints.end(); ++it) { try { socket = std::make_unique<asio::ip::udp::socket>(io_service); endpoint = *it; socket->open(endpoint.protocol()); break; } catch (const boost::system::system_error& err) { std::cout << err.what() << std::endl; continue; } } } void consume(const std::string& message) { try { socket->send_to(boost::asio::buffer(message.data(), message.size()), endpoint); } catch (const std::exception& err) { std::cout << "!" << err.what() << std::endl; } catch (...) { std::cout << "WTF?" << std::endl; } } }; } // namespace sink } // namespace blackhole TEST(socket_t, Class) { sink::socket_t sink("localhost", 50030); sink.consume("{\"@message\": \"le message\"}"); } //!@todo: TestCanSendMessages. //!@todo: ThrowsExceptionIfAnyErrorOccurred. //!@todo: DoSomethingIfCannotCreateSocket //!@todo: DoSomethingIfCannotConnect //!@todo: DoSomethingOnWriteError <|endoftext|>
<commit_before>/** * @file posix/wait.cpp * @brief POSIX event/timeout handling * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #include "mega/thread/posixthread.h" #ifdef USE_PTHREAD namespace mega { PosixThread::PosixThread() { thread = new pthread_t; } void PosixThread::start(void *(*start_routine)(void*), void *parameter) { pthread_create(thread, NULL, start_routine, parameter); } void PosixThread::join() { pthread_join(*thread, NULL); } PosixThread::~PosixThread() { delete thread; } //PosixMutex PosixMutex::PosixMutex() { mutex = NULL; attr = NULL; } void PosixMutex::init(bool recursive) { if(recursive) { mutex = new pthread_mutex_t; attr = new pthread_mutexattr_t; pthread_mutexattr_init(attr); pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(mutex, attr); } else { mutex = new pthread_mutex_t; pthread_mutex_init(mutex, NULL); } } void PosixMutex::lock() { pthread_mutex_lock(mutex); } void PosixMutex::unlock() { pthread_mutex_unlock(mutex); } PosixMutex::~PosixMutex() { if (mutex) { pthread_mutex_destroy(mutex); delete mutex; } if (attr) { pthread_mutexattr_destroy(attr); delete attr; } } //PosixSemaphore PosixSemaphore::PosixSemaphore() { semaphore = new sem_t; if (sem_init(semaphore, 0, 0) == -1) { LOG_fatal << "Error creating semaphore: " << errno; } } void PosixSemaphore::wait() { while (sem_wait(&semaphore) == -1) { if (errno == EINTR) { continue; } LOG_fatal << "Error in sem_wait: " << errno; } } static inline void timespec_add_msec(struct timespec *tv, int milliseconds) { int seconds = milliseconds / 1000; int milliseconds_left = milliseconds % 1000; tv->tv_sec += seconds; tv->tv_nsec += milliseconds_left * 1000000; if (tv->tv_nsec >= 1000000000) { tv->tv_nsec -= 1000000000; tv->tv_sec++; } } int PosixSemaphore::timedwait(int milliseconds) { int ret; struct timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { LOG_err << "Error in clock_gettime"; return -2; } timespec_add_msec (&ts, milliseconds); while (true) { ret = sem_timedwait(semaphore, &ts); if (!ret) { return 0; } if (errno == ETIMEDOUT) { return -1; } if (errno == EINTR) { continue; } LOG_err << "Error in sem_timedwait: " << errno; return -2; } } void PosixSemaphore::release() { if (sem_post(semaphore) == -1) { LOG_fatal << "Error in sem_post: " << errno; } } PosixSemaphore::~PosixSemaphore() { sem_destroy(semaphore); delete semaphore; } }// namespace #endif <commit_msg>fix posixsemaphore wait<commit_after>/** * @file posix/wait.cpp * @brief POSIX event/timeout handling * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #include "mega/thread/posixthread.h" #ifdef USE_PTHREAD namespace mega { PosixThread::PosixThread() { thread = new pthread_t; } void PosixThread::start(void *(*start_routine)(void*), void *parameter) { pthread_create(thread, NULL, start_routine, parameter); } void PosixThread::join() { pthread_join(*thread, NULL); } PosixThread::~PosixThread() { delete thread; } //PosixMutex PosixMutex::PosixMutex() { mutex = NULL; attr = NULL; } void PosixMutex::init(bool recursive) { if(recursive) { mutex = new pthread_mutex_t; attr = new pthread_mutexattr_t; pthread_mutexattr_init(attr); pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(mutex, attr); } else { mutex = new pthread_mutex_t; pthread_mutex_init(mutex, NULL); } } void PosixMutex::lock() { pthread_mutex_lock(mutex); } void PosixMutex::unlock() { pthread_mutex_unlock(mutex); } PosixMutex::~PosixMutex() { if (mutex) { pthread_mutex_destroy(mutex); delete mutex; } if (attr) { pthread_mutexattr_destroy(attr); delete attr; } } //PosixSemaphore PosixSemaphore::PosixSemaphore() { semaphore = new sem_t; if (sem_init(semaphore, 0, 0) == -1) { LOG_fatal << "Error creating semaphore: " << errno; } } void PosixSemaphore::wait() { while (sem_wait(semaphore) == -1) { if (errno == EINTR) { continue; } LOG_fatal << "Error in sem_wait: " << errno; } } static inline void timespec_add_msec(struct timespec *tv, int milliseconds) { int seconds = milliseconds / 1000; int milliseconds_left = milliseconds % 1000; tv->tv_sec += seconds; tv->tv_nsec += milliseconds_left * 1000000; if (tv->tv_nsec >= 1000000000) { tv->tv_nsec -= 1000000000; tv->tv_sec++; } } int PosixSemaphore::timedwait(int milliseconds) { int ret; struct timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { LOG_err << "Error in clock_gettime"; return -2; } timespec_add_msec (&ts, milliseconds); while (true) { ret = sem_timedwait(semaphore, &ts); if (!ret) { return 0; } if (errno == ETIMEDOUT) { return -1; } if (errno == EINTR) { continue; } LOG_err << "Error in sem_timedwait: " << errno; return -2; } } void PosixSemaphore::release() { if (sem_post(semaphore) == -1) { LOG_fatal << "Error in sem_post: " << errno; } } PosixSemaphore::~PosixSemaphore() { sem_destroy(semaphore); delete semaphore; } }// namespace #endif <|endoftext|>
<commit_before>#include "stdafx.h" #include "Calculator.h" float Calculator::parseExpr(boost::string_ref &ref) { float result = parseExprSum(ref); if (!ref.empty()) { return std::numeric_limits<float>::quiet_NaN(); } return result; } float Calculator::parseExprSum(boost::string_ref &ref) { float value = parseExprMul(ref); while (true) { skipSpaces(ref); if (!ref.empty() && ref[0] == '+') { ref.remove_prefix(1); value += parseExprMul(ref); } else if (!ref.empty() && ref[0] == '-') { ref.remove_prefix(1); value -= parseExprMul(ref); } else { break; } } return value; } float Calculator::parseExprMul(boost::string_ref &ref) { float value = parseSymbol(ref); while (true) { skipSpaces(ref); if (!ref.empty() && ref[0] == '*') { ref.remove_prefix(1); value *= parseSymbol(ref); } else if (!ref.empty() && ref[0] == '/') { ref.remove_prefix(1); value /= parseSymbol(ref); } else { break; } } return value; } float Calculator::parseSymbol(boost::string_ref &ref) { float value = 0; skipSpaces(ref); if (!ref.empty() && ref[0] == '(') { ref.remove_prefix(1); value = parseExprSum(ref); skipSpaces(ref); if (!ref.empty() && ref[0] == ')') { ref.remove_prefix(1); return value; } else { return std::numeric_limits<float>::quiet_NaN(); } } else { return parseFloat(ref); } } float Calculator::parseFloat(boost::string_ref &ref) { float value = 0; bool parsedAny = false; skipSpaces(ref); while (!ref.empty() && std::isdigit(ref[0])) { parsedAny = true; const int digit = ref[0] - '0'; value = value * 10.0f + float(digit); ref.remove_prefix(1); } if (!parsedAny) { return std::numeric_limits<float>::quiet_NaN(); } if (ref.empty() || (ref[0] != '.')) { return value; } ref.remove_prefix(1); float factor = 1.f; while (!ref.empty() && std::isdigit(ref[0])) { const int digit = ref[0] - '0'; factor *= 0.1f; value += factor * float(digit); ref.remove_prefix(1); } return value; } void Calculator::skipSpaces(boost::string_ref &ref) { size_t i = 0; while (i < ref.size() && std::isspace(ref[i])) { ++i; } ref.remove_prefix(i); } <commit_msg>Вывод в обратной польской нотации в консоль<commit_after>#include "stdafx.h" #include "Calculator.h" float Calculator::parseExpr(boost::string_ref &ref) { float result = parseExprSum(ref); if (!ref.empty()) { return std::numeric_limits<float>::quiet_NaN(); } return result; } float Calculator::parseExprSum(boost::string_ref &ref) { float value = parseExprMul(ref); while (true) { skipSpaces(ref); if (!ref.empty() && ref[0] == '+') { ref.remove_prefix(1); value += parseExprMul(ref); std::cout << "+ "; } else if (!ref.empty() && ref[0] == '-') { ref.remove_prefix(1); value -= parseExprMul(ref); std::cout << "- "; } else { break; } } return value; } float Calculator::parseExprMul(boost::string_ref &ref) { float value = parseSymbol(ref); while (true) { skipSpaces(ref); if (!ref.empty() && ref[0] == '*') { ref.remove_prefix(1); value *= parseSymbol(ref); std::cout << "* "; } else if (!ref.empty() && ref[0] == '/') { ref.remove_prefix(1); value /= parseSymbol(ref); std::cout << "/ "; } else { break; } } return value; } float Calculator::parseSymbol(boost::string_ref &ref) { float value = 0; skipSpaces(ref); if (!ref.empty() && ref[0] == '(') { ref.remove_prefix(1); value = parseExprSum(ref); skipSpaces(ref); if (!ref.empty() && ref[0] == ')') { ref.remove_prefix(1); return value; } else { return std::numeric_limits<float>::quiet_NaN(); } } else { return parseFloat(ref); } } float Calculator::parseFloat(boost::string_ref &ref) { float value = 0; bool parsedAny = false; skipSpaces(ref); while (!ref.empty() && std::isdigit(ref[0])) { parsedAny = true; const int digit = ref[0] - '0'; value = value * 10.0f + float(digit); ref.remove_prefix(1); } if (!parsedAny) { return std::numeric_limits<float>::quiet_NaN(); } if (ref.empty() || (ref[0] != '.')) { std::cout << value << " "; return value; } ref.remove_prefix(1); float factor = 1.f; while (!ref.empty() && std::isdigit(ref[0])) { const int digit = ref[0] - '0'; factor *= 0.1f; value += factor * float(digit); ref.remove_prefix(1); } std::cout << value << " "; return value; } void Calculator::skipSpaces(boost::string_ref &ref) { size_t i = 0; while (i < ref.size() && std::isspace(ref[i])) { ++i; } ref.remove_prefix(i); } <|endoftext|>
<commit_before>#pragma once #include "../geometry/point2d.hpp" #include "../base/assert.hpp" #include "../base/base.hpp" #include "../base/buffer_vector.hpp" #include "../base/logging.hpp" #include "../base/math.hpp" #include "../std/algorithm.hpp" namespace covering { enum CellObjectIntersection { CELL_OBJECT_NO_INTERSECTION = 0, CELL_OBJECT_INTERSECT = 1, CELL_INSIDE_OBJECT = 2, OBJECT_INSIDE_CELL = 3 }; template <class CellIdT> inline CellObjectIntersection IntersectCellWithLine(CellIdT const cell, m2::PointD const & a, m2::PointD const & b) { pair<uint32_t, uint32_t> const xy = cell.XY(); uint32_t const r = cell.Radius(); m2::PointD const cellCorners[4] = { m2::PointD(xy.first - r, xy.second - r), m2::PointD(xy.first - r, xy.second + r), m2::PointD(xy.first + r, xy.second + r), m2::PointD(xy.first + r, xy.second - r) }; for (int i = 0; i < 4; ++i) if (m2::SegmentsIntersect(a, b, cellCorners[i], cellCorners[i == 0 ? 3 : i - 1])) return CELL_OBJECT_INTERSECT; if (xy.first - r <= a.x && a.x <= xy.first + r && xy.second - r <= a.y && a.y <= xy.second + r) return OBJECT_INSIDE_CELL; return CELL_OBJECT_NO_INTERSECTION; } template <class CellIdT> CellObjectIntersection IntersectCellWithTriangle( CellIdT const cell, m2::PointD const & a, m2::PointD const & b, m2::PointD const & c) { CellObjectIntersection const i1 = IntersectCellWithLine(cell, a, b); if (i1 == CELL_OBJECT_INTERSECT) return CELL_OBJECT_INTERSECT; CellObjectIntersection const i2 = IntersectCellWithLine(cell, b, c); if (i2 == CELL_OBJECT_INTERSECT) return CELL_OBJECT_INTERSECT; CellObjectIntersection const i3 = IntersectCellWithLine(cell, c, a); if (i3 == CELL_OBJECT_INTERSECT) return CELL_OBJECT_INTERSECT; ASSERT_EQUAL(i1, i2, (cell, a, b, c)); ASSERT_EQUAL(i2, i3, (cell, a, b, c)); ASSERT_EQUAL(i3, i1, (cell, a, b, c)); return i1; } template <class CellIdT, class CellIdContainerT, typename IntersectF> void CoverObject(IntersectF const & intersect, uint64_t cellPenaltyArea, CellIdContainerT & out, CellIdT cell) { uint64_t const cellArea = my::sq(uint64_t(1 << (CellIdT::DEPTH_LEVELS - 1 - cell.Level()))); CellObjectIntersection const intersection = intersect(cell); if (intersection == CELL_OBJECT_NO_INTERSECTION) return; if (intersection == CELL_INSIDE_OBJECT || cell.Level() == CellIdT::DEPTH_LEVELS - 1 || cellPenaltyArea >= cellArea) { out.push_back(cell); return; } buffer_vector<CellIdT, 32> subdiv; for (uint8_t i = 0; i < 4; ++i) CoverObject(intersect, cellPenaltyArea, subdiv, cell.Child(i)); uint64_t subdivArea = 0; for (size_t i = 0; i < subdiv.size(); ++i) subdivArea += my::sq(uint64_t(1 << (CellIdT::DEPTH_LEVELS - 1 - subdiv[i].Level()))); ASSERT(!subdiv.empty(), (cellPenaltyArea, out, cell)); if (subdiv.empty() || cellPenaltyArea * (int(subdiv.size()) - 1) >= cellArea - subdivArea) out.push_back(cell); else for (size_t i = 0; i < subdiv.size(); ++i) out.push_back(subdiv[i]); } } // namespace covering <commit_msg>Fix bug in IntersectCellWithTriangle()!! It was detected by a unit test, restored in commit 647b4bf4.<commit_after>#pragma once #include "../geometry/point2d.hpp" #include "../base/assert.hpp" #include "../base/base.hpp" #include "../base/buffer_vector.hpp" #include "../base/logging.hpp" #include "../base/math.hpp" #include "../std/algorithm.hpp" namespace covering { enum CellObjectIntersection { CELL_OBJECT_NO_INTERSECTION = 0, CELL_OBJECT_INTERSECT = 1, CELL_INSIDE_OBJECT = 2, OBJECT_INSIDE_CELL = 3 }; template <class CellIdT> inline CellObjectIntersection IntersectCellWithLine(CellIdT const cell, m2::PointD const & a, m2::PointD const & b) { pair<uint32_t, uint32_t> const xy = cell.XY(); uint32_t const r = cell.Radius(); m2::PointD const cellCorners[4] = { m2::PointD(xy.first - r, xy.second - r), m2::PointD(xy.first - r, xy.second + r), m2::PointD(xy.first + r, xy.second + r), m2::PointD(xy.first + r, xy.second - r) }; for (int i = 0; i < 4; ++i) if (m2::SegmentsIntersect(a, b, cellCorners[i], cellCorners[i == 0 ? 3 : i - 1])) return CELL_OBJECT_INTERSECT; if (xy.first - r <= a.x && a.x <= xy.first + r && xy.second - r <= a.y && a.y <= xy.second + r) return OBJECT_INSIDE_CELL; return CELL_OBJECT_NO_INTERSECTION; } template <class CellIdT> CellObjectIntersection IntersectCellWithTriangle( CellIdT const cell, m2::PointD const & a, m2::PointD const & b, m2::PointD const & c) { CellObjectIntersection const i1 = IntersectCellWithLine(cell, a, b); if (i1 == CELL_OBJECT_INTERSECT) return CELL_OBJECT_INTERSECT; CellObjectIntersection const i2 = IntersectCellWithLine(cell, b, c); if (i2 == CELL_OBJECT_INTERSECT) return CELL_OBJECT_INTERSECT; CellObjectIntersection const i3 = IntersectCellWithLine(cell, c, a); if (i3 == CELL_OBJECT_INTERSECT) return CELL_OBJECT_INTERSECT; // At this point either: // 1. Triangle is inside cell. // 2. Cell is inside triangle. // 3. Cell and triangle do not intersect. ASSERT_EQUAL(i1, i2, (cell, a, b, c)); ASSERT_EQUAL(i2, i3, (cell, a, b, c)); ASSERT_EQUAL(i3, i1, (cell, a, b, c)); if (i1 == OBJECT_INSIDE_CELL || i2 == OBJECT_INSIDE_CELL || i3 == OBJECT_INSIDE_CELL) return OBJECT_INSIDE_CELL; pair<uint32_t, uint32_t> const xy = cell.XY(); if (m2::IsPointStrictlyInsideTriangle(m2::PointD(xy.first, xy.second), a, b, c)) return CELL_INSIDE_OBJECT; return CELL_OBJECT_NO_INTERSECTION; } template <class CellIdT, class CellIdContainerT, typename IntersectF> void CoverObject(IntersectF const & intersect, uint64_t cellPenaltyArea, CellIdContainerT & out, CellIdT cell) { uint64_t const cellArea = my::sq(uint64_t(1 << (CellIdT::DEPTH_LEVELS - 1 - cell.Level()))); CellObjectIntersection const intersection = intersect(cell); if (intersection == CELL_OBJECT_NO_INTERSECTION) return; if (intersection == CELL_INSIDE_OBJECT || cell.Level() == CellIdT::DEPTH_LEVELS - 1 || cellPenaltyArea >= cellArea) { out.push_back(cell); return; } buffer_vector<CellIdT, 32> subdiv; for (uint8_t i = 0; i < 4; ++i) CoverObject(intersect, cellPenaltyArea, subdiv, cell.Child(i)); uint64_t subdivArea = 0; for (size_t i = 0; i < subdiv.size(); ++i) subdivArea += my::sq(uint64_t(1 << (CellIdT::DEPTH_LEVELS - 1 - subdiv[i].Level()))); ASSERT(!subdiv.empty(), (cellPenaltyArea, out, cell)); if (subdiv.empty() || cellPenaltyArea * (int(subdiv.size()) - 1) >= cellArea - subdivArea) out.push_back(cell); else for (size_t i = 0; i < subdiv.size(); ++i) out.push_back(subdiv[i]); } } // namespace covering <|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008 Kevin Ottens <ervin@kde.org> Copyright 2008, 2009 Mario Bensi <nef@ipsquad.net> 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "todoproxymodelbase.h" #include <QtCore/QStringList> #include <KDE/KDebug> #include <KDE/KIcon> #include <KDE/KLocale> #include "todonode.h" #include "todonodemanager.h" TodoProxyModelBase::TodoProxyModelBase(MappingType type, QObject *parent) : QAbstractProxyModel(parent), m_manager(new TodoNodeManager(this, (type==MultiMapping ? true : false))), m_inboxNode(0), m_mappingType(type) { } TodoProxyModelBase::~TodoProxyModelBase() { delete m_manager; } void TodoProxyModelBase::init() { if (!m_inboxNode) { beginInsertRows(QModelIndex(), 0, 0); m_inboxNode = createInbox(); m_manager->insertNode(m_inboxNode); endInsertRows(); } } QModelIndex TodoProxyModelBase::index(int row, int column, const QModelIndex &parent) const { return m_manager->index(row, column, parent); } QModelIndex TodoProxyModelBase::buddy(const QModelIndex &index) const { return index; } QModelIndex TodoProxyModelBase::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } TodoNode *parent = m_manager->nodeForIndex(index)->parent(); if (parent == 0) { return QModelIndex(); } else { return m_manager->indexForNode(parent, 0); } } int TodoProxyModelBase::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { return m_manager->roots().size(); } else if (parent.column() == 0) { // Only one set of children per row TodoNode *node = m_manager->nodeForIndex(parent); return node->children().size(); } return 0; } int TodoProxyModelBase::columnCount(const QModelIndex &parent) const { if (!sourceModel()) { return 1; } if (parent.isValid()) { TodoNode *node = m_manager->nodeForIndex(parent); if (node && node->children().size() > 0) { return sourceModel()->columnCount(); } else { return 0; } } else { return sourceModel()->columnCount(mapToSource(parent)); } } bool TodoProxyModelBase::hasChildren(const QModelIndex &parent) const { // Since Qt 4.8, QAbstractProxyModel just forwards hasChildren to the source model // so that's not based on the current model rowCount() and columnCount(), because // of that it's easy to end up with inconsistent replies between rowCount() and // hasChildren() for instance (resulting in empty views or crashes in proxies). // // So, here we just use the hasChildren() implementation inherited from QAbstractItemModel // since it is based on rowCount() and columnCount(). return QAbstractItemModel::hasChildren(parent); } QVariant TodoProxyModelBase::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical) { return QAbstractProxyModel::headerData(section, orientation, role); } else { if (!sourceModel()) { return QVariant(); } return sourceModel()->headerData(section, orientation, role); } } QVariant TodoProxyModelBase::data(const QModelIndex &index, int role) const { Q_ASSERT(index.model() == this); TodoNode *node = m_manager->nodeForIndex(index); if (node == 0) { return QVariant(); } return node->data(index.column(), role); } Qt::ItemFlags TodoProxyModelBase::flags(const QModelIndex &index) const { TodoNode *node = m_manager->nodeForIndex(index); if (node == 0) { return Qt::NoItemFlags; } return node->flags(index.column()); } QModelIndex TodoProxyModelBase::mapToSource(const QModelIndex &proxyIndex) const { TodoNode *node = m_manager->nodeForIndex(proxyIndex); if (!node) { return QModelIndex(); } else { QModelIndex rowSourceIndex = node->rowSourceIndex(); return rowSourceIndex.sibling(rowSourceIndex.row(), proxyIndex.column()); } } QList<QModelIndex> TodoProxyModelBase::mapFromSourceAll(const QModelIndex &sourceIndex) const { if (m_mappingType==SimpleMapping) { kError() << "Never call mapFromSourceAll() for a SimpleMapping model"; return QList<QModelIndex>(); } QList<TodoNode*> nodes = m_manager->nodesForSourceIndex(sourceIndex); QList<QModelIndex> indexes; foreach (TodoNode *node, nodes) { indexes << m_manager->indexForNode(node, sourceIndex.column()); } return indexes; } QModelIndex TodoProxyModelBase::mapFromSource(const QModelIndex &sourceIndex) const { if (m_mappingType==MultiMapping) { kWarning() << "Never call mapFromSource() for a MultiMapping model"; //This is useful for selecting an item in the list //If we just return an empty index we break EntityTreeModel::modelIndexesForItem QList<TodoNode*> nodes = m_manager->nodesForSourceIndex(sourceIndex); if (nodes.isEmpty()) { return QModelIndex(); } return m_manager->indexForNode(nodes.first(), sourceIndex.column()); } TodoNode *node = m_manager->nodeForSourceIndex(sourceIndex); return m_manager->indexForNode(node, sourceIndex.column()); } void TodoProxyModelBase::setSourceModel(QAbstractItemModel *model) { init(); if (sourceModel()) { disconnect(sourceModel(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(onSourceDataChanged(QModelIndex,QModelIndex))); disconnect(sourceModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(onSourceInsertRows(QModelIndex,int,int))); disconnect(sourceModel(), SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(onSourceRemoveRows(QModelIndex,int,int))); disconnect(sourceModel(), SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(onRowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int))); disconnect(sourceModel(), SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(onRowsMoved(QModelIndex,int,int,QModelIndex,int))); connect(sourceModel(), SIGNAL(modelReset()), this, SLOT(onModelReset())); } if (model) { connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(onSourceDataChanged(QModelIndex,QModelIndex))); connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(onSourceInsertRows(QModelIndex,int,int))); connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(onSourceRemoveRows(QModelIndex,int,int))); connect(model, SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(onRowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int))); connect(model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(onRowsMoved(QModelIndex,int,int,QModelIndex,int))); connect(model, SIGNAL(modelReset()), this, SLOT(onModelReset())); } QAbstractProxyModel::setSourceModel(model); onSourceInsertRows(QModelIndex(), 0, sourceModel()->rowCount() - 1); } TodoNode *TodoProxyModelBase::addChildNode(const QModelIndex &sourceIndex, TodoNode *parent) { QModelIndex proxyParentIndex = m_manager->indexForNode(parent, 0); int row = 0; if (parent) { row = parent->children().size(); } else { row = m_manager->roots().size(); } beginInsertRows(proxyParentIndex, row, row); TodoNode *child = new TodoNode(sourceIndex, parent); m_manager->insertNode(child); endInsertRows(); return child; } void TodoProxyModelBase::onRowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &/*destinationParent*/, int /*destinationRow*/) { onSourceRemoveRows(sourceParent, sourceStart, sourceEnd); } void TodoProxyModelBase::onRowsMoved(const QModelIndex &/*parent*/, int start, int end, const QModelIndex &destination, int row) { onSourceInsertRows(destination, row, row + end - start); } void TodoProxyModelBase::onModelReset() { beginResetModel(); resetInternalData(); endResetModel(); init(); } void TodoProxyModelBase::resetInternalData() { foreach(TodoNode* node, m_manager->roots()) { m_manager->removeNode(node); delete node; } m_inboxNode = 0; } <commit_msg>Don't assert if invalid index is passed to the function.<commit_after>/* This file is part of Zanshin Todo. Copyright 2008 Kevin Ottens <ervin@kde.org> Copyright 2008, 2009 Mario Bensi <nef@ipsquad.net> 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "todoproxymodelbase.h" #include <QtCore/QStringList> #include <KDE/KDebug> #include <KDE/KIcon> #include <KDE/KLocale> #include "todonode.h" #include "todonodemanager.h" TodoProxyModelBase::TodoProxyModelBase(MappingType type, QObject *parent) : QAbstractProxyModel(parent), m_manager(new TodoNodeManager(this, (type==MultiMapping ? true : false))), m_inboxNode(0), m_mappingType(type) { } TodoProxyModelBase::~TodoProxyModelBase() { delete m_manager; } void TodoProxyModelBase::init() { if (!m_inboxNode) { beginInsertRows(QModelIndex(), 0, 0); m_inboxNode = createInbox(); m_manager->insertNode(m_inboxNode); endInsertRows(); } } QModelIndex TodoProxyModelBase::index(int row, int column, const QModelIndex &parent) const { return m_manager->index(row, column, parent); } QModelIndex TodoProxyModelBase::buddy(const QModelIndex &index) const { return index; } QModelIndex TodoProxyModelBase::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } TodoNode *parent = m_manager->nodeForIndex(index)->parent(); if (parent == 0) { return QModelIndex(); } else { return m_manager->indexForNode(parent, 0); } } int TodoProxyModelBase::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { return m_manager->roots().size(); } else if (parent.column() == 0) { // Only one set of children per row TodoNode *node = m_manager->nodeForIndex(parent); return node->children().size(); } return 0; } int TodoProxyModelBase::columnCount(const QModelIndex &parent) const { if (!sourceModel()) { return 1; } if (parent.isValid()) { TodoNode *node = m_manager->nodeForIndex(parent); if (node && node->children().size() > 0) { return sourceModel()->columnCount(); } else { return 0; } } else { return sourceModel()->columnCount(mapToSource(parent)); } } bool TodoProxyModelBase::hasChildren(const QModelIndex &parent) const { // Since Qt 4.8, QAbstractProxyModel just forwards hasChildren to the source model // so that's not based on the current model rowCount() and columnCount(), because // of that it's easy to end up with inconsistent replies between rowCount() and // hasChildren() for instance (resulting in empty views or crashes in proxies). // // So, here we just use the hasChildren() implementation inherited from QAbstractItemModel // since it is based on rowCount() and columnCount(). return QAbstractItemModel::hasChildren(parent); } QVariant TodoProxyModelBase::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical) { return QAbstractProxyModel::headerData(section, orientation, role); } else { if (!sourceModel()) { return QVariant(); } return sourceModel()->headerData(section, orientation, role); } } QVariant TodoProxyModelBase::data(const QModelIndex &index, int role) const { if (!index.isValid()) { kDebug() << "invalid index: " << index << role; return QVariant(); } Q_ASSERT(index.model() == this); TodoNode *node = m_manager->nodeForIndex(index); if (node == 0) { return QVariant(); } return node->data(index.column(), role); } Qt::ItemFlags TodoProxyModelBase::flags(const QModelIndex &index) const { TodoNode *node = m_manager->nodeForIndex(index); if (node == 0) { return Qt::NoItemFlags; } return node->flags(index.column()); } QModelIndex TodoProxyModelBase::mapToSource(const QModelIndex &proxyIndex) const { TodoNode *node = m_manager->nodeForIndex(proxyIndex); if (!node) { return QModelIndex(); } else { QModelIndex rowSourceIndex = node->rowSourceIndex(); return rowSourceIndex.sibling(rowSourceIndex.row(), proxyIndex.column()); } } QList<QModelIndex> TodoProxyModelBase::mapFromSourceAll(const QModelIndex &sourceIndex) const { if (m_mappingType==SimpleMapping) { kError() << "Never call mapFromSourceAll() for a SimpleMapping model"; return QList<QModelIndex>(); } QList<TodoNode*> nodes = m_manager->nodesForSourceIndex(sourceIndex); QList<QModelIndex> indexes; foreach (TodoNode *node, nodes) { indexes << m_manager->indexForNode(node, sourceIndex.column()); } return indexes; } QModelIndex TodoProxyModelBase::mapFromSource(const QModelIndex &sourceIndex) const { if (m_mappingType==MultiMapping) { kWarning() << "Never call mapFromSource() for a MultiMapping model"; //This is useful for selecting an item in the list //If we just return an empty index we break EntityTreeModel::modelIndexesForItem QList<TodoNode*> nodes = m_manager->nodesForSourceIndex(sourceIndex); if (nodes.isEmpty()) { return QModelIndex(); } return m_manager->indexForNode(nodes.first(), sourceIndex.column()); } TodoNode *node = m_manager->nodeForSourceIndex(sourceIndex); return m_manager->indexForNode(node, sourceIndex.column()); } void TodoProxyModelBase::setSourceModel(QAbstractItemModel *model) { init(); if (sourceModel()) { disconnect(sourceModel(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(onSourceDataChanged(QModelIndex,QModelIndex))); disconnect(sourceModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(onSourceInsertRows(QModelIndex,int,int))); disconnect(sourceModel(), SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(onSourceRemoveRows(QModelIndex,int,int))); disconnect(sourceModel(), SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(onRowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int))); disconnect(sourceModel(), SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(onRowsMoved(QModelIndex,int,int,QModelIndex,int))); connect(sourceModel(), SIGNAL(modelReset()), this, SLOT(onModelReset())); } if (model) { connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(onSourceDataChanged(QModelIndex,QModelIndex))); connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(onSourceInsertRows(QModelIndex,int,int))); connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(onSourceRemoveRows(QModelIndex,int,int))); connect(model, SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(onRowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int))); connect(model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(onRowsMoved(QModelIndex,int,int,QModelIndex,int))); connect(model, SIGNAL(modelReset()), this, SLOT(onModelReset())); } QAbstractProxyModel::setSourceModel(model); onSourceInsertRows(QModelIndex(), 0, sourceModel()->rowCount() - 1); } TodoNode *TodoProxyModelBase::addChildNode(const QModelIndex &sourceIndex, TodoNode *parent) { QModelIndex proxyParentIndex = m_manager->indexForNode(parent, 0); int row = 0; if (parent) { row = parent->children().size(); } else { row = m_manager->roots().size(); } beginInsertRows(proxyParentIndex, row, row); TodoNode *child = new TodoNode(sourceIndex, parent); m_manager->insertNode(child); endInsertRows(); return child; } void TodoProxyModelBase::onRowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &/*destinationParent*/, int /*destinationRow*/) { onSourceRemoveRows(sourceParent, sourceStart, sourceEnd); } void TodoProxyModelBase::onRowsMoved(const QModelIndex &/*parent*/, int start, int end, const QModelIndex &destination, int row) { onSourceInsertRows(destination, row, row + end - start); } void TodoProxyModelBase::onModelReset() { beginResetModel(); resetInternalData(); endResetModel(); init(); } void TodoProxyModelBase::resetInternalData() { foreach(TodoNode* node, m_manager->roots()) { m_manager->removeNode(node); delete node; } m_inboxNode = 0; } <|endoftext|>
<commit_before>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <topologyreader.h> #include <trajectoryreader.h> #include <boost/program_options.hpp> #include <boost/tokenizer.hpp> #include "version.h" #include <iostream> #include <fstream> using namespace std; namespace po = boost::program_options; /** * *** Analyze particle distribution as a function of a coordinate *** * * This program reads a topology and (set of) trajectory(ies). For every * binned value of a chose coordinate, it outputs the time-averaged number of * particles, listed by particle types. */ void help_text(void) { votca::csg::HelpTextHeader("csg_part_dist"); cout << "This program reads a topology and (set of) trajectory(ies). For every\n" "binned value of a chose coordinate, it outputs the time-averaged number of\n" "particles, listed by particle types.\n\n"; } void check_option(po::options_description &desc, po::variables_map &vm, const string &option) { if(!vm.count(option)) { cout << "csg_part_dist \n\n"; cout << desc << endl << "parameter " << option << " is not specified\n"; exit(1); } } int main(int argc, char** argv) { string top_file, trj_file, ptypes_file, out_file, grid, comment, string_tmp, coordinate="z"; double min, max, step, coord, com(0.); vector<int> ptypes; ifstream fl_ptypes; ofstream fl_out; Topology top; TopologyReader *reader; TrajectoryReader *trajreader; int part_type, n_bins, first_frame(0), last_frame(-1), flag_found(0), **p_occ = NULL, n_part(0); MoleculeContainer::iterator mol; // Load topology+trajectory formats TopologyReader::RegisterPlugins(); TrajectoryReader::RegisterPlugins(); // read program options namespace po = boost::program_options; // Declare the supported options. po::options_description desc("Allowed options"); // let cg_engine add some program options desc.add_options() ("top", po::value<string>(&top_file), "topology file") ("trj", po::value<string>(&trj_file), "trajectory file") ("grid", po::value<string>(&grid), "output grid spacing (min:step:max)") ("out", po::value<string>(&out_file), "output particle distribution table") ("ptypes", po::value<string>(&ptypes_file), "particle types to include in the analysis\n" " arg: file - particle types separated by space" "\n default: all particle types") ("first_frame", po::value<int>(&first_frame), "first frame considered for analysis") ("last_frame", po::value<int>(&last_frame), "last frame considered for analysis") ("coord", po::value<string>(&coordinate), "coordinate analyzed ('x', 'y', or 'z' (default))") ("shift_com", "shift center of mass to zero") ("comment", po::value<string>(&comment), "store a comment in the output table") ("help", "produce this help message"); // now read in the command line po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch(po::error err) { cout << "error parsing command line: " << err.what() << endl; return -1; } // does the user want help? if (vm.count("help")) { help_text(); cout << desc << endl; return 0; } check_option(desc, vm, "top"); check_option(desc, vm, "trj"); check_option(desc, vm, "out"); check_option(desc, vm, "grid"); if (coordinate.compare("x") != 0 && coordinate.compare("y") != 0 && coordinate.compare("z") != 0) { cout << "Bad format for coordinate: " << coordinate << endl; return 1; } // Parse grid Tokenizer tok(grid, ":"); vector<string> toks; tok.ToVector(toks); if(toks.size()!=3) { cout << "Wrong range format, use min:step:max\n"; return 1; } min = boost::lexical_cast<double>(toks[0]); step = boost::lexical_cast<double>(toks[1]); max = boost::lexical_cast<double>(toks[2]); // Calculate number of bins n_bins = (int)((max-min)/(1.*step)+1); try { // Load topology reader = TopReaderFactory().Create(vm["top"].as<string>()); if(reader == NULL) throw std::runtime_error("input format not supported: " + vm["top"].as<string>()); reader->ReadTopology(vm["top"].as<string>(), top); // Read the particle types file and save to variable ptypes if(vm.count("ptypes")) { fl_ptypes.open(vm["ptypes"].as<string>().c_str()); if(!fl_ptypes.is_open()) throw std::runtime_error("can't open " + vm["ptypes"].as<string>()); // build the list of particle types if(fl_ptypes.eof()) throw std::runtime_error("file " + vm["ptypes"].as<string>() + " is empty"); while (!fl_ptypes.eof()) { // Not very elegant, but makes sure we don't count the same element twice string_tmp = "__"; fl_ptypes >> string_tmp; if (string_tmp != "" && string_tmp != "__") { ptypes.push_back(atoi(string_tmp.c_str())); } } fl_ptypes.close(); } else { // Include all particle types for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) { for(int i=0; i<(*mol)->BeadCount(); ++i) { flag_found = 0; part_type = atoi((*mol)->getBead(i)->getType()->getName().c_str()); for (int j=0; j < ptypes.size(); ++j) { if (part_type == ptypes[j]) flag_found = 1; } if (!flag_found) ptypes.push_back(part_type); } } } // Allocate array used to store particle occupancy p_occ p_occ = (int**) calloc(ptypes.size(),sizeof(int*)); for (int i=0; i < ptypes.size(); ++i) p_occ[i] = (int*) calloc(n_bins,sizeof(int)); // If we need to shift the center of mass, calculate the number of // particles (only the ones that belong to the particle type index // ptypes) if (vm.count("shift_com")) { for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) { for(int i=0; i<(*mol)->BeadCount(); ++i) { part_type = atoi((*mol)->getBead(i)->getType()->getName().c_str()); for (int j=0; j < ptypes.size(); ++j) if (part_type == ptypes[j]) ++n_part; } } } // Now load trajectory trajreader = TrjReaderFactory().Create(vm["trj"].as<string>()); if(trajreader == NULL) throw std::runtime_error("input format not supported: " + vm["trj"].as<string>()); trajreader->Open(vm["trj"].as<string>()); // Read the trajectory. Analyze each frame to obtain // particle occupancy as a function of coordinate z. bool moreframes = 1; bool not_the_last = 1; int frame_id = 0; while (moreframes) { // Read frame if (frame_id == 0) moreframes = trajreader->FirstFrame(top); else moreframes = trajreader->NextFrame(top); // Was this the last frame we read? if (last_frame == -1) not_the_last = 1; else { if (frame_id <= last_frame) not_the_last = 1; else not_the_last = 0; } // Calculate new center of mass position in the direction of 'coordinate' com = 0.; if (vm.count("shift_com")) { for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) { for(int i=0; i<(*mol)->BeadCount(); ++i) { part_type = atoi((*mol)->getBead(i)->getType()->getName().c_str()); for (int j=0; j < ptypes.size(); ++j) if (part_type == ptypes[j]) if (coordinate.compare("x") == 0) com += (*mol)->getBead(i)->getPos().getX(); else if (coordinate.compare("y") == 0) com += (*mol)->getBead(i)->getPos().getY(); else com += (*mol)->getBead(i)->getPos().getZ(); } } com /= n_part; } // Analyze frame if (moreframes && frame_id >= first_frame && not_the_last) { // Loop over each atom property for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) { for(int i=0; i<(*mol)->BeadCount(); ++i) { part_type = atoi((*mol)->getBead(i)->getType()->getName().c_str()); for (int j=0; j < ptypes.size(); ++j) { if (part_type == ptypes[j]) { if (coordinate.compare("x") == 0) coord = (*mol)->getBead(i)->getPos().getX(); else if (coordinate.compare("y") == 0) coord = (*mol)->getBead(i)->getPos().getY(); else coord = (*mol)->getBead(i)->getPos().getZ(); if (coord-com > min && coord-com < max) ++p_occ[j][(int)floor((coord-com-min)/step)]; } } } } } ++frame_id; } trajreader->Close(); } catch(std::exception &error) { cerr << "An error occured!" << endl << error.what() << endl; } // Output particle occupancy try { fl_out.open(vm["out"].as<string>().c_str()); if(!fl_out.is_open()) throw std::runtime_error("can't open " + vm["out"].as<string>()); fl_out << "#z\t" << flush; for (int i=0; i < ptypes.size(); ++i) fl_out << "type " << ptypes[i] << "\t" << flush; fl_out << endl; for (int k=0; k < n_bins; ++k) { fl_out << min+k*step << "\t" << flush; for (int j=0; j < ptypes.size(); ++j) { fl_out << p_occ[j][k] << "\t" << flush; } fl_out << endl; } fl_out.close(); } catch(std::exception &error) { cerr << "An error occured!" << endl << error.what() << endl; } for (int i=0; i < ptypes.size(); ++i) free(p_occ[i]); free(p_occ); cout << "The table was written to " << vm["out"].as<string>() << endl; return 0; } <commit_msg>csg_part_dist was missing a normalization factor'<commit_after>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <topologyreader.h> #include <trajectoryreader.h> #include <boost/program_options.hpp> #include <boost/tokenizer.hpp> #include "version.h" #include <iostream> #include <fstream> using namespace std; namespace po = boost::program_options; /** * *** Analyze particle distribution as a function of a coordinate *** * * This program reads a topology and (set of) trajectory(ies). For every * binned value of a chose coordinate, it outputs the time-averaged number of * particles, listed by particle types. */ void help_text(void) { votca::csg::HelpTextHeader("csg_part_dist"); cout << "This program reads a topology and (set of) trajectory(ies). For every\n" "binned value of a chose coordinate, it outputs the time-averaged number of\n" "particles, listed by particle types.\n\n"; } void check_option(po::options_description &desc, po::variables_map &vm, const string &option) { if(!vm.count(option)) { cout << "csg_part_dist \n\n"; cout << desc << endl << "parameter " << option << " is not specified\n"; exit(1); } } int main(int argc, char** argv) { string top_file, trj_file, ptypes_file, out_file, grid, comment, string_tmp, coordinate="z"; double min, max, step, coord, com(0.); vector<int> ptypes; ifstream fl_ptypes; ofstream fl_out; Topology top; TopologyReader *reader; TrajectoryReader *trajreader; int part_type, n_bins, first_frame(0), last_frame(-1), flag_found(0), **p_occ = NULL, n_part(0), frame_id(0), analyzed_frames(0); bool moreframes(1), not_the_last(1); MoleculeContainer::iterator mol; // Load topology+trajectory formats TopologyReader::RegisterPlugins(); TrajectoryReader::RegisterPlugins(); // read program options namespace po = boost::program_options; // Declare the supported options. po::options_description desc("Allowed options"); // let cg_engine add some program options desc.add_options() ("top", po::value<string>(&top_file), "topology file") ("trj", po::value<string>(&trj_file), "trajectory file") ("grid", po::value<string>(&grid), "output grid spacing (min:step:max)") ("out", po::value<string>(&out_file), "output particle distribution table") ("ptypes", po::value<string>(&ptypes_file), "particle types to include in the analysis\n" " arg: file - particle types separated by space" "\n default: all particle types") ("first_frame", po::value<int>(&first_frame), "first frame considered for analysis") ("last_frame", po::value<int>(&last_frame), "last frame considered for analysis") ("coord", po::value<string>(&coordinate), "coordinate analyzed ('x', 'y', or 'z' (default))") ("shift_com", "shift center of mass to zero") ("comment", po::value<string>(&comment), "store a comment in the output table") ("help", "produce this help message"); // now read in the command line po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch(po::error err) { cout << "error parsing command line: " << err.what() << endl; return -1; } // does the user want help? if (vm.count("help")) { help_text(); cout << desc << endl; return 0; } check_option(desc, vm, "top"); check_option(desc, vm, "trj"); check_option(desc, vm, "out"); check_option(desc, vm, "grid"); if (coordinate.compare("x") != 0 && coordinate.compare("y") != 0 && coordinate.compare("z") != 0) { cout << "Bad format for coordinate: " << coordinate << endl; return 1; } // Parse grid Tokenizer tok(grid, ":"); vector<string> toks; tok.ToVector(toks); if(toks.size()!=3) { cout << "Wrong range format, use min:step:max\n"; return 1; } min = boost::lexical_cast<double>(toks[0]); step = boost::lexical_cast<double>(toks[1]); max = boost::lexical_cast<double>(toks[2]); // Calculate number of bins n_bins = (int)((max-min)/(1.*step)+1); try { // Load topology reader = TopReaderFactory().Create(vm["top"].as<string>()); if(reader == NULL) throw std::runtime_error("input format not supported: " + vm["top"].as<string>()); reader->ReadTopology(vm["top"].as<string>(), top); // Read the particle types file and save to variable ptypes if(vm.count("ptypes")) { fl_ptypes.open(vm["ptypes"].as<string>().c_str()); if(!fl_ptypes.is_open()) throw std::runtime_error("can't open " + vm["ptypes"].as<string>()); // build the list of particle types if(fl_ptypes.eof()) throw std::runtime_error("file " + vm["ptypes"].as<string>() + " is empty"); while (!fl_ptypes.eof()) { // Not very elegant, but makes sure we don't count the same element twice string_tmp = "__"; fl_ptypes >> string_tmp; if (string_tmp != "" && string_tmp != "__") { ptypes.push_back(atoi(string_tmp.c_str())); } } fl_ptypes.close(); } else { // Include all particle types for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) { for(int i=0; i<(*mol)->BeadCount(); ++i) { flag_found = 0; part_type = atoi((*mol)->getBead(i)->getType()->getName().c_str()); for (int j=0; j < ptypes.size(); ++j) { if (part_type == ptypes[j]) flag_found = 1; } if (!flag_found) ptypes.push_back(part_type); } } } // Allocate array used to store particle occupancy p_occ p_occ = (int**) calloc(ptypes.size(),sizeof(int*)); for (int i=0; i < ptypes.size(); ++i) p_occ[i] = (int*) calloc(n_bins,sizeof(int)); // If we need to shift the center of mass, calculate the number of // particles (only the ones that belong to the particle type index // ptypes) if (vm.count("shift_com")) { for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) { for(int i=0; i<(*mol)->BeadCount(); ++i) { part_type = atoi((*mol)->getBead(i)->getType()->getName().c_str()); for (int j=0; j < ptypes.size(); ++j) if (part_type == ptypes[j]) ++n_part; } } } // Now load trajectory trajreader = TrjReaderFactory().Create(vm["trj"].as<string>()); if(trajreader == NULL) throw std::runtime_error("input format not supported: " + vm["trj"].as<string>()); trajreader->Open(vm["trj"].as<string>()); // Read the trajectory. Analyze each frame to obtain // particle occupancy as a function of coordinate z. while (moreframes) { // Read frame if (frame_id == 0) moreframes = trajreader->FirstFrame(top); else moreframes = trajreader->NextFrame(top); // Was this the last frame we read? if (last_frame == -1) not_the_last = 1; else { if (frame_id <= last_frame) not_the_last = 1; else not_the_last = 0; } // Calculate new center of mass position in the direction of 'coordinate' com = 0.; if (vm.count("shift_com")) { for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) { for(int i=0; i<(*mol)->BeadCount(); ++i) { part_type = atoi((*mol)->getBead(i)->getType()->getName().c_str()); for (int j=0; j < ptypes.size(); ++j) if (part_type == ptypes[j]) if (coordinate.compare("x") == 0) com += (*mol)->getBead(i)->getPos().getX(); else if (coordinate.compare("y") == 0) com += (*mol)->getBead(i)->getPos().getY(); else com += (*mol)->getBead(i)->getPos().getZ(); } } com /= n_part; } // Analyze frame if (moreframes && frame_id >= first_frame && not_the_last) { ++analyzed_frames; // Loop over each atom property for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) { for(int i=0; i<(*mol)->BeadCount(); ++i) { part_type = atoi((*mol)->getBead(i)->getType()->getName().c_str()); for (int j=0; j < ptypes.size(); ++j) { if (part_type == ptypes[j]) { if (coordinate.compare("x") == 0) coord = (*mol)->getBead(i)->getPos().getX(); else if (coordinate.compare("y") == 0) coord = (*mol)->getBead(i)->getPos().getY(); else coord = (*mol)->getBead(i)->getPos().getZ(); if (coord-com > min && coord-com < max) ++p_occ[j][(int)floor((coord-com-min)/step)]; } } } } } ++frame_id; } trajreader->Close(); } catch(std::exception &error) { cerr << "An error occured!" << endl << error.what() << endl; } // Output particle occupancy try { fl_out.open(vm["out"].as<string>().c_str()); if(!fl_out.is_open()) throw std::runtime_error("can't open " + vm["out"].as<string>()); fl_out << "#z\t" << flush; for (int i=0; i < ptypes.size(); ++i) fl_out << "type " << ptypes[i] << "\t" << flush; fl_out << endl; for (int k=0; k < n_bins; ++k) { fl_out << min+k*step << "\t" << flush; for (int j=0; j < ptypes.size(); ++j) { if (p_occ[j][k] == 0) fl_out << 0 << "\t" << flush; else fl_out << p_occ[j][k]/(1.*analyzed_frames) << "\t" << flush; } fl_out << endl; } fl_out.close(); } catch(std::exception &error) { cerr << "An error occured!" << endl << error.what() << endl; } for (int i=0; i < ptypes.size(); ++i) free(p_occ[i]); free(p_occ); cout << "The table was written to " << vm["out"].as<string>() << endl; return 0; } <|endoftext|>
<commit_before>#include "messages/MessageElement.hpp" #include "Application.hpp" #include "controllers/moderationactions/ModerationActions.hpp" #include "debug/Benchmark.hpp" #include "messages/Emote.hpp" #include "messages/layouts/MessageLayoutContainer.hpp" #include "messages/layouts/MessageLayoutElement.hpp" #include "singletons/Settings.hpp" #include "singletons/Theme.hpp" #include "util/DebugCount.hpp" namespace chatterino { MessageElement::MessageElement(MessageElementFlags flags) : flags_(flags) { DebugCount::increase("message elements"); } MessageElement::~MessageElement() { DebugCount::decrease("message elements"); } MessageElement *MessageElement::setLink(const Link &link) { this->link_ = link; return this; } MessageElement *MessageElement::setText(const QString &text) { this->text_ = text; return this; } MessageElement *MessageElement::setTooltip(const QString &tooltip) { this->tooltip_ = tooltip; return this; } MessageElement *MessageElement::setTrailingSpace(bool value) { this->trailingSpace = value; return this; } const QString &MessageElement::getTooltip() const { return this->tooltip_; } const Link &MessageElement::getLink() const { return this->link_; } bool MessageElement::hasTrailingSpace() const { return this->trailingSpace; } MessageElementFlags MessageElement::getFlags() const { return this->flags_; } MessageElement *MessageElement::updateLink() { this->linkChanged.invoke(); return this; } // IMAGE ImageElement::ImageElement(ImagePtr image, MessageElementFlags flags) : MessageElement(flags) , image_(image) { // this->setTooltip(image->getTooltip()); } void ImageElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { if (flags.hasAny(this->getFlags())) { auto size = QSize(this->image_->width() * container.getScale(), this->image_->height() * container.getScale()); container.addElement((new ImageLayoutElement(*this, this->image_, size)) ->setLink(this->getLink())); } } // EMOTE EmoteElement::EmoteElement(const EmotePtr &emote, MessageElementFlags flags) : MessageElement(flags) , emote_(emote) { this->textElement_.reset( new TextElement(emote->getCopyString(), MessageElementFlag::Misc)); this->setTooltip(emote->tooltip.string); } EmotePtr EmoteElement::getEmote() const { return this->emote_; } void EmoteElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { if (flags.hasAny(this->getFlags())) { if (flags.has(MessageElementFlag::EmoteImages)) { auto image = this->emote_->images.getImage(container.getScale()); if (image->isEmpty()) return; auto emoteScale = getSettings()->emoteScale.getValue(); auto size = QSize(int(container.getScale() * image->width() * emoteScale), int(container.getScale() * image->height() * emoteScale)); container.addElement((new ImageLayoutElement(*this, image, size)) ->setLink(this->getLink())); } else { if (this->textElement_) { this->textElement_->addToContainer(container, MessageElementFlag::Misc); } } } } // TEXT TextElement::TextElement(const QString &text, MessageElementFlags flags, const MessageColor &color, FontStyle style) : MessageElement(flags) , color_(color) , style_(style) { for (const auto &word : text.split(' ')) { this->words_.push_back({word, -1}); // fourtf: add logic to store multiple spaces after message } } void TextElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { auto app = getApp(); if (flags.hasAny(this->getFlags())) { QFontMetrics metrics = app->fonts->getFontMetrics(this->style_, container.getScale()); for (Word &word : this->words_) { auto getTextLayoutElement = [&](QString text, int width, bool trailingSpace) { auto color = this->color_.getColor(*app->themes); app->themes->normalizeColor(color); auto e = (new TextLayoutElement( *this, text, QSize(width, metrics.height()), color, this->style_, container.getScale())) ->setLink(this->getLink()); e->setTrailingSpace(trailingSpace); e->setText(text); // If URL link was changed, // Should update it in MessageLayoutElement too! if (this->getLink().type == Link::Url) { static_cast<TextLayoutElement *>(e)->listenToLinkChanges(); } return e; }; // fourtf: add again // if (word.width == -1) { word.width = metrics.width(word.text); // } // see if the text fits in the current line if (container.fitsInLine(word.width)) { container.addElementNoLineBreak(getTextLayoutElement( word.text, word.width, this->hasTrailingSpace())); continue; } // see if the text fits in the next line if (!container.atStartOfLine()) { container.breakLine(); if (container.fitsInLine(word.width)) { container.addElementNoLineBreak(getTextLayoutElement( word.text, word.width, this->hasTrailingSpace())); continue; } } // we done goofed, we need to wrap the text QString text = word.text; int textLength = text.length(); int wordStart = 0; int width = 0; // QChar::isHighSurrogate(text[0].unicode()) ? 2 : 1 for (int i = 0; i < textLength; i++) // { auto isSurrogate = text.size() > i + 1 && QChar::isHighSurrogate(text[i].unicode()); auto charWidth = isSurrogate ? metrics.width(text.mid(i, 2)) : metrics.width(text[i]); if (!container.fitsInLine(width + charWidth)) // { container.addElementNoLineBreak(getTextLayoutElement( text.mid(wordStart, i - wordStart), width, false)); container.breakLine(); wordStart = i; width = charWidth; if (isSurrogate) i++; continue; } width += charWidth; if (isSurrogate) i++; } container.addElement(getTextLayoutElement( text.mid(wordStart), width, this->hasTrailingSpace())); container.breakLine(); } } } // TIMESTAMP TimestampElement::TimestampElement(QTime time) : MessageElement(MessageElementFlag::Timestamp) , time_(time) , element_(this->formatTime(time)) { assert(this->element_ != nullptr); } void TimestampElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { if (flags.hasAny(this->getFlags())) { auto app = getApp(); if (getSettings()->timestampFormat != this->format_) { this->format_ = getSettings()->timestampFormat.getValue(); this->element_.reset(this->formatTime(this->time_)); } this->element_->addToContainer(container, flags); } } TextElement *TimestampElement::formatTime(const QTime &time) { static QLocale locale("en_US"); QString format = locale.toString(time, getSettings()->timestampFormat); return new TextElement(format, MessageElementFlag::Timestamp, MessageColor::System, FontStyle::ChatMedium); } // TWITCH MODERATION TwitchModerationElement::TwitchModerationElement() : MessageElement(MessageElementFlag::ModeratorTools) { } void TwitchModerationElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { if (flags.has(MessageElementFlag::ModeratorTools)) { QSize size(int(container.getScale() * 16), int(container.getScale() * 16)); for (const auto &action : getApp()->moderationActions->items.getVector()) { if (auto image = action.getImage()) { container.addElement( (new ImageLayoutElement(*this, image.get(), size)) ->setLink(Link(Link::UserAction, action.getAction()))); } else { container.addElement( (new TextIconLayoutElement(*this, action.getLine1(), action.getLine2(), container.getScale(), size)) ->setLink(Link(Link::UserAction, action.getAction()))); } } } } } // namespace chatterino <commit_msg>fixed badges scaling with emote scaling slider<commit_after>#include "messages/MessageElement.hpp" #include "Application.hpp" #include "controllers/moderationactions/ModerationActions.hpp" #include "debug/Benchmark.hpp" #include "messages/Emote.hpp" #include "messages/layouts/MessageLayoutContainer.hpp" #include "messages/layouts/MessageLayoutElement.hpp" #include "singletons/Settings.hpp" #include "singletons/Theme.hpp" #include "util/DebugCount.hpp" namespace chatterino { MessageElement::MessageElement(MessageElementFlags flags) : flags_(flags) { DebugCount::increase("message elements"); } MessageElement::~MessageElement() { DebugCount::decrease("message elements"); } MessageElement *MessageElement::setLink(const Link &link) { this->link_ = link; return this; } MessageElement *MessageElement::setText(const QString &text) { this->text_ = text; return this; } MessageElement *MessageElement::setTooltip(const QString &tooltip) { this->tooltip_ = tooltip; return this; } MessageElement *MessageElement::setTrailingSpace(bool value) { this->trailingSpace = value; return this; } const QString &MessageElement::getTooltip() const { return this->tooltip_; } const Link &MessageElement::getLink() const { return this->link_; } bool MessageElement::hasTrailingSpace() const { return this->trailingSpace; } MessageElementFlags MessageElement::getFlags() const { return this->flags_; } MessageElement *MessageElement::updateLink() { this->linkChanged.invoke(); return this; } // IMAGE ImageElement::ImageElement(ImagePtr image, MessageElementFlags flags) : MessageElement(flags) , image_(image) { // this->setTooltip(image->getTooltip()); } void ImageElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { if (flags.hasAny(this->getFlags())) { auto size = QSize(this->image_->width() * container.getScale(), this->image_->height() * container.getScale()); container.addElement((new ImageLayoutElement(*this, this->image_, size)) ->setLink(this->getLink())); } } // EMOTE EmoteElement::EmoteElement(const EmotePtr &emote, MessageElementFlags flags) : MessageElement(flags) , emote_(emote) { this->textElement_.reset( new TextElement(emote->getCopyString(), MessageElementFlag::Misc)); this->setTooltip(emote->tooltip.string); } EmotePtr EmoteElement::getEmote() const { return this->emote_; } void EmoteElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { if (flags.hasAny(this->getFlags())) { if (flags.has(MessageElementFlag::EmoteImages)) { auto image = this->emote_->images.getImage(container.getScale()); if (image->isEmpty()) return; auto emoteScale = this->getFlags().hasAny(MessageElementFlag::Badges) ? 1 : getSettings()->emoteScale.getValue(); auto size = QSize(int(container.getScale() * image->width() * emoteScale), int(container.getScale() * image->height() * emoteScale)); container.addElement((new ImageLayoutElement(*this, image, size)) ->setLink(this->getLink())); } else { if (this->textElement_) { this->textElement_->addToContainer(container, MessageElementFlag::Misc); } } } } // TEXT TextElement::TextElement(const QString &text, MessageElementFlags flags, const MessageColor &color, FontStyle style) : MessageElement(flags) , color_(color) , style_(style) { for (const auto &word : text.split(' ')) { this->words_.push_back({word, -1}); // fourtf: add logic to store multiple spaces after message } } void TextElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { auto app = getApp(); if (flags.hasAny(this->getFlags())) { QFontMetrics metrics = app->fonts->getFontMetrics(this->style_, container.getScale()); for (Word &word : this->words_) { auto getTextLayoutElement = [&](QString text, int width, bool trailingSpace) { auto color = this->color_.getColor(*app->themes); app->themes->normalizeColor(color); auto e = (new TextLayoutElement( *this, text, QSize(width, metrics.height()), color, this->style_, container.getScale())) ->setLink(this->getLink()); e->setTrailingSpace(trailingSpace); e->setText(text); // If URL link was changed, // Should update it in MessageLayoutElement too! if (this->getLink().type == Link::Url) { static_cast<TextLayoutElement *>(e)->listenToLinkChanges(); } return e; }; // fourtf: add again // if (word.width == -1) { word.width = metrics.width(word.text); // } // see if the text fits in the current line if (container.fitsInLine(word.width)) { container.addElementNoLineBreak(getTextLayoutElement( word.text, word.width, this->hasTrailingSpace())); continue; } // see if the text fits in the next line if (!container.atStartOfLine()) { container.breakLine(); if (container.fitsInLine(word.width)) { container.addElementNoLineBreak(getTextLayoutElement( word.text, word.width, this->hasTrailingSpace())); continue; } } // we done goofed, we need to wrap the text QString text = word.text; int textLength = text.length(); int wordStart = 0; int width = 0; // QChar::isHighSurrogate(text[0].unicode()) ? 2 : 1 for (int i = 0; i < textLength; i++) // { auto isSurrogate = text.size() > i + 1 && QChar::isHighSurrogate(text[i].unicode()); auto charWidth = isSurrogate ? metrics.width(text.mid(i, 2)) : metrics.width(text[i]); if (!container.fitsInLine(width + charWidth)) // { container.addElementNoLineBreak(getTextLayoutElement( text.mid(wordStart, i - wordStart), width, false)); container.breakLine(); wordStart = i; width = charWidth; if (isSurrogate) i++; continue; } width += charWidth; if (isSurrogate) i++; } container.addElement(getTextLayoutElement( text.mid(wordStart), width, this->hasTrailingSpace())); container.breakLine(); } } } // TIMESTAMP TimestampElement::TimestampElement(QTime time) : MessageElement(MessageElementFlag::Timestamp) , time_(time) , element_(this->formatTime(time)) { assert(this->element_ != nullptr); } void TimestampElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { if (flags.hasAny(this->getFlags())) { auto app = getApp(); if (getSettings()->timestampFormat != this->format_) { this->format_ = getSettings()->timestampFormat.getValue(); this->element_.reset(this->formatTime(this->time_)); } this->element_->addToContainer(container, flags); } } TextElement *TimestampElement::formatTime(const QTime &time) { static QLocale locale("en_US"); QString format = locale.toString(time, getSettings()->timestampFormat); return new TextElement(format, MessageElementFlag::Timestamp, MessageColor::System, FontStyle::ChatMedium); } // TWITCH MODERATION TwitchModerationElement::TwitchModerationElement() : MessageElement(MessageElementFlag::ModeratorTools) { } void TwitchModerationElement::addToContainer(MessageLayoutContainer &container, MessageElementFlags flags) { if (flags.has(MessageElementFlag::ModeratorTools)) { QSize size(int(container.getScale() * 16), int(container.getScale() * 16)); for (const auto &action : getApp()->moderationActions->items.getVector()) { if (auto image = action.getImage()) { container.addElement( (new ImageLayoutElement(*this, image.get(), size)) ->setLink(Link(Link::UserAction, action.getAction()))); } else { container.addElement( (new TextIconLayoutElement(*this, action.getLine1(), action.getLine2(), container.getScale(), size)) ->setLink(Link(Link::UserAction, action.getAction()))); } } } } } // namespace chatterino <|endoftext|>
<commit_before>#include "AgentController.h" #include <assert.h> namespace fetch { namespace ui { AgentController::AgentController(Agent* agent) : agent_(agent) , runlevel_(UNKNOWN) { assert(agent); } void AgentController::poll() { RunLevel current = queryRunLevel(); if(current==runlevel_) return; // nothing to do. handleTransition(runlevel_,current); runlevel_=current; } void AgentController::handleTransition(AgentController::RunLevel src, AgentController::RunLevel dst) { assert(dst!=UNKNOWN); if(src<dst && (dst-src)>1) // move up the runlevel chain { handleTransition(src,(RunLevel)(src+1)); handleTransition((RunLevel)(src+1),dst); return; } if(src>dst && (src-dst)>1) // move down the runlevel chain { handleTransition(src,(RunLevel)(src-1)); handleTransition((RunLevel)(src-1),dst); return; } //Below: either src-dst = 1 or dst-src = 1 if(src==UNKNOWN) return; // nothing to do switch(dst) { case OFF: if(src==ATTACHED) emit onDetach(); else UNREACHABLE; break; case ATTACHED: if(src==OFF) emit onAttach(); else if(src==ARMED) emit onDisarm(); else UNREACHABLE; break; case ARMED: if(src==ATTACHED) { emit onArm(agent_->_task); emit onArm(); } else if(src==RUNNING) emit onStop(); else UNREACHABLE; break; case RUNNING: if(src==ARMED) emit onRun(); else UNREACHABLE; break; default: //UNKNOWN...nothing to do UNREACHABLE; } } AgentController::RunLevel AgentController::queryRunLevel() { if(agent_->is_running()) return RUNNING; if(agent_->is_armed()) return ARMED; if(agent_->is_attached()) return ATTACHED; return OFF; } void AgentController::attach() { Guarded_Assert_WinErr(agent_->attach_nowait()); } void AgentController::detach() { Guarded_Assert_WinErr(agent_->detach_nowait()); } void AgentController::arm( Task *t ) { Guarded_Assert_WinErr(agent_->arm_nowait(t,agent_->_owner,INFINITE)); } void AgentController::disarm() { Guarded_Assert_WinErr(agent_->disarm_nowait(INFINITE)); } void AgentController::run() { Guarded_Assert_WinErr(agent_->run_nowait()); } void AgentController::stop() { Guarded_Assert_WinErr(agent_->stop_nowait(INFINITE)); } QTimer * AgentController::createPollingTimer() { QTimer *poller = new QTimer(this); connect(poller,SIGNAL(timeout()),this,SLOT(poll())); return poller; } QDockWidget* AgentController::createTaskDockWidget(const QString & title, Task *task, QWidget* parent) { QDockWidget* d = new QDockWidget(title,parent); QWidget* w = new QWidget(d); QFormLayout* layout = new QFormLayout; layout->addRow(new AgentControllerButtonPanel(this,task)); w->setLayout(layout); d->setWidget(w); return d; } /** class AgentControllerButtonPanel : public QWidget { Q_OBJECT QStateMachine stateMachine_; Task *armTarget_; AgentController *ac_; public: AgentControllerButtonPanel(AgentController *ac, Task *task=NULL); public slots: void onArmFilter(Task* t); }; **/ AgentControllerButtonPanel::AgentControllerButtonPanel(AgentController *ac, Task *task) : armTarget_(task) , ac_(ac) { btnDetach = new QPushButton("Detach"); btnAttach = new QPushButton("Attach"); btnArm = new QPushButton("Arm"); btnDisarm = new QPushButton("Disarm"); btnRun = new QPushButton("Run"); btnStop = new QPushButton("Stop"); QObject::connect(btnDetach,SIGNAL(clicked()),ac_,SLOT(detach())); QObject::connect(btnAttach,SIGNAL(clicked()),ac_,SLOT(attach())); QObject::connect(btnArm,SIGNAL(clicked()),this,SLOT(armTargetTask())); QObject::connect(btnDisarm,SIGNAL(clicked()),ac_,SLOT(disarm())); QObject::connect(btnRun,SIGNAL(clicked()),ac_,SLOT(run())); QObject::connect(btnStop,SIGNAL(clicked()),ac_,SLOT(stop())); // // State machine // taskDetached = new QState; taskAttached = new QState; taskArmed = new QState; taskArmedNonTarget = new QState; taskRunning = new QState; taskDetached->addTransition(ac_,SIGNAL(onAttach()),taskAttached); taskAttached->addTransition(ac_,SIGNAL(onDetach()),taskDetached); connect(ac_,SIGNAL(onArm(Task*)),this,SLOT(onArmFilter(Task*))); taskAttached->addTransition(this,SIGNAL(onArmTargetTask()),taskArmed); taskAttached->addTransition(this,SIGNAL(onArmNonTargetTask()),taskArmedNonTarget); taskArmed->addTransition(ac_,SIGNAL(onDisarm()),taskAttached); taskArmed->addTransition(ac_,SIGNAL(onRun()),taskRunning); taskArmedNonTarget->addTransition(ac_,SIGNAL(onDisarm()),taskAttached); taskRunning->addTransition(ac_,SIGNAL(onStop()),taskArmed); stateMachine_.addState(taskArmed); stateMachine_.addState(taskArmedNonTarget); stateMachine_.addState(taskAttached); stateMachine_.addState(taskDetached); stateMachine_.addState(taskRunning); stateMachine_.setInitialState(taskDetached); stateMachine_.start(); { QState *c = taskDetached; c->assignProperty(btnDetach,"enabled",false); c->assignProperty(btnAttach,"enabled",true); c->assignProperty(btnArm, "enabled",false); c->assignProperty(btnDisarm,"enabled",false); c->assignProperty(btnRun, "enabled",false); c->assignProperty(btnStop, "enabled",false); c = taskAttached; c->assignProperty(btnDetach,"enabled",true); c->assignProperty(btnAttach,"enabled",false); c->assignProperty(btnArm, "enabled",armTarget_!=NULL); c->assignProperty(btnDisarm,"enabled",false); c->assignProperty(btnRun, "enabled",false); c->assignProperty(btnStop, "enabled",false); c = taskArmed; c->assignProperty(btnDetach,"enabled",true); c->assignProperty(btnAttach,"enabled",false); c->assignProperty(btnArm, "enabled",false); c->assignProperty(btnDisarm,"enabled",true); c->assignProperty(btnRun, "enabled",true); c->assignProperty(btnStop, "enabled",true); c = taskArmedNonTarget; c->assignProperty(btnDetach,"enabled",true); c->assignProperty(btnAttach,"enabled",false); c->assignProperty(btnArm, "enabled",false); c->assignProperty(btnDisarm,"enabled",true); c->assignProperty(btnRun, "enabled",false); c->assignProperty(btnStop, "enabled",false); c = taskRunning; c->assignProperty(btnDetach,"enabled",true); c->assignProperty(btnAttach,"enabled",false); c->assignProperty(btnArm, "enabled",false); c->assignProperty(btnDisarm,"enabled",true); c->assignProperty(btnRun, "enabled",false); c->assignProperty(btnStop, "enabled",true); } QGridLayout *layout; layout = new QGridLayout; layout->addWidget(btnAttach,0,0); layout->addWidget(btnArm,0,1); layout->addWidget(btnRun,0,2); layout->addWidget(btnDetach,1,0); layout->addWidget(btnDisarm,1,1); layout->addWidget(btnStop,1,2); setLayout(layout); } void AgentControllerButtonPanel::onArmFilter( Task* t ) { if(t==armTarget_) emit onArmTargetTask(); else emit onArmNonTargetTask(); } void AgentControllerButtonPanel::armTargetTask() { if(armTarget_) emit ac_->arm(armTarget_); } }} //end fetch::ui <commit_msg>Disable attach/detach buttons<commit_after>#include "AgentController.h" #include <assert.h> namespace fetch { namespace ui { AgentController::AgentController(Agent* agent) : agent_(agent) , runlevel_(UNKNOWN) { assert(agent); } void AgentController::poll() { RunLevel current = queryRunLevel(); if(current==runlevel_) return; // nothing to do. handleTransition(runlevel_,current); runlevel_=current; } void AgentController::handleTransition(AgentController::RunLevel src, AgentController::RunLevel dst) { assert(dst!=UNKNOWN); if(src<dst && (dst-src)>1) // move up the runlevel chain { handleTransition(src,(RunLevel)(src+1)); handleTransition((RunLevel)(src+1),dst); return; } if(src>dst && (src-dst)>1) // move down the runlevel chain { handleTransition(src,(RunLevel)(src-1)); handleTransition((RunLevel)(src-1),dst); return; } //Below: either src-dst = 1 or dst-src = 1 if(src==UNKNOWN) return; // nothing to do switch(dst) { case OFF: if(src==ATTACHED) emit onDetach(); else UNREACHABLE; break; case ATTACHED: if(src==OFF) emit onAttach(); else if(src==ARMED) emit onDisarm(); else UNREACHABLE; break; case ARMED: if(src==ATTACHED) { emit onArm(agent_->_task); emit onArm(); } else if(src==RUNNING) emit onStop(); else UNREACHABLE; break; case RUNNING: if(src==ARMED) emit onRun(); else UNREACHABLE; break; default: //UNKNOWN...nothing to do UNREACHABLE; } } AgentController::RunLevel AgentController::queryRunLevel() { if(agent_->is_running()) return RUNNING; if(agent_->is_armed()) return ARMED; if(agent_->is_attached()) return ATTACHED; return OFF; } void AgentController::attach() { Guarded_Assert_WinErr(agent_->attach_nowait()); } void AgentController::detach() { Guarded_Assert_WinErr(agent_->detach_nowait()); } void AgentController::arm( Task *t ) { Guarded_Assert_WinErr(agent_->arm_nowait(t,agent_->_owner,INFINITE)); } void AgentController::disarm() { Guarded_Assert_WinErr(agent_->disarm_nowait(INFINITE)); } void AgentController::run() { Guarded_Assert_WinErr(agent_->run_nowait()); } void AgentController::stop() { Guarded_Assert_WinErr(agent_->stop_nowait(INFINITE)); } QTimer * AgentController::createPollingTimer() { QTimer *poller = new QTimer(this); connect(poller,SIGNAL(timeout()),this,SLOT(poll())); return poller; } QDockWidget* AgentController::createTaskDockWidget(const QString & title, Task *task, QWidget* parent) { QDockWidget* d = new QDockWidget(title,parent); QWidget* w = new QWidget(d); QFormLayout* layout = new QFormLayout; layout->addRow(new AgentControllerButtonPanel(this,task)); w->setLayout(layout); d->setWidget(w); return d; } /** NOTE: I've disabled the attach and detach buttons (by not adding them to the widget layout). They were not tremendously useful. When I was tempted to use them, usually it was better just to close and reopen the application. With the buttons present, there was a chance for a misclick. Perhaps one day, it will be prudent to remove associated code, but for now, they live on in purgatory. **/ AgentControllerButtonPanel::AgentControllerButtonPanel(AgentController *ac, Task *task) : armTarget_(task) , ac_(ac) { btnDetach = new QPushButton("Detach"); btnAttach = new QPushButton("Attach"); btnArm = new QPushButton("Arm"); btnDisarm = new QPushButton("Disarm"); btnRun = new QPushButton("Run"); btnStop = new QPushButton("Stop"); QObject::connect(btnDetach,SIGNAL(clicked()),ac_,SLOT(detach())); QObject::connect(btnAttach,SIGNAL(clicked()),ac_,SLOT(attach())); QObject::connect(btnArm,SIGNAL(clicked()),this,SLOT(armTargetTask())); QObject::connect(btnDisarm,SIGNAL(clicked()),ac_,SLOT(disarm())); QObject::connect(btnRun,SIGNAL(clicked()),ac_,SLOT(run())); QObject::connect(btnStop,SIGNAL(clicked()),ac_,SLOT(stop())); // // State machine // taskDetached = new QState; taskAttached = new QState; taskArmed = new QState; taskArmedNonTarget = new QState; taskRunning = new QState; taskDetached->addTransition(ac_,SIGNAL(onAttach()),taskAttached); taskAttached->addTransition(ac_,SIGNAL(onDetach()),taskDetached); connect(ac_,SIGNAL(onArm(Task*)),this,SLOT(onArmFilter(Task*))); taskAttached->addTransition(this,SIGNAL(onArmTargetTask()),taskArmed); taskAttached->addTransition(this,SIGNAL(onArmNonTargetTask()),taskArmedNonTarget); taskArmed->addTransition(ac_,SIGNAL(onDisarm()),taskAttached); taskArmed->addTransition(ac_,SIGNAL(onRun()),taskRunning); taskArmedNonTarget->addTransition(ac_,SIGNAL(onDisarm()),taskAttached); taskRunning->addTransition(ac_,SIGNAL(onStop()),taskArmed); stateMachine_.addState(taskArmed); stateMachine_.addState(taskArmedNonTarget); stateMachine_.addState(taskAttached); stateMachine_.addState(taskDetached); stateMachine_.addState(taskRunning); stateMachine_.setInitialState(taskDetached); stateMachine_.start(); { QState *c = taskDetached; c->assignProperty(btnDetach,"enabled",false); c->assignProperty(btnAttach,"enabled",true); c->assignProperty(btnArm, "enabled",false); c->assignProperty(btnDisarm,"enabled",false); c->assignProperty(btnRun, "enabled",false); c->assignProperty(btnStop, "enabled",false); c = taskAttached; c->assignProperty(btnDetach,"enabled",true); c->assignProperty(btnAttach,"enabled",false); c->assignProperty(btnArm, "enabled",armTarget_!=NULL); c->assignProperty(btnDisarm,"enabled",false); c->assignProperty(btnRun, "enabled",false); c->assignProperty(btnStop, "enabled",false); c = taskArmed; c->assignProperty(btnDetach,"enabled",true); c->assignProperty(btnAttach,"enabled",false); c->assignProperty(btnArm, "enabled",false); c->assignProperty(btnDisarm,"enabled",true); c->assignProperty(btnRun, "enabled",true); c->assignProperty(btnStop, "enabled",true); c = taskArmedNonTarget; c->assignProperty(btnDetach,"enabled",true); c->assignProperty(btnAttach,"enabled",false); c->assignProperty(btnArm, "enabled",false); c->assignProperty(btnDisarm,"enabled",true); c->assignProperty(btnRun, "enabled",false); c->assignProperty(btnStop, "enabled",false); c = taskRunning; c->assignProperty(btnDetach,"enabled",true); c->assignProperty(btnAttach,"enabled",false); c->assignProperty(btnArm, "enabled",false); c->assignProperty(btnDisarm,"enabled",true); c->assignProperty(btnRun, "enabled",false); c->assignProperty(btnStop, "enabled",true); } QGridLayout *layout; layout = new QGridLayout; //layout->addWidget(btnAttach,0,0); layout->addWidget(btnArm,0,1); layout->addWidget(btnRun,0,2); //layout->addWidget(btnDetach,1,0); layout->addWidget(btnDisarm,1,1); layout->addWidget(btnStop,1,2); setLayout(layout); } void AgentControllerButtonPanel::onArmFilter( Task* t ) { if(t==armTarget_) emit onArmTargetTask(); else emit onArmNonTargetTask(); } void AgentControllerButtonPanel::armTargetTask() { if(armTarget_) emit ac_->arm(armTarget_); } }} //end fetch::ui <|endoftext|>
<commit_before>#include "QsLog.h" #include "AutoUpdateDialog.h" #include "ui_AutoUpdateDialog.h" #include <QMessageBox> #include <QDesktopServices> #include <QPushButton> AutoUpdateDialog::AutoUpdateDialog(const QString &version, const QString &targetFilename, const QString &url, QWidget *parent) : QDialog(parent), ui(new Ui::AutoUpdateDialog), m_sourceUrl(url), m_targetFilename(targetFilename), m_networkReply(NULL), m_skipVersion(FALSE), m_skipVersionString(version) { ui->setupUi(this); ui->progressBar->hide(); ui->versionLabel->setText(version); connect(ui->skipPushButton, SIGNAL(clicked()), this, SLOT(skipClicked())); connect(ui->yesPushButton, SIGNAL(clicked()), this, SLOT(yesClicked())); connect(ui->noPushButton, SIGNAL(clicked()), this, SLOT(noClicked())); } AutoUpdateDialog::~AutoUpdateDialog() { delete ui; } void AutoUpdateDialog::noClicked() { deleteLater(); reject(); } void AutoUpdateDialog::skipClicked() { emit autoUpdateCancelled(m_skipVersionString); } void AutoUpdateDialog::yesClicked() { startDownload(m_sourceUrl, m_targetFilename); } bool AutoUpdateDialog::skipVersion() { return m_skipVersion; } bool AutoUpdateDialog::startDownload(const QString& url, const QString& filename) { QString targetDir = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation); if (filename.isEmpty()) return false; if (QFile::exists(targetDir + "/" + filename)) { int result = QMessageBox::question(this, tr("HTTP"), tr("There already exists a file called %1 in " "%2. Overwrite?").arg(filename, targetDir), QMessageBox::Yes|QMessageBox::No, QMessageBox::No); if (result == QMessageBox::No){ return false; } } // Always must remove file before proceeding QFile::remove(targetDir + filename); m_targetFile = new QFile(targetDir + "/" + filename); if (!m_targetFile->open(QIODevice::WriteOnly)) { QMessageBox::information(this, tr("HTTP"), tr("Unable to save the file %1: %2.") .arg(filename).arg(m_targetFile->errorString())); delete m_targetFile; m_targetFile = NULL; return false; } QLOG_DEBUG() << "Start Downloading new version" << url; m_url = QUrl(url); startFileDownloadRequest(m_url); return true; } void AutoUpdateDialog::startFileDownloadRequest(QUrl url) { ui->progressBar->show(); ui->noPushButton->setText(tr("Cancel")); ui->yesPushButton->setEnabled(false); ui->titleLabel->setText(tr("<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">Downloading</span></p></body></html>")); ui->questionLabel->setText(tr("")); ui->statusLabel->setText(tr("Downloading %1").arg(m_targetFilename)); m_httpRequestAborted = false; if (m_networkReply != NULL){ delete m_networkReply; m_networkReply = NULL; } m_networkReply = m_networkAccessManager.get(QNetworkRequest(url)); connect(m_networkReply, SIGNAL(finished()), this, SLOT(httpFinished())); connect(m_networkReply, SIGNAL(readyRead()), this, SLOT(httpReadyRead())); connect(m_networkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDataReadProgress(qint64,qint64))); } void AutoUpdateDialog::cancelDownload() { ui->statusLabel->setText(tr("Download canceled.")); m_httpRequestAborted = true; m_networkReply->abort(); } void AutoUpdateDialog::httpFinished() { bool result = false; if (m_httpRequestAborted) { if (m_targetFile) { m_targetFile->close(); m_targetFile->remove(); delete m_targetFile; m_targetFile = NULL; } m_networkReply->deleteLater(); return; } m_targetFile->flush(); m_targetFile->close(); QVariant redirectionTarget = m_networkReply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (m_networkReply->error()) { m_targetFile->remove(); QMessageBox::information(this, tr("HTTP"), tr("Download failed: %1.") .arg(m_networkReply->errorString())); } else if (!redirectionTarget.isNull()) { QUrl newUrl = m_url.resolved(redirectionTarget.toUrl()); if (QMessageBox::question(this, tr("HTTP"), tr("Redirect to %1 ?").arg(newUrl.toString()), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { m_url = newUrl; m_networkReply->deleteLater(); m_targetFile->open(QIODevice::WriteOnly); m_targetFile->resize(0); startFileDownloadRequest(m_url); return; } } else { QString filename = m_targetFile->fileName(); ui->statusLabel->setText(tr("Downloaded to %2.").arg(filename)); result = true; } m_networkReply->deleteLater(); m_networkReply = NULL; if (!result){ ui->titleLabel->setText(tr("<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">Download Failed</span></p></body></html>")); ui->statusLabel->setText(tr("ERROR: Download Failed!")); } else { ui->titleLabel->setText(tr("<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">Download Complete</span></p></body></html>")); ui->questionLabel->setText(tr("")); ui->statusLabel->setText(tr("Mounting Disk Image")); executeDownloadedFile(); } ui->noPushButton->setText(tr("OK")); this->raise(); delete m_targetFile; m_targetFile = NULL; } void AutoUpdateDialog::executeDownloadedFile() { // [TODO] need to check the extension for .dmg or .pkg #ifdef Q_OS_MACX QString filelocation = m_targetFile->fileName(); QProcess *process = new QProcess(); QLOG_INFO() << "LAUNCHING: DiskImageMounter" << filelocation; QStringList args; args.append(filelocation); process->start("/System/Library/CoreServices/DiskImageMounter.app/Contents/MacOS/DiskImageMounter", args); connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(dmgMounted(int,QProcess::ExitStatus))); process->waitForStarted(); #elif defined(Q_OS_UNIX) QLOG_ERROR() << "TODO: Launch deb installer"; #else QString program = m_targetFile->fileName(); QProcess *process = new QProcess(); process->start(program); #endif } void AutoUpdateDialog::dmgMounted(int result, QProcess::ExitStatus exitStatus) { QLOG_DEBUG() << "dmgMounted:" << result << "exitStatus:" << exitStatus; this->raise(); ui->skipPushButton->setEnabled(false); ui->yesPushButton->setEnabled(false); if (result != 0){ ui->statusLabel->setText(tr("ERROR:Failed to mount Disk Image!")); this->exec(); } ui->statusLabel->setText(tr("Complete")); accept(); } void AutoUpdateDialog::httpReadyRead() { // this slot gets called every time the QNetworkReply has new data. // We read all of its new data and write it into the file. // That way we use less RAM than when reading it at the finished() // signal of the QNetworkReply if (m_targetFile){ m_targetFile->write(m_networkReply->readAll()); } } void AutoUpdateDialog::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes) { if (m_httpRequestAborted) return; ui->progressBar->setMaximum(totalBytes); ui->progressBar->setValue(bytesRead); } <commit_msg>Change so windows auto-update now properly triggers the installer, and works with UAC<commit_after>#include "QsLog.h" #include "AutoUpdateDialog.h" #include "ui_AutoUpdateDialog.h" #include <QMessageBox> #include <QDesktopServices> #include <QPushButton> AutoUpdateDialog::AutoUpdateDialog(const QString &version, const QString &targetFilename, const QString &url, QWidget *parent) : QDialog(parent), ui(new Ui::AutoUpdateDialog), m_sourceUrl(url), m_targetFilename(targetFilename), m_networkReply(NULL), m_skipVersion(FALSE), m_skipVersionString(version) { ui->setupUi(this); ui->progressBar->hide(); ui->versionLabel->setText(version); connect(ui->skipPushButton, SIGNAL(clicked()), this, SLOT(skipClicked())); connect(ui->yesPushButton, SIGNAL(clicked()), this, SLOT(yesClicked())); connect(ui->noPushButton, SIGNAL(clicked()), this, SLOT(noClicked())); } AutoUpdateDialog::~AutoUpdateDialog() { delete ui; } void AutoUpdateDialog::noClicked() { deleteLater(); reject(); } void AutoUpdateDialog::skipClicked() { emit autoUpdateCancelled(m_skipVersionString); } void AutoUpdateDialog::yesClicked() { startDownload(m_sourceUrl, m_targetFilename); } bool AutoUpdateDialog::skipVersion() { return m_skipVersion; } bool AutoUpdateDialog::startDownload(const QString& url, const QString& filename) { QString targetDir = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation); if (filename.isEmpty()) return false; if (QFile::exists(targetDir + "/" + filename)) { int result = QMessageBox::question(this, tr("HTTP"), tr("There already exists a file called %1 in " "%2. Overwrite?").arg(filename, targetDir), QMessageBox::Yes|QMessageBox::No, QMessageBox::No); if (result == QMessageBox::No){ return false; } } // Always must remove file before proceeding QFile::remove(targetDir + filename); m_targetFile = new QFile(targetDir + "/" + filename); if (!m_targetFile->open(QIODevice::WriteOnly)) { QMessageBox::information(this, tr("HTTP"), tr("Unable to save the file %1: %2.") .arg(filename).arg(m_targetFile->errorString())); delete m_targetFile; m_targetFile = NULL; return false; } QLOG_DEBUG() << "Start Downloading new version" << url; m_url = QUrl(url); startFileDownloadRequest(m_url); return true; } void AutoUpdateDialog::startFileDownloadRequest(QUrl url) { ui->progressBar->show(); ui->noPushButton->setText(tr("Cancel")); ui->yesPushButton->setEnabled(false); ui->titleLabel->setText(tr("<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">Downloading</span></p></body></html>")); ui->questionLabel->setText(tr("")); ui->statusLabel->setText(tr("Downloading %1").arg(m_targetFilename)); m_httpRequestAborted = false; if (m_networkReply != NULL){ delete m_networkReply; m_networkReply = NULL; } m_networkReply = m_networkAccessManager.get(QNetworkRequest(url)); connect(m_networkReply, SIGNAL(finished()), this, SLOT(httpFinished())); connect(m_networkReply, SIGNAL(readyRead()), this, SLOT(httpReadyRead())); connect(m_networkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDataReadProgress(qint64,qint64))); } void AutoUpdateDialog::cancelDownload() { ui->statusLabel->setText(tr("Download canceled.")); m_httpRequestAborted = true; m_networkReply->abort(); } void AutoUpdateDialog::httpFinished() { bool result = false; if (m_httpRequestAborted) { if (m_targetFile) { m_targetFile->close(); m_targetFile->remove(); delete m_targetFile; m_targetFile = NULL; } m_networkReply->deleteLater(); return; } m_targetFile->flush(); m_targetFile->close(); QVariant redirectionTarget = m_networkReply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (m_networkReply->error()) { m_targetFile->remove(); QMessageBox::information(this, tr("HTTP"), tr("Download failed: %1.") .arg(m_networkReply->errorString())); } else if (!redirectionTarget.isNull()) { QUrl newUrl = m_url.resolved(redirectionTarget.toUrl()); if (QMessageBox::question(this, tr("HTTP"), tr("Redirect to %1 ?").arg(newUrl.toString()), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { m_url = newUrl; m_networkReply->deleteLater(); m_targetFile->open(QIODevice::WriteOnly); m_targetFile->resize(0); startFileDownloadRequest(m_url); return; } } else { QString filename = m_targetFile->fileName(); ui->statusLabel->setText(tr("Downloaded to %2.").arg(filename)); result = true; } m_networkReply->deleteLater(); m_networkReply = NULL; if (!result){ ui->titleLabel->setText(tr("<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">Download Failed</span></p></body></html>")); ui->statusLabel->setText(tr("ERROR: Download Failed!")); } else { ui->titleLabel->setText(tr("<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">Download Complete</span></p></body></html>")); ui->questionLabel->setText(tr("")); ui->statusLabel->setText(tr("Mounting Disk Image")); executeDownloadedFile(); } ui->noPushButton->setText(tr("OK")); this->raise(); delete m_targetFile; m_targetFile = NULL; } void AutoUpdateDialog::executeDownloadedFile() { // [TODO] need to check the extension for .dmg or .pkg #ifdef Q_OS_MACX QString filelocation = m_targetFile->fileName(); QProcess *process = new QProcess(); QLOG_INFO() << "LAUNCHING: DiskImageMounter" << filelocation; QStringList args; args.append(filelocation); process->start("/System/Library/CoreServices/DiskImageMounter.app/Contents/MacOS/DiskImageMounter", args); connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(dmgMounted(int,QProcess::ExitStatus))); process->waitForStarted(); #elif defined(Q_OS_UNIX) QLOG_ERROR() << "TODO: Launch deb installer"; #else QLOG_INFO() << "Launching" << m_targetFile->fileName(); QDesktopServices::openUrl(QUrl(m_targetFile->fileName(), QUrl::TolerantMode)); QTimer::singleShot(3000,this,SLOT(raise())); exit(0); #endif } void AutoUpdateDialog::dmgMounted(int result, QProcess::ExitStatus exitStatus) { QLOG_DEBUG() << "dmgMounted:" << result << "exitStatus:" << exitStatus; this->raise(); ui->skipPushButton->setEnabled(false); ui->yesPushButton->setEnabled(false); if (result != 0){ ui->statusLabel->setText(tr("ERROR:Failed to mount Disk Image!")); this->exec(); } ui->statusLabel->setText(tr("Complete")); accept(); } void AutoUpdateDialog::httpReadyRead() { // this slot gets called every time the QNetworkReply has new data. // We read all of its new data and write it into the file. // That way we use less RAM than when reading it at the finished() // signal of the QNetworkReply if (m_targetFile){ m_targetFile->write(m_networkReply->readAll()); } } void AutoUpdateDialog::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes) { if (m_httpRequestAborted) return; ui->progressBar->setMaximum(totalBytes); ui->progressBar->setValue(bytesRead); } <|endoftext|>