#include "ui_mainwindow.h"
enum {
- COL_NO,
- COL_TYPE,
- COL_CONTENT
+ COL_NO,
+ COL_TYPE,
+ COL_CONTENT
};
MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow),
- m_dropNo(0)
+ QMainWindow(parent),
+ ui(new Ui::MainWindow),
+ m_dropNo(0)
{
- ui->setupUi(this);
- ui->tableWidgetDragInfo->setMainWindow(this);
- connect(ui->comboBoxMimeType, SIGNAL(currentIndexChanged(const QString&)),
- this, SLOT(currentIndexChanged(const QString&)));
+ ui->setupUi(this);
+ ui->tableWidgetDragInfo->setMainWindow(this);
+ connect(ui->comboBoxMimeType, SIGNAL(currentIndexChanged(const QString&)),
+ this, SLOT(currentIndexChanged(const QString&)));
}
MainWindow::~MainWindow()
{
- delete ui;
+ delete ui;
}
void MainWindow::log(const QString& type, const QString& data)
{
- ui->tableWidgetDragInfo->insertRow(0);
- ui->tableWidgetDragInfo->setItem(0, COL_NO, new QTableWidgetItem(QString::number(m_dropNo)));
- ui->tableWidgetDragInfo->setItem(0, COL_TYPE, new QTableWidgetItem(type));
- ui->tableWidgetDragInfo->setItem(0, COL_CONTENT, new QTableWidgetItem(data));
+ ui->tableWidgetDragInfo->insertRow(0);
+ ui->tableWidgetDragInfo->setItem(0, COL_NO, new QTableWidgetItem(QString::number(m_dropNo)));
+ ui->tableWidgetDragInfo->setItem(0, COL_TYPE, new QTableWidgetItem(type));
+ ui->tableWidgetDragInfo->setItem(0, COL_CONTENT, new QTableWidgetItem(data));
}
bool MainWindow::isBinary(const QByteArray& data)
{
- bool rc = false;
- for (int ix = 0; ix < data.length(); ix++){
- if (data.at(ix) == 0){
- rc = true;
- break;
- }
- }
- return rc;
+ bool rc = false;
+ for (int ix = 0; ix < data.length(); ix++){
+ if (data.at(ix) == 0){
+ rc = true;
+ break;
+ }
+ }
+ return rc;
}
double MainWindow::fontWidth(){
- QFont myFont;
- QString str("0005: 61 62 63 64 65 66 67 68 69 6a|abcdefghijk");
+ QFont myFont;
+ QString str("0005: 61 62 63 64 65 66 67 68 69 6a|abcdefghijk");
- QFontMetrics fm(myFont);
- double width = fm.width(str) / str.length();
- return width;
+ QFontMetrics fm(myFont);
+ double width = fm.width(str) / str.length();
+ return width;
}
inline char toHex(int value){
- return value < 10 ? '0' + value : 'a' + (value - 10);
+ return value < 10 ? '0' + value : 'a' + (value - 10);
}
void MainWindow::setData(const char* data, int dataSize, int lineLength)
{
- if (lineLength < 0)
- lineLength = int (ui->plainTextEdit->width() / fontWidth()) - 1;
- int offsetWidth = dataSize >= 1000*1000 ? 10 : dataSize > 10000 ? 6 : 4;
- int charPerLine = (lineLength - offsetWidth - 1) / 4;
- int countLines = (dataSize + charPerLine - 1) / charPerLine;
- int restLength = dataSize;
- char formatOffset[10];
- snprintf(formatOffset, sizeof formatOffset, "%%0%dd:", offsetWidth);
- const unsigned char* ptr = reinterpret_cast<const unsigned char*>(data);
- QByteArray buffer;
- buffer.reserve(countLines * (charPerLine + 1) + 100);
- char lineNo[32];
- int offset = 0;
- while (restLength > 0){
- snprintf(lineNo, sizeof lineNo, formatOffset, offset);
- buffer.append(lineNo);
- for (int ix = 0; ix < charPerLine; ix++){
- if (ix >= restLength)
- buffer.append(" ");
- else
- buffer.append(toHex(ptr[ix]/16)).append(toHex(ptr[ix]%16)).append(' ');
- }
- buffer[buffer.length() - 1] = '|';
- for (int ix = 0; ix < charPerLine; ix++){
- if (ix >= restLength)
- buffer.append(" ");
- else if (ptr[ix] > 0x7f || ptr[ix] < ' ')
- buffer.append('.');
- else
- buffer.append((char) ptr[ix]);
- }
- buffer.append('\n');
- restLength -= charPerLine;
- ptr += charPerLine;
- offset += charPerLine;
- }
- ui->plainTextEdit->setPlainText(QString::fromUtf8(buffer));
+ if (lineLength < 0)
+ lineLength = int (ui->plainTextEdit->width() / fontWidth()) - 1;
+ int offsetWidth = dataSize >= 1000*1000 ? 10 : dataSize > 10000 ? 6 : 4;
+ int charPerLine = (lineLength - offsetWidth - 1) / 4;
+ int countLines = (dataSize + charPerLine - 1) / charPerLine;
+ int restLength = dataSize;
+ char formatOffset[10];
+ snprintf(formatOffset, sizeof formatOffset, "%%0%dd:", offsetWidth);
+ const unsigned char* ptr = reinterpret_cast<const unsigned char*>(data);
+ QByteArray buffer;
+ buffer.reserve(countLines * (charPerLine + 1) + 100);
+ char lineNo[32];
+ int offset = 0;
+ while (restLength > 0){
+ snprintf(lineNo, sizeof lineNo, formatOffset, offset);
+ buffer.append(lineNo);
+ for (int ix = 0; ix < charPerLine; ix++){
+ if (ix >= restLength)
+ buffer.append(" ");
+ else
+ buffer.append(toHex(ptr[ix]/16)).append(toHex(ptr[ix]%16)).append(' ');
+ }
+ buffer[buffer.length() - 1] = '|';
+ for (int ix = 0; ix < charPerLine; ix++){
+ if (ix >= restLength)
+ buffer.append(" ");
+ else if (ptr[ix] > 0x7f || ptr[ix] < ' ')
+ buffer.append('.');
+ else
+ buffer.append((char) ptr[ix]);
+ }
+ buffer.append('\n');
+ restLength -= charPerLine;
+ ptr += charPerLine;
+ offset += charPerLine;
+ }
+ ui->plainTextEdit->setPlainText(QString::fromUtf8(buffer));
}
QByteArray urlAsBytes(const QList<QUrl>& urls){
- QByteArray rc;
- rc.reserve(urls.length() * 80);
- QList<QUrl>::const_iterator it;
- for (it = urls.begin(); it != urls.end(); ++it){
- rc.append(it->path()).append('\n');
- }
- return rc;
+ QByteArray rc;
+ rc.reserve(urls.length() * 80);
+ QList<QUrl>::const_iterator it;
+ for (it = urls.begin(); it != urls.end(); ++it){
+ rc.append(it->path()).append('\n');
+ }
+ return rc;
}
void MainWindow::setMimeData(const QMimeData* mime){
ui->comboBoxMimeType->clear();
ui->comboBoxMimeType->addItems(formats);
for (int ix = 0; ix < formats.length(); ix++){
- QString name = formats.at(ix);
- if (name.indexOf("html") >= 0)
- m_mimeData[name] = mime->html().toUtf8();
- else if (name.indexOf("text") >= 0)
- m_mimeData[name] = mime->text().toUtf8();
- else if (name.indexOf("image") >= 0)
- m_mimeData[name] = mime->imageData().toByteArray();
- else if (name.indexOf("uri-list") >= 0)
- m_mimeData[name] = urlAsBytes(mime->urls());
- else
- m_mimeData[name] = mime->data(name);
+ QString name = formats.at(ix);
+ if (name.indexOf("html") >= 0)
+ m_mimeData[name] = I18N::s2b(mime->html());
+ else if (name.indexOf("text") >= 0)
+ m_mimeData[name] = I18N::s2b(mime->text());
+ else if (name.indexOf("image") >= 0)
+ m_mimeData[name] = mime->imageData().toByteArray();
+ else if (name.indexOf("uri-list") >= 0)
+ m_mimeData[name] = urlAsBytes(mime->urls());
+ else
+ m_mimeData[name] = mime->data(name);
}
}
void MainWindow::currentIndexChanged(const QString& text)
{
- QByteArray data = m_mimeData[text];
- if (isBinary(data)){
- setData(data.constData(), data.length());
- } else {
- ui->plainTextEdit->setPlainText(QString::fromUtf8(data.constData()));
- }
+ QByteArray data = m_mimeData[text];
+ if (isBinary(data)){
+ setData(data.constData(), data.length());
+ } else {
+ ui->plainTextEdit->setPlainText(QString::fromUtf8(data.constData()));
+ }
}
comboText(ui->comboBoxFooter);
if (ui->radioButtonFile->isChecked()){
QString fn = ui->comboBoxExportFile->currentText();
- FILE* fp = fopen(fn.toUtf8(), "w");
+ FILE* fp = fopen( I18N::s2b(fn), "w");
if (fp == NULL)
guiError(ui->comboBoxExportFile, tr("not a valid file: ") + fn);
else{
/ CLOCKS_PER_SEC;
QString msg;
msg.sprintf(
- QObject::tr(
- "Found: %d dir(s) and %d file(s) with %.6f MByte. Duration of the search: %.3f sec").toUtf8(),
+ I18N::s2b(QObject::tr(
+ "Found: %d dir(s) and %d file(s) with %.6f MByte. Duration of the search: %.3f sec")),
m_statistics.m_dirs, m_statistics.m_files,
m_statistics.m_bytes / 1000000.0, m_statistics.m_runtimeSeconds);
say(LOG_INFO, msg);
handler->m_text = cols.at(0);
handler->m_program = cols.at(1);
handler->m_arguments = cols.at(2);
- const char* sValue = cols.at(3).toUtf8().constData();
- handler->m_fileType = ContextHandler::FileType(atol(sValue));
- sValue = cols.at(4).toUtf8().constData();
- handler->m_directoryMode = ContextHandler::DirMode(atol(sValue));
+ long int lValue = atol(cols.at(3).toLatin1().constData());
+ handler->m_fileType = ContextHandler::FileType(lValue);
+ lValue = atol(cols.at(4).toLatin1().constData());
+ handler->m_directoryMode = ContextHandler::DirMode(atol(lValue));
m_list.append(handler);
}
if (m_list.size() == 0){
m_delayedStorage(NULL){
setLayout(new QVBoxLayout);
if (workspace == NULL)
- workspace = QDir::homePath().toUtf8();
+ workspace = I18N::s2b(QDir::homePath());
changeWorkspace(workspace == NULL ? QDir::homePath() : workspace);
QString proj(project == NULL ? "" : project);
const QString& sourcePattern, const QString& targetType, int landscapeX,
int landscapeY, int portraitX, int portraitY, int squareX, int quality,
MainWindow* mainWindow) :
- m_dir(directory),
- m_targetDir(
- targetDirectory.indexOf(QDir::separator()) >= 0 ?
- targetDirectory :
- directory + QDir::separator() + targetDirectory),
- m_sourcePattern(sourcePattern),
- m_targetType(targetType),
- m_landscapeWidth(landscapeX),
- m_landscapeHeight(landscapeY),
- m_portraitWidth(portraitX),
- m_portraitHeight(portraitY),
- m_squareWidth(squareX),
- m_quality(targetType == "jpg" ? quality : 0),
- m_mainWindows(mainWindow),
- m_shouldStop(false),
- m_imageInfo(
- new QRegularExpression(" (PNG|GIF|JPEG) (\\d+)x(\\d+) ")),
- m_groupWidth(2),
- m_groupHeight(3){
+ m_dir(directory),
+ m_targetDir(
+ targetDirectory.indexOf(QDir::separator()) >= 0 ?
+ targetDirectory :
+ directory + QDir::separator() + targetDirectory),
+ m_sourcePattern(sourcePattern),
+ m_targetType(targetType),
+ m_landscapeWidth(landscapeX),
+ m_landscapeHeight(landscapeY),
+ m_portraitWidth(portraitX),
+ m_portraitHeight(portraitY),
+ m_squareWidth(squareX),
+ m_quality(targetType == "jpg" ? quality : 0),
+ m_mainWindows(mainWindow),
+ m_shouldStop(false),
+ m_imageInfo(
+ new QRegularExpression(" (PNG|GIF|JPEG) (\\d+)x(\\d+) ")),
+ m_groupWidth(2),
+ m_groupHeight(3){
}
/**
args << "-size" << QString::number(width) + "x" + QString::number(height);
args << source;
if (quality > 0)
- args << "-quality" << QString::number(quality);
+ args << "-quality" << QString::number(quality);
args << "-resize"
- << QString::number(widthNew) + "x" + QString::number(heightNew);
+ << QString::number(widthNew) + "x" + QString::number(heightNew);
args << target;
QProcess process;
process.start("/usr/bin/convert", args);
QByteArray output;
while (process.waitForReadyRead()){
- output = process.readAll();
+ output = process.readAll();
}
output = process.readAllStandardError();
if (!output.isEmpty())
- error(output);
+ error(output);
process.close();
}
QString info;
clock_t start = clock();
if (readProperties(source, width, height, info)){
- bool doConvert = false;
- int widthNew, heightNew;
- if (abs(width - height) < 5){
- // Square format:
- doConvert = width > m_squareWidth;
- if (doConvert)
- widthNew = heightNew = m_squareWidth;
- }else if (width > height){
- // Landscape:
- doConvert = width > m_landscapeWidth || height > m_landscapeHeight;
- if (doConvert){
- if (width > m_landscapeWidth && m_landscapeWidth > 0){
- widthNew = m_landscapeWidth;
- heightNew = height * m_landscapeWidth / width;
- }else{
- heightNew = m_landscapeHeight;
- widthNew = width * m_landscapeHeight / height;
- }
- }
- }else{
- // Portrait
- doConvert = width > m_portraitWidth || height > m_portraitHeight;
- if (doConvert){
- if (width > m_portraitWidth && m_portraitWidth > 0){
- widthNew = m_portraitWidth;
- heightNew = height * m_portraitWidth / width;
- }else{
- heightNew = m_portraitHeight;
- widthNew = width * m_portraitHeight / height;
- }
- }
- }
- log(
- source + " " + info + " " + sizeToString(size)
- + QString(" -> %1x%2 ").arg(widthNew).arg(heightNew));
- convert(source, target, width, height, widthNew, heightNew, m_quality);
- struct stat info;
- if (stat(target.toUtf8().constData(), &info) == 0)
- m_mainWindows->logAppendLast(sizeToString(info.st_size) + " ");
+ bool doConvert = false;
+ int widthNew, heightNew;
+ if (abs(width - height) < 5){
+ // Square format:
+ doConvert = width > m_squareWidth;
+ if (doConvert)
+ widthNew = heightNew = m_squareWidth;
+ }else if (width > height){
+ // Landscape:
+ doConvert = width > m_landscapeWidth || height > m_landscapeHeight;
+ if (doConvert){
+ if (width > m_landscapeWidth && m_landscapeWidth > 0){
+ widthNew = m_landscapeWidth;
+ heightNew = height * m_landscapeWidth / width;
+ }else{
+ heightNew = m_landscapeHeight;
+ widthNew = width * m_landscapeHeight / height;
+ }
+ }
+ }else{
+ // Portrait
+ doConvert = width > m_portraitWidth || height > m_portraitHeight;
+ if (doConvert){
+ if (width > m_portraitWidth && m_portraitWidth > 0){
+ widthNew = m_portraitWidth;
+ heightNew = height * m_portraitWidth / width;
+ }else{
+ heightNew = m_portraitHeight;
+ widthNew = width * m_portraitHeight / height;
+ }
+ }
+ }
+ log(
+ source + " " + info + " " + sizeToString(size)
+ + QString(" -> %1x%2 ").arg(widthNew).arg(heightNew));
+ convert(source, target, width, height, widthNew, heightNew, m_quality);
+ struct stat info;
+ if (stat(I18N::s2b(target).constData(), &info) == 0)
+ m_mainWindows->logAppendLast(sizeToString(info.st_size) + " ");
}
m_mainWindows->logAppendLast(
- QString("").sprintf("%.3f sec",
- double(clock() - start) / CLOCKS_PER_SEC));
+ QString("").sprintf("%.3f sec",
+ double(clock() - start) / CLOCKS_PER_SEC));
}
/**
* @return <code>true</code>
*/
bool Converter::log(const QString& message){
- printf("%s\n", message.toUtf8().constData());
+ printf("%s\n", I18N::s2b(message).constData());
m_mainWindows->log(message);
return true;
}
QByteArray output;
bool rc = false;
while (process.waitForReadyRead()){
- output = process.readAll();
- QRegularExpressionMatch match = m_imageInfo->match(output);
- if (!match.hasMatch())
- error(
- QObject::tr("I am confused (wrong image data):\n%1\nExpected: %2").arg(
- output.constData()).arg(m_imageInfo->pattern()));
- else{
- width = match.captured(m_groupWidth).toInt();
- height = match.captured(m_groupHeight).toInt();
- rc = true;
- info = QString("%1x%2").arg(width).arg(height);
- break;
- }
+ output = process.readAll();
+ QRegularExpressionMatch match = m_imageInfo->match(output);
+ if (!match.hasMatch())
+ error(
+ QObject::tr("I am confused (wrong image data):\n%1\nExpected: %2").arg(
+ output.constData()).arg(m_imageInfo->pattern()));
+ else{
+ width = match.captured(m_groupWidth).toInt();
+ height = match.captured(m_groupHeight).toInt();
+ rc = true;
+ info = QString("%1x%2").arg(width).arg(height);
+ break;
+ }
}
output = process.readAll();
output = process.readAllStandardError();
if (!output.isEmpty())
- error(output);
+ error(output);
process.close();
return rc;
}
QString msg;
int no = 0;
try{
- if (!m_dir.exists())
- error(
- QObject::tr("Directory does not exist: ") + m_dir.absolutePath());
- if (!m_targetDir.exists()){
- QString parentName = m_targetDir.path();
- QString subdir = m_targetDir.dirName();
- QDir parent(m_targetDir.path());
- parent.cdUp();
- parent.mkdir(subdir);
- }
- if (!m_targetDir.exists()){
- error(
- QObject::tr("Cannot create the target directory: ")
- + m_targetDir.absolutePath());
- }
- changeState(Converter::STATE_STARTING, "");
- m_shouldStop = false;
- QDirIterator it(m_dir.absolutePath());
- QRegExp regExpr(m_sourcePattern, Qt::CaseInsensitive, QRegExp::Wildcard);
- while (it.hasNext()){
- if (m_shouldStop){
- log(QObject::tr("Canceled by the user"));
- break;
- }
- it.next();
- if (it.fileInfo().isDir())
- continue;
- QString node = it.fileName();
- if (regExpr.indexIn(node) >= 0){
- no++;
- QString path = m_dir.absoluteFilePath(node);
- qint64 length = it.fileInfo().size();
- QString nodeTarget = ReQStringUtil::replaceExtension(node,
- "." + m_targetType);
- QString target = m_targetDir.absoluteFilePath(nodeTarget);
- convertOneFile(path, target, length);
- }
- }
- changeState(Converter::STATE_SUB_TASK_STOPPED, msg);
+ if (!m_dir.exists())
+ error(
+ QObject::tr("Directory does not exist: ") + m_dir.absolutePath());
+ if (!m_targetDir.exists()){
+ QString parentName = m_targetDir.path();
+ QString subdir = m_targetDir.dirName();
+ QDir parent(m_targetDir.path());
+ parent.cdUp();
+ parent.mkdir(subdir);
+ }
+ if (!m_targetDir.exists()){
+ error(
+ QObject::tr("Cannot create the target directory: ")
+ + m_targetDir.absolutePath());
+ }
+ changeState(Converter::STATE_STARTING, "");
+ m_shouldStop = false;
+ QDirIterator it(m_dir.absolutePath());
+ QRegExp regExpr(m_sourcePattern, Qt::CaseInsensitive, QRegExp::Wildcard);
+ while (it.hasNext()){
+ if (m_shouldStop){
+ log(QObject::tr("Canceled by the user"));
+ break;
+ }
+ it.next();
+ if (it.fileInfo().isDir())
+ continue;
+ QString node = it.fileName();
+ if (regExpr.indexIn(node) >= 0){
+ no++;
+ QString path = m_dir.absoluteFilePath(node);
+ qint64 length = it.fileInfo().size();
+ QString nodeTarget = ReQStringUtil::replaceExtension(node,
+ "." + m_targetType);
+ QString target = m_targetDir.absoluteFilePath(nodeTarget);
+ convertOneFile(path, target, length);
+ }
+ }
+ changeState(Converter::STATE_SUB_TASK_STOPPED, msg);
} catch (ConverterException exc){
- log(
- QObject::tr("Execution stopped because of error(s): ")
- + exc.message());
+ log(
+ QObject::tr("Execution stopped because of error(s): ")
+ + exc.message());
}
msg = QObject::tr("%1 file(s) converted").arg(no);
changeState(Converter::STATE_READY, msg);
static QString rc;
if (rc.isEmpty()){
- QDir dir = QDir::current();
- QFile scriptFile(dir.filePath(node));
- if (!scriptFile.exists()){
- extern char** g_argv;
- dir.setPath(g_argv[0]);
- dir.cdUp();
- scriptFile.setFileName(dir.filePath(node));
- }
- if (scriptFile.exists())
- rc = scriptFile.fileName();
+ QDir dir = QDir::current();
+ QFile scriptFile(dir.filePath(node));
+ if (!scriptFile.exists()){
+ extern char** g_argv;
+ dir.setPath(g_argv[0]);
+ dir.cdUp();
+ scriptFile.setFileName(dir.filePath(node));
+ }
+ if (scriptFile.exists())
+ rc = scriptFile.fileName();
}
return rc;
}
QString sizeToString(qint64 size){
QString rc;
if (size < 10 * 1024)
- rc.sprintf("%d Bytes", (int) size);
+ rc.sprintf("%d Bytes", (int) size);
else if (size < qint64(10 * 1024 * 1024))
- rc.sprintf("%d KiBytes", (int) (size / 1024));
+ rc.sprintf("%d KiBytes", (int) (size / 1024));
else if (size < qint64(10 * 1024 * 1024) * 1024)
- rc.sprintf("%d MiBytes", (int) (size / 1024 / 1024));
+ rc.sprintf("%d MiBytes", (int) (size / 1024 / 1024));
else
- rc.sprintf("%d GiBytes", (int) (size / 1024 / 1024 / 1024));
+ rc.sprintf("%d GiBytes", (int) (size / 1024 / 1024 / 1024));
return rc;
}
void toFile(const char* prefix, int64_t* primes, int count){
QByteArray fn = QByteArray(prefix) + "."
+ QDateTime::currentDateTime().toLocalTime()
- .toString("yyyy.MM.dd_hh_mm_ss").toUtf8() + ".txt";
+ .toString("yyyy.MM.dd_hh_mm_ss").toLatin1() + ".txt";
FILE* fp = fopen(fn.constData(), "w");
if (fp != NULL){
fprintf(stderr, "Result in %s\n", fn.constData());
* @param bufferSize the size of one buffer
*/
ReByteStorage::ReByteStorage(int bufferSize) :
- m_bufferSize(bufferSize),
- m_buffer(NULL),
- m_rest(0),
- m_freePosition(NULL),
- m_summarySize(0),
- m_buffers(0) {
+ m_bufferSize(bufferSize),
+ m_buffer(NULL),
+ m_rest(0),
+ m_freePosition(NULL),
+ m_summarySize(0),
+ m_buffers(0) {
}
/**
*/
char* ReByteStorage::allocBuffer(int size) {
m_rest =
- size + sizeof(uint8_t*) <= (size_t) m_bufferSize ?
- m_bufferSize : size + sizeof(uint8_t*);
+ size + sizeof(uint8_t*) <= (size_t) m_bufferSize ?
+ m_bufferSize : size + sizeof(uint8_t*);
m_summarySize += m_rest;
m_buffers++;
uint8_t* rc = new uint8_t[m_rest];
* @return a copy of the source string. The copy ends always with '\0'
*/
const char* ReByteStorage::allocUtf8(const ReString& source) {
- const char* rc = allocateChars(source.toUtf8().constData());
+ const char* rc = allocateChars(I18N::s2b(source).constData());
return rc;
}
*/
uint8_t* ReByteStorage::allocateBytes(int size) {
uint8_t* rc =
- size <= m_rest ?
- m_freePosition : reinterpret_cast<uint8_t*>(allocBuffer(size));
+ size <= m_rest ?
+ m_freePosition : reinterpret_cast<uint8_t*>(allocBuffer(size));
m_freePosition += size;
m_rest -= size;
return rc;
* Constructor.
*/
ReLines::ReLines() :
- QStringList(),
- m_empty() {
+ QStringList(),
+ m_empty() {
}
/**
* Destructor.
if (dir.exists(path)) {
QFileInfo info;
QStringList names = dir.entryList(
- QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs
- | QDir::Files);
+ QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs
+ | QDir::Files);
QStringList::const_iterator it;
for (it = names.constBegin(); it != names.constEnd(); ++it) {
QString full(path);
if (info.isDir()) {
if (!deleteTree(full, true, logger))
rc = false;
- else if (rmdir(full.toUtf8()) != 0) {
+ else if (rmdir(I18N::s2b(full)) != 0) {
rc = false;
if (logger != NULL)
logger->logv(LOG_ERROR, LOC_DELETE_TREE_1,
- "cannot delete directory (%d): %s", errno,
- full.toUtf8().constData());
+ "cannot delete directory (%d): %s", errno,
+ I18N::s2b(full).constData());
}
} else {
if (!QFile::remove(full)) {
rc = false;
if (logger != NULL)
logger->logv(LOG_ERROR, LOC_DELETE_TREE_2,
- "cannot delete file (%d): %s", errno,
- full.toUtf8().constData());
+ "cannot delete file (%d): %s", errno,
+ I18N::s2b(full).constData());
}
}
}
}
- if (withBase && (rmdir(path.toUtf8())) != 0) {
+ if (withBase && (rmdir(I18N::s2b(path))) != 0) {
rc = false;
logger->logv(LOG_ERROR, LOC_DELETE_TREE_3,
- "cannot delete directory (%d): %s", errno, path.toUtf8().constData());
+ "cannot delete directory (%d): %s", errno, I18N::s2b(path).constData());
}
return rc;
}
* <code>false</code>: undo is impossible
*/
void ReLines::insertPart(int lineNo, int col, const QString& text,
- bool withUndo) {
+ bool withUndo) {
if (lineNo >= 0 && lineNo < lineCount() && col >= 0) {
if (withUndo)
storeInsertPart(lineNo, col, text.length());
if (lastEoLn != endOfLine) {
int oldCount = lineCount();
insertLines(lineNo + 1,
- text.mid(endOfLine + 1, lastEoLn - endOfLine), true);
+ text.mid(endOfLine + 1, lastEoLn - endOfLine), true);
newLines = lineCount() - oldCount;
}
if (lastEoLn != text.length() - 1) {
* @param logger the logger
*/
ReFile::ReFile(const QString& filename, bool readOnly, ReLogger* logger) :
- ReLineSource(),
- ReLines(),
- m_endOfLine(),
- m_filename(filename),
- m_file(filename),
- m_block(NULL),
- // in 32-bit address space we allocate only 10 MByte, in 64-bit environments 100 GByte
- m_blocksize(
- sizeof(void*) <= 4 ?
- 10 * 1024 * 1024ll : 0x100ll * 0x10000 * 0x10000),
- m_blockOffset(0),
- m_filesize(0),
- m_startOfLine(NULL),
- m_lineLength(0),
- m_lineOffset(0),
- m_currentLineNo(0),
- m_maxLineLength(0x10000),
- m_content(),
- m_readOnly(readOnly),
- m_logger(logger) {
+ ReLineSource(),
+ ReLines(),
+ m_endOfLine(),
+ m_filename(filename),
+ m_file(filename),
+ m_block(NULL),
+ // in 32-bit address space we allocate only 10 MByte, in 64-bit environments 100 GByte
+ m_blocksize(
+ sizeof(void*) <= 4 ?
+ 10 * 1024 * 1024ll : 0x100ll * 0x10000 * 0x10000),
+ m_blockOffset(0),
+ m_filesize(0),
+ m_startOfLine(NULL),
+ m_lineLength(0),
+ m_lineOffset(0),
+ m_currentLineNo(0),
+ m_maxLineLength(0x10000),
+ m_content(),
+ m_readOnly(readOnly),
+ m_logger(logger) {
#if defined __linux__
setEndOfLine("\n");
#elif defined __WIN32__
* false: a line has not been found
*/
bool ReFile::findLine(const char* toFind, bool ignoreCase, int& lineNo,
- QString* line) {
+ QString* line) {
bool rc = false;
int length;
int sourceLength = strlen(toFind);
const char* ptr = start;
int restLength = length - sourceLength + 1;
while (restLength > 0
- && (ptr = reinterpret_cast<const char*>(
- ignoreCase ?
- memchr(start, first, restLength) :
- memichr(start, first, restLength))) != NULL) {
+ && (ptr = reinterpret_cast<const char*>(
+ ignoreCase ?
+ memchr(start, first, restLength) :
+ memichr(start, first, restLength))) != NULL) {
if ((
- ignoreCase ?
- _memicmp(ptr, toFind, sourceLength) :
- memcmp(ptr, toFind, sourceLength)) == 0) {
+ ignoreCase ?
+ _memicmp(ptr, toFind, sourceLength) :
+ memcmp(ptr, toFind, sourceLength)) == 0) {
rc = true;
lineNo = m_currentLineNo;
QByteArray buffer(m_startOfLine, m_lineLength);
* false: a line has not been found
*/
bool ReFile::findLine(const QString& includePattern, bool includeIsRegExpr,
- bool includeIgnoreCase, const QString& excludePattern,
- bool excludeIsRegExpr, bool excludeIgnoreCase, int& lineNo, QString* line) {
+ bool includeIgnoreCase, const QString& excludePattern,
+ bool excludeIsRegExpr, bool excludeIgnoreCase, int& lineNo, QString* line) {
bool rc = false;
if (line != NULL)
*line = "";
if (m_currentLineNo == 65639)
m_currentLineNo += 0;
rc = m_startOfLine = remap(m_lineOffset += m_lineLength,
- m_maxLineLength, lineLength);
+ m_maxLineLength, lineLength);
const char* ptr = reinterpret_cast<const char*>(memchr(rc, '\n',
- lineLength));
+ lineLength));
if (ptr != NULL)
lineLength = ptr - rc + 1;
length = m_lineLength = lineLength;
size = m_filesize - offset;
// Note: size <= m_blocksize
if (m_block != NULL && offset >= m_blockOffset
- && offset + size <= m_blockOffset + m_blocksize) {
+ && offset + size <= m_blockOffset + m_blocksize) {
// new block is inside the internal block:
// no remapping needed
rc = m_block + (offset - m_blockOffset);
if (m_block != NULL)
m_file.unmap(reinterpret_cast<uchar*>(m_block));
m_block = reinterpret_cast<char*>(m_file.map(m_blockOffset,
- m_blocksize));
+ m_blocksize));
rc = m_block + (offset - m_blockOffset);
length = m_blocksize - (rc - m_block);
if (length > size)
* @return the name of an existing directory
*/
QByteArray ReFile::tempDir(const char* node, const char* parent,
- bool withSeparator) {
+ bool withSeparator) {
#if defined __linux__
QByteArray temp("/tmp");
static const char* firstVar = "TMP";
* @return the full name of a temporary file
*/
QByteArray ReFile::tempFile(const char* node, const char* parent,
- bool deleteIfExists) {
+ bool deleteIfExists) {
QByteArray rc(tempDir(parent));
if (!rc.endsWith('/'))
rc += '/';
int maxIx = length() - 1;
for (int ix = 0; ix <= maxIx; ix++) {
const QString& line = at(ix);
- buffer = line.toUtf8();
+ buffer = I18N::s2b(line);
outputFile.write(buffer.constData(), buffer.length());
outputFile.write(m_endOfLine.constData(), m_endOfLine.length());
}
* @param mode file write mode: "w" (write) or "a" (append)
*/
void ReFile::writeToFile(const char* filename, const char* content,
- size_t contentLength, const char* mode) {
+ size_t contentLength, const char* mode) {
FILE* fp = fopen(filename, mode);
if (fp != NULL) {
if (contentLength == (size_t) - 1)
* Constructor.
*/
ReUndoList::ReUndoList() :
- m_list(),
- m_current(NULL),
- m_lastLine(-1),
- m_lastPosition(-1),
- m_maxUndoSize(10 * 1024 * 1024),
- m_currentUndoSize(0) {
+ m_list(),
+ m_current(NULL),
+ m_lastLine(-1),
+ m_lastPosition(-1),
+ m_maxUndoSize(10 * 1024 * 1024),
+ m_currentUndoSize(0) {
}
/**
* @param list the list containing the lines for extracting the line content
*/
void ReUndoList::storeRemoveLines(int lineNo, int count,
- const QStringList& list) {
+ const QStringList& list) {
qint64 size = 0;
// Calculate the additional space
for (int ii = lineNo + count - 1; ii >= lineNo; ii--)
if (info.isDir()) {
if (!deleteTree(full, false, logger))
rc = false;
- else if (rmdir(full.toUtf8()) != 0) {
+ else if (rmdir(I18N::s2b(full)) != 0) {
rc = false;
if (logger != NULL)
logger->logv(LOG_ERROR, LOC_DELETE_TREE_1,
"cannot delete directory (%d): %s", errno,
- full.toUtf8().constData());
+ I18N::s2b(full).constData());
}
} else {
if (!QFile::remove(full)) {
if (logger != NULL)
logger->logv(LOG_ERROR, LOC_DELETE_TREE_2,
"cannot delete file (%d): %s", errno,
- full.toUtf8().constData());
+ I18N::s2b(full).constData());
}
}
}
}
- if (withBase && (rmdir(path.toUtf8())) != 0) {
+ if (withBase && (rmdir(I18N::s2b(path))) != 0) {
rc = false;
logger->logv(LOG_ERROR, LOC_DELETE_TREE_3,
- "cannot delete directory (%d): %s", errno, path.toUtf8().constData());
+ "cannot delete directory (%d): %s", errno, I18N::s2b(path).constData());
}
return rc;
}
* @return the path without duplicated separators and "." and ".."
*/
QString ReFileUtils::cleanPath(const QString& path) {
- return (QString) cleanPath(path.toUtf8().constData());
+ return (QString) cleanPath(I18N::s2b(path).constData());
}
/**
* @return true: for chaining
*/
bool ReLogger::log(ReLoggerLevel level, int location, const ReString& message) {
- return log(level, location, message.toUtf8().data());
+ return log(level, location, I18N::s2b(message).data());
}
/**
ReOptionException::ReOptionException(ReProgramArgs* caller, const QString& message) :
ReException()
{
- m_message = message.toUtf8();
+ m_message = I18N::s2b(message);
if (caller != NULL)
caller->setLastError(m_message);
}
*/
void ReProgramArgs::help(const char* message, bool issueLastError,
QByteArrayList& lines) const {
- lines.append(m_usage);
+ lines = m_usage;
lines.append("");
if (m_options.size() > 0) {
- lines.append(QObject::tr("<options>:").toUtf8());
+ lines.append(QObject::tr("<options>:").toLatin1());
}
QByteArray line;
QByteArray param;
param.resize(0);
switch (opt->m_type) {
case DT_INT:
- param.append(QObject::tr("<number>"));
+ param = I18N::s2b(QObject::tr("<number>"));
break;
case DT_STRING:
- param.append(QObject::tr("<not empty string>"));
+ param = I18N::s2b(QObject::tr("<not empty string>"));
break;
case DT_STRING_EMPTY:
- param.append(QObject::tr("[<string>]"));
+ param = I18N::s2b(QObject::tr("[<string>]"));
break;
default:
break;
}
- if (opt->m_shortName != HIDDEN_SHORT_NAME) {
+ if (opt->m_shortName != UNDEF_SHORT_NAME) {
line.append("-").append(opt->m_shortName);
- line.append(param).append(' ').append(QObject::tr(" or ").toUtf8());
+ line.append(param).append(' ').append(I18N::s2b(QObject::tr(" or ")));
}
line.append("--").append(opt->m_longName);
if (param.length() > 0) {
line.append("=", -1).append(param.constData(), -1);
if (opt->m_type != DT_STRING
|| ! opt->m_defaultValue.isEmpty()) {
- line.append(QObject::tr(" Default value: ").toUtf8());
+ line.append(I18N::s2b(QObject::tr(" Default value: ")));
if (opt->m_type == DT_STRING)
line.append('\'');
line.append(opt->m_defaultValue);
line.resize(0);
line.append(PREFIX_LINE_OPTION).append(opt->m_description);
lines.append(line.constData());
+ line.resize(0);
}
if (m_examples.count() > 0) {
- lines.append(QObject::tr("Example(s):").toUtf8());
+ lines.append(I18N::s2b(QObject::tr("Example(s):")));
lines.append(m_examples);
}
if (issueLastError && m_lastError.length() > 0) {
static QByteArray UNDEFINED_STRING;
public:
enum DataType {
- DT_UNDEF = 0,
- DT_INT = 'i',
- DT_BOOL = 'b',
- DT_STRING = 's',
- DT_STRING_EMPTY = 'S'
+ DT_UNDEF,
+ DT_INT,
+ DT_BOOL,
+ DT_STRING,
+ DT_STRING_EMPTY
};
enum {
- HIDDEN_SHORT_NAME = 2
+ UNDEF_SHORT_NAME = 0
};
public:
ReProgramArgs(const char* usageList[], const char* examples[] = NULL);
*/
#include "base/rebase.hpp"
+I18N::CharSet I18N::m_standardCharSet = I18N::SYSTEM;
+
const QStringList ReQStringUtils::m_emptyList;
const QString ReQStringUtils::m_empty;
#ifndef REQSTRINGUTILS_HPP
#define REQSTRINGUTILS_HPP
+/**
+ * A pure static class for internationalization.
+ */
+class I18N {
+public:
+ enum CharSet { SYSTEM, UTF8, LATIN };
+public:
+ /** Converts a <code>QString</code> into a <code>QByteArray</code>.
+ * The character set is a global setting: <code>m_standardCharSet</code>.
+ * @param source the string to convert
+ * @return the converted string
+ */
+ inline static QByteArray s2b(const QString& source){
+ if (m_standardCharSet == UTF8)
+ return source.toUtf8();
+ else if (m_standardCharSet == LATIN)
+ return source.toLatin1();
+ else
+ return source.toLocal8Bit();
+ }
+public:
+ static CharSet m_standardCharSet;
+};
/**
* Some useful static functions handling <code>QString</code> instances.
*/
bool ReTest::assertEquals(const char* expected, const ReString& current,
const char* file, int lineNo) {
- bool equal = assertEquals(expected, current.toUtf8().constData(), file,
+ bool equal = assertEquals(expected, I18N::s2b(current).constData(), file,
lineNo);
return equal;
}
*/
bool ReTest::assertEquals(const ReString& expected, const ReString& current,
const char* file, int lineNo) {
- bool equal = assertEquals(expected.toUtf8().constData(),
- current.toUtf8().constData(), file, lineNo);
+ bool equal = assertEquals(I18N::s2b(expected).constData(),
+ I18N::s2b(current).constData(), file, lineNo);
return equal;
}
QString node;
for (int ix = 1; ix <= 7; ix++) {
node.sprintf("test%d.txt", ix);
- QByteArray fn = ReFileUtils::tempFile(node.toUtf8().constData(),
+ QByteArray fn = ReFileUtils::tempFile(I18N::s2b(node).constData(),
"refilesystem", false);
- ReFileUtils::writeToFile(fn.constData(), node.toUtf8().constData());
+ ReFileUtils::writeToFile(fn.constData(), I18N::s2b(node).constData());
fn = m_subDir1;
fn.append("text").append(QByteArray::number(ix));
ReFileUtils::writeToFile(fn.constData(), fn.constData());
QString path = fsTarget.fullName(metaSource.m_node);
checkT(path.indexOf("dir.01"));
struct stat info;
- checkEqu(0, stat(path.toUtf8().constData(), &info));
+ checkEqu(0, stat(I18N::s2b(path).constData(), &info));
}
void testReOSPermissions(){
ReOSPermissions p1;
--- /dev/null
+/*
+ * cuReProgArguments.cpp
+ *
+ * License: Public Domain
+ * You can use and modify this file without any restriction.
+ * Do what you want.
+ * No warranties and disclaimer of any damages.
+ * You also can use this license: http://www.wtfpl.net
+ * The latest sources: https://github.com/republib
+ */
+
+/** @file
+ * @brief Unit test of the QByteArray tools.
+ */
+#include "base/rebase.hpp"
+/**
+ * @brief Unit test for <code>ReProgArguments</code>.
+ */
+class TestReProgArgs: public ReTest {
+public:
+ TestReProgArgs() :
+ ReTest("ReProgArgs") {
+ doIt();
+ }
+
+public:
+ void testBase(){
+ ReProgramArgs args("usage: example prog", "example -a");
+ args.addBool("boolArg", "a bool arg", 'b', "bool-arg", false);
+ args.addInt("intArg", "integer arg", 'i', "int-arg", 99);
+ args.addString("stringArg", "string argument", 's', "string-arg", true, "");
+ const char* arguments[] = { "example" };
+ args.init(1, arguments);
+ checkF(args.getBool("boolArg"));
+ checkEqu(99, args.getInt("intArg"));
+ QByteArray buffer = "123";
+ checkEqu("", args.getString("stringArg", buffer));
+ checkEqu("", buffer);
+ }
+
+ void testBool(){
+ ReProgramArgs args("usage: example prog", "example -a");
+ args.addBool("trueArg", "a bool arg", 't', "true-arg", false);
+ args.addBool("falseArg", "a bool arg", 'f', "false-arg", true);
+ args.addBool("trueArg2", "a bool arg", 0, "true-arg2", false);
+ args.addBool("falseArg2", "a bool arg", 0, "false-arg2", true);
+ args.addBool("trueArg3", "a bool arg", 0, "true-arg3", false);
+ args.addBool("falseArg3", "a bool arg", 0, "false-arg3", true);
+ args.addBool("trueArg4", "a bool arg", 0, "true-arg4", false);
+ args.addBool("falseArg4", "a bool arg", 0, "false-arg4", true);
+ const char* arguments[] = {
+ "example",
+ "--true-arg4=n", "--false-arg3=y",
+ "--true-arg3=y", "--false-arg3=n",
+ "--true-arg2", "--false-arg2",
+ "-t", "-f",
+ NULL
+ };
+ args.init(9, arguments);
+ checkT(args.getBool("trueArg"));
+ checkF(args.getBool("falseArg"));
+ checkT(args.getBool("trueArg2"));
+ checkF(args.getBool("falseArg2"));
+ checkT(args.getBool("trueArg3"));
+ checkF(args.getBool("falseArg3"));
+ checkF(args.getBool("trueArg4"));
+ checkT(args.getBool("falseArg4"));
+ }
+ void testInt(){
+ ReProgramArgs args("usage: example prog", "example -a");
+ args.addInt("intArg", "an int arg", 'i', "arg", 4711);
+ args.addInt("intArg2", "an int arg", 0, "arg2", 4712);
+ const char* arguments[] = {
+ "example",
+ "-i", "2244",
+ "--arg2=3355",
+ NULL
+ };
+ args.init(4, arguments);
+ checkEqu(2244, args.getInt("intArg"));
+ checkEqu(3355, args.getInt("intArg2"));
+
+ ReProgramArgs args2("usage: example prog", "example -a");
+ args2.addInt("intArg", "an int arg", 'i', "arg2", 4711);
+ const char* arguments2[] = {
+ "example",
+ "--arg2",
+ NULL
+ };
+ try {
+ args2.init(2, arguments2);
+ error("exception expected: missing parameter");
+ } catch(ReOptionException e){
+ checkT(e.getMessage().indexOf("arg2") > 0);
+ }
+ }
+ void testString(){
+ ReProgramArgs args("usage: example prog", "example -a");
+ args.addString("stringArg", "a string arg", 's', "arg", false, "abc");
+ args.addString("stringArg2", "a string arg", 0, "arg2", true, "bcd");
+ args.addString("stringArg3", "a string arg", 0, "arg3", true, "def");
+ const char* arguments[] = {
+ "example",
+ "-s", "wow",
+ "--arg2=1 2 3",
+ "--arg3=",
+ NULL
+ };
+ args.init(5, arguments);
+ QByteArray buffer;
+ checkEqu("wow", args.getString("stringArg", buffer));
+ checkEqu("1 2 3", args.getString("stringArg2", buffer));
+ checkEqu("", args.getString("stringArg3", buffer));
+
+ ReProgramArgs args2("usage: example prog", "example -a");
+ args2.addString("stringArg", "a string arg", 'i', "arg2", false, "king");
+ const char* arguments2[] = {
+ "example",
+ "--arg2",
+ NULL
+ };
+ try {
+ args2.init(2, arguments2);
+ error("exception expected: missing parameter");
+ } catch(ReOptionException e){
+ checkT(e.getMessage().indexOf("arg2") > 0);
+ }
+ ReProgramArgs args3("usage: example prog", "example -a");
+ args3.addString("stringArg", "a string arg", 0, "arg", true, NULL);
+ args3.addString("stringArg2", "a string arg", 'i', "arg2", false, "king");
+ const char* arguments3[] = {
+ "example",
+ "--arg=",
+ "--arg2=",
+ NULL
+ };
+ try {
+ args3.init(3, arguments3);
+ error("exception expected: empty string is not allowed");
+ } catch(ReOptionException e){
+ checkT(e.getMessage().indexOf("arg2") > 0);
+ }
+ }
+ void testHelp(){
+ ReProgramArgs args("usage: example prog", "example -a");
+ args.addBool("boolArg", "a bool arg", 'b', "bool-arg", false);
+ args.addInt("intArg", "integer arg", 'i', "int-arg", 99);
+ args.addString("stringArg", "string argument", 's', "string-arg", true, "");
+ const char* arguments[] = { "example" };
+ QByteArrayList list;
+ args.help("dummy error", false, list);
+ QByteArray expected = "usage: example prog\n"
+ "\n"
+ "<options>:\n"
+ "-b or --bool-arg\n"
+ " a bool arg\n"
+ "-i<number> or --int-arg=<number> Default value: 99\n"
+ " integer arg\n"
+ "-s[<string>] or --string-arg=[<string>] Default value: \n"
+ " string argument\n"
+ "Example(s):\n"
+ "example -a\n"
+ "+++ dummy error\n";
+ checkEqu(expected, list.join('\n'));
+ }
+ virtual void run() {
+ try {
+ testHelp();
+ testString();
+ testInt();
+ testBool();
+ testBase();
+ } catch (ReOptionException e){
+ error(e.getMessage());
+ }
+ log("ready");
+ }
+};
+
+
+void testReProgArgs() {
+ TestReProgArgs test;
+}
+
unsigned int ReASItem::m_nextId = 1;
#define DEFINE_TABS(indent) \
- char tabs[32]; \
- memset(tabs, '\t', sizeof tabs); \
- tabs[(unsigned) indent < sizeof tabs ? indent : sizeof tabs - 1] = '\0'
+ char tabs[32]; \
+ memset(tabs, '\t', sizeof tabs); \
+ tabs[(unsigned) indent < sizeof tabs ? indent : sizeof tabs - 1] = '\0'
/**
* @brief Writes a map into a file.
for (it2 = sorted.begin(); it2 != sorted.end(); it2++) {
ReASVariant* value = map[*it2];
writer.format("%c'%s':%s", first ? '{' : ',', (*it2).constData(),
- value->toString().constData());
+ value->toString().constData());
first = false;
}
if (first)
* @param varList the values for the placeholders in the format.
*/
void ReASException::build(const ReSourcePosition* position, const char* format,
- va_list varList) {
+ va_list varList) {
char buffer[64000];
if (position != NULL) {
- m_message = position->toString().toUtf8();
+ m_message = I18N::s2b(position->toString());
m_message += ": ";
}
qvsnprintf(buffer, sizeof buffer, format, varList);
* @param ... the values for the placeholders in the format.
*/
ReASException::ReASException(const ReSourcePosition* position,
- const char* format, ...) :
- ReException("") {
+ const char* format, ...) :
+ ReException("") {
va_list ap;
va_start(ap, format);
build(position, format, ap);
* @brief Constructor.
*/
ReASException::ReASException() :
- ReException("") {
+ ReException("") {
}
/** @class ReASVariant ReASTree.hpp "expr/ReASTree.hpp"
* @brief Constructor.
*/
ReASVariant::ReASVariant() :
- m_variantType(VT_UNDEF),
- m_flags(VF_UNDEF),
- // m_value(),
- m_class(NULL) {
+ m_variantType(VT_UNDEF),
+ m_flags(VF_UNDEF),
+ // m_value(),
+ m_class(NULL) {
}
/**
* @brief Destructor.
* @param source the source to copy
*/
ReASVariant::ReASVariant(const ReASVariant& source) :
- m_variantType(source.m_variantType),
- m_flags(source.m_flags),
- // m_value
- m_class(source.m_class) {
+ m_variantType(source.m_variantType),
+ m_flags(source.m_flags),
+ // m_value
+ m_class(source.m_class) {
copyValue(source);
}
qreal ReASVariant::asFloat() const {
if (m_variantType != VT_FLOAT)
throw ReException("ReASVariant::asNumber: not a number: %d",
- m_variantType);
+ m_variantType);
return m_value.m_float;
}
/**
int ReASVariant::asInt() const {
if (m_variantType != VT_INTEGER)
throw ReException("ReASVariant::asInt: not an integer: %d",
- m_variantType);
+ m_variantType);
return m_value.m_int;
}
bool ReASVariant::asBool() const {
if (m_variantType != VT_BOOL)
throw ReException("ReASVariant::asBool: not a boolean: %d",
- m_variantType);
+ m_variantType);
return m_value.m_bool;
}
void* ReASVariant::asObject(const ReASClass** clazz) const {
if (m_variantType != VT_OBJECT)
throw ReException("ReASVariant::asObject: not an object: %d",
- m_variantType);
+ m_variantType);
if (clazz != NULL)
*clazz = m_class;
return m_value.m_object;
if (clazz != ReASString::m_instance) {
const QByteArray& name = clazz->name();
throw ReException("ReASVariant::asString: not a string: %s",
- name.constData());
+ name.constData());
}
return rc;
}
* @param type the type of the instance
*/
ReASItem::ReASItem(ReASItemType type) :
- m_id(m_nextId++),
- m_nodeType(type),
- m_flags(0),
- m_position(NULL) {
+ m_id(m_nextId++),
+ m_nodeType(type),
+ m_flags(0),
+ m_position(NULL) {
}
/**
* @brief Destructor.
* <code>false</code>: otherwise
*/
bool ReASItem::checkAsCalculable(const char* description,
- ReASClass* expectedClass, ReParser& parser) {
+ ReASClass* expectedClass, ReParser& parser) {
RE_UNUSED(expectedClass);
bool rc = true;
if (!check(parser))
ReASCalculable* expr = dynamic_cast<ReASCalculable*>(this);
if (expr == NULL)
rc = error(LOC_ITEM_AS_INT_1, parser, "%s not calculable: %s",
- description, nameOfItemType());
+ description, nameOfItemType());
else if (expr->clazz() != ReASInteger::m_instance)
rc = error(LOC_ITEM_AS_INT_2, parser,
- "%s: wrong type %s instead of integer", description,
- expr->clazz()->name().constData());
+ "%s: wrong type %s instead of integer", description,
+ expr->clazz()->name().constData());
}
return rc;
}
char buffer[1024];
int halfBufferSize = (sizeof buffer) / 2;
qsnprintf(buffer, halfBufferSize, "id: %d [%s]:", m_id,
- positionStr(buffer + halfBufferSize, halfBufferSize));
+ positionStr(buffer + halfBufferSize, halfBufferSize));
int length = strlen(buffer);
va_list ap;
va_start(ap, format);
rc = false;
if (dynamic_cast<ReASStatement*>(list) == NULL)
rc = list->error(LOC_ITEM_STATEM_LIST_1, parser,
- "not a statement: %s", list->nameOfItemType());
+ "not a statement: %s", list->nameOfItemType());
ReASNode1* node = dynamic_cast<ReASNode1*>(list);
if (node == NULL) {
list->error(LOC_ITEM_STATEM_LIST_1, parser, "not a node: %s",
- list->nameOfItemType());
+ list->nameOfItemType());
list = NULL;
} else {
list = node->child();
va_list varList;
va_start(varList, format);
parser.addMessage(ReParser::LT_ERROR, location, m_position, format,
- varList);
+ varList);
va_end(varList);
return false;
}
bool ReASItem::ensureError(ReParser& parser, const char* info) {
if (parser.errors() == 0)
error(LOC_ITEM_FORCE_ERROR_1, parser, "lost error (internal error): %s",
- info);
+ info);
return false;
}
* @brief Constructor.
*/
ReASCalculable::ReASCalculable() :
- m_class(NULL) {
+ m_class(NULL) {
}
/**
* @brief Returns the class of the node
*
*/
ReASConstant::ReASConstant() :
- ReASItem(AST_CONSTANT),
- m_value() {
+ ReASItem(AST_CONSTANT),
+ m_value() {
}
/**
void ReASConstant::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent, "const id: %d value: %s %s", m_id,
- m_value.toString().constData(), positionStr(buffer, sizeof buffer));
+ m_value.toString().constData(), positionStr(buffer, sizeof buffer));
}
/**
* @brief Constructor.
*/
ReASListConstant::ReASListConstant() :
- ReASNode1(AST_LIST_CONSTANT),
- ReASCalculable() {
+ ReASNode1(AST_LIST_CONSTANT),
+ ReASCalculable() {
m_value.setObject(ReASList::m_instance->newValueInstance(),
- ReASList::m_instance);
+ ReASList::m_instance);
}
/**
* @brief Returns the list.
*/
ReASListOfVariants* ReASListConstant::list() {
ReASListOfVariants* rc = static_cast<ReASListOfVariants*>(m_value.asObject(
- NULL));
+ NULL));
return rc;
}
void ReASListConstant::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent, "listConst id: %d %s", m_id,
- positionStr(buffer, sizeof buffer));
+ positionStr(buffer, sizeof buffer));
QByteArray sValue = m_value.toString(8092);
writer.writeIndented(indent + 1, sValue.constData());
* @brief ReASMapConstant::ReASMapConstant
*/
ReASMapConstant::ReASMapConstant() :
- ReASNode1(AST_MAP_CONSTANT),
- ReASCalculable(),
- m_value() {
+ ReASNode1(AST_MAP_CONSTANT),
+ ReASCalculable(),
+ m_value() {
m_value.setObject(new ReASMapOfVariants, ReASMap::m_instance);
}
void ReASMapConstant::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent, "mapConst id: %d %s", m_id,
- positionStr(buffer, sizeof buffer));
+ positionStr(buffer, sizeof buffer));
writer.indent(indent);
dumpMap(writer, *map(), true);
}
*/
ReASMapOfVariants* ReASMapConstant::map() {
ReASMapOfVariants* rc = static_cast<ReASMapOfVariants*>(m_value.asObject(
- NULL));
+ NULL));
return rc;
}
* @param attributes the attributes of the variable
*/
ReASNamedValue::ReASNamedValue(ReASClass* clazz, ReSymbolSpace* space,
- const QByteArray& name, int attributes) :
- ReASItem(AST_NAMED_VALUE),
- m_name(name),
- m_attributes(attributes),
- m_symbolSpace(space),
- m_variableNo(-1) {
+ const QByteArray& name, int attributes) :
+ ReASItem(AST_NAMED_VALUE),
+ m_name(name),
+ m_attributes(attributes),
+ m_symbolSpace(space),
+ m_variableNo(-1) {
m_class = clazz;
}
thread.valueToTop(m_symbolSpace, m_variableNo);
if (thread.tracing())
thread.vm()->traceWriter()->format("nVal %s=%.80s", m_name.constData(),
- thread.topOfValues().toString().constData());
+ thread.topOfValues().toString().constData());
}
/**
void ReASNamedValue::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent, "namedValue %s id: %d attr: 0x%x %s",
- m_name.constData(), m_id, m_attributes,
- positionStr(buffer, sizeof buffer));
+ m_name.constData(), m_id, m_attributes,
+ positionStr(buffer, sizeof buffer));
}
/**
* @param expression the expression to convert
*/
ReASConversion::ReASConversion(ReASItem* expression) :
- ReASNode1(AST_CONVERSION),
- m_conversion(C_UNDEF) {
+ ReASNode1(AST_CONVERSION),
+ m_conversion(C_UNDEF) {
m_child = expression;
m_position = expression->position();
}
}
if (thread.tracing())
thread.vm()->traceWriter()->format("(%s): %s",
- m_class->name().constData(), value.toString().constData());
+ m_class->name().constData(), value.toString().constData());
}
/**
* otherwise: the conversion type
*/
ReASConversion::Conversion ReASConversion::findConversion(ReASClass* from,
- ReASClass* to) {
+ ReASClass* to) {
Conversion rc = C_UNDEF;
if (from == ReASFloat::m_instance) {
if (to == ReASInteger::m_instance)
rc = true;
else
parser.error(LOC_CONV_CHECK_1,
- "invalid data type conversion: %s -> %s",
- from->name().constData(), m_class->name().constData());
+ "invalid data type conversion: %s -> %s",
+ from->name().constData(), m_class->name().constData());
}
return rc;
}
void ReASConversion::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent, "conversion %s id: %d expr: %d %s",
- m_class->name().constData(), m_id, m_child->id(),
- positionStr(buffer, sizeof buffer));
+ m_class->name().constData(), m_id, m_child->id(),
+ positionStr(buffer, sizeof buffer));
}
/**
* otherwise: a converter to the given type
*/
ReASConversion* ReASConversion::tryConversion(ReASClass* expected,
- ReASItem* expr, ReParser& parser, bool& isCorrect) {
+ ReASItem* expr, ReParser& parser, bool& isCorrect) {
ReASConversion* rc = NULL;
if (!expr->check(parser))
isCorrect = false;
Conversion type = findConversion(expr2->clazz(), expected);
if (type == C_UNDEF) {
isCorrect = parser.error(LOC_CONV_TRY_1,
- "invalid data type conversion: %s -> %s",
- expr2->clazz()->name().constData(),
- expected->name().constData());
+ "invalid data type conversion: %s -> %s",
+ expr2->clazz()->name().constData(),
+ expected->name().constData());
} else if (expr2->clazz() != expected) {
rc = new ReASConversion(expr);
rc->m_conversion = type;
* <code>m_child2</code>: the index expression
*/
ReASIndexedValue::ReASIndexedValue() :
- ReASNode2(AST_INDEXED_VALUE) {
+ ReASNode2(AST_INDEXED_VALUE) {
}
/**
//@ToDo: access to the lists element: assignment or to stack
if (thread.tracing())
thread.vm()->traceWriter()->format("[%d]: %.80s", ix,
- thread.topOfValues().toString().constData());
+ thread.topOfValues().toString().constData());
}
/**
// index value:
// tryConversion() calls m_child2->check()!
ReASConversion* converter = ReASConversion::tryConversion(
- ReASInteger::m_instance, m_child2, parser, rc);
+ ReASInteger::m_instance, m_child2, parser, rc);
if (rc && converter != NULL)
m_child = converter;
if (rc) {
void ReASIndexedValue::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent, "indexedValue id: %d index: %d parent: %d %s",
- m_id, m_child2->id(), m_child->id(),
- positionStr(buffer, sizeof buffer));
+ m_id, m_child2->id(), m_child->id(),
+ positionStr(buffer, sizeof buffer));
m_child2->dump(writer, indent + 1);
m_child->dump(writer, indent + 1);
}
* @brief Constructor.
*/
ReASVarDefinition::ReASVarDefinition() :
- ReASNode3(AST_VAR_DEFINITION),
- ReASStatement(),
- m_endOfScope(0) {
+ ReASNode3(AST_VAR_DEFINITION),
+ ReASStatement(),
+ m_endOfScope(0) {
m_flags |= NF_STATEMENT;
}
qsnprintf(endOfScope, sizeof endOfScope, "-%d:0", m_endOfScope);
char buffer[256];
writer.formatIndented(indent,
- "varDef %s %s id: %d namedValue: %d value: %d succ: %d %s%s",
- clazz() == NULL ? "?" : clazz()->name().constData(), name.constData(),
- m_id, m_child2 == NULL ? 0 : m_child2->id(),
- m_child3 == NULL ? 0 : m_child3->id(),
- m_child == NULL ? 0 : m_child->id(), positionStr(buffer, sizeof buffer),
- endOfScope);
+ "varDef %s %s id: %d namedValue: %d value: %d succ: %d %s%s",
+ clazz() == NULL ? "?" : clazz()->name().constData(), name.constData(),
+ m_id, m_child2 == NULL ? 0 : m_child2->id(),
+ m_child3 == NULL ? 0 : m_child3->id(),
+ m_child == NULL ? 0 : m_child->id(), positionStr(buffer, sizeof buffer),
+ endOfScope);
if (m_child2 != NULL)
m_child2->dump(writer, indent + 1);
if (m_child3 != NULL)
ReASCalculable* expr = dynamic_cast<ReASCalculable*>(m_child3);
if (expr == NULL)
rc = error(LOC_VARDEF_CHECK_1, parser,
- "Not a calculable expression: %s",
- m_child3->nameOfItemType());
+ "Not a calculable expression: %s",
+ m_child3->nameOfItemType());
else if (!typeCheck(var->clazz(), expr->clazz()))
rc = error(LOC_VARDEF_CHECK_2, parser,
- "data types are not compatible: %s/%s",
- var->clazz()->name().constData(),
- expr->clazz() == NULL ?
- "?" : expr->clazz()->name().constData());
+ "data types are not compatible: %s/%s",
+ var->clazz()->name().constData(),
+ expr->clazz() == NULL ?
+ "?" : expr->clazz()->name().constData());
}
}
return rc;
expr->calc(thread);
ReASVariant& value = thread.popValue();
ReASVariant& destination = thread.valueOfVariable(var->m_symbolSpace,
- var->m_variableNo);
+ var->m_variableNo);
if (thread.tracing())
thread.vm()->traceWriter()->format("%s = %.80s [%.80s]",
- var->m_name.constData(), value.toString().constData(),
- destination.toString().constData());
+ var->m_name.constData(), value.toString().constData(),
+ destination.toString().constData());
destination.copyValue(value);
}
return 0;
* @brief Constructor.
*/
ReASExprStatement::ReASExprStatement() :
- ReASNode2(AST_EXPR_STATEMENT),
- ReASStatement() {
+ ReASNode2(AST_EXPR_STATEMENT),
+ ReASStatement() {
m_flags |= NF_STATEMENT;
}
ReASVariant& value = thread.popValue();
if (thread.tracing())
thread.vm()->traceWriter()->format("expr: %s",
- value.toString().constData());
+ value.toString().constData());
value.destroyValue();
return 0;
}
if (m_id == 40)
m_id = 40;
writer.formatIndented(indent, "Expr id: %d expr: %d succ: %d %s", m_id,
- m_child2 == NULL ? 0 : m_child2->id(),
- m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ m_child2 == NULL ? 0 : m_child2->id(),
+ m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
if (m_child2 != NULL)
m_child2->dump(writer, indent + 1);
}
* @param type
*/
ReASNode1::ReASNode1(ReASItemType type) :
- ReASItem(type),
- m_child(NULL) {
+ ReASItem(type),
+ m_child(NULL) {
}
/**
* @param statements the chain of statements to dump
*/
void ReASNode1::dumpStatements(ReWriter& writer, int indent,
- ReASItem* statements) {
+ ReASItem* statements) {
ReASNode1* chain = dynamic_cast<ReASNode1*>(statements);
while (chain != NULL) {
chain->dump(writer, indent);
* @param type
*/
ReASNode2::ReASNode2(ReASItemType type) :
- ReASNode1(type),
- m_child2(NULL) {
+ ReASNode1(type),
+ m_child2(NULL) {
}
/**
* @param type
*/
ReASNode3::ReASNode3(ReASItemType type) :
- ReASNode2(type),
- m_child3(NULL) {
+ ReASNode2(type),
+ m_child3(NULL) {
}
/**
* @param type
*/
ReASNode4::ReASNode4(ReASItemType type) :
- ReASNode3(type),
- m_child4(NULL) {
+ ReASNode3(type),
+ m_child4(NULL) {
}
/**
* @param type
*/
ReASNode5::ReASNode5(ReASItemType type) :
- ReASNode4(type),
- m_child5(NULL) {
+ ReASNode4(type),
+ m_child5(NULL) {
}
/**
* @param type
*/
ReASNode6::ReASNode6(ReASItemType type) :
- ReASNode5(type),
- m_child6(NULL) {
+ ReASNode5(type),
+ m_child6(NULL) {
}
/**
* @param type the node type
*/
ReASUnaryOp::ReASUnaryOp(UnaryOp op, ReASItemType type) :
- ReASNode1(type),
- m_operator(op) {
+ ReASNode1(type),
+ m_operator(op) {
}
/**
case UOP_INC:
default:
error(thread.logger(), LOC_UNOP_CALC_1, "unknown operator: %d",
- m_operator);
+ m_operator);
break;
}
if (thread.tracing())
thread.vm()->traceWriter()->format("unary %s: %s", nameOfOp(m_operator),
- value.toString().constData());
+ value.toString().constData());
}
/**
switch (m_operator) {
case UOP_PLUS:
if (clazz != ReASInteger::m_instance
- && clazz != ReASFloat::m_instance)
+ && clazz != ReASFloat::m_instance)
rc = error(LOC_UNARY_CHECK_1, parser,
- "wrong data type for unary operator '+': %s",
- clazz->name().constData());
+ "wrong data type for unary operator '+': %s",
+ clazz->name().constData());
break;
case UOP_MINUS_INT:
if (clazz != ReASFloat::m_instance)
m_operator = UOP_MINUS_FLOAT;
else if (clazz != ReASInteger::m_instance)
rc = error(LOC_UNARY_CHECK_2, parser,
- "wrong data type for unary operator '-': %s",
- clazz->name().constData());
+ "wrong data type for unary operator '-': %s",
+ clazz->name().constData());
break;
case UOP_NOT_BOOL:
if (clazz != ReASBoolean::m_instance)
rc = error(LOC_UNARY_CHECK_3, parser,
- "wrong data type for unary operator '!': %s",
- clazz->name().constData());
+ "wrong data type for unary operator '!': %s",
+ clazz->name().constData());
break;
case UOP_NOT_INT:
if (clazz != ReASInteger::m_instance)
rc = error(LOC_UNARY_CHECK_4, parser,
- "wrong data type for unary operator '!': %s",
- clazz->name().constData());
+ "wrong data type for unary operator '!': %s",
+ clazz->name().constData());
break;
case UOP_DEC:
break;
break;
default:
throw ReASException(position(), "unknown operator: %d",
- m_operator);
+ m_operator);
break;
}
}
void ReASUnaryOp::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent, "Unary %d op: %s (%d) expr: %d %s", m_id,
- nameOfOp(m_operator), m_operator, m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ nameOfOp(m_operator), m_operator, m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
if (m_child != NULL)
m_child->dump(writer, indent + 1);
}
*/
ReASIf::ReASIf() :
- ReASNode4(AST_IF) {
+ ReASNode4(AST_IF) {
m_flags |= NF_STATEMENT;
}
if (m_child2 == NULL)
rc = ensureError(parser, "'if' misses condition");
else if (m_child2->checkAsCalculable("condition", ReASBoolean::m_instance,
- parser))
+ parser))
rc = false;
if (m_child3 != NULL && !checkStatementList(m_child3, parser))
rc = false;
bool condition = calcAsBoolean(m_child2, thread);
if (thread.tracing())
thread.vm()->traceWriter()->format("if %s",
- condition ? "true" : "false");
+ condition ? "true" : "false");
ReASItem* list = condition ? m_child3 : m_child4;
if (list != NULL) {
void ReASIf::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent,
- "If id: %d condition: %d then: %d else: %d succ: %d%s", m_id,
- m_child2 == NULL ? 0 : m_child2->id(),
- m_child3 == NULL ? 0 : m_child3->id(),
- m_child4 == NULL ? 0 : m_child4->id(),
- m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ "If id: %d condition: %d then: %d else: %d succ: %d%s", m_id,
+ m_child2 == NULL ? 0 : m_child2->id(),
+ m_child3 == NULL ? 0 : m_child3->id(),
+ m_child4 == NULL ? 0 : m_child4->id(),
+ m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
m_child2->dump(writer, indent + 1);
if (m_child3 != NULL)
m_child3->dump(writer, indent + 1);
* @param variable NULL or the iterator variable
*/
ReASForIterated::ReASForIterated(ReASVarDefinition* variable) :
- ReASNode4(AST_ITERATED_FOR),
- ReASStatement() {
+ ReASNode4(AST_ITERATED_FOR),
+ ReASStatement() {
m_flags |= NF_STATEMENT;
m_child2 = variable;
}
void ReASForIterated::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent,
- "forIt id: %d var: %d set: %d body: %d succ: %d %s", m_id,
- m_child3 == NULL ? 0 : m_child3->id(),
- m_child4 == NULL ? 0 : m_child4->id(),
- m_child2 == NULL ? 0 : m_child2->id(),
- m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ "forIt id: %d var: %d set: %d body: %d succ: %d %s", m_id,
+ m_child3 == NULL ? 0 : m_child3->id(),
+ m_child4 == NULL ? 0 : m_child4->id(),
+ m_child2 == NULL ? 0 : m_child2->id(),
+ m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
if (m_child3 != NULL)
m_child3->dump(writer, indent + 1);
if (m_child4 != NULL)
* @param variable NULL or the counter variable
*/
ReASForCounted::ReASForCounted(ReASVarDefinition* variable) :
- ReASNode6(AST_ITERATED_FOR),
- ReASStatement() {
+ ReASNode6(AST_ITERATED_FOR),
+ ReASStatement() {
m_flags |= NF_STATEMENT;
m_child3 = variable;
}
rc = false;
if (var == NULL)
rc = error(LOC_FORC_CHECK_1, parser, "not a variable: %s",
- m_child3->nameOfItemType());
+ m_child3->nameOfItemType());
}
if (m_child4 != NULL
- && !m_child4->checkAsCalculable("start value", ReASInteger::m_instance,
- parser))
+ && !m_child4->checkAsCalculable("start value", ReASInteger::m_instance,
+ parser))
rc = false;
if (m_child5 != NULL
- && !m_child5->checkAsCalculable("end value", ReASInteger::m_instance,
- parser))
+ && !m_child5->checkAsCalculable("end value", ReASInteger::m_instance,
+ parser))
rc = false;
if (m_child6 != NULL
- && !m_child6->checkAsCalculable("step value", ReASInteger::m_instance,
- parser))
+ && !m_child6->checkAsCalculable("step value", ReASInteger::m_instance,
+ parser))
rc = false;
if (m_child2 != NULL && !checkStatementList(m_child2, parser))
rc = false;
ReASStatement* body = dynamic_cast<ReASStatement*>(m_child2);
if (body == NULL)
throw ReASException(
- m_child2 == NULL ? m_position : m_child2->position(),
- "forc statement: body is not a statement");
+ m_child2 == NULL ? m_position : m_child2->position(),
+ "forc statement: body is not a statement");
int start = m_child4 == NULL ? 1 : calcAsInteger(m_child4, thread);
int end = m_child5 == NULL ? 0 : calcAsInteger(m_child5, thread);
int step = m_child6 == NULL ? 1 : calcAsInteger(m_child6, thread);
ReASNamedValue* var =
- m_child3 == NULL ? NULL : dynamic_cast<ReASNamedValue*>(m_child3);
+ m_child3 == NULL ? NULL : dynamic_cast<ReASNamedValue*>(m_child3);
if (thread.tracing())
thread.vm()->traceWriter()->format("for %s from %d to %d step %d",
- var == NULL ? "?" : var->name().constData(), start, end, step);
+ var == NULL ? "?" : var->name().constData(), start, end, step);
for (int ii = start; ii <= end; ii += step) {
//@ToDo: assign to the variable
void ReASForCounted::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent,
- "forC id: %d var: %d from: %d to: %d step: %d body: %d succ: %d %s",
- m_id, m_child3 == NULL ? 0 : m_child3->id(),
- m_child4 == NULL ? 0 : m_child4->id(),
- m_child5 == NULL ? 0 : m_child5->id(),
- m_child6 == NULL ? 0 : m_child6->id(),
- m_child2 == NULL ? 0 : m_child2->id(),
- m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ "forC id: %d var: %d from: %d to: %d step: %d body: %d succ: %d %s",
+ m_id, m_child3 == NULL ? 0 : m_child3->id(),
+ m_child4 == NULL ? 0 : m_child4->id(),
+ m_child5 == NULL ? 0 : m_child5->id(),
+ m_child6 == NULL ? 0 : m_child6->id(),
+ m_child2 == NULL ? 0 : m_child2->id(),
+ m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
if (m_child3 != NULL)
m_child3->dump(writer, indent + 1);
if (m_child4 != NULL)
*/
ReASWhile::ReASWhile() :
- ReASNode3(AST_WHILE),
- ReASStatement() {
+ ReASNode3(AST_WHILE),
+ ReASStatement() {
m_flags |= NF_STATEMENT;
}
ensureError(parser, "missing condition for 'while''");
else
rc = m_child2->checkAsCalculable("condition", ReASBoolean::m_instance,
- parser);
+ parser);
if (m_child3 != NULL && !checkStatementList(m_child3, parser))
rc = false;
return rc;
char buffer[256];
writer.formatIndented(indent,
- "while id: %d condition: %d body: %d succ: %d %s", m_id,
- m_child2 == NULL ? 0 : m_child2->id(),
- m_child3 == NULL ? 0 : m_child3->id(),
- m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ "while id: %d condition: %d body: %d succ: %d %s", m_id,
+ m_child2 == NULL ? 0 : m_child2->id(),
+ m_child3 == NULL ? 0 : m_child3->id(),
+ m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
if (m_child2 != NULL)
m_child2->dump(writer, indent + 1);
dumpStatements(writer, indent + 1, m_child3);
*/
ReASRepeat::ReASRepeat() :
- ReASNode3(AST_REPEAT),
- ReASStatement() {
+ ReASNode3(AST_REPEAT),
+ ReASStatement() {
m_flags |= NF_STATEMENT;
}
if (m_child2 == NULL)
ensureError(parser, "missing condition for 'repeat''");
else if (!m_child2->checkAsCalculable("condition", ReASBoolean::m_instance,
- parser))
+ parser))
rc = false;
return rc;
}
void ReASRepeat::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent,
- "repeat id: %d condition: %d body: %d succ: %d %s", m_id,
- m_child2 == NULL ? 0 : m_child2->id(),
- m_child3 == NULL ? 0 : m_child3->id(),
- m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ "repeat id: %d condition: %d body: %d succ: %d %s", m_id,
+ m_child2 == NULL ? 0 : m_child2->id(),
+ m_child3 == NULL ? 0 : m_child3->id(),
+ m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
if (m_child2 != NULL)
m_child2->dump(writer, indent + 1);
dumpStatements(writer, indent + 1, m_child3);
* @brief Constructor.
*/
ReASClass::ReASClass(const QByteArray& name, ReASTree& tree) :
- m_name(name),
- m_symbols(NULL),
- m_superClass(NULL),
- m_tree(tree) {
+ m_name(name),
+ m_symbols(NULL),
+ m_superClass(NULL),
+ m_tree(tree) {
}
/**
*/
void ReASClass::dump(ReWriter& writer, int indent) {
writer.formatIndented(indent, "class %s super: %s", m_name.constData(),
- m_superClass == NULL ? "<none>" : m_superClass->name().constData());
+ m_superClass == NULL ? "<none>" : m_superClass->name().constData());
m_symbols->dump(writer, indent);
}
* @brief Constructor.
*/
ReASTree::ReASTree() :
- m_global(NULL),
- m_modules(),
- m_symbolSpaces(),
- m_currentSpace(NULL),
- m_store(128 * 1024) {
+ m_global(NULL),
+ m_modules(),
+ m_symbolSpaces(),
+ m_currentSpace(NULL),
+ m_store(128 * 1024) {
init();
}
if (!rc) {
// freed in ~ReASTree()
ReSymbolSpace* space = new ReSymbolSpace(ReSymbolSpace::SST_MODULE,
- name, m_global);
+ name, m_global);
m_symbolSpaceHeap[name] = space;
m_modules[name] = space;
m_symbolSpaces.append(space);
ReSymbolSpace* top = m_symbolSpaces.at(m_symbolSpaces.size() - 1);
if (top->name() != name)
throw ReException("ReASTree::finishModule(): module is not top: %s",
- name);
+ name);
else {
m_symbolSpaces.removeLast();
// "global" is always the bottom:
* @return the new symbol space
*/
ReSymbolSpace* ReASTree::startClassOrMethod(const QByteArray& name,
- ReSymbolSpace::SymbolSpaceType type) {
+ ReSymbolSpace::SymbolSpaceType type) {
// the stack m_modules is never empty because of "global" and modules.
ReSymbolSpace* parent = m_symbolSpaces[m_symbolSpaces.size() - 1];
QByteArray fullName = parent->name() + "." + name;
ReSymbolSpace* top = m_symbolSpaces.at(m_symbolSpaces.size() - 1);
if (!top->name().endsWith("." + name))
throw ReException("ReASTree::finishModule(): class is not top: %s",
- name.constData());
+ name.constData());
else {
m_symbolSpaces.removeLast();
// "global" is the bottom always!
*/
ReASMethodCall::ReASMethodCall(const QByteArray& name, ReASItem* parent) :
- ReASNode3(AST_METHOD_CALL),
- ReASStatement(),
- m_name(name),
- m_method(NULL) {
+ ReASNode3(AST_METHOD_CALL),
+ ReASStatement(),
+ m_name(name),
+ m_method(NULL) {
m_flags |= NF_STATEMENT;
m_child3 = parent;
}
int argCount = 0;
ReASMethod* method = m_method;
ReASVarDefinition* params =
- dynamic_cast<ReASVarDefinition*>(method->child2());
+ dynamic_cast<ReASVarDefinition*>(method->child2());
while (args != NULL && params != NULL) {
argCount++;
ReASCalculable* argExpr = dynamic_cast<ReASCalculable*>(args->child2());
if (argExpr == NULL)
rc = error(LOC_METHOD_CALL_CHECK_1, parser,
- "argument %d misses expr", argCount);
+ "argument %d misses expr", argCount);
else {
ReASNamedValue* var;
ReASItem* param = params->child2();
if (param == NULL
- || (var = dynamic_cast<ReASNamedValue*>(param)) == NULL)
+ || (var = dynamic_cast<ReASNamedValue*>(param)) == NULL)
rc = error(LOC_MEHTOD_CALL_CHECK_2, parser,
- "parameter %d misses named value: %s", argCount,
- param == NULL ? "<null>" : param->nameOfItemType());
+ "parameter %d misses named value: %s", argCount,
+ param == NULL ? "<null>" : param->nameOfItemType());
else {
// tryConversion() calls args->args->child2()->check()!
ReASConversion* converter = ReASConversion::tryConversion(
- var->clazz(), args->child2(), parser, rc);
+ var->clazz(), args->child2(), parser, rc);
if (rc && converter != NULL)
args->setChild2(converter);
}
if (args != NULL && params == NULL)
rc = error(LOC_MEHTOD_CALL_CHECK_3, parser,
- "too many arguments: %d are enough", argCount);
+ "too many arguments: %d are enough", argCount);
else if (args == NULL && params != NULL && params->child3() != NULL)
rc = error(LOC_MEHTOD_CALL_CHECK_4, parser,
- "too few arguments: %d are not enough", argCount);
+ "too few arguments: %d are not enough", argCount);
return rc;
}
void ReASMethodCall::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent,
- "call %s Id: %d args: %d parent: %d succ: %d %s", m_name.constData(),
- m_id, m_child2 == NULL ? 0 : m_child2->id(),
- m_child3 == NULL ? 0 : m_child3->id(),
- m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ "call %s Id: %d args: %d parent: %d succ: %d %s", m_name.constData(),
+ m_id, m_child2 == NULL ? 0 : m_child2->id(),
+ m_child3 == NULL ? 0 : m_child3->id(),
+ m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
if (m_child2 != NULL)
m_child2->dump(writer, indent + 1);
if (m_child3 != NULL)
* @brief Constructor.
*/
ReASBinaryOp::ReASBinaryOp() :
- ReASNode2(AST_BINARY_OP),
- m_operator(BOP_UNDEF) {
+ ReASNode2(AST_BINARY_OP),
+ m_operator(BOP_UNDEF) {
}
/**
ReASCalculable* op2 = dynamic_cast<ReASCalculable*>(m_child2);
if (op1 == NULL || op2 == NULL)
error(thread.logger(), LOC_BINOP_CALC_1, "operand is null: %d / %d",
- m_child == NULL ? 0 : m_child->id(),
- m_child2 == NULL ? 0 : m_child2->id());
+ m_child == NULL ? 0 : m_child->id(),
+ m_child2 == NULL ? 0 : m_child2->id());
else {
op1->calc(thread);
op2->calc(thread);
//if (val1.getClass() == ReASString::m_instance)
default:
error(thread.logger(), LOC_BINOP_CALC_2,
- "invalid type for '+': %s", val1.nameOfType());
+ "invalid type for '+': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_3,
- "invalid type for '-': %s", val1.nameOfType());
+ "invalid type for '-': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_4,
- "invalid type for '*': %s", val1.nameOfType());
+ "invalid type for '*': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_5,
- "invalid type for '/': %s", val1.nameOfType());
+ "invalid type for '/': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_6,
- "invalid type for '%': %s", val1.nameOfType());
+ "invalid type for '%': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_7,
- "invalid type for '**': %s", val1.nameOfType());
+ "invalid type for '**': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_8,
- "invalid type for '||': %s", val1.nameOfType());
+ "invalid type for '||': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_9,
- "invalid type for '&&': %s", val1.nameOfType());
+ "invalid type for '&&': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_9,
- "invalid type for '^^': %s", val1.nameOfType());
+ "invalid type for '^^': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_10,
- "invalid type for '|': %s", val1.nameOfType());
+ "invalid type for '|': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_11,
- "invalid type for '&': %s", val1.nameOfType());
+ "invalid type for '&': %s", val1.nameOfType());
break;
}
break;
break;
default:
error(thread.logger(), LOC_BINOP_CALC_12,
- "invalid type for '^': %s", val1.nameOfType());
+ "invalid type for '^': %s", val1.nameOfType());
break;
}
break;
const QByteArray& opName = nameOfOp(m_operator);
char buffer[256];
writer.formatIndented(indent,
- "BinOp id: %d op: %s (%d) left: %d right: %d %s", m_id,
- opName.constData(), m_operator, m_child == NULL ? 0 : m_child->id(),
- m_child2 == NULL ? 0 : m_child2->id(),
- positionStr(buffer, sizeof buffer));
+ "BinOp id: %d op: %s (%d) left: %d right: %d %s", m_id,
+ opName.constData(), m_operator, m_child == NULL ? 0 : m_child->id(),
+ m_child2 == NULL ? 0 : m_child2->id(),
+ positionStr(buffer, sizeof buffer));
if (indent < 32 && m_child != NULL)
m_child->dump(writer, indent + 1);
if (indent < 32 && m_child2 != NULL)
ReASCalculable* expr = dynamic_cast<ReASCalculable*>(m_child2);
if (expr == NULL)
error(thread.logger(), LOC_BINOP_1, "not a calculable: id: %d",
- m_child2 == NULL ? 0 : m_child2->id());
+ m_child2 == NULL ? 0 : m_child2->id());
else {
ReASVariant& value = thread.popValue();
switch (m_operator) {
* @param tree the abstract syntax tree
*/
ReASMethod::ReASMethod(const QByteArray& name, ReASTree& tree) :
- ReASNode2(AST_METHOD),
- m_name(name),
- m_resultType(NULL),
- m_symbols(NULL),
- m_sibling(NULL),
- m_tree(tree),
- firstParamWithDefault(-1) {
+ ReASNode2(AST_METHOD),
+ m_name(name),
+ m_resultType(NULL),
+ m_symbols(NULL),
+ m_sibling(NULL),
+ m_tree(tree),
+ firstParamWithDefault(-1) {
}
/**
char buffer[256];
writer.indent(indent);
writer.format("Method %s %s(",
- m_resultType == NULL ? "<NoneType>" : m_resultType->name().constData(),
- m_name.constData());
+ m_resultType == NULL ? "<NoneType>" : m_resultType->name().constData(),
+ m_name.constData());
ReSymbolSpace* parent = m_symbols->parent();
writer.formatLine(") id: %d parent: %s args: %d body: %d %s", m_id,
- parent == NULL ? "" : parent->name().constData(),
- m_child2 == NULL ? 0 : m_child2->id(), m_child->id(),
- positionStr(buffer, sizeof buffer));
+ parent == NULL ? "" : parent->name().constData(),
+ m_child2 == NULL ? 0 : m_child2->id(), m_child->id(),
+ positionStr(buffer, sizeof buffer));
if (m_child2 != NULL)
m_child2->dump(writer, indent + 1);
dumpStatements(writer, indent + 1, m_child);
bool rc = true;
ReASExprStatement* args = dynamic_cast<ReASExprStatement*>(m_child2);
ReASExprStatement* otherArgs =
- dynamic_cast<ReASExprStatement*>(other.child2());
+ dynamic_cast<ReASExprStatement*>(other.child2());
while (rc && (args != NULL || otherArgs != NULL)) {
if (args == NULL || otherArgs == NULL)
rc = false;
else {
ReASVarDefinition* def = dynamic_cast<ReASVarDefinition*>(args
- ->child2());
+ ->child2());
ReASVarDefinition* defOther =
- dynamic_cast<ReASVarDefinition*>(otherArgs->child2());
+ dynamic_cast<ReASVarDefinition*>(otherArgs->child2());
if (def->clazz() != defOther->clazz())
rc = false;
}
* @param name name of the field
*/
ReASField::ReASField(const QByteArray& name) :
- ReASNode1(AST_FIELD),
- m_name(name) {
+ ReASNode1(AST_FIELD),
+ m_name(name) {
}
/**
void ReASField::dump(ReWriter& writer, int indent) {
char buffer[256];
writer.formatIndented(indent, "field %s id: %d parent: %d succ: %s",
- m_name.constData(), m_id, m_child == NULL ? 0 : m_child->id(),
- positionStr(buffer, sizeof buffer));
+ m_name.constData(), m_id, m_child == NULL ? 0 : m_child->id(),
+ positionStr(buffer, sizeof buffer));
m_child->dump(writer, indent + 1);
}
const char* format, ...) :
ReException("") {
char buffer[64000];
- m_message = position.toString().toUtf8();
+ m_message = I18N::s2b(position.toString());
va_list ap;
va_start(ap, format);
qvsnprintf(buffer, sizeof buffer, format, ap);
else if (!property->isValid(value, &error))
m_logger->logv(LOG_ERROR, LOC_CHANGE_VALUE_2,
"invalid value for %s: %s\n+++ %s", name,
- value.toUtf8().constData(), error.toUtf8().constData());
+ I18N::s2b(value).constData(), I18N::s2b(error).constData());
else
property->m_value = value;
}
QFile file(m_fileSettings);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
m_logger->logv(LOG_ERROR, LOC_READ_SETTINGS_1, "cannot open (%d): ",
- errno, m_fileSettings.toUtf8().constData());
+ errno, I18N::s2b(m_fileSettings).constData());
else {
QTextStream input(&file);
int lineNo = 0;
if (ix < 0)
m_logger->logv(LOG_ERROR, LOC_READ_SETTINGS_2,
"missing '=': %s-%d: %s",
- m_fileSettings.toUtf8().constData(), lineNo,
- line.mid(0, 20).toUtf8().constData());
+ I18N::s2b(m_fileSettings).constData(), lineNo,
+ I18N::s2b(line.mid(0, 20)).constData());
else if (ix == 0 || (ix == 1 && line.at(0) == '!'))
m_logger->logv(LOG_ERROR, LOC_READ_SETTINGS_3,
"line starts with '=': %s-%d: %s",
- m_fileSettings.toUtf8().constData(), lineNo,
- line.mid(0, 20).toUtf8().constData());
+ I18N::s2b(m_fileSettings).constData(), lineNo,
+ I18N::s2b(line.mid(0, 20)).constData());
else {
QByteArray name;
QString value;
if (line.at(ix - 1) == '!') {
- name = line.left(ix - 1).toUtf8();
+ name = I18N::s2b(line.left(ix - 1));
value = line.mid(ix + 1);
value.replace("\\\\", "\01").replace("\\n", "\n").replace(
"\\r", "\r").replace('\01', '\\');
} else {
- name = line.left(ix).toUtf8();
+ name = I18N::s2b(line.left(ix));
value = line.mid(ix + 1);
}
ReProperty* property = m_settings.value(name, NULL);
QFile file(m_fileSettings);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
m_logger->logv(LOG_ERROR, LOC_WRITE_SETTINGS_1, "cannot open (%d): ",
- errno, m_fileSettings.toUtf8().constData());
+ errno, I18N::s2b(m_fileSettings).constData());
else {
QTextStream out(&file);
QMap<QByteArray, ReProperty*>::const_iterator it;
*/
bool ReStateStorage::initForRead() {
if (m_fp == NULL)
- if ((m_fp = fopen(m_filename.toUtf8().constData(), "rb")) == NULL) {
+ if ((m_fp = fopen(I18N::s2b(m_filename).constData(), "rb")) == NULL) {
if (m_logger != NULL)
m_logger->logv(LOG_ERROR, LOC_INIT_FOR_READ_1,
- "cannot open %s: %d", m_filename.toUtf8().constData(),
+ "cannot open %s: %d", I18N::s2b(m_filename).constData(),
errno);
}
if (m_fp != NULL && m_stream == NULL) {
int ixAssignment = line.indexOf('=');
if (ixAssignment > 0) {
value = line.mid(ixAssignment + 1);
- QByteArray key = line.left(ixAssignment).toUtf8();
+ QByteArray key = I18N::s2b(line.left(ixAssignment));
m_map.insert(key, value);
}
}
*/
bool ReStateStorage::initForWrite() {
if (m_fp == NULL)
- m_fp = fopen(m_filename.toUtf8().constData(), "wb");
+ m_fp = fopen(I18N::s2b(m_filename).constData(), "wb");
if (m_fp == NULL) {
if (m_logger != NULL)
m_logger->logv(LOG_ERROR, LOC_INIT_FOR_WRITE_1,
- "cannot open %s: %d", m_filename.toUtf8().constData(), errno);
+ "cannot open %s: %d", I18N::s2b(m_filename).constData(), errno);
} else
m_stream = new QTextStream(m_fp, QIODevice::ReadWrite);
return m_stream != NULL;
* @return an instance of <code>ReTCPPeer</code>
*/
ReTCPPeer* ReTCPPeer::createPeer(ReConfigurator& configurator, QThread* thread,
- ReTerminator* terminator, ReLogger* logger) {
+ ReTerminator* terminator, ReLogger* logger) {
return new ReTCPPeer(configurator, thread, terminator, logger);
}
* @param logger logger. If Null the global logger will be taken (not thread safe!)
*/
ReTCPPeer::ReTCPPeer(ReConfigurator& configurator, QThread* thread,
- ReTerminator* terminator, bool isServer, ReLogger* logger) :
- m_socket(NULL),
- m_logger(logger == NULL ? ReLogger::globalLogger() : logger),
- m_thread(thread),
- m_random(),
- m_timeout(isServer ? 0 : configurator.asInt("connection.timeout", 60)),
- m_terminator(terminator),
- m_configurator(configurator),
- m_isServer(isServer),
- m_dataLocker(QMutex::NonRecursive),
- m_waitForData() {
+ ReTerminator* terminator, bool isServer, ReLogger* logger) :
+ m_socket(NULL),
+ m_logger(logger == NULL ? ReLogger::globalLogger() : logger),
+ m_thread(thread),
+ m_random(),
+ m_timeout(isServer ? 0 : configurator.asInt("connection.timeout", 60)),
+ m_terminator(terminator),
+ m_configurator(configurator),
+ m_isServer(isServer),
+ m_dataLocker(QMutex::NonRecursive),
+ m_waitForData() {
// Simulate a true random with time, and addresses from stack and code segment:
m_random.setSeed(
- time(NULL) + ((int64_t) this << 8) + ((int64_t) &s_dummy << 16)
- + ((int64_t) &createPeer << 24));
+ time(NULL) + ((int64_t) this << 8) + ((int64_t) &s_dummy << 16)
+ + ((int64_t) &createPeer << 24));
}
/**
QByteArray header;
QByteArray data2 = ReStringUtil::toCString(data.constData(), 20);
m_logger->logv(LOG_INFO, LOC_SEND_1, "send: flags: %x %s %s (%d)", flags,
- command, data2.constData(), data.length());
+ command, data2.constData(), data.length());
header.reserve(16);
header.append((char) flags);
if (flags & FLAG_ENCRYPT) {
m_thread->msleep(1);
if (++count % 20 == 0) {
if (m_terminator == NULL || m_terminator->isStopped()
- || time(NULL) > endTime)
+ || time(NULL) > endTime)
break;
}
}
}
if (m_logger->isActive(LOG_DEBUG))
m_logger->logv(LOG_DEBUG, LOC_SEND_1, "send %s: %s len=%d loops=%d %s",
- m_address.constData(), command, data.length(), count,
- ReStringUtil::hexDump((const void*) data.constData(), 16, 16)
- .constData());
+ m_address.constData(), command, data.length(), count,
+ ReStringUtil::hexDump((const void*) data.constData(), 16, 16)
+ .constData());
return rc;
}
if (++loops % divider == 0 && !m_isServer) {
if (time(NULL) > maxTime) {
m_logger->logv(LOG_ERROR, LOC_READ_BYTES_1,
- "receive: timeout (%d)", m_timeout);
+ "receive: timeout (%d)", m_timeout);
success = false;
break;
}
}
available = socket->bytesAvailable();
m_logger->logv(LOG_DEBUG, LOC_READ_BYTES_4,
- "readBytes(): available: %ld/%ld", available, bytes);
+ "readBytes(): available: %ld/%ld", available, bytes);
QByteArray rc;
if (success) {
rc = socket->read(bytes);
if (rc.length() != bytes) {
m_logger->logv(LOG_ERROR, LOC_READ_BYTES_3,
- "receive: too few bytes: %d of %d", rc.length(), bytes);
+ "receive: too few bytes: %d of %d", rc.length(), bytes);
}
}
return rc;
headerSize += 4;
if (headerSize != minHeaderSize) {
QByteArray restHeader = readBytes(headerSize - minHeaderSize,
- maxTime, loops);
+ maxTime, loops);
if (restHeader.length() == 0)
header.clear();
else
* false: error occurred
*/
bool ReTCPPeer::sendAndReceive(uint8_t flags, char command[4], QByteArray* data,
- QByteArray& answer, QByteArray& answerData) {
+ QByteArray& answer, QByteArray& answerData) {
answer.clear();
answerData.clear();
bool rc = send(flags, command, data == NULL ? QByteArray("") : *data);
*/
void ReTCPPeer::handleError(QTcpSocket::SocketError socketError) {
m_logger->logv(LOG_ERROR, LOC_HANDLE_ERROR_1, "Network error %d",
- socketError);
+ socketError);
}
/**
if (m_socket == NULL)
rc = "<not connected>";
else
- rc = m_socket->peerAddress().toString().toUtf8();
+ rc = m_socket->peerAddress().toString().toLatin1();
return rc;
}
ErrorCode rc2 = m_host.makeDir(hostName);
if (rc2 != EC_SUCCESS){
m_logger2->logv(LOG_ERROR, LOC_MAKE_DIR_1, "cannot create hosted directory %s: %s",
- hostName.toUtf8().constData(),
- errorMessage(rc2).toUtf8().constData());
+ I18N::s2b(hostName).constData(),
+ I18N::s2b(errorMessage(rc2)).constData());
rc = EC_REMOTE_MKDIR;
} else {
m_list.append(ReFileMetaData(node, now, now, m_osPermissions.m_user,
const ReFileMetaData* entry = find(node);
if (entry == NULL)
rc = ! m_logger->logv(LOG_ERROR, LOC_REMOVE_ENTRY_1, "cannot remove file %s: not found",
- node.toUtf8().constData());
+ I18N::s2b(node).constData());
else {
ReFileMetaData& entry2 = *(ReFileMetaData*) entry;
//@ToDo:
m_list.clear();
QString fnMetaFile = m_parentFS->host().directory()
+ ReCryptFileSystem::NODE_META_DIR;
- FILE* fp = fopen(fnMetaFile.toUtf8().constData(), "rb");
+ FILE* fp = fopen(I18N::s2b(fnMetaFile).constData(), "rb");
m_maxFileId = 0;
if (fp != NULL){
QByteArray header;
if (nRead != META_DIR_HEADER_LENGTH){
rc = ! m_logger->logv(LOG_ERROR, LOC_READ_META_FILE_1,
"header of %s too small: %d/%d",
- fnMetaFile.toUtf8().constData(), nRead, META_DIR_HEADER_LENGTH);
+ I18N::s2b(fnMetaFile).constData(), nRead, META_DIR_HEADER_LENGTH);
} else {
QByteArray info;
rc = initFromHeader(0, MARKER_LENGTH, META_INFO_LENGTH, 0, &header, info);
if (sumLength != meta->m_size){
m_logger->logv(LOG_ERROR, LOC_READ_META_FILE_2,
"file %s too small: %d/%d",
- fnMetaFile.toUtf8().constData(),
+ I18N::s2b(fnMetaFile).constData(),
sumLength, meta->m_size);
}
}
meta2->m_size = meta2->m_countFiles * sizeof(FileEntry_t);
ReFileMetaDataList::const_iterator it;
for (it = m_list.cbegin(); it != m_list.cend(); ++it){
- int length = it->m_node.toUtf8().length();
+ int length = I18N::s2b(it->m_node).length();
meta2->m_size += length + (length < 256 ? 0 : 1);
}
TRACE2("count: %d size: %d\n", meta2->m_countFiles, meta2->m_size);
initHeader(0, MARKER_LENGTH, META_INFO_LENGTH, 0, meta);
QByteArray node;
for (it = m_list.cbegin(); it != m_list.cend(); ++it){
- node = it->m_node.toUtf8();
+ node = I18N::s2b(it->m_node);
int length = node.length();
meta2->m_size += length + (length < 256 ? 0 : 1);
}
QString fnMetaFile = m_parentFS->host().directory()
+ ReCryptFileSystem::NODE_META_DIR;
- FILE* fp = fopen(fnMetaFile.toUtf8().constData(), "wb");
+ FILE* fp = fopen(I18N::s2b(fnMetaFile).constData(), "wb");
if (fp == NULL){
m_logger->logv(LOG_ERROR, LOC_WRITE_META_1, "cannot write (%d): %s",
errno, fnMetaFile.constData());
trg.m_size = file.m_size;
trg.m_mode = file.m_mode;
trg.m_id = file.m_id;
- node = file.m_node.toUtf8();
+ node = I18N::s2b(file.m_node);
int length = node.length();
trg.m_nodeLength = length < 256 ? length : 0;
m_fileBuffer.append(reinterpret_cast<const char*>(&trg), sizeof trg);
ReCryptLeafFile::ReCryptLeafFile(const ReFileMetaData& metadata,
const QString& fullName, ReCryptDirectory& directory, ReLogger* logger) :
ReLeafFile(metadata, fullName, logger),
- m_fullHostedName((directory.parentFS()->host().directory()
- + directory.parentFS()->buildHostedNode(metadata.m_id)).toUtf8()),
+ m_fullHostedName(I18N::s2b(directory.parentFS()->host().directory()
+ + directory.parentFS()->buildHostedNode(metadata.m_id))),
m_fileHeader(),
m_dataSum(0x7b644ac5d1187d25L, 0x6b85115d6064365bL),
m_sumOfEncrypted(0x7b644ac5d1187d25L, 0x6b85115d6064365bL),
ReFileMetaData metaTarget;
QByteArray dir;
if (verboseLevel > V_SILENT)
- dir = directory().toUtf8();
+ dir = I18N::s2b(directory());
if (source.listInfos(fileMatcher, sourceList, LO_FILES) > 0){
QString sourceDir = source.directory();
QString targetDir = directory();
> metaTarget.m_modified.currentMSecsSinceEpoch()){
if (verboseLevel > V_SILENT)
printf("%c%s%s\n", alreadyExists ? '<' : '+',
- dir.constData(), it->m_node.toUtf8().constData());
+ dir.constData(), I18N::s2b(it->m_node).constData());
copy(*it, source);
} else if (verboseLevel > V_IMPORTANT){
printf("%c%s%s\n",
it->m_modified == metaTarget.m_modified ? '=' : '>',
- dir.constData(), it->m_node.toUtf8().constData());
+ dir.constData(), I18N::s2b(it->m_node).constData());
}
}
}
if (! alreadyExists && S_ISDIR(metaTarget.m_mode)){
if (verboseLevel > V_SILENT)
printf("-%s%s\n", dir.constData(),
- it->m_node.toUtf8().constData());
+ I18N::s2b(it->m_node).constData());
remove(metaTarget);
alreadyExists = exists(it->m_node, &metaTarget);
}
if (! alreadyExists){
if (verboseLevel > V_SILENT)
printf("&%s%s\n", dir.constData(),
- it->m_node.toUtf8().constData());
+ I18N::s2b(it->m_node).constData());
if (makeDir(it->m_node) != EC_SUCCESS)
continue;
}
! earlyMatching || patterns.size() == 0
? m_dir.entryList() : m_dir.entryList(patterns);
QStringList::const_iterator it;
- QByteArray full = m_directory.toUtf8();
+ QByteArray full = I18N::s2b(m_directory);
int pathLength = full.length();
struct stat info;
const ReListMatcher& excludeMatcher = matcher.excludes();
continue;
}
full.resize(pathLength);
- full.append(node.toUtf8());
+ full.append(I18N::s2b(node));
if (stat(full.constData(), &info) == 0) {
bool isDir = S_ISDIR(info.st_mode);
if ((isDir && ! withDirs) || (! isDir && ! withFiles))
name = fullNameAsUTF8(target.m_node);
m_logger->logv(LOG_ERROR, LOC_SET_PROPERTIES_3,
"renaming impossible: %s -> %s",
- source.m_node.toUtf8().constData(), name.constData());
+ I18N::s2b(source.m_node).constData(), name.constData());
break;
} else {
name.resize(0);
*/
ReFileSystem::ErrorCode ReLocalLeafFile::open(bool writeable){
ReFileSystem::ErrorCode rc = ReFileSystem::EC_SUCCESS;
- if ( (m_fp = fopen(m_fullName.toUtf8().constData(),
+ if ( (m_fp = fopen(I18N::s2b(m_fullName).constData(),
writeable ?"wb" : "rb")) == NULL){
rc = ReFileSystem::EC_NOT_EXISTS;
m_logger->logv(LOG_ERROR, LOC_OPEN_1, "cannot open: %s",
- m_fullName.toUtf8().constData());
+ I18N::s2b(m_fullName).constData());
}
return rc;
}
if ( (nRead = fread(buffer.data(), 1, maxSize, m_fp)) != maxSize){
rc = ReFileSystem::EC_READ;
m_logger->logv(LOG_ERROR, LOC_READ_1, "cannnot read %s (%d): %d/%d",
- m_fullName.toUtf8().constData(), errno, nRead, maxSize);
+ I18N::s2b(m_fullName).constData(), errno, nRead, maxSize);
}
}
return rc;
if ( (nWritten = fwrite(buffer.constData(), 1, nToWrite, m_fp)) != nToWrite){
rc = ReFileSystem::EC_WRITE;
m_logger->logv(LOG_ERROR, LOC_WRITE_1, "cannnot read %s (%d): %d/%d",
- m_fullName.toUtf8().constData(), errno, nWritten, nToWrite);
+ I18N::s2b(m_fullName).constData(), errno, nWritten, nToWrite);
}
}
return rc;