Use cutelogger for Rockbox Utility internal trace.

Change tracing from qDebug() to use cutelogger, which is available under the
LGPL2.1. This allows to automatically add filename and line number to the log,
and also provides multiple log levels.

Change-Id: I5dbdaf902ba54ea99f07ae10a07467c52fdac910
This commit is contained in:
Dominik Riebeling 2013-11-03 11:08:18 +01:00
parent 335ec75d60
commit 4d2ce949b3
65 changed files with 2420 additions and 455 deletions

View file

@ -28,6 +28,7 @@
#include "system.h" #include "system.h"
#include "utils.h" #include "utils.h"
#include "rockboxinfo.h" #include "rockboxinfo.h"
#include "Logger.h"
Autodetection::Autodetection(QObject* parent): QObject(parent) Autodetection::Autodetection(QObject* parent): QObject(parent)
{ {
@ -67,8 +68,8 @@ bool Autodetection::detect(void)
} }
} }
for(int i = 0; i < m_detected.size(); ++i) { for(int i = 0; i < m_detected.size(); ++i) {
qDebug() << "[Autodetect] Detected player:" << m_detected.at(i).device LOG_INFO() << "Detected player:" << m_detected.at(i).device
<< "at" << m_detected.at(i).mountpoint << states[m_detected.at(i).status]; << "at" << m_detected.at(i).mountpoint << states[m_detected.at(i).status];
} }
return m_detected.size() > 0; return m_detected.size() > 0;
@ -98,14 +99,14 @@ void Autodetection::detectUsb()
d.status = PlayerOk; d.status = PlayerOk;
d.usbdevices = usbids.value(attached.at(i)); d.usbdevices = usbids.value(attached.at(i));
m_detected.append(d); m_detected.append(d);
qDebug() << "[USB] detected supported player" << d.usbdevices; LOG_INFO() << "[USB] detected supported player" << d.usbdevices;
} }
if(usberror.contains(attached.at(i))) { if(usberror.contains(attached.at(i))) {
struct Detected d; struct Detected d;
d.status = PlayerMtpMode; d.status = PlayerMtpMode;
d.device = usbids.value(attached.at(i)).at(0); d.device = usbids.value(attached.at(i)).at(0);
m_detected.append(d); m_detected.append(d);
qDebug() << "[USB] detected problem with player" << d.device; LOG_WARNING() << "[USB] detected problem with player" << d.device;
} }
QString idstring = QString("%1").arg(attached.at(i), 8, 16, QChar('0')); QString idstring = QString("%1").arg(attached.at(i), 8, 16, QChar('0'));
if(!SystemInfo::platformValue(idstring, SystemInfo::CurName).toString().isEmpty()) { if(!SystemInfo::platformValue(idstring, SystemInfo::CurName).toString().isEmpty()) {
@ -113,7 +114,7 @@ void Autodetection::detectUsb()
d.status = PlayerIncompatible; d.status = PlayerIncompatible;
d.device = idstring; d.device = idstring;
m_detected.append(d); m_detected.append(d);
qDebug() << "[USB] detected incompatible player" << d.device; LOG_WARNING() << "[USB] detected incompatible player" << d.device;
} }
} }
} }
@ -125,7 +126,7 @@ void Autodetection::detectUsb()
void Autodetection::mergeMounted(void) void Autodetection::mergeMounted(void)
{ {
QStringList mounts = Utils::mountpoints(Utils::MountpointsSupported); QStringList mounts = Utils::mountpoints(Utils::MountpointsSupported);
qDebug() << "[Autodetect] paths to check:" << mounts; LOG_INFO() << "paths to check:" << mounts;
for(int i = 0; i < mounts.size(); i++) for(int i = 0; i < mounts.size(); i++)
{ {
@ -143,8 +144,8 @@ void Autodetection::mergeMounted(void)
d.mountpoint = mounts.at(i); d.mountpoint = mounts.at(i);
d.status = PlayerOk; d.status = PlayerOk;
updateDetectedDevice(d); updateDetectedDevice(d);
qDebug() << "[Autodetect] rbutil.log detected:" LOG_INFO() << "rbutil.log detected:"
<< log.value("platform").toString() << mounts.at(i); << log.value("platform").toString() << mounts.at(i);
} }
} }
@ -157,8 +158,8 @@ void Autodetection::mergeMounted(void)
d.mountpoint = mounts.at(i); d.mountpoint = mounts.at(i);
d.status = PlayerOk; d.status = PlayerOk;
updateDetectedDevice(d); updateDetectedDevice(d);
qDebug() << "[Autodetect] rockbox-info.txt detected:" LOG_INFO() << "rockbox-info.txt detected:"
<< info.target() << mounts.at(i); << info.target() << mounts.at(i);
} }
// check for some specific files in root folder // check for some specific files in root folder
@ -193,13 +194,13 @@ void Autodetection::mergeMounted(void)
} }
if(rootentries.contains("ajbrec.ajz", Qt::CaseInsensitive)) if(rootentries.contains("ajbrec.ajz", Qt::CaseInsensitive))
{ {
qDebug() << "[Autodetect] ajbrec.ajz found. Trying detectAjbrec()"; LOG_INFO() << "ajbrec.ajz found. Trying detectAjbrec()";
struct Detected d; struct Detected d;
d.device = detectAjbrec(mounts.at(i)); d.device = detectAjbrec(mounts.at(i));
d.mountpoint = mounts.at(i); d.mountpoint = mounts.at(i);
d.status = PlayerOk; d.status = PlayerOk;
if(!d.device.isEmpty()) { if(!d.device.isEmpty()) {
qDebug() << "[Autodetect]" << d.device; LOG_INFO() << d.device;
updateDetectedDevice(d); updateDetectedDevice(d);
} }
} }
@ -255,7 +256,7 @@ void Autodetection::mergePatcher(void)
n = ipod_scan(&ipod); n = ipod_scan(&ipod);
// FIXME: handle more than one Ipod connected in ipodpatcher. // FIXME: handle more than one Ipod connected in ipodpatcher.
if(n == 1) { if(n == 1) {
qDebug() << "[Autodetect] Ipod found:" << ipod.modelstr << "at" << ipod.diskname; LOG_INFO() << "Ipod found:" << ipod.modelstr << "at" << ipod.diskname;
// since resolveMountPoint is doing exact matches we need to select // since resolveMountPoint is doing exact matches we need to select
// the correct partition. // the correct partition.
QString mp(ipod.diskname); QString mp(ipod.diskname);
@ -276,7 +277,7 @@ void Autodetection::mergePatcher(void)
updateDetectedDevice(d); updateDetectedDevice(d);
} }
else { else {
qDebug() << "[Autodetect] ipodpatcher: no Ipod found." << n; LOG_INFO() << "ipodpatcher: no Ipod found." << n;
} }
ipod_dealloc_buffer(&ipod); ipod_dealloc_buffer(&ipod);
@ -286,8 +287,8 @@ void Autodetection::mergePatcher(void)
sansa_alloc_buffer(&sansa, BUFFER_SIZE); sansa_alloc_buffer(&sansa, BUFFER_SIZE);
n = sansa_scan(&sansa); n = sansa_scan(&sansa);
if(n == 1) { if(n == 1) {
qDebug() << "[Autodetect] Sansa found:" LOG_INFO() << "Sansa found:"
<< sansa.targetname << "at" << sansa.diskname; << sansa.targetname << "at" << sansa.diskname;
QString mp(sansa.diskname); QString mp(sansa.diskname);
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX
mp.append("1"); mp.append("1");
@ -302,7 +303,7 @@ void Autodetection::mergePatcher(void)
updateDetectedDevice(d); updateDetectedDevice(d);
} }
else { else {
qDebug() << "[Autodetect] sansapatcher: no Sansa found." << n; LOG_INFO() << "sansapatcher: no Sansa found." << n;
} }
sansa_dealloc_buffer(&sansa); sansa_dealloc_buffer(&sansa);
} }
@ -323,8 +324,8 @@ QString Autodetection::detectAjbrec(QString root)
// recorder v1 has the binary length in the first 4 bytes, so check // recorder v1 has the binary length in the first 4 bytes, so check
// for them first. // for them first.
int len = (header[0]<<24) | (header[1]<<16) | (header[2]<<8) | header[3]; int len = (header[0]<<24) | (header[1]<<16) | (header[2]<<8) | header[3];
qDebug() << "[Autodetect] ABJREC possible bin length:" << len LOG_INFO() << "abjrec.ajz possible bin length:" << len
<< "file len:" << f.size(); << "file len:" << f.size();
if((f.size() - 6) == len) if((f.size() - 6) == len)
return "recorder"; return "recorder";

View file

@ -19,6 +19,7 @@
#include <QtCore> #include <QtCore>
#include "bootloaderinstallbase.h" #include "bootloaderinstallbase.h"
#include "bootloaderinstallams.h" #include "bootloaderinstallams.h"
#include "Logger.h"
#include "../mkamsboot/mkamsboot.h" #include "../mkamsboot/mkamsboot.h"
@ -51,7 +52,7 @@ bool BootloaderInstallAms::install(void)
if(m_offile.isEmpty()) if(m_offile.isEmpty())
return false; return false;
qDebug() << "[BootloaderInstallAms] installing bootloader"; LOG_INFO() << "installing bootloader";
// download firmware from server // download firmware from server
emit logItem(tr("Downloading bootloader file"), LOGINFO); emit logItem(tr("Downloading bootloader file"), LOGINFO);
@ -64,7 +65,7 @@ bool BootloaderInstallAms::install(void)
void BootloaderInstallAms::installStage2(void) void BootloaderInstallAms::installStage2(void)
{ {
qDebug() << "[BootloaderInstallAms] installStage2"; LOG_INFO() << "installStage2";
unsigned char* buf; unsigned char* buf;
unsigned char* of_packed; unsigned char* of_packed;
@ -94,7 +95,7 @@ void BootloaderInstallAms::installStage2(void)
errstr,sizeof(errstr)); errstr,sizeof(errstr));
if (rb_packed == NULL) if (rb_packed == NULL)
{ {
qDebug() << "[BootloaderInstallAms] could not load bootloader: " << bootfile; LOG_ERROR() << "could not load bootloader: " << bootfile;
emit logItem(errstr, LOGERROR); emit logItem(errstr, LOGERROR);
emit logItem(tr("Could not load %1").arg(bootfile), LOGERROR); emit logItem(tr("Could not load %1").arg(bootfile), LOGERROR);
emit done(true); emit done(true);
@ -107,7 +108,7 @@ void BootloaderInstallAms::installStage2(void)
errstr, sizeof(errstr)); errstr, sizeof(errstr));
if (buf == NULL) if (buf == NULL)
{ {
qDebug() << "[BootloaderInstallAms] could not load OF: " << m_offile; LOG_ERROR() << "could not load OF: " << m_offile;
emit logItem(errstr, LOGERROR); emit logItem(errstr, LOGERROR);
emit logItem(tr("Could not load %1").arg(m_offile), LOGERROR); emit logItem(tr("Could not load %1").arg(m_offile), LOGERROR);
free(rb_packed); free(rb_packed);
@ -121,7 +122,7 @@ void BootloaderInstallAms::installStage2(void)
if (!patchable) if (!patchable)
{ {
qDebug() << "[BootloaderInstallAms] No room to insert bootloader"; LOG_ERROR() << "No room to insert bootloader";
emit logItem(errstr, LOGERROR); emit logItem(errstr, LOGERROR);
emit logItem(tr("No room to insert bootloader, try another firmware version"), emit logItem(tr("No room to insert bootloader, try another firmware version"),
LOGERROR); LOGERROR);
@ -143,7 +144,7 @@ void BootloaderInstallAms::installStage2(void)
if(!out.open(QIODevice::WriteOnly | QIODevice::Truncate)) if(!out.open(QIODevice::WriteOnly | QIODevice::Truncate))
{ {
qDebug() << "[BootloaderInstallAms] Could not open" << m_blfile << "for writing"; LOG_ERROR() << "Could not open" << m_blfile << "for writing";
emit logItem(tr("Could not open %1 for writing").arg(m_blfile),LOGERROR); emit logItem(tr("Could not open %1 for writing").arg(m_blfile),LOGERROR);
free(buf); free(buf);
free(of_packed); free(of_packed);
@ -156,7 +157,7 @@ void BootloaderInstallAms::installStage2(void)
if (n != len) if (n != len)
{ {
qDebug() << "[BootloaderInstallAms] Could not write firmware file"; LOG_ERROR() << "Could not write firmware file";
emit logItem(tr("Could not write firmware file"),LOGERROR); emit logItem(tr("Could not write firmware file"),LOGERROR);
free(buf); free(buf);
free(of_packed); free(of_packed);
@ -172,7 +173,7 @@ void BootloaderInstallAms::installStage2(void)
free(rb_packed); free(rb_packed);
//end of install //end of install
qDebug() << "[BootloaderInstallAms] install successfull"; LOG_INFO() << "install successfull";
emit logItem(tr("Success: modified firmware file created"), LOGINFO); emit logItem(tr("Success: modified firmware file created"), LOGINFO);
logInstall(LogAdd); logInstall(LogAdd);
emit done(false); emit done(false);

View file

@ -23,6 +23,7 @@
#include "utils.h" #include "utils.h"
#include "ziputil.h" #include "ziputil.h"
#include "mspackutil.h" #include "mspackutil.h"
#include "Logger.h"
#if defined(Q_OS_MACX) #if defined(Q_OS_MACX)
#include <sys/param.h> #include <sys/param.h>
@ -58,8 +59,8 @@ void BootloaderInstallBase::downloadBlStart(QUrl source)
void BootloaderInstallBase::downloadReqFinished(int id, bool error) void BootloaderInstallBase::downloadReqFinished(int id, bool error)
{ {
qDebug() << "[BootloaderInstallBase] Download Request" << id LOG_INFO() << "Download Request" << id
<< "finished, error:" << m_http.errorString(); << "finished, error:" << m_http.errorString();
downloadBlFinish(error); downloadBlFinish(error);
} }
@ -67,8 +68,8 @@ void BootloaderInstallBase::downloadReqFinished(int id, bool error)
void BootloaderInstallBase::downloadBlFinish(bool error) void BootloaderInstallBase::downloadBlFinish(bool error)
{ {
qDebug() << "[BootloaderInstallBase] Downloading bootloader finished, error:" LOG_INFO() << "Downloading bootloader finished, error:"
<< error; << error;
// update progress bar // update progress bar
emit logProgress(100, 100); emit logProgress(100, 100);
@ -98,7 +99,7 @@ void BootloaderInstallBase::downloadBlFinish(bool error)
void BootloaderInstallBase::installBlfile(void) void BootloaderInstallBase::installBlfile(void)
{ {
qDebug() << "[BootloaderInstallBase] installBlFile(void)"; LOG_INFO() << "installBlFile(void)";
} }
@ -107,7 +108,7 @@ void BootloaderInstallBase::installBlfile(void)
//! @return true on success, false on error. //! @return true on success, false on error.
bool BootloaderInstallBase::backup(QString to) bool BootloaderInstallBase::backup(QString to)
{ {
qDebug() << "[BootloaderInstallBase] Backing up bootloader file"; LOG_INFO() << "Backing up bootloader file";
QDir targetDir("."); QDir targetDir(".");
emit logItem(tr("Creating backup of original firmware file."), LOGINFO); emit logItem(tr("Creating backup of original firmware file."), LOGINFO);
if(!targetDir.mkpath(to)) { if(!targetDir.mkpath(to)) {
@ -115,7 +116,7 @@ bool BootloaderInstallBase::backup(QString to)
return false; return false;
} }
QString tofile = to + "/" + QFileInfo(m_blfile).fileName(); QString tofile = to + "/" + QFileInfo(m_blfile).fileName();
qDebug() << "[BootloaderInstallBase] trying to backup" << m_blfile << "to" << tofile; LOG_INFO() << "trying to backup" << m_blfile << "to" << tofile;
if(!QFile::copy(Utils::resolvePathCase(m_blfile), tofile)) { if(!QFile::copy(Utils::resolvePathCase(m_blfile), tofile)) {
emit logItem(tr("Creating backup copy failed."), LOGERROR); emit logItem(tr("Creating backup copy failed."), LOGERROR);
return false; return false;
@ -137,8 +138,8 @@ int BootloaderInstallBase::logInstall(LogMode mode)
if(mode == LogAdd) { if(mode == LogAdd) {
s.setValue("Bootloader/" + section, m_blversion.toString(Qt::ISODate)); s.setValue("Bootloader/" + section, m_blversion.toString(Qt::ISODate));
qDebug() << "[BootloaderInstallBase] Writing log, version:" LOG_INFO() << "Writing log, version:"
<< m_blversion.toString(Qt::ISODate); << m_blversion.toString(Qt::ISODate);
} }
else { else {
s.remove("Bootloader/" + section); s.remove("Bootloader/" + section);
@ -182,7 +183,7 @@ void BootloaderInstallBase::checkRemount()
if(!status) { if(!status) {
// still not remounted, restart timer. // still not remounted, restart timer.
QTimer::singleShot(500, this, SLOT(checkRemount())); QTimer::singleShot(500, this, SLOT(checkRemount()));
qDebug() << "[BootloaderInstallBase] Player not remounted yet" << m_remountDevice; LOG_INFO() << "Player not remounted yet" << m_remountDevice;
} }
else { else {
emit logItem(tr("Player remounted"), LOGINFO); emit logItem(tr("Player remounted"), LOGINFO);
@ -244,11 +245,11 @@ bool BootloaderInstallBase::setOfFile(QString of, QStringList blfile)
// check if the file set is in zip format // check if the file set is in zip format
if(util) { if(util) {
QStringList contents = util->files(); QStringList contents = util->files();
qDebug() << "[BootloaderInstallBase] archive contains:" << contents; LOG_INFO() << "archive contains:" << contents;
for(int i = 0; i < blfile.size(); ++i) { for(int i = 0; i < blfile.size(); ++i) {
// strip any path, we don't know the structure in the zip // strip any path, we don't know the structure in the zip
QString f = QFileInfo(blfile.at(i)).fileName(); QString f = QFileInfo(blfile.at(i)).fileName();
qDebug() << "[BootloaderInstallBase] searching archive for" << f; LOG_INFO() << "searching archive for" << f;
// contents.indexOf() works case sensitive. Since the filename // contents.indexOf() works case sensitive. Since the filename
// casing is unknown (and might change) do this manually. // casing is unknown (and might change) do this manually.
// FIXME: support files in folders // FIXME: support files in folders

View file

@ -20,6 +20,7 @@
#include <QtDebug> #include <QtDebug>
#include "bootloaderinstallfile.h" #include "bootloaderinstallfile.h"
#include "utils.h" #include "utils.h"
#include "Logger.h"
BootloaderInstallFile::BootloaderInstallFile(QObject *parent) BootloaderInstallFile::BootloaderInstallFile(QObject *parent)
@ -31,7 +32,7 @@ BootloaderInstallFile::BootloaderInstallFile(QObject *parent)
bool BootloaderInstallFile::install(void) bool BootloaderInstallFile::install(void)
{ {
emit logItem(tr("Downloading bootloader"), LOGINFO); emit logItem(tr("Downloading bootloader"), LOGINFO);
qDebug() << "[BootloaderInstallFile] installing bootloader"; LOG_INFO() << "installing bootloader";
downloadBlStart(m_blurl); downloadBlStart(m_blurl);
connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2())); connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2()));
return true; return true;
@ -46,7 +47,7 @@ void BootloaderInstallFile::installStage2(void)
QString fwfile(Utils::resolvePathCase(m_blfile)); QString fwfile(Utils::resolvePathCase(m_blfile));
if(!fwfile.isEmpty()) { if(!fwfile.isEmpty()) {
QString moved = Utils::resolvePathCase(m_blfile) + ".ORIG"; QString moved = Utils::resolvePathCase(m_blfile) + ".ORIG";
qDebug() << "[BootloaderInstallFile] renaming" << fwfile << "to" << moved; LOG_INFO() << "renaming" << fwfile << "to" << moved;
QFile::rename(fwfile, moved); QFile::rename(fwfile, moved);
} }
@ -80,8 +81,8 @@ void BootloaderInstallFile::installStage2(void)
// place (new) bootloader // place (new) bootloader
m_tempfile.open(); m_tempfile.open();
qDebug() << "[BootloaderInstallFile] renaming" << m_tempfile.fileName() LOG_INFO() << "renaming" << m_tempfile.fileName()
<< "to" << fwfile; << "to" << fwfile;
m_tempfile.close(); m_tempfile.close();
if(!Utils::resolvePathCase(fwfile).isEmpty()) { if(!Utils::resolvePathCase(fwfile).isEmpty()) {
@ -106,7 +107,7 @@ void BootloaderInstallFile::installStage2(void)
bool BootloaderInstallFile::uninstall(void) bool BootloaderInstallFile::uninstall(void)
{ {
qDebug() << "[BootloaderInstallFile] Uninstalling bootloader"; LOG_INFO() << "Uninstalling bootloader";
emit logItem(tr("Removing Rockbox bootloader"), LOGINFO); emit logItem(tr("Removing Rockbox bootloader"), LOGINFO);
// check if a .ORIG file is present, and allow moving it back. // check if a .ORIG file is present, and allow moving it back.
QString origbl = Utils::resolvePathCase(m_blfile + ".ORIG"); QString origbl = Utils::resolvePathCase(m_blfile + ".ORIG");
@ -138,7 +139,7 @@ bool BootloaderInstallFile::uninstall(void)
//! @return BootloaderRockbox, BootloaderOther or BootloaderUnknown. //! @return BootloaderRockbox, BootloaderOther or BootloaderUnknown.
BootloaderInstallBase::BootloaderType BootloaderInstallFile::installed(void) BootloaderInstallBase::BootloaderType BootloaderInstallFile::installed(void)
{ {
qDebug() << "[BootloaderInstallFile] checking installed bootloader"; LOG_INFO() << "checking installed bootloader";
if(!Utils::resolvePathCase(m_blfile).isEmpty() if(!Utils::resolvePathCase(m_blfile).isEmpty()
&& !Utils::resolvePathCase(m_blfile + ".ORIG").isEmpty()) && !Utils::resolvePathCase(m_blfile + ".ORIG").isEmpty())
return BootloaderRockbox; return BootloaderRockbox;
@ -151,7 +152,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallFile::installed(void)
BootloaderInstallBase::Capabilities BootloaderInstallFile::capabilities(void) BootloaderInstallBase::Capabilities BootloaderInstallFile::capabilities(void)
{ {
qDebug() << "[BootloaderInstallFile] getting capabilities"; LOG_INFO() << "getting capabilities";
return Install | Uninstall | IsFile | CanCheckInstalled | Backup; return Install | Uninstall | IsFile | CanCheckInstalled | Backup;
} }

View file

@ -20,6 +20,7 @@
#include "bootloaderinstallbase.h" #include "bootloaderinstallbase.h"
#include "bootloaderinstallhex.h" #include "bootloaderinstallhex.h"
#include "utils.h" #include "utils.h"
#include "Logger.h"
#include "../../tools/iriver.h" #include "../../tools/iriver.h"
#include "../../tools/mkboot.h" #include "../../tools/mkboot.h"
@ -74,7 +75,7 @@ bool BootloaderInstallHex::install(void)
file.close(); file.close();
QString hash = QCryptographicHash::hash(filedata, QString hash = QCryptographicHash::hash(filedata,
QCryptographicHash::Md5).toHex(); QCryptographicHash::Md5).toHex();
qDebug() << "[BootloaderInstallHex] hexfile hash:" << hash; LOG_INFO() << "hexfile hash:" << hash;
if(file.error() != QFile::NoError) { if(file.error() != QFile::NoError) {
emit logItem(tr("Could not verify original firmware file"), LOGERROR); emit logItem(tr("Could not verify original firmware file"), LOGERROR);
emit done(true); emit done(true);
@ -112,7 +113,7 @@ bool BootloaderInstallHex::install(void)
int result; int result;
result = iriver_decode(m_offile.toLatin1().data(), result = iriver_decode(m_offile.toLatin1().data(),
m_descrambled.fileName().toLatin1().data(), FALSE, STRIP_NONE); m_descrambled.fileName().toLatin1().data(), FALSE, STRIP_NONE);
qDebug() << "[BootloaderInstallHex] iriver_decode" << result; LOG_INFO() << "iriver_decode():" << result;
if(result < 0) { if(result < 0) {
emit logItem(tr("Error in descramble: %1").arg(scrambleError(result)), LOGERROR); emit logItem(tr("Error in descramble: %1").arg(scrambleError(result)), LOGERROR);
@ -200,7 +201,7 @@ void BootloaderInstallHex::installStage2(void)
targethex.close(); targethex.close();
QString hash = QCryptographicHash::hash(filedata, QString hash = QCryptographicHash::hash(filedata,
QCryptographicHash::Md5).toHex(); QCryptographicHash::Md5).toHex();
qDebug() << "[BootloaderInstallHex] created hexfile hash:" << hash; LOG_INFO() << "created hexfile hash:" << hash;
emit logItem(tr("Checking modified firmware file"), LOGINFO); emit logItem(tr("Checking modified firmware file"), LOGINFO);
if(hash != QString(md5sums[m_hashindex].patched)) { if(hash != QString(md5sums[m_hashindex].patched)) {

View file

@ -21,6 +21,7 @@
#include "bootloaderinstallbase.h" #include "bootloaderinstallbase.h"
#include "bootloaderinstallimx.h" #include "bootloaderinstallimx.h"
#include "../mkimxboot/mkimxboot.h" #include "../mkimxboot/mkimxboot.h"
#include "Logger.h"
// class for running mkimxboot() in a separate thread to keep the UI responsive. // class for running mkimxboot() in a separate thread to keep the UI responsive.
class BootloaderThreadImx : public QThread class BootloaderThreadImx : public QThread
@ -45,7 +46,7 @@ class BootloaderThreadImx : public QThread
void BootloaderThreadImx::run(void) void BootloaderThreadImx::run(void)
{ {
qDebug() << "[BootloaderThreadImx] Thread started."; LOG_INFO() << "Thread started.";
struct imx_option_t opt; struct imx_option_t opt;
memset(&opt, 0, sizeof(opt)); memset(&opt, 0, sizeof(opt));
opt.debug = false; opt.debug = false;
@ -55,7 +56,7 @@ void BootloaderThreadImx::run(void)
m_error = mkimxboot(m_inputfile.toLocal8Bit().constData(), m_error = mkimxboot(m_inputfile.toLocal8Bit().constData(),
m_bootfile.toLocal8Bit().constData(), m_bootfile.toLocal8Bit().constData(),
m_outputfile.toLocal8Bit().constData(), opt); m_outputfile.toLocal8Bit().constData(), opt);
qDebug() << "[BootloaderThreadImx] Thread finished, result:" << m_error; LOG_INFO() << "Thread finished, result:" << m_error;
} }
@ -88,13 +89,13 @@ bool BootloaderInstallImx::install(void)
{ {
if(!QFileInfo(m_offile).isReadable()) if(!QFileInfo(m_offile).isReadable())
{ {
qDebug() << "[BootloaderInstallImx] could not read original firmware file" LOG_ERROR() << "could not read original firmware file"
<< m_offile; << m_offile;
emit logItem(tr("Could not read original firmware file"), LOGERROR); emit logItem(tr("Could not read original firmware file"), LOGERROR);
return false; return false;
} }
qDebug() << "[BootloaderInstallImx] downloading bootloader"; LOG_INFO() << "downloading bootloader";
// download bootloader from server // download bootloader from server
emit logItem(tr("Downloading bootloader file"), LOGINFO); emit logItem(tr("Downloading bootloader file"), LOGINFO);
connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2())); connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2()));
@ -105,7 +106,7 @@ bool BootloaderInstallImx::install(void)
void BootloaderInstallImx::installStage2(void) void BootloaderInstallImx::installStage2(void)
{ {
qDebug() << "[BootloaderInstallImx] patching file..."; LOG_INFO() << "patching file...";
emit logItem(tr("Patching file..."), LOGINFO); emit logItem(tr("Patching file..."), LOGINFO);
m_tempfile.open(); m_tempfile.open();
@ -132,26 +133,26 @@ void BootloaderInstallImx::installStage3(void)
// if the patch failed // if the patch failed
if (err != IMX_SUCCESS) if (err != IMX_SUCCESS)
{ {
qDebug() << "[BootloaderInstallImx] Could not patch the original firmware file"; LOG_ERROR() << "Could not patch the original firmware file";
emit logItem(tr("Patching the original firmware failed"), LOGERROR); emit logItem(tr("Patching the original firmware failed"), LOGERROR);
emit done(true); emit done(true);
return; return;
} }
qDebug() << "[BootloaderInstallImx] Original Firmware succesfully patched"; LOG_INFO() << "Original Firmware succesfully patched";
emit logItem(tr("Succesfully patched firmware file"), LOGINFO); emit logItem(tr("Succesfully patched firmware file"), LOGINFO);
// if a bootloader is already present delete it. // if a bootloader is already present delete it.
QString fwfile(m_blfile); QString fwfile(m_blfile);
if(QFileInfo(fwfile).isFile()) if(QFileInfo(fwfile).isFile())
{ {
qDebug() << "[BootloaderInstallImx] deleting old target file"; LOG_INFO() << "deleting old target file";
QFile::remove(fwfile); QFile::remove(fwfile);
} }
// place (new) bootloader. Copy, since the temporary file will be removed // place (new) bootloader. Copy, since the temporary file will be removed
// automatically. // automatically.
qDebug() << "[BootloaderInstallImx] moving patched bootloader to" << fwfile; LOG_INFO() << "moving patched bootloader to" << fwfile;
if(m_patchedFile.copy(fwfile)) if(m_patchedFile.copy(fwfile))
{ {
emit logItem(tr("Bootloader successful installed"), LOGOK); emit logItem(tr("Bootloader successful installed"), LOGOK);

View file

@ -22,6 +22,7 @@
#include "../ipodpatcher/ipodpatcher.h" #include "../ipodpatcher/ipodpatcher.h"
#include "utils.h" #include "utils.h"
#include "Logger.h"
BootloaderInstallIpod::BootloaderInstallIpod(QObject *parent) BootloaderInstallIpod::BootloaderInstallIpod(QObject *parent)
@ -131,7 +132,8 @@ void BootloaderInstallIpod::installStage3(bool mounted)
emit logItem(tr("Writing log aborted"), LOGERROR); emit logItem(tr("Writing log aborted"), LOGERROR);
emit done(true); emit done(true);
} }
qDebug() << "[BootloaderInstallIpod] version installed:" << m_blversion.toString(Qt::ISODate); LOG_INFO() << "version installed:"
<< m_blversion.toString(Qt::ISODate);
} }
@ -190,7 +192,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallIpod::installed(void)
BootloaderInstallBase::BootloaderType result = BootloaderRockbox; BootloaderInstallBase::BootloaderType result = BootloaderRockbox;
if(!ipodInitialize(&ipod)) { if(!ipodInitialize(&ipod)) {
qDebug() << "[BootloaderInstallIpod] installed: BootloaderUnknown"; LOG_INFO() << "installed: BootloaderUnknown";
result = BootloaderUnknown; result = BootloaderUnknown;
} }
else { else {
@ -200,7 +202,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallIpod::installed(void)
result = BootloaderOther; result = BootloaderOther;
} }
else { else {
qDebug() << "[BootloaderInstallIpod] installed: BootloaderRockbox"; LOG_INFO() << "installed: BootloaderRockbox";
} }
} }
ipod_close(&ipod); ipod_close(&ipod);
@ -235,12 +237,12 @@ bool BootloaderInstallIpod::ipodInitialize(struct ipod_t *ipod)
sprintf(ipod->diskname, "%s", sprintf(ipod->diskname, "%s",
qPrintable(devicename.remove(QRegExp("[0-9]+$")))); qPrintable(devicename.remove(QRegExp("[0-9]+$"))));
#endif #endif
qDebug() << "[BootloaderInstallIpod] ipodpatcher: overriding scan, using" LOG_INFO() << "ipodpatcher: overriding scan, using"
<< ipod->diskname; << ipod->diskname;
} }
else { else {
emit logItem(tr("Error: no mountpoint specified!"), LOGERROR); emit logItem(tr("Error: no mountpoint specified!"), LOGERROR);
qDebug() << "[BootloaderInstallIpod] no mountpoint specified!"; LOG_ERROR() << "no mountpoint specified!";
} }
int result = ipod_open(ipod, 1); int result = ipod_open(ipod, 1);
if(result == -2) { if(result == -2) {

View file

@ -21,6 +21,7 @@
#include <QtDebug> #include <QtDebug>
#include "bootloaderinstallmi4.h" #include "bootloaderinstallmi4.h"
#include "utils.h" #include "utils.h"
#include "Logger.h"
BootloaderInstallMi4::BootloaderInstallMi4(QObject *parent) BootloaderInstallMi4::BootloaderInstallMi4(QObject *parent)
: BootloaderInstallBase(parent) : BootloaderInstallBase(parent)
@ -31,7 +32,7 @@ BootloaderInstallMi4::BootloaderInstallMi4(QObject *parent)
bool BootloaderInstallMi4::install(void) bool BootloaderInstallMi4::install(void)
{ {
emit logItem(tr("Downloading bootloader"), LOGINFO); emit logItem(tr("Downloading bootloader"), LOGINFO);
qDebug() << "[BootloaderInstallMi4] installing bootloader"; LOG_INFO() << "installing bootloader";
downloadBlStart(m_blurl); downloadBlStart(m_blurl);
connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2())); connect(this, SIGNAL(downloadDone()), this, SLOT(installStage2()));
return true; return true;
@ -48,18 +49,18 @@ void BootloaderInstallMi4::installStage2(void)
QString moved = QFileInfo(Utils::resolvePathCase(m_blfile)).absolutePath() QString moved = QFileInfo(Utils::resolvePathCase(m_blfile)).absolutePath()
+ "/OF.mi4"; + "/OF.mi4";
if(!QFileInfo(moved).exists()) { if(!QFileInfo(moved).exists()) {
qDebug() << "[BootloaderInstallMi4] renaming" << fwfile << "to" << moved; LOG_INFO() << "renaming" << fwfile << "to" << moved;
oldbl.rename(moved); oldbl.rename(moved);
} }
else { else {
qDebug() << "[BootloaderInstallMi4] OF.mi4 already present, not renaming again."; LOG_INFO() << "OF.mi4 already present, not renaming again.";
oldbl.remove(); oldbl.remove();
} }
// place new bootloader // place new bootloader
m_tempfile.open(); m_tempfile.open();
qDebug() << "[BootloaderInstallMi4] renaming" << m_tempfile.fileName() LOG_INFO() << "renaming" << m_tempfile.fileName()
<< "to" << fwfile; << "to" << fwfile;
m_tempfile.close(); m_tempfile.close();
if(!Utils::resolvePathCase(fwfile).isEmpty()) { if(!Utils::resolvePathCase(fwfile).isEmpty()) {
emit logItem(tr("A firmware file is already present on player"), LOGERROR); emit logItem(tr("A firmware file is already present on player"), LOGERROR);
@ -84,7 +85,7 @@ void BootloaderInstallMi4::installStage2(void)
bool BootloaderInstallMi4::uninstall(void) bool BootloaderInstallMi4::uninstall(void)
{ {
qDebug() << "[BootloaderInstallMi4] Uninstalling bootloader"; LOG_INFO() << "Uninstalling bootloader";
// check if it's actually a Rockbox bootloader // check if it's actually a Rockbox bootloader
emit logItem(tr("Checking for Rockbox bootloader"), LOGINFO); emit logItem(tr("Checking for Rockbox bootloader"), LOGINFO);
@ -128,7 +129,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallMi4::installed(void)
QString resolved; QString resolved;
resolved = Utils::resolvePathCase(m_blfile); resolved = Utils::resolvePathCase(m_blfile);
if(resolved.isEmpty()) { if(resolved.isEmpty()) {
qDebug() << "[BootloaderInstallMi4] installed: BootloaderNone"; LOG_INFO() << "installed: BootloaderNone";
return BootloaderNone; return BootloaderNone;
} }
@ -140,11 +141,11 @@ BootloaderInstallBase::BootloaderType BootloaderInstallMi4::installed(void)
f.close(); f.close();
if(!memcmp(magic, "RBBL", 4)) { if(!memcmp(magic, "RBBL", 4)) {
qDebug() << "[BootloaderInstallMi4] installed: BootloaderRockbox"; LOG_INFO() << "installed: BootloaderRockbox";
return BootloaderRockbox; return BootloaderRockbox;
} }
else { else {
qDebug() << "[BootloaderInstallMi4] installed: BootloaderOther"; LOG_INFO() << "installed: BootloaderOther";
return BootloaderOther; return BootloaderOther;
} }
} }
@ -152,7 +153,7 @@ BootloaderInstallBase::BootloaderType BootloaderInstallMi4::installed(void)
BootloaderInstallBase::Capabilities BootloaderInstallMi4::capabilities(void) BootloaderInstallBase::Capabilities BootloaderInstallMi4::capabilities(void)
{ {
qDebug() << "[BootloaderInstallMi4] getting capabilities"; LOG_INFO() << "getting capabilities";
return Install | Uninstall | Backup | IsFile | CanCheckInstalled | CanCheckVersion; return Install | Uninstall | Backup | IsFile | CanCheckInstalled | CanCheckVersion;
} }

View file

@ -20,6 +20,7 @@
#include <QtCore> #include <QtCore>
#include "bootloaderinstallbase.h" #include "bootloaderinstallbase.h"
#include "bootloaderinstallmpio.h" #include "bootloaderinstallmpio.h"
#include "Logger.h"
#include "../mkmpioboot/mkmpioboot.h" #include "../mkmpioboot/mkmpioboot.h"
@ -46,7 +47,7 @@ bool BootloaderInstallMpio::install(void)
if(m_offile.isEmpty()) if(m_offile.isEmpty())
return false; return false;
qDebug() << "[BootloaderInstallMpio] installing bootloader"; LOG_INFO() << "installing bootloader";
// download firmware from server // download firmware from server
emit logItem(tr("Downloading bootloader file"), LOGINFO); emit logItem(tr("Downloading bootloader file"), LOGINFO);
@ -59,7 +60,7 @@ bool BootloaderInstallMpio::install(void)
void BootloaderInstallMpio::installStage2(void) void BootloaderInstallMpio::installStage2(void)
{ {
qDebug() << "[BootloaderInstallMpio] installStage2"; LOG_INFO() << "installStage2";
int origin = 0xe0000; /* MPIO HD200 bootloader address */ int origin = 0xe0000; /* MPIO HD200 bootloader address */
@ -107,14 +108,14 @@ void BootloaderInstallMpio::installStage2(void)
break; break;
} }
qDebug() << "[BootloaderInstallMpio] Patching original firmware failed:" << error; LOG_ERROR() << "Patching original firmware failed:" << error;
emit logItem(tr("Patching original firmware failed: %1").arg(error), LOGERROR); emit logItem(tr("Patching original firmware failed: %1").arg(error), LOGERROR);
emit done(true); emit done(true);
return; return;
} }
//end of install //end of install
qDebug() << "[BootloaderInstallMpio] install successful"; LOG_INFO() << "install successful";
emit logItem(tr("Success: modified firmware file created"), LOGINFO); emit logItem(tr("Success: modified firmware file created"), LOGINFO);
logInstall(LogAdd); logInstall(LogAdd);
emit done(false); emit done(false);

View file

@ -19,6 +19,7 @@
#include <QtCore> #include <QtCore>
#include "bootloaderinstallbase.h" #include "bootloaderinstallbase.h"
#include "bootloaderinstallsansa.h" #include "bootloaderinstallsansa.h"
#include "Logger.h"
#include "../sansapatcher/sansapatcher.h" #include "../sansapatcher/sansapatcher.h"
#include "utils.h" #include "utils.h"
@ -116,7 +117,7 @@ void BootloaderInstallSansa::installStage2(void)
m_tempfile.close(); m_tempfile.close();
if(memcmp(sansa.targetname, magic, 4) != 0) { if(memcmp(sansa.targetname, magic, 4) != 0) {
emit logItem(tr("Bootloader mismatch! Aborting."), LOGERROR); emit logItem(tr("Bootloader mismatch! Aborting."), LOGERROR);
qDebug("[BootloaderInstallSansa] Targetname: %s, mi4 magic: %c%c%c%c", LOG_INFO("Targetname: %s, mi4 magic: %c%c%c%c",
sansa.targetname, magic[0], magic[1], magic[2], magic[3]); sansa.targetname, magic[0], magic[1], magic[2], magic[3]);
emit done(true); emit done(true);
sansa_close(&sansa); sansa_close(&sansa);
@ -157,7 +158,8 @@ void BootloaderInstallSansa::installStage3(bool mounted)
emit logItem(tr("Writing log aborted"), LOGERROR); emit logItem(tr("Writing log aborted"), LOGERROR);
emit done(true); emit done(true);
} }
qDebug() << "[BootloaderInstallSansa] version installed:" << m_blversion.toString(Qt::ISODate); LOG_INFO() << "version installed:"
<< m_blversion.toString(Qt::ISODate);
} }
@ -245,8 +247,8 @@ bool BootloaderInstallSansa::sansaInitialize(struct sansa_t *sansa)
sprintf(sansa->diskname, sprintf(sansa->diskname,
qPrintable(devicename.remove(QRegExp("[0-9]+$")))); qPrintable(devicename.remove(QRegExp("[0-9]+$"))));
#endif #endif
qDebug() << "[BootloaderInstallSansa] sansapatcher: overriding scan, using" LOG_INFO() << "sansapatcher: overriding scan, using"
<< sansa->diskname; << sansa->diskname;
} }
else if(sansa_scan(sansa) != 1) { else if(sansa_scan(sansa) != 1) {
emit logItem(tr("Can't find Sansa"), LOGERROR); emit logItem(tr("Can't find Sansa"), LOGERROR);

View file

@ -20,6 +20,7 @@
#include "encoderexe.h" #include "encoderexe.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "utils.h" #include "utils.h"
#include "Logger.h"
EncoderExe::EncoderExe(QString name,QObject *parent) : EncoderBase(parent) EncoderExe::EncoderExe(QString name,QObject *parent) : EncoderBase(parent)
{ {
@ -69,14 +70,13 @@ bool EncoderExe::start()
bool EncoderExe::encode(QString input,QString output) bool EncoderExe::encode(QString input,QString output)
{ {
//qDebug() << "encoding..";
QString execstring = m_EncTemplate; QString execstring = m_EncTemplate;
execstring.replace("%exe",m_EncExec); execstring.replace("%exe",m_EncExec);
execstring.replace("%options",m_EncOpts); execstring.replace("%options",m_EncOpts);
execstring.replace("%input",input); execstring.replace("%input",input);
execstring.replace("%output",output); execstring.replace("%output",output);
qDebug() << "[EncoderExe] cmd: " << execstring; LOG_INFO() << "cmd: " << execstring;
int result = QProcess::execute(execstring); int result = QProcess::execute(execstring);
return (result == 0) ? true : false; return (result == 0) ? true : false;
} }

View file

@ -20,13 +20,14 @@
#include "encoderlame.h" #include "encoderlame.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "lame/lame.h" #include "lame/lame.h"
#include "Logger.h"
/** Resolve a symbol from loaded library. /** Resolve a symbol from loaded library.
*/ */
#define SYMBOLRESOLVE(symbol, type) \ #define SYMBOLRESOLVE(symbol, type) \
do { m_##symbol = (type)lib->resolve(#symbol); \ do { m_##symbol = (type)lib->resolve(#symbol); \
if(!m_##symbol) return; \ if(!m_##symbol) return; \
qDebug() << "[EncoderLame] Resolved symbol " #symbol; } \ LOG_INFO() << "Resolved symbol " #symbol; } \
while(0) while(0)
EncoderLame::EncoderLame(QObject *parent) : EncoderBase(parent) EncoderLame::EncoderLame(QObject *parent) : EncoderBase(parent)
@ -50,7 +51,7 @@ EncoderLame::EncoderLame(QObject *parent) : EncoderBase(parent)
SYMBOLRESOLVE(lame_encode_flush, int (*)(lame_global_flags*, unsigned char*, int)); SYMBOLRESOLVE(lame_encode_flush, int (*)(lame_global_flags*, unsigned char*, int));
SYMBOLRESOLVE(lame_close, int (*)(lame_global_flags*)); SYMBOLRESOLVE(lame_close, int (*)(lame_global_flags*));
qDebug() << "[EncoderLame] libmp3lame loaded:" << lib->isLoaded(); LOG_INFO() << "libmp3lame loaded:" << lib->isLoaded();
m_encoderVolume = RbSettings::subValue("lame", RbSettings::EncoderVolume).toDouble(); m_encoderVolume = RbSettings::subValue("lame", RbSettings::EncoderVolume).toDouble();
m_encoderQuality = RbSettings::subValue("lame", RbSettings::EncoderQuality).toDouble(); m_encoderQuality = RbSettings::subValue("lame", RbSettings::EncoderQuality).toDouble();
@ -108,9 +109,9 @@ bool EncoderLame::start()
bool EncoderLame::encode(QString input,QString output) bool EncoderLame::encode(QString input,QString output)
{ {
qDebug() << "[EncoderLame] Encoding" << QDir::cleanPath(input); LOG_INFO() << "Encoding" << QDir::cleanPath(input);
if(!m_symbolsResolved) { if(!m_symbolsResolved) {
qDebug() << "[EncoderLame] Symbols not successfully resolved, cannot run!"; LOG_ERROR() << "Symbols not successfully resolved, cannot run!";
return false; return false;
} }
@ -144,21 +145,21 @@ bool EncoderLame::encode(QString input,QString output)
m_lame_set_bWriteVbrTag(gfp, 0); // disable LAME tag. m_lame_set_bWriteVbrTag(gfp, 0); // disable LAME tag.
if(!fin.open(QIODevice::ReadOnly)) { if(!fin.open(QIODevice::ReadOnly)) {
qDebug() << "[EncoderLame] Could not open input file" << input; LOG_ERROR() << "Could not open input file" << input;
return false; return false;
} }
// read RIFF header // read RIFF header
fin.read((char*)header, 12); fin.read((char*)header, 12);
if(memcmp("RIFF", header, 4) != 0) { if(memcmp("RIFF", header, 4) != 0) {
qDebug() << "[EncoderLame] RIFF header not found!" LOG_ERROR() << "RIFF header not found!"
<< header[0] << header[1] << header[2] << header[3]; << header[0] << header[1] << header[2] << header[3];
fin.close(); fin.close();
return false; return false;
} }
if(memcmp("WAVE", &header[8], 4) != 0) { if(memcmp("WAVE", &header[8], 4) != 0) {
qDebug() << "[EncoderLame] WAVE FOURCC not found!" LOG_ERROR() << "WAVE FOURCC not found!"
<< header[8] << header[9] << header[10] << header[11]; << header[8] << header[9] << header[10] << header[11];
fin.close(); fin.close();
return false; return false;
} }
@ -178,7 +179,7 @@ bool EncoderLame::encode(QString input,QString output)
// input format used should be known. In case some TTS uses a // input format used should be known. In case some TTS uses a
// different wave encoding some time this needs to get adjusted. // different wave encoding some time this needs to get adjusted.
if(chunkdatalen < 16) { if(chunkdatalen < 16) {
qDebug() << "[EncoderLame] fmt chunk too small!"; LOG_ERROR() << "fmt chunk too small!";
} }
else { else {
unsigned char *buf = new unsigned char[chunkdatalen]; unsigned char *buf = new unsigned char[chunkdatalen];
@ -196,18 +197,18 @@ bool EncoderLame::encode(QString input,QString output)
} }
else { else {
// unknown chunk, just skip its data. // unknown chunk, just skip its data.
qDebug() << "[EncoderLame] unknown chunk, skipping." LOG_WARNING() << "unknown chunk, skipping."
<< chunkheader[0] << chunkheader[1] << chunkheader[0] << chunkheader[1]
<< chunkheader[2] << chunkheader[3]; << chunkheader[2] << chunkheader[3];
fin.seek(fin.pos() + chunkdatalen); fin.seek(fin.pos() + chunkdatalen);
} }
} while(!fin.atEnd()); } while(!fin.atEnd());
// check format // check format
if(channels == 0 || samplerate == 0 || samplesize == 0 || datalength == 0) { if(channels == 0 || samplerate == 0 || samplesize == 0 || datalength == 0) {
qDebug() << "[EncoderLame] invalid format. Channels:" << channels LOG_ERROR() << "invalid format. Channels:" << channels
<< "Samplerate:" << samplerate << "Samplesize:" << samplesize << "Samplerate:" << samplerate << "Samplesize:" << samplesize
<< "Data chunk length:" << datalength; << "Data chunk length:" << datalength;
fin.close(); fin.close();
return false; return false;
} }
@ -220,7 +221,7 @@ bool EncoderLame::encode(QString input,QString output)
// initialize encoder. // initialize encoder.
ret = m_lame_init_params(gfp); ret = m_lame_init_params(gfp);
if(ret != 0) { if(ret != 0) {
qDebug() << "[EncoderLame] lame_init_params() failed with" << ret; LOG_ERROR() << "lame_init_params() failed with" << ret;
fin.close(); fin.close();
return false; return false;
} }
@ -230,7 +231,7 @@ bool EncoderLame::encode(QString input,QString output)
// bytes the input file has. This wastes space but should be ok. // bytes the input file has. This wastes space but should be ok.
// Put an upper limit of 8MiB. // Put an upper limit of 8MiB.
if(datalength > 8*1024*1024) { if(datalength > 8*1024*1024) {
qDebug() << "[EncoderLame] Input file too large:" << datalength; LOG_ERROR() << "Input file too large:" << datalength;
fin.close(); fin.close();
return false; return false;
} }
@ -255,7 +256,7 @@ bool EncoderLame::encode(QString input,QString output)
} }
} }
else { else {
qDebug() << "[EncoderLame] Unknown samplesize:" << samplesize; LOG_ERROR() << "Unknown samplesize:" << samplesize;
fin.close(); fin.close();
delete[] mp3buf; delete[] mp3buf;
delete[] wavbuf; delete[] wavbuf;
@ -270,10 +271,10 @@ bool EncoderLame::encode(QString input,QString output)
fout.open(QIODevice::ReadWrite); fout.open(QIODevice::ReadWrite);
ret = m_lame_encode_buffer(gfp, wavbuf, wavbuf, num_samples, mp3buf, mp3buflen); ret = m_lame_encode_buffer(gfp, wavbuf, wavbuf, num_samples, mp3buf, mp3buflen);
if(ret < 0) { if(ret < 0) {
qDebug() << "[EncoderLame] Error during encoding:" << ret; LOG_ERROR() << "Error during encoding:" << ret;
} }
if(fout.write((char*)mp3buf, ret) != (unsigned int)ret) { if(fout.write((char*)mp3buf, ret) != (unsigned int)ret) {
qDebug() << "[EncoderLame] Writing mp3 data failed!" << ret; LOG_ERROR() << "Writing mp3 data failed!" << ret;
fout.close(); fout.close();
delete[] mp3buf; delete[] mp3buf;
delete[] wavbuf; delete[] wavbuf;
@ -282,7 +283,7 @@ bool EncoderLame::encode(QString input,QString output)
// flush remaining data // flush remaining data
ret = m_lame_encode_flush(gfp, mp3buf, mp3buflen); ret = m_lame_encode_flush(gfp, mp3buf, mp3buflen);
if(fout.write((char*)mp3buf, ret) != (unsigned int)ret) { if(fout.write((char*)mp3buf, ret) != (unsigned int)ret) {
qDebug() << "[EncoderLame] Writing final mp3 data failed!"; LOG_ERROR() << "Writing final mp3 data failed!";
fout.close(); fout.close();
delete[] mp3buf; delete[] mp3buf;
delete[] wavbuf; delete[] wavbuf;

View file

@ -20,6 +20,7 @@
#include "encoderrbspeex.h" #include "encoderrbspeex.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "rbspeex.h" #include "rbspeex.h"
#include "Logger.h"
EncoderRbSpeex::EncoderRbSpeex(QObject *parent) : EncoderBase(parent) EncoderRbSpeex::EncoderRbSpeex(QObject *parent) : EncoderBase(parent)
{ {
@ -78,16 +79,16 @@ bool EncoderRbSpeex::start()
bool EncoderRbSpeex::encode(QString input,QString output) bool EncoderRbSpeex::encode(QString input,QString output)
{ {
qDebug() << "[RbSpeex] Encoding " << input << " to "<< output; LOG_INFO() << "Encoding " << input << " to "<< output;
char errstr[512]; char errstr[512];
FILE *fin,*fout; FILE *fin,*fout;
if ((fin = fopen(input.toLocal8Bit(), "rb")) == NULL) { if ((fin = fopen(input.toLocal8Bit(), "rb")) == NULL) {
qDebug() << "[RbSpeex] Error: could not open input file\n"; LOG_ERROR() << "Error: could not open input file\n";
return false; return false;
} }
if ((fout = fopen(output.toLocal8Bit(), "wb")) == NULL) { if ((fout = fopen(output.toLocal8Bit(), "wb")) == NULL) {
qDebug() << "[RbSpeex] Error: could not open output file\n"; LOG_ERROR() << "Error: could not open output file\n";
fclose(fin); fclose(fin);
return false; return false;
} }
@ -99,7 +100,7 @@ bool EncoderRbSpeex::encode(QString input,QString output)
if (!ret) { if (!ret) {
/* Attempt to delete unfinished output */ /* Attempt to delete unfinished output */
qDebug() << "[RbSpeex] Error:" << errstr; LOG_ERROR() << "Error:" << errstr;
QFile(output).remove(); QFile(output).remove();
return false; return false;
} }

View file

@ -23,6 +23,7 @@
#include <QNetworkRequest> #include <QNetworkRequest>
#include "httpget.h" #include "httpget.h"
#include "Logger.h"
QString HttpGet::m_globalUserAgent; //< globally set user agent for requests QString HttpGet::m_globalUserAgent; //< globally set user agent for requests
QDir HttpGet::m_globalCache; //< global cach path value for new objects QDir HttpGet::m_globalCache; //< global cach path value for new objects
@ -71,14 +72,14 @@ void HttpGet::setCache(bool c)
QString path = m_cachedir.absolutePath(); QString path = m_cachedir.absolutePath();
if(!c || m_cachedir.absolutePath().isEmpty()) { if(!c || m_cachedir.absolutePath().isEmpty()) {
qDebug() << "[HttpGet] disabling download cache"; LOG_INFO() << "disabling download cache";
} }
else { else {
// append the cache path to make it unique in case the path points to // append the cache path to make it unique in case the path points to
// the system temporary path. In that case using it directly might // the system temporary path. In that case using it directly might
// cause problems. Extra path also used in configure dialog. // cause problems. Extra path also used in configure dialog.
path += "/rbutil-cache"; path += "/rbutil-cache";
qDebug() << "[HttpGet] setting cache folder to" << path; LOG_INFO() << "setting cache folder to" << path;
m_cache = new QNetworkDiskCache(this); m_cache = new QNetworkDiskCache(this);
m_cache->setCacheDirectory(path); m_cache->setCacheDirectory(path);
} }
@ -97,7 +98,7 @@ QByteArray HttpGet::readAll()
void HttpGet::setProxy(const QUrl &proxy) void HttpGet::setProxy(const QUrl &proxy)
{ {
qDebug() << "[HttpGet] Proxy set to" << proxy; LOG_INFO() << "Proxy set to" << proxy;
m_proxy.setType(QNetworkProxy::HttpProxy); m_proxy.setType(QNetworkProxy::HttpProxy);
m_proxy.setHostName(proxy.host()); m_proxy.setHostName(proxy.host());
m_proxy.setPort(proxy.port()); m_proxy.setPort(proxy.port());
@ -130,10 +131,10 @@ void HttpGet::requestFinished(QNetworkReply* reply)
{ {
m_lastStatusCode m_lastStatusCode
= reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << "[HttpGet] Request finished, status code:" << m_lastStatusCode; LOG_INFO() << "Request finished, status code:" << m_lastStatusCode;
m_lastServerTimestamp m_lastServerTimestamp
= reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toLocalTime(); = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toLocalTime();
qDebug() << "[HttpGet] Data from cache:" LOG_INFO() << "Data from cache:"
<< reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); << reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
m_lastRequestCached = m_lastRequestCached =
reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
@ -150,7 +151,7 @@ void HttpGet::requestFinished(QNetworkReply* reply)
#else #else
url.setQuery(org.query()); url.setQuery(org.query());
#endif #endif
qDebug() << "[HttpGet] Redirected to" << url; LOG_INFO() << "Redirected to" << url;
startRequest(url); startRequest(url);
return; return;
} }
@ -179,7 +180,7 @@ void HttpGet::downloadProgress(qint64 received, qint64 total)
void HttpGet::startRequest(QUrl url) void HttpGet::startRequest(QUrl url)
{ {
qDebug() << "[HttpGet] Request started"; LOG_INFO() << "Request started";
QNetworkRequest req(url); QNetworkRequest req(url);
if(!m_globalUserAgent.isEmpty()) if(!m_globalUserAgent.isEmpty())
req.setRawHeader("User-Agent", m_globalUserAgent.toLatin1()); req.setRawHeader("User-Agent", m_globalUserAgent.toLatin1());
@ -194,15 +195,14 @@ void HttpGet::startRequest(QUrl url)
void HttpGet::networkError(QNetworkReply::NetworkError error) void HttpGet::networkError(QNetworkReply::NetworkError error)
{ {
qDebug() << "[HttpGet] NetworkError occured:" LOG_ERROR() << "NetworkError occured:" << error << m_reply->errorString();
<< error << m_reply->errorString();
m_lastErrorString = m_reply->errorString(); m_lastErrorString = m_reply->errorString();
} }
bool HttpGet::getFile(const QUrl &url) bool HttpGet::getFile(const QUrl &url)
{ {
qDebug() << "[HttpGet] Get URI" << url.toString(); LOG_INFO() << "Get URI" << url.toString();
m_data.clear(); m_data.clear();
startRequest(url); startRequest(url);

View file

@ -25,6 +25,7 @@
#include <QtCore> #include <QtCore>
#include <QtNetwork> #include <QtNetwork>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include "Logger.h"
class HttpGet : public QObject class HttpGet : public QObject
{ {
@ -49,13 +50,13 @@ class HttpGet : public QObject
//< set global cache path //< set global cache path
static void setGlobalCache(const QDir& d) static void setGlobalCache(const QDir& d)
{ {
qDebug() << "[HttpGet] Global cache set to" << d.absolutePath(); LOG_INFO() << "Global cache set to" << d.absolutePath();
m_globalCache = d; m_globalCache = d;
} }
//< set global proxy value //< set global proxy value
static void setGlobalProxy(const QUrl& p) static void setGlobalProxy(const QUrl& p)
{ {
qDebug() << "[HttpGet] setting global proxy" << p; LOG_INFO() << "setting global proxy" << p;
if(!p.isValid() || p.isEmpty()) { if(!p.isValid() || p.isEmpty()) {
HttpGet::m_globalProxy.setType(QNetworkProxy::NoProxy); HttpGet::m_globalProxy.setType(QNetworkProxy::NoProxy);
} }

View file

@ -17,7 +17,7 @@
****************************************************************************/ ****************************************************************************/
#include <QtCore> #include <QtCore>
#include <QDebug> #include "Logger.h"
#include "mspackutil.h" #include "mspackutil.h"
#include "progressloggerinterface.h" #include "progressloggerinterface.h"
@ -27,7 +27,7 @@ MsPackUtil::MsPackUtil(QObject* parent)
m_cabd = mspack_create_cab_decompressor(NULL); m_cabd = mspack_create_cab_decompressor(NULL);
m_cabinet = NULL; m_cabinet = NULL;
if(!m_cabd) if(!m_cabd)
qDebug() << "[MsPackUtil] CAB decompressor creation failed!"; LOG_ERROR() << "CAB decompressor creation failed!";
} }
MsPackUtil::~MsPackUtil() MsPackUtil::~MsPackUtil()
@ -43,7 +43,7 @@ bool MsPackUtil::open(QString& mspackfile)
if(m_cabd == NULL) if(m_cabd == NULL)
{ {
qDebug() << "[MsPackUtil] No CAB decompressor available: cannot open file!"; LOG_ERROR() << "No CAB decompressor available: cannot open file!";
return false; return false;
} }
m_cabinet = m_cabd->search(m_cabd, QFile::encodeName(mspackfile).constData()); m_cabinet = m_cabd->search(m_cabd, QFile::encodeName(mspackfile).constData());
@ -60,10 +60,10 @@ bool MsPackUtil::close(void)
bool MsPackUtil::extractArchive(const QString& dest, QString file) bool MsPackUtil::extractArchive(const QString& dest, QString file)
{ {
qDebug() << "[MsPackUtil] extractArchive" << dest << file; LOG_INFO() << "extractArchive" << dest << file;
if(!m_cabinet) if(!m_cabinet)
{ {
qDebug() << "[MsPackUtil] CAB file not open!"; LOG_ERROR() << "CAB file not open!";
return false; return false;
} }
@ -78,7 +78,7 @@ bool MsPackUtil::extractArchive(const QString& dest, QString file)
struct mscabd_file *f = m_cabinet->files; struct mscabd_file *f = m_cabinet->files;
if(f == NULL) if(f == NULL)
{ {
qDebug() << "[MsPackUtil] CAB doesn't contain file" << file; LOG_WARNING() << "CAB doesn't contain file" << file;
return true; return true;
} }
bool found = false; bool found = false;
@ -99,7 +99,7 @@ bool MsPackUtil::extractArchive(const QString& dest, QString file)
if(!QDir().mkpath(QFileInfo(path).absolutePath())) if(!QDir().mkpath(QFileInfo(path).absolutePath()))
{ {
emit logItem(tr("Creating output path failed"), LOGERROR); emit logItem(tr("Creating output path failed"), LOGERROR);
qDebug() << "[MsPackUtil] creating output path failed for:" << path; LOG_ERROR() << "creating output path failed for:" << path;
emit logProgress(1, 1); emit logProgress(1, 1);
return false; return false;
} }
@ -107,7 +107,8 @@ bool MsPackUtil::extractArchive(const QString& dest, QString file)
if(ret != MSPACK_ERR_OK) if(ret != MSPACK_ERR_OK)
{ {
emit logItem(tr("Error during CAB operation"), LOGERROR); emit logItem(tr("Error during CAB operation"), LOGERROR);
qDebug() << "[MsPackUtil] mspack error: " << ret << "(" << errorStringMsPack(ret) << ")"; LOG_ERROR() << "mspack error: " << ret
<< "(" << errorStringMsPack(ret) << ")";
emit logProgress(1, 1); emit logProgress(1, 1);
return false; return false;
} }
@ -125,7 +126,7 @@ QStringList MsPackUtil::files(void)
QStringList list; QStringList list;
if(!m_cabinet) if(!m_cabinet)
{ {
qDebug() << "[MsPackUtil] CAB file not open!"; LOG_WARNING() << "CAB file not open!";
return list; return list;
} }
struct mscabd_file *file = m_cabinet->files; struct mscabd_file *file = m_cabinet->files;

View file

@ -19,6 +19,7 @@
#include "rbsettings.h" #include "rbsettings.h"
#include "systeminfo.h" #include "systeminfo.h"
#include <QSettings> #include <QSettings>
#include "Logger.h"
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
#include <unistd.h> #include <unistd.h>
@ -96,13 +97,13 @@ void RbSettings::ensureRbSettingsExists()
{ {
userSettings = new QSettings(QCoreApplication::instance()->applicationDirPath() userSettings = new QSettings(QCoreApplication::instance()->applicationDirPath()
+ "/RockboxUtility.ini", QSettings::IniFormat, NULL); + "/RockboxUtility.ini", QSettings::IniFormat, NULL);
qDebug() << "[Settings] configuration: portable"; LOG_INFO() << "configuration: portable";
} }
else else
{ {
userSettings = new QSettings(QSettings::IniFormat, userSettings = new QSettings(QSettings::IniFormat,
QSettings::UserScope, "rockbox.org", "RockboxUtility",NULL); QSettings::UserScope, "rockbox.org", "RockboxUtility",NULL);
qDebug() << "[Settings] configuration: system"; LOG_INFO() << "configuration: system";
} }
} }
} }
@ -158,7 +159,7 @@ QVariant RbSettings::subValue(QString sub, enum UserSettings setting)
i++; i++;
QString s = constructSettingPath(UserSettingsList[i].name, sub); QString s = constructSettingPath(UserSettingsList[i].name, sub);
qDebug() << "[Settings] GET U:" << s << userSettings->value(s).toString(); LOG_INFO() << "GET U:" << s << userSettings->value(s).toString();
return userSettings->value(s, UserSettingsList[i].def); return userSettings->value(s, UserSettingsList[i].def);
} }
@ -179,7 +180,7 @@ void RbSettings::setSubValue(QString sub, enum UserSettings setting, QVariant va
QString s = constructSettingPath(UserSettingsList[i].name, sub); QString s = constructSettingPath(UserSettingsList[i].name, sub);
userSettings->setValue(s, value); userSettings->setValue(s, value);
qDebug() << "[Settings] SET U:" << s << userSettings->value(s).toString(); LOG_INFO() << "SET U:" << s << userSettings->value(s).toString();
} }
QString RbSettings::constructSettingPath(QString path, QString substitute) QString RbSettings::constructSettingPath(QString path, QString substitute)

View file

@ -20,10 +20,11 @@
#include <QtCore> #include <QtCore>
#include <QDebug> #include <QDebug>
#include "Logger.h"
RockboxInfo::RockboxInfo(QString mountpoint, QString fname) RockboxInfo::RockboxInfo(QString mountpoint, QString fname)
{ {
qDebug() << "[RockboxInfo] Getting version info from rockbox-info.txt"; LOG_INFO() << "Getting version info from rockbox-info.txt";
QFile file(mountpoint + "/" + fname); QFile file(mountpoint + "/" + fname);
m_success = false; m_success = false;
m_voicefmt = 400; // default value for compatibility m_voicefmt = 400; // default value for compatibility

View file

@ -19,6 +19,7 @@
#include "serverinfo.h" #include "serverinfo.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "systeminfo.h" #include "systeminfo.h"
#include "Logger.h"
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
#include <unistd.h> #include <unistd.h>
@ -181,7 +182,7 @@ QVariant ServerInfo::value(enum ServerInfos info)
QString s = ServerInfoList[i].name; QString s = ServerInfoList[i].name;
s.replace(":platform:", RbSettings::value(RbSettings::CurrentPlatform).toString()); s.replace(":platform:", RbSettings::value(RbSettings::CurrentPlatform).toString());
qDebug() << "[ServerInfo] GET:" << s << serverInfos.value(s, ServerInfoList[i].def).toString(); LOG_INFO() << "GET:" << s << serverInfos.value(s, ServerInfoList[i].def).toString();
return serverInfos.value(s, ServerInfoList[i].def); return serverInfos.value(s, ServerInfoList[i].def);
} }
@ -201,7 +202,7 @@ void ServerInfo::setPlatformValue(QString platform, enum ServerInfos info, QVari
QString s = ServerInfoList[i].name; QString s = ServerInfoList[i].name;
s.replace(":platform:", platform); s.replace(":platform:", platform);
serverInfos.insert(s, value); serverInfos.insert(s, value);
qDebug() << "[ServerInfo] SET:" << s << serverInfos.value(s).toString(); LOG_INFO() << "SET:" << s << serverInfos.value(s).toString();
} }
QVariant ServerInfo::platformValue(QString platform, enum ServerInfos info) QVariant ServerInfo::platformValue(QString platform, enum ServerInfos info)
@ -215,7 +216,7 @@ QVariant ServerInfo::platformValue(QString platform, enum ServerInfos info)
s.replace(":platform:", platform); s.replace(":platform:", platform);
QString d = ServerInfoList[i].def; QString d = ServerInfoList[i].def;
d.replace(":platform:", platform); d.replace(":platform:", platform);
qDebug() << "[ServerInfo] GET:" << s << serverInfos.value(s, d).toString(); LOG_INFO() << "GET:" << s << serverInfos.value(s, d).toString();
return serverInfos.value(s, d); return serverInfos.value(s, d);
} }

View file

@ -69,6 +69,7 @@
#include "utils.h" #include "utils.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "Logger.h"
/** @brief detect permission of user (only Windows at moment). /** @brief detect permission of user (only Windows at moment).
* @return enum userlevel. * @return enum userlevel.
@ -242,17 +243,17 @@ QMap<uint32_t, QString> System::listUsbDevices(void)
{ {
QMap<uint32_t, QString> usbids; QMap<uint32_t, QString> usbids;
// usb pid detection // usb pid detection
qDebug() << "[System] Searching for USB devices"; LOG_INFO() << "Searching for USB devices";
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
#if defined(LIBUSB1) #if defined(LIBUSB1)
libusb_device **devs; libusb_device **devs;
if(libusb_init(NULL) != 0) { if(libusb_init(NULL) != 0) {
qDebug() << "[System] Initializing libusb-1 failed."; LOG_ERROR() << "Initializing libusb-1 failed.";
return usbids; return usbids;
} }
if(libusb_get_device_list(NULL, &devs) < 1) { if(libusb_get_device_list(NULL, &devs) < 1) {
qDebug() << "[System] Error getting device list."; LOG_ERROR() << "Error getting device list.";
return usbids; return usbids;
} }
libusb_device *dev; libusb_device *dev;
@ -277,7 +278,7 @@ QMap<uint32_t, QString> System::listUsbDevices(void)
name = tr("(no description available)"); name = tr("(no description available)");
if(id) { if(id) {
usbids.insertMulti(id, name); usbids.insertMulti(id, name);
qDebug("[System] USB: 0x%08x, %s", id, name.toLocal8Bit().data()); LOG_INFO("USB: 0x%08x, %s", id, name.toLocal8Bit().data());
} }
} }
} }
@ -323,7 +324,7 @@ QMap<uint32_t, QString> System::listUsbDevices(void)
if(id) { if(id) {
usbids.insertMulti(id, name); usbids.insertMulti(id, name);
qDebug() << "[System] USB:" << QString("0x%1").arg(id, 8, 16) << name; LOG_INFO() << "USB:" << QString("0x%1").arg(id, 8, 16) << name;
} }
u = u->next; u = u->next;
} }
@ -341,7 +342,7 @@ QMap<uint32_t, QString> System::listUsbDevices(void)
result = IOServiceGetMatchingServices(kIOMasterPortDefault, usb_matching_dictionary, result = IOServiceGetMatchingServices(kIOMasterPortDefault, usb_matching_dictionary,
&usb_iterator); &usb_iterator);
if(result) { if(result) {
qDebug() << "[System] USB: IOKit: Could not get matching services."; LOG_ERROR() << "USB: IOKit: Could not get matching services.";
return usbids; return usbids;
} }
@ -404,7 +405,7 @@ QMap<uint32_t, QString> System::listUsbDevices(void)
if(id) { if(id) {
usbids.insertMulti(id, name); usbids.insertMulti(id, name);
qDebug() << "[System] USB:" << QString("0x%1").arg(id, 8, 16) << name; LOG_INFO() << "USB:" << QString("0x%1").arg(id, 8, 16) << name;
} }
} }
@ -468,7 +469,7 @@ QMap<uint32_t, QString> System::listUsbDevices(void)
uint32_t id; uint32_t id;
id = vid << 16 | pid; id = vid << 16 | pid;
usbids.insert(id, description); usbids.insert(id, description);
qDebug("[System] USB VID: %04x, PID: %04x", vid, pid); LOG_INFO("USB VID: %04x, PID: %04x", vid, pid);
} }
if(buffer) free(buffer); if(buffer) free(buffer);
} }
@ -507,7 +508,7 @@ QUrl System::systemProxy(void)
RegCloseKey(hk); RegCloseKey(hk);
//qDebug() << QString::fromWCharArray(proxyval) << QString("%1").arg(enable); //LOG_INFO() << QString::fromWCharArray(proxyval) << QString("%1").arg(enable);
if(enable != 0) if(enable != 0)
return QUrl("http://" + QString::fromWCharArray(proxyval)); return QUrl("http://" + QString::fromWCharArray(proxyval));
else else
@ -537,7 +538,7 @@ QUrl System::systemProxy(void)
bufsize = CFStringGetLength(stringref) * 2 + 1; bufsize = CFStringGetLength(stringref) * 2 + 1;
buf = (char*)malloc(sizeof(char) * bufsize); buf = (char*)malloc(sizeof(char) * bufsize);
if(buf == NULL) { if(buf == NULL) {
qDebug() << "[System] can't allocate memory for proxy string!"; LOG_ERROR() << "can't allocate memory for proxy string!";
CFRelease(dictref); CFRelease(dictref);
return QUrl(""); return QUrl("");
} }

View file

@ -20,6 +20,7 @@
#include "rbsettings.h" #include "rbsettings.h"
#include <QSettings> #include <QSettings>
#include "Logger.h"
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
#include <unistd.h> #include <unistd.h>
@ -89,7 +90,7 @@ QVariant SystemInfo::value(enum SystemInfos info)
s.replace(":platform:", platform); s.replace(":platform:", platform);
QString d = SystemInfosList[i].def; QString d = SystemInfosList[i].def;
d.replace(":platform:", platform); d.replace(":platform:", platform);
qDebug() << "[SystemInfo] GET:" << s << systemInfos->value(s, d).toString(); LOG_INFO() << "GET:" << s << systemInfos->value(s, d).toString();
return systemInfos->value(s, d); return systemInfos->value(s, d);
} }
@ -106,7 +107,7 @@ QVariant SystemInfo::platformValue(QString platform, enum SystemInfos info)
s.replace(":platform:", platform); s.replace(":platform:", platform);
QString d = SystemInfosList[i].def; QString d = SystemInfosList[i].def;
d.replace(":platform:", platform); d.replace(":platform:", platform);
qDebug() << "[SystemInfo] GET P:" << s << systemInfos->value(s, d).toString(); LOG_INFO() << "GET P:" << s << systemInfos->value(s, d).toString();
return systemInfos->value(s, d); return systemInfos->value(s, d);
} }

View file

@ -18,6 +18,7 @@
#include "talkfile.h" #include "talkfile.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "Logger.h"
TalkFileCreator::TalkFileCreator(QObject* parent): QObject(parent) TalkFileCreator::TalkFileCreator(QObject* parent): QObject(parent)
{ {
@ -109,7 +110,7 @@ void TalkFileCreator::doAbort()
//! \param startDir The directory from which to start scanning //! \param startDir The directory from which to start scanning
bool TalkFileCreator::createTalkList(QDir startDir) bool TalkFileCreator::createTalkList(QDir startDir)
{ {
qDebug() << "[TalkGenerator] generating list of files" << startDir; LOG_INFO() << "generating list of files" << startDir;
m_talkList.clear(); m_talkList.clear();
// create Iterator // create Iterator
@ -161,9 +162,9 @@ bool TalkFileCreator::createTalkList(QDir startDir)
entry.target = dir.path() + "/_dirname.talk"; entry.target = dir.path() + "/_dirname.talk";
entry.voiced = false; entry.voiced = false;
entry.encoded = false; entry.encoded = false;
qDebug() << "[TalkFileCreator] toSpeak:" << entry.toSpeak LOG_INFO() << "toSpeak:" << entry.toSpeak
<< "target:" << entry.target << "target:" << entry.target
<< "intermediates:" << entry.wavfilename << entry.talkfilename; << "intermediates:" << entry.wavfilename << entry.talkfilename;
m_talkList.append(entry); m_talkList.append(entry);
} }
} }
@ -205,16 +206,16 @@ bool TalkFileCreator::createTalkList(QDir startDir)
entry.target = fileInf.path() + "/" + fileInf.fileName() + ".talk"; entry.target = fileInf.path() + "/" + fileInf.fileName() + ".talk";
entry.voiced = false; entry.voiced = false;
entry.encoded = false; entry.encoded = false;
qDebug() << "[TalkFileCreator] toSpeak:" << entry.toSpeak LOG_INFO() << "toSpeak:" << entry.toSpeak
<< "target:" << entry.target << "target:" << entry.target
<< "intermediates:" << << "intermediates:"
entry.wavfilename << entry.talkfilename; << entry.wavfilename << entry.talkfilename;
m_talkList.append(entry); m_talkList.append(entry);
} }
} }
QCoreApplication::processEvents(); QCoreApplication::processEvents();
} }
qDebug() << "[TalkFileCreator] list created, entries:" << m_talkList.size(); LOG_INFO() << "list created, entries:" << m_talkList.size();
return true; return true;
} }
@ -251,8 +252,8 @@ bool TalkFileCreator::copyTalkFiles(QString* errString)
QFile::remove(m_talkList[i].target); QFile::remove(m_talkList[i].target);
// copying // copying
qDebug() << "[TalkFileCreator] copying" << m_talkList[i].talkfilename LOG_INFO() << "copying" << m_talkList[i].talkfilename
<< "to" << m_talkList[i].target; << "to" << m_talkList[i].target;
if(!QFile::copy(m_talkList[i].talkfilename,m_talkList[i].target)) if(!QFile::copy(m_talkList[i].talkfilename,m_talkList[i].target))
{ {
*errString = tr("Copying of %1 to %2 failed").arg(m_talkList[i].talkfilename).arg(m_talkList[i].target); *errString = tr("Copying of %1 to %2 failed").arg(m_talkList[i].talkfilename).arg(m_talkList[i].target);

View file

@ -20,6 +20,7 @@
#include "rbsettings.h" #include "rbsettings.h"
#include "systeminfo.h" #include "systeminfo.h"
#include "wavtrim.h" #include "wavtrim.h"
#include "Logger.h"
TalkGenerator::TalkGenerator(QObject* parent): QObject(parent) TalkGenerator::TalkGenerator(QObject* parent): QObject(parent)
{ {
@ -39,7 +40,7 @@ TalkGenerator::Status TalkGenerator::process(QList<TalkEntry>* list,int wavtrimt
m_tts = TTSBase::getTTS(this, RbSettings::value(RbSettings::Tts).toString()); m_tts = TTSBase::getTTS(this, RbSettings::value(RbSettings::Tts).toString());
if(!m_tts) if(!m_tts)
{ {
qDebug() << "[TalkGenerator] getting the TTS object failed!"; LOG_ERROR() << "getting the TTS object failed!";
emit logItem(tr("Init of TTS engine failed"), LOGERROR); emit logItem(tr("Init of TTS engine failed"), LOGERROR);
emit done(true); emit done(true);
return eERROR; return eERROR;
@ -131,7 +132,7 @@ TalkGenerator::Status TalkGenerator::voiceList(QList<TalkEntry>* list,int wavtri
duplicates.append(list->at(i).wavfilename); duplicates.append(list->at(i).wavfilename);
else else
{ {
qDebug() << "[TalkGenerator] duplicate skipped"; LOG_INFO() << "duplicate skipped";
(*list)[i].voiced = true; (*list)[i].voiced = true;
emit logProgress(++m_progress,progressMax); emit logProgress(++m_progress,progressMax);
continue; continue;
@ -152,7 +153,7 @@ TalkGenerator::Status TalkGenerator::voiceList(QList<TalkEntry>* list,int wavtri
// voice entry // voice entry
QString error; QString error;
qDebug() << "[TalkGenerator] voicing: " << list->at(i).toSpeak LOG_INFO() << "voicing: " << list->at(i).toSpeak
<< "to" << list->at(i).wavfilename; << "to" << list->at(i).wavfilename;
TTSStatus status = m_tts->voice(list->at(i).toSpeak,list->at(i).wavfilename, &error); TTSStatus status = m_tts->voice(list->at(i).toSpeak,list->at(i).wavfilename, &error);
if(status == Warning) if(status == Warning)
@ -177,8 +178,8 @@ TalkGenerator::Status TalkGenerator::voiceList(QList<TalkEntry>* list,int wavtri
if(wavtrim(list->at(i).wavfilename.toLocal8Bit().data(), if(wavtrim(list->at(i).wavfilename.toLocal8Bit().data(),
wavtrimth, buffer, 255)) wavtrimth, buffer, 255))
{ {
qDebug() << "[TalkGenerator] wavtrim returned error on" LOG_ERROR() << "wavtrim returned error on"
<< list->at(i).wavfilename; << list->at(i).wavfilename;
return eERROR; return eERROR;
} }
} }
@ -214,8 +215,8 @@ TalkGenerator::Status TalkGenerator::encodeList(QList<TalkEntry>* list)
//skip non-voiced entrys //skip non-voiced entrys
if(list->at(i).voiced == false) if(list->at(i).voiced == false)
{ {
qDebug() << "[TalkGenerator] non voiced entry detected:" LOG_WARNING() << "non voiced entry detected:"
<< list->at(i).toSpeak; << list->at(i).toSpeak;
emit logProgress(++m_progress,progressMax); emit logProgress(++m_progress,progressMax);
continue; continue;
} }
@ -224,15 +225,15 @@ TalkGenerator::Status TalkGenerator::encodeList(QList<TalkEntry>* list)
duplicates.append(list->at(i).talkfilename); duplicates.append(list->at(i).talkfilename);
else else
{ {
qDebug() << "[TalkGenerator] duplicate skipped"; LOG_INFO() << "duplicate skipped";
(*list)[i].encoded = true; (*list)[i].encoded = true;
emit logProgress(++m_progress,progressMax); emit logProgress(++m_progress,progressMax);
continue; continue;
} }
//encode entry //encode entry
qDebug() << "[TalkGenerator] encoding " << list->at(i).wavfilename LOG_INFO() << "encoding " << list->at(i).wavfilename
<< "to" << list->at(i).talkfilename; << "to" << list->at(i).talkfilename;
if(!m_enc->encode(list->at(i).wavfilename,list->at(i).talkfilename)) if(!m_enc->encode(list->at(i).wavfilename,list->at(i).talkfilename))
{ {
emit logItem(tr("Encoding of %1 failed").arg( emit logItem(tr("Encoding of %1 failed").arg(
@ -268,7 +269,7 @@ QString TalkGenerator::correctString(QString s)
} }
if(corrected != s) if(corrected != s)
qDebug() << "[VoiceFileCreator] corrected string" << s << "to" << corrected; LOG_INFO() << "corrected string" << s << "to" << corrected;
return corrected; return corrected;
m_abort = true; m_abort = true;
@ -287,7 +288,7 @@ void TalkGenerator::setLang(QString name)
TTSBase* tts = TTSBase::getTTS(this,RbSettings::value(RbSettings::Tts).toString()); TTSBase* tts = TTSBase::getTTS(this,RbSettings::value(RbSettings::Tts).toString());
if(!tts) if(!tts)
{ {
qDebug() << "[TalkGenerator] getting the TTS object failed!"; LOG_ERROR() << "getting the TTS object failed!";
return; return;
} }
QString vendor = tts->voiceVendor(); QString vendor = tts->voiceVendor();
@ -295,8 +296,8 @@ void TalkGenerator::setLang(QString name)
if(m_lang.isEmpty()) if(m_lang.isEmpty())
m_lang = "english"; m_lang = "english";
qDebug() << "[TalkGenerator] building string corrections list for" LOG_INFO() << "building string corrections list for"
<< m_lang << engine << vendor; << m_lang << engine << vendor;
QTextStream stream(&correctionsFile); QTextStream stream(&correctionsFile);
while(!stream.atEnd()) { while(!stream.atEnd()) {
QString line = stream.readLine(); QString line = stream.readLine();

View file

@ -28,6 +28,7 @@
#include <unistd.h> #include <unistd.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <inttypes.h> #include <inttypes.h>
#include "Logger.h"
TTSCarbon::TTSCarbon(QObject* parent) : TTSBase(parent) TTSCarbon::TTSCarbon(QObject* parent) : TTSBase(parent)
{ {
@ -74,7 +75,7 @@ bool TTSCarbon::start(QString *errStr)
if(voiceIndex == numVoices) { if(voiceIndex == numVoices) {
// voice not found. Add user notification here and proceed with // voice not found. Add user notification here and proceed with
// system default voice. // system default voice.
qDebug() << "[TTSCarbon] Selected voice not found, using system default!"; LOG_WARNING() << "Selected voice not found, using system default!";
GetVoiceDescription(&vspec, &vdesc, sizeof(vdesc)); GetVoiceDescription(&vspec, &vdesc, sizeof(vdesc));
if(vdesc.script != -1) if(vdesc.script != -1)
m_voiceScript = (CFStringBuiltInEncodings)vdesc.script; m_voiceScript = (CFStringBuiltInEncodings)vdesc.script;

View file

@ -20,6 +20,7 @@
#include "ttsexes.h" #include "ttsexes.h"
#include "utils.h" #include "utils.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "Logger.h"
TTSExes::TTSExes(QObject* parent) : TTSBase(parent) TTSExes::TTSExes(QObject* parent) : TTSBase(parent)
{ {
@ -85,15 +86,15 @@ TTSStatus TTSExes::voice(QString text, QString wavfile, QString *errStr)
QString execstring; QString execstring;
if(wavfile.isEmpty() && m_capabilities & TTSBase::CanSpeak) { if(wavfile.isEmpty() && m_capabilities & TTSBase::CanSpeak) {
if(m_TTSSpeakTemplate.isEmpty()) { if(m_TTSSpeakTemplate.isEmpty()) {
qDebug() << "[TTSExes] internal error: TTS announces CanSpeak " LOG_ERROR() << "internal error: TTS announces CanSpeak "
"but template empty!"; "but template empty!";
return FatalError; return FatalError;
} }
execstring = m_TTSSpeakTemplate; execstring = m_TTSSpeakTemplate;
} }
else if(wavfile.isEmpty()) { else if(wavfile.isEmpty()) {
qDebug() << "[TTSExes] no output file passed to voice() " LOG_ERROR() << "no output file passed to voice() "
"but TTS can't speak directly."; "but TTS can't speak directly.";
return FatalError; return FatalError;
} }
else { else {
@ -108,7 +109,7 @@ TTSStatus TTSExes::voice(QString text, QString wavfile, QString *errStr)
QProcess::execute(execstring); QProcess::execute(execstring);
if(!wavfile.isEmpty() && !QFileInfo(wavfile).isFile()) { if(!wavfile.isEmpty() && !QFileInfo(wavfile).isFile()) {
qDebug() << "[TTSExes] output file does not exist:" << wavfile; LOG_ERROR() << "output file does not exist:" << wavfile;
return FatalError; return FatalError;
} }
return NoError; return NoError;

View file

@ -22,10 +22,11 @@
#include "ttsfestival.h" #include "ttsfestival.h"
#include "utils.h" #include "utils.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "Logger.h"
TTSFestival::~TTSFestival() TTSFestival::~TTSFestival()
{ {
qDebug() << "[Festival] Destroying instance"; LOG_INFO() << "Destroying instance";
stop(); stop();
} }
@ -130,9 +131,10 @@ void TTSFestival::startServer()
QCoreApplication::processEvents(QEventLoop::AllEvents, 50); QCoreApplication::processEvents(QEventLoop::AllEvents, 50);
if(serverProcess.state() == QProcess::Running) if(serverProcess.state() == QProcess::Running)
qDebug() << "[Festival] Server is up and running"; LOG_INFO() << "Server is up and running";
else else
qDebug() << "[Festival] Server failed to start, state: " << serverProcess.state(); LOG_ERROR() << "Server failed to start, state:"
<< serverProcess.state();
} }
} }
@ -147,7 +149,8 @@ bool TTSFestival::ensureServerRunning()
bool TTSFestival::start(QString* errStr) bool TTSFestival::start(QString* errStr)
{ {
qDebug() << "[Festival] Starting server with voice " << RbSettings::subValue("festival", RbSettings::TtsVoice).toString(); LOG_INFO() << "Starting server with voice"
<< RbSettings::subValue("festival", RbSettings::TtsVoice).toString();
bool running = ensureServerRunning(); bool running = ensureServerRunning();
if (!RbSettings::subValue("festival",RbSettings::TtsVoice).toString().isEmpty()) if (!RbSettings::subValue("festival",RbSettings::TtsVoice).toString().isEmpty())
@ -162,7 +165,7 @@ bool TTSFestival::start(QString* errStr)
prologFile.write(voiceSelect.toLatin1()); prologFile.write(voiceSelect.toLatin1());
prologFile.close(); prologFile.close();
prologPath = QFileInfo(prologFile).absoluteFilePath(); prologPath = QFileInfo(prologFile).absoluteFilePath();
qDebug() << "[Festival] Prolog created at " << prologPath; LOG_INFO() << "Prolog created at" << prologPath;
} }
} }
@ -182,13 +185,13 @@ bool TTSFestival::stop()
TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr) TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr)
{ {
qDebug() << "[Festival] Voicing " << text << "->" << wavfile; LOG_INFO() << "Voicing" << text << "->" << wavfile;
QString path = RbSettings::subValue("festival-client", QString path = RbSettings::subValue("festival-client",
RbSettings::TtsPath).toString(); RbSettings::TtsPath).toString();
QString cmd = QString("%1 --server localhost --otype riff --ttw --withlisp" QString cmd = QString("%1 --server localhost --otype riff --ttw --withlisp"
" --output \"%2\" --prolog \"%3\" - ").arg(path).arg(wavfile).arg(prologPath); " --output \"%2\" --prolog \"%3\" - ").arg(path).arg(wavfile).arg(prologPath);
qDebug() << "[Festival] Client cmd: " << cmd; LOG_INFO() << "Client cmd:" << cmd;
QProcess clientProcess; QProcess clientProcess;
clientProcess.start(cmd); clientProcess.start(cmd);
@ -200,7 +203,7 @@ TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr)
response = response.trimmed(); response = response.trimmed();
if(!response.contains("Utterance")) if(!response.contains("Utterance"))
{ {
qDebug() << "[Festival] Could not voice string: " << response; LOG_WARNING() << "Could not voice string: " << response;
*errStr = tr("engine could not voice string"); *errStr = tr("engine could not voice string");
return Warning; return Warning;
/* do not stop the voicing process because of a single string /* do not stop the voicing process because of a single string
@ -245,7 +248,7 @@ QStringList TTSFestival::getVoiceList()
if(voices.size() > 0) if(voices.size() > 0)
{ {
qDebug() << "[Festival] Using voice cache"; LOG_INFO() << "Using voice cache";
return voices; return voices;
} }
@ -261,9 +264,9 @@ QStringList TTSFestival::getVoiceList()
if (voices.size() == 1 && voices[0].size() == 0) if (voices.size() == 1 && voices[0].size() == 0)
voices.removeAt(0); voices.removeAt(0);
if (voices.size() > 0) if (voices.size() > 0)
qDebug() << "[Festival] Voices: " << voices; LOG_INFO() << "Voices:" << voices;
else else
qDebug() << "[Festival] No voices. Response was: " << response; LOG_WARNING() << "No voices. Response was:" << response;
return voices; return voices;
} }
@ -290,7 +293,7 @@ QString TTSFestival::getVoiceInfo(QString voice)
{ {
response = response.remove(QRegExp("(description \"*\")", response = response.remove(QRegExp("(description \"*\")",
Qt::CaseInsensitive, QRegExp::Wildcard)); Qt::CaseInsensitive, QRegExp::Wildcard));
qDebug() << "[Festival] voiceInfo w/o descr: " << response; LOG_INFO() << "voiceInfo w/o descr:" << response;
response = response.remove(')'); response = response.remove(')');
QStringList responseLines = response.split('(', QString::SkipEmptyParts); QStringList responseLines = response.split('(', QString::SkipEmptyParts);
responseLines.removeAt(0); // the voice name itself responseLines.removeAt(0); // the voice name itself
@ -328,11 +331,11 @@ QString TTSFestival::queryServer(QString query, int timeout)
// this operation could take some time // this operation could take some time
emit busy(); emit busy();
qDebug() << "[Festival] queryServer with " << query; LOG_INFO() << "queryServer with" << query;
if (!ensureServerRunning()) if (!ensureServerRunning())
{ {
qDebug() << "[Festival] queryServer: ensureServerRunning failed"; LOG_ERROR() << "queryServer: ensureServerRunning failed";
emit busyEnd(); emit busyEnd();
return ""; return "";
} }
@ -393,7 +396,7 @@ QString TTSFestival::queryServer(QString query, int timeout)
lines.removeLast(); /* should be ft_StUfF_keyOK */ lines.removeLast(); /* should be ft_StUfF_keyOK */
} }
else else
qDebug() << "[Festival] Response too short: " << response; LOG_ERROR() << "Response too short:" << response;
emit busyEnd(); emit busyEnd();
return lines.join("\n"); return lines.join("\n");

View file

@ -20,6 +20,7 @@
#include "utils.h" #include "utils.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "systeminfo.h" #include "systeminfo.h"
#include "Logger.h"
TTSSapi::TTSSapi(QObject* parent) : TTSBase(parent) TTSSapi::TTSSapi(QObject* parent) : TTSBase(parent)
{ {
@ -89,7 +90,7 @@ void TTSSapi::saveSettings()
void TTSSapi::updateVoiceList() void TTSSapi::updateVoiceList()
{ {
qDebug() << "[TTSSapi] updating voicelist"; LOG_INFO() << "updating voicelist";
QStringList voiceList = getVoiceList(getSetting(eLANGUAGE)->current().toString()); QStringList voiceList = getVoiceList(getSetting(eLANGUAGE)->current().toString());
getSetting(eVOICE)->setList(voiceList); getSetting(eVOICE)->setList(voiceList);
if(voiceList.size() > 0) getSetting(eVOICE)->setCurrent(voiceList.at(0)); if(voiceList.size() > 0) getSetting(eVOICE)->setCurrent(voiceList.at(0));
@ -122,15 +123,15 @@ bool TTSSapi::start(QString *errStr)
execstring.replace("%voice",m_TTSVoice); execstring.replace("%voice",m_TTSVoice);
execstring.replace("%speed",m_TTSSpeed); execstring.replace("%speed",m_TTSSpeed);
qDebug() << "[TTSSapi] Start:" << execstring; LOG_INFO() << "Start:" << execstring;
voicescript = new QProcess(NULL); voicescript = new QProcess(NULL);
//connect(voicescript,SIGNAL(readyReadStandardError()),this,SLOT(error())); //connect(voicescript,SIGNAL(readyReadStandardError()),this,SLOT(error()));
voicescript->start(execstring); voicescript->start(execstring);
qDebug() << "[TTSSapi] wait for process"; LOG_INFO() << "wait for process";
if(!voicescript->waitForStarted()) if(!voicescript->waitForStarted())
{ {
*errStr = tr("Could not start SAPI process"); *errStr = tr("Could not start SAPI process");
qDebug() << "[TTSSapi] starting process timed out!"; LOG_ERROR() << "starting process timed out!";
return false; return false;
} }
@ -161,7 +162,7 @@ QString TTSSapi::voiceVendor(void)
while((vendor = voicestream->readLine()).isEmpty()) while((vendor = voicestream->readLine()).isEmpty())
QCoreApplication::processEvents(); QCoreApplication::processEvents();
qDebug() << "[TTSSAPI] TTS vendor:" << vendor; LOG_INFO() << "TTS vendor:" << vendor;
if(!keeprunning) { if(!keeprunning) {
stop(); stop();
} }
@ -184,12 +185,12 @@ QStringList TTSSapi::getVoiceList(QString language)
execstring.replace("%exe",m_TTSexec); execstring.replace("%exe",m_TTSexec);
execstring.replace("%lang",language); execstring.replace("%lang",language);
qDebug() << "[TTSSapi] Start:" << execstring; LOG_INFO() << "Start:" << execstring;
voicescript = new QProcess(NULL); voicescript = new QProcess(NULL);
voicescript->start(execstring); voicescript->start(execstring);
qDebug() << "[TTSSapi] wait for process"; LOG_INFO() << "wait for process";
if(!voicescript->waitForStarted()) { if(!voicescript->waitForStarted()) {
qDebug() << "[TTSSapi] process startup timed out!"; LOG_INFO() << "process startup timed out!";
return result; return result;
} }
voicescript->closeWriteChannel(); voicescript->closeWriteChannel();
@ -197,7 +198,7 @@ QStringList TTSSapi::getVoiceList(QString language)
QString dataRaw = voicescript->readAllStandardError().data(); QString dataRaw = voicescript->readAllStandardError().data();
if(dataRaw.startsWith("Error")) { if(dataRaw.startsWith("Error")) {
qDebug() << "[TTSSapi] Error:" << dataRaw; LOG_INFO() << "Error:" << dataRaw;
} }
result = dataRaw.split(";",QString::SkipEmptyParts); result = dataRaw.split(";",QString::SkipEmptyParts);
if(result.size() > 0) if(result.size() > 0)
@ -226,7 +227,7 @@ TTSStatus TTSSapi::voice(QString text,QString wavfile, QString *errStr)
{ {
(void) errStr; (void) errStr;
QString query = "SPEAK\t"+wavfile+"\t"+text; QString query = "SPEAK\t"+wavfile+"\t"+text;
qDebug() << "[TTSSapi] voicing" << query; LOG_INFO() << "voicing" << query;
// append newline to query. Done now to keep debug output more readable. // append newline to query. Done now to keep debug output more readable.
query.append("\r\n"); query.append("\r\n");
*voicestream << query; *voicestream << query;
@ -236,7 +237,7 @@ TTSStatus TTSSapi::voice(QString text,QString wavfile, QString *errStr)
voicescript->waitForReadyRead(); voicescript->waitForReadyRead();
if(!QFileInfo(wavfile).isFile()) { if(!QFileInfo(wavfile).isFile()) {
qDebug() << "[TTSSapi] output file does not exist:" << wavfile; LOG_ERROR() << "output file does not exist:" << wavfile;
return FatalError; return FatalError;
} }
return NoError; return NoError;

View file

@ -19,6 +19,7 @@
#include <QtCore> #include <QtCore>
#include "uninstall.h" #include "uninstall.h"
#include "utils.h" #include "utils.h"
#include "Logger.h"
Uninstaller::Uninstaller(QObject* parent,QString mountpoint): QObject(parent) Uninstaller::Uninstaller(QObject* parent,QString mountpoint): QObject(parent)
{ {
@ -66,7 +67,7 @@ void Uninstaller::uninstall(void)
if(installlog.contains(toDeleteList.at(j))) if(installlog.contains(toDeleteList.at(j)))
{ {
deleteFile = false; deleteFile = false;
qDebug() << "[Uninstaller] file still in use:" << toDeleteList.at(j); LOG_INFO() << "file still in use:" << toDeleteList.at(j);
} }
installlog.endGroup(); installlog.endGroup();
} }
@ -79,7 +80,7 @@ void Uninstaller::uninstall(void)
emit logItem(tr("Could not delete %1") emit logItem(tr("Could not delete %1")
.arg(toDelete.filePath()), LOGWARNING); .arg(toDelete.filePath()), LOGWARNING);
installlog.remove(toDeleteList.at(j)); installlog.remove(toDeleteList.at(j));
qDebug() << "[Uninstaller] deleted:" << toDelete.filePath(); LOG_INFO() << "deleted:" << toDelete.filePath();
} }
else // if it is a dir, remember it for later deletion else // if it is a dir, remember it for later deletion
{ {

View file

@ -21,6 +21,7 @@
#include "system.h" #include "system.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "systeminfo.h" #include "systeminfo.h"
#include "Logger.h"
#ifdef UNICODE #ifdef UNICODE
#define _UNICODE #define _UNICODE
@ -125,7 +126,7 @@ QString Utils::resolvePathCase(QString path)
else else
return QString(""); return QString("");
} }
qDebug() << "[Utils] resolving path" << path << "->" << realpath; LOG_INFO() << "resolving path" << path << "->" << realpath;
return realpath; return realpath;
} }
@ -179,7 +180,7 @@ QString Utils::filesystemName(QString path)
} while(result == noErr); } while(result == noErr);
#endif #endif
qDebug() << "[Utils] Volume name of" << path << "is" << name; LOG_INFO() << "Volume name of" << path << "is" << name;
return name; return name;
} }
@ -190,7 +191,7 @@ QString Utils::filesystemName(QString path)
qulonglong Utils::filesystemFree(QString path) qulonglong Utils::filesystemFree(QString path)
{ {
qulonglong size = filesystemSize(path, FilesystemFree); qulonglong size = filesystemSize(path, FilesystemFree);
qDebug() << "[Utils] free disk space for" << path << size; LOG_INFO() << "free disk space for" << path << size;
return size; return size;
} }
@ -198,7 +199,7 @@ qulonglong Utils::filesystemFree(QString path)
qulonglong Utils::filesystemTotal(QString path) qulonglong Utils::filesystemTotal(QString path)
{ {
qulonglong size = filesystemSize(path, FilesystemTotal); qulonglong size = filesystemSize(path, FilesystemTotal);
qDebug() << "[Utils] total disk space for" << path << size; LOG_INFO() << "total disk space for" << path << size;
return size; return size;
} }
@ -206,7 +207,7 @@ qulonglong Utils::filesystemTotal(QString path)
qulonglong Utils::filesystemClusterSize(QString path) qulonglong Utils::filesystemClusterSize(QString path)
{ {
qulonglong size = filesystemSize(path, FilesystemClusterSize); qulonglong size = filesystemSize(path, FilesystemClusterSize);
qDebug() << "[Utils] cluster size for" << path << size; LOG_INFO() << "cluster size for" << path << size;
return size; return size;
} }
@ -273,7 +274,7 @@ QString Utils::findExecutable(QString name)
#elif defined(Q_OS_WIN) #elif defined(Q_OS_WIN)
QStringList path = QString(getenv("PATH")).split(";", QString::SkipEmptyParts); QStringList path = QString(getenv("PATH")).split(";", QString::SkipEmptyParts);
#endif #endif
qDebug() << "[Utils] system path:" << path; LOG_INFO() << "system path:" << path;
for(int i = 0; i < path.size(); i++) for(int i = 0; i < path.size(); i++)
{ {
QString executable = QDir::fromNativeSeparators(path.at(i)) + "/" + name; QString executable = QDir::fromNativeSeparators(path.at(i)) + "/" + name;
@ -284,11 +285,11 @@ QString Utils::findExecutable(QString name)
#endif #endif
if(QFileInfo(executable).isExecutable()) if(QFileInfo(executable).isExecutable())
{ {
qDebug() << "[Utils] findExecutable: found" << executable; LOG_INFO() << "findExecutable: found" << executable;
return QDir::toNativeSeparators(executable); return QDir::toNativeSeparators(executable);
} }
} }
qDebug() << "[Utils] findExecutable: could not find" << name; LOG_INFO() << "findExecutable: could not find" << name;
return ""; return "";
} }
@ -299,7 +300,7 @@ QString Utils::findExecutable(QString name)
*/ */
QString Utils::checkEnvironment(bool permission) QString Utils::checkEnvironment(bool permission)
{ {
qDebug() << "[Utils] checking environment"; LOG_INFO() << "checking environment";
QString text = ""; QString text = "";
// check permission // check permission
@ -338,7 +339,7 @@ QString Utils::checkEnvironment(bool permission)
*/ */
int Utils::compareVersionStrings(QString s1, QString s2) int Utils::compareVersionStrings(QString s1, QString s2)
{ {
qDebug() << "[Utils] comparing version strings" << s1 << "and" << s2; LOG_INFO() << "comparing version strings" << s1 << "and" << s2;
QString a = s1.trimmed(); QString a = s1.trimmed();
QString b = s2.trimmed(); QString b = s2.trimmed();
// if strings are identical return 0. // if strings are identical return 0.
@ -418,7 +419,7 @@ int Utils::compareVersionStrings(QString s1, QString s2)
*/ */
QString Utils::resolveDevicename(QString path) QString Utils::resolveDevicename(QString path)
{ {
qDebug() << "[Utils] resolving device name" << path; LOG_INFO() << "resolving device name" << path;
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
FILE *mn = setmntent("/etc/mtab", "r"); FILE *mn = setmntent("/etc/mtab", "r");
if(!mn) if(!mn)
@ -434,7 +435,7 @@ QString Utils::resolveDevicename(QString path)
&& (QString(ent->mnt_type).contains("vfat", Qt::CaseInsensitive) && (QString(ent->mnt_type).contains("vfat", Qt::CaseInsensitive)
|| QString(ent->mnt_type).contains("hfs", Qt::CaseInsensitive))) { || QString(ent->mnt_type).contains("hfs", Qt::CaseInsensitive))) {
endmntent(mn); endmntent(mn);
qDebug() << "[Utils] device name is" << ent->mnt_fsname; LOG_INFO() << "device name is" << ent->mnt_fsname;
return QString(ent->mnt_fsname); return QString(ent->mnt_fsname);
} }
} }
@ -453,7 +454,7 @@ QString Utils::resolveDevicename(QString path)
if(QString(mntinf->f_mntonname) == path if(QString(mntinf->f_mntonname) == path
&& (QString(mntinf->f_fstypename).contains("msdos", Qt::CaseInsensitive) && (QString(mntinf->f_fstypename).contains("msdos", Qt::CaseInsensitive)
|| QString(mntinf->f_fstypename).contains("hfs", Qt::CaseInsensitive))) { || QString(mntinf->f_fstypename).contains("hfs", Qt::CaseInsensitive))) {
qDebug() << "[Utils] device name is" << mntinf->f_mntfromname; LOG_INFO() << "device name is" << mntinf->f_mntfromname;
return QString(mntinf->f_mntfromname); return QString(mntinf->f_mntfromname);
} }
mntinf++; mntinf++;
@ -471,17 +472,17 @@ QString Utils::resolveDevicename(QString path)
h = CreateFile(uncpath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, h = CreateFile(uncpath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL); NULL, OPEN_EXISTING, 0, NULL);
if(h == INVALID_HANDLE_VALUE) { if(h == INVALID_HANDLE_VALUE) {
//qDebug() << "error getting extents for" << uncpath; //LOG_INFO() << "error getting extents for" << uncpath;
return ""; return "";
} }
// get the extents // get the extents
if(DeviceIoControl(h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, if(DeviceIoControl(h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
NULL, 0, extents, sizeof(buffer), &written, NULL)) { NULL, 0, extents, sizeof(buffer), &written, NULL)) {
if(extents->NumberOfDiskExtents > 1) { if(extents->NumberOfDiskExtents > 1) {
qDebug() << "[Utils] resolving device name: volume spans multiple disks!"; LOG_INFO() << "resolving device name: volume spans multiple disks!";
return ""; return "";
} }
qDebug() << "[Utils] device name is" << extents->Extents[0].DiskNumber; LOG_INFO() << "device name is" << extents->Extents[0].DiskNumber;
return QString("%1").arg(extents->Extents[0].DiskNumber); return QString("%1").arg(extents->Extents[0].DiskNumber);
} }
#endif #endif
@ -496,7 +497,7 @@ QString Utils::resolveDevicename(QString path)
*/ */
QString Utils::resolveMountPoint(QString device) QString Utils::resolveMountPoint(QString device)
{ {
qDebug() << "[Utils] resolving mountpoint:" << device; LOG_INFO() << "resolving mountpoint:" << device;
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
FILE *mn = setmntent("/etc/mtab", "r"); FILE *mn = setmntent("/etc/mtab", "r");
@ -511,11 +512,11 @@ QString Utils::resolveMountPoint(QString device)
QString result; QString result;
if(QString(ent->mnt_type).contains("vfat", Qt::CaseInsensitive) if(QString(ent->mnt_type).contains("vfat", Qt::CaseInsensitive)
|| QString(ent->mnt_type).contains("hfs", Qt::CaseInsensitive)) { || QString(ent->mnt_type).contains("hfs", Qt::CaseInsensitive)) {
qDebug() << "[Utils] resolved mountpoint is:" << ent->mnt_dir; LOG_INFO() << "resolved mountpoint is:" << ent->mnt_dir;
result = QString(ent->mnt_dir); result = QString(ent->mnt_dir);
} }
else { else {
qDebug() << "[Utils] mountpoint is wrong filesystem!"; LOG_INFO() << "mountpoint is wrong filesystem!";
} }
endmntent(mn); endmntent(mn);
return result; return result;
@ -536,11 +537,11 @@ QString Utils::resolveMountPoint(QString device)
if(QString(mntinf->f_mntfromname) == device) { if(QString(mntinf->f_mntfromname) == device) {
if(QString(mntinf->f_fstypename).contains("msdos", Qt::CaseInsensitive) if(QString(mntinf->f_fstypename).contains("msdos", Qt::CaseInsensitive)
|| QString(mntinf->f_fstypename).contains("hfs", Qt::CaseInsensitive)) { || QString(mntinf->f_fstypename).contains("hfs", Qt::CaseInsensitive)) {
qDebug() << "[Utils] resolved mountpoint is:" << mntinf->f_mntonname; LOG_INFO() << "resolved mountpoint is:" << mntinf->f_mntonname;
return QString(mntinf->f_mntonname); return QString(mntinf->f_mntonname);
} }
else { else {
qDebug() << "[Utils] mountpoint is wrong filesystem!"; LOG_INFO() << "mountpoint is wrong filesystem!";
return QString(); return QString();
} }
} }
@ -556,14 +557,14 @@ QString Utils::resolveMountPoint(QString device)
for(letter = 'A'; letter <= 'Z'; letter++) { for(letter = 'A'; letter <= 'Z'; letter++) {
if(resolveDevicename(QString(letter)).toUInt() == driveno) { if(resolveDevicename(QString(letter)).toUInt() == driveno) {
result = letter; result = letter;
qDebug() << "[Utils] resolved mountpoint is:" << result; LOG_INFO() << "resolved mountpoint is:" << result;
break; break;
} }
} }
if(!result.isEmpty()) if(!result.isEmpty())
return result + ":/"; return result + ":/";
#endif #endif
qDebug() << "[Utils] resolving mountpoint failed!"; LOG_INFO() << "resolving mountpoint failed!";
return QString(""); return QString("");
} }
@ -589,11 +590,11 @@ QStringList Utils::mountpoints(enum MountpointsFilter type)
QString fstype = QString::fromWCharArray(t); QString fstype = QString::fromWCharArray(t);
if(type == MountpointsAll || supported.contains(fstype)) { if(type == MountpointsAll || supported.contains(fstype)) {
tempList << list.at(i).absolutePath(); tempList << list.at(i).absolutePath();
qDebug() << "[Utils] Added:" << list.at(i).absolutePath() LOG_INFO() << "Added:" << list.at(i).absolutePath()
<< "type" << fstype; << "type" << fstype;
} }
else { else {
qDebug() << "[Utils] Ignored:" << list.at(i).absolutePath() LOG_INFO() << "Ignored:" << list.at(i).absolutePath()
<< "type" << fstype; << "type" << fstype;
} }
} }
@ -607,11 +608,11 @@ QStringList Utils::mountpoints(enum MountpointsFilter type)
while(num--) { while(num--) {
if(type == MountpointsAll || supported.contains(mntinf->f_fstypename)) { if(type == MountpointsAll || supported.contains(mntinf->f_fstypename)) {
tempList << QString(mntinf->f_mntonname); tempList << QString(mntinf->f_mntonname);
qDebug() << "[Utils] Added:" << mntinf->f_mntonname LOG_INFO() << "Added:" << mntinf->f_mntonname
<< "is" << mntinf->f_mntfromname << "type" << mntinf->f_fstypename; << "is" << mntinf->f_mntfromname << "type" << mntinf->f_fstypename;
} }
else { else {
qDebug() << "[Utils] Ignored:" << mntinf->f_mntonname LOG_INFO() << "Ignored:" << mntinf->f_mntonname
<< "is" << mntinf->f_mntfromname << "type" << mntinf->f_fstypename; << "is" << mntinf->f_mntfromname << "type" << mntinf->f_fstypename;
} }
mntinf++; mntinf++;
@ -626,11 +627,11 @@ QStringList Utils::mountpoints(enum MountpointsFilter type)
while((ent = getmntent(mn))) { while((ent = getmntent(mn))) {
if(type == MountpointsAll || supported.contains(ent->mnt_type)) { if(type == MountpointsAll || supported.contains(ent->mnt_type)) {
tempList << QString(ent->mnt_dir); tempList << QString(ent->mnt_dir);
qDebug() << "[Utils] Added:" << ent->mnt_dir LOG_INFO() << "Added:" << ent->mnt_dir
<< "is" << ent->mnt_fsname << "type" << ent->mnt_type; << "is" << ent->mnt_fsname << "type" << ent->mnt_type;
} }
else { else {
qDebug() << "[Utils] Ignored:" << ent->mnt_dir LOG_INFO() << "Ignored:" << ent->mnt_dir
<< "is" << ent->mnt_fsname << "type" << ent->mnt_type; << "is" << ent->mnt_fsname << "type" << ent->mnt_type;
} }
} }
@ -658,13 +659,13 @@ QStringList Utils::findRunningProcess(QStringList names)
hdl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); hdl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hdl == INVALID_HANDLE_VALUE) { if(hdl == INVALID_HANDLE_VALUE) {
qDebug() << "[Utils] CreateToolhelp32Snapshot failed."; LOG_ERROR() << "CreateToolhelp32Snapshot failed.";
return found; return found;
} }
entry.dwSize = sizeof(PROCESSENTRY32); entry.dwSize = sizeof(PROCESSENTRY32);
entry.szExeFile[0] = '\0'; entry.szExeFile[0] = '\0';
if(!Process32First(hdl, &entry)) { if(!Process32First(hdl, &entry)) {
qDebug() << "[Utils] Process32First failed."; LOG_ERROR() << "Process32First failed.";
return found; return found;
} }
@ -721,7 +722,7 @@ QStringList Utils::findRunningProcess(QStringList names)
found.append(processlist.at(index)); found.append(processlist.at(index));
} }
} }
qDebug() << "[Utils] Found listed processes running:" << found; LOG_INFO() << "Found listed processes running:" << found;
return found; return found;
} }

View file

@ -23,6 +23,7 @@
#include "rbsettings.h" #include "rbsettings.h"
#include "systeminfo.h" #include "systeminfo.h"
#include "ziputil.h" #include "ziputil.h"
#include "Logger.h"
VoiceFileCreator::VoiceFileCreator(QObject* parent) :QObject(parent) VoiceFileCreator::VoiceFileCreator(QObject* parent) :QObject(parent)
{ {
@ -65,7 +66,7 @@ bool VoiceFileCreator::createVoiceFile()
// check if voicefile is present on target // check if voicefile is present on target
QString fn = m_mountpoint + "/.rockbox/langs/voicestrings.zip"; QString fn = m_mountpoint + "/.rockbox/langs/voicestrings.zip";
qDebug() << "[VoiceFile] searching for zipped voicestrings at" << fn; LOG_INFO() << "searching for zipped voicestrings at" << fn;
if(QFileInfo(fn).isFile()) { if(QFileInfo(fn).isFile()) {
// search for binary voice strings file in archive // search for binary voice strings file in archive
ZipUtil z(this); ZipUtil z(this);
@ -79,7 +80,7 @@ bool VoiceFileCreator::createVoiceFile()
} }
} }
if(index < contents.size()) { if(index < contents.size()) {
qDebug() << "[VoiceFile] extracting strings file from zip"; LOG_INFO() << "extracting strings file from zip";
// extract strings // extract strings
QTemporaryFile stringsfile; QTemporaryFile stringsfile;
stringsfile.open(); stringsfile.open();
@ -153,7 +154,7 @@ bool VoiceFileCreator::createVoiceFile()
genlang.replace("%REVISION%", version); genlang.replace("%REVISION%", version);
genlang.replace("%FEATURES%", features); genlang.replace("%FEATURES%", features);
QUrl genlangUrl(genlang); QUrl genlangUrl(genlang);
qDebug() << "[VoiceFileCreator] downloading" << genlangUrl; LOG_INFO() << "downloading" << genlangUrl;
//download the correct genlang output //download the correct genlang output
QTemporaryFile *downloadFile = new QTemporaryFile(this); QTemporaryFile *downloadFile = new QTemporaryFile(this);
@ -175,7 +176,7 @@ bool VoiceFileCreator::createVoiceFile()
void VoiceFileCreator::downloadDone(bool error) void VoiceFileCreator::downloadDone(bool error)
{ {
qDebug() << "[VoiceFileCreator] download done, error:" << error; LOG_INFO() << "download done, error:" << error;
// update progress bar // update progress bar
emit logProgress(1,1); emit logProgress(1,1);
@ -253,7 +254,7 @@ void VoiceFileCreator::create(void)
m_talkList.append(entry); m_talkList.append(entry);
} }
else if(entry.toSpeak.isEmpty()) { else if(entry.toSpeak.isEmpty()) {
qDebug() << "[Voicefile] Empty voice string for ID" << id; LOG_WARNING() << "Empty voice string for ID" << id;
} }
else { else {
m_talkList.append(entry); m_talkList.append(entry);
@ -314,7 +315,7 @@ void VoiceFileCreator::create(void)
return; return;
} }
qDebug() << "[VoiceFile] Running voicefont, format" << m_voiceformat; LOG_INFO() << "Running voicefont, format" << m_voiceformat;
voicefont(ids2,m_targetid,m_path.toLocal8Bit().data(), output, m_voiceformat); voicefont(ids2,m_targetid,m_path.toLocal8Bit().data(), output, m_voiceformat);
// ids2 and output are closed by voicefont(). // ids2 and output are closed by voicefont().

View file

@ -20,6 +20,7 @@
#include "zipinstaller.h" #include "zipinstaller.h"
#include "utils.h" #include "utils.h"
#include "ziputil.h" #include "ziputil.h"
#include "Logger.h"
ZipInstaller::ZipInstaller(QObject* parent): QObject(parent) ZipInstaller::ZipInstaller(QObject* parent): QObject(parent)
{ {
@ -31,7 +32,7 @@ ZipInstaller::ZipInstaller(QObject* parent): QObject(parent)
void ZipInstaller::install() void ZipInstaller::install()
{ {
qDebug() << "[ZipInstall] initializing installation"; LOG_INFO() << "initializing installation";
runner = 0; runner = 0;
connect(this, SIGNAL(cont()), this, SLOT(installContinue())); connect(this, SIGNAL(cont()), this, SLOT(installContinue()));
@ -44,17 +45,17 @@ void ZipInstaller::install()
void ZipInstaller::abort() void ZipInstaller::abort()
{ {
qDebug() << "[ZipInstall] Aborted"; LOG_INFO() << "Aborted";
emit internalAborted(); emit internalAborted();
} }
void ZipInstaller::installContinue() void ZipInstaller::installContinue()
{ {
qDebug() << "[ZipInstall] continuing installation"; LOG_INFO() << "continuing installation";
runner++; // this gets called when a install finished, so increase first. runner++; // this gets called when a install finished, so increase first.
qDebug() << "[ZipInstall] runner done:" << runner << "/" << m_urllist.size(); LOG_INFO() << "runner done:" << runner << "/" << m_urllist.size();
if(runner < m_urllist.size()) { if(runner < m_urllist.size()) {
emit logItem(tr("done."), LOGOK); emit logItem(tr("done."), LOGOK);
m_url = m_urllist.at(runner); m_url = m_urllist.at(runner);
@ -74,7 +75,7 @@ void ZipInstaller::installContinue()
void ZipInstaller::installStart() void ZipInstaller::installStart()
{ {
qDebug() << "[ZipInstall] starting installation"; LOG_INFO() << "starting installation";
emit logItem(tr("Downloading file %1.%2").arg(QFileInfo(m_url).baseName(), emit logItem(tr("Downloading file %1.%2").arg(QFileInfo(m_url).baseName(),
QFileInfo(m_url).completeSuffix()),LOGINFO); QFileInfo(m_url).completeSuffix()),LOGINFO);
@ -105,7 +106,7 @@ void ZipInstaller::installStart()
void ZipInstaller::downloadDone(bool error) void ZipInstaller::downloadDone(bool error)
{ {
qDebug() << "[ZipInstall] download done, error:" << error; LOG_INFO() << "download done, error:" << error;
QStringList zipContents; // needed later QStringList zipContents; // needed later
// update progress bar // update progress bar
@ -127,7 +128,7 @@ void ZipInstaller::downloadDone(bool error)
QCoreApplication::processEvents(); QCoreApplication::processEvents();
if(m_unzip) { if(m_unzip) {
// unzip downloaded file // unzip downloaded file
qDebug() << "[ZipInstall] about to unzip " << m_file << "to" << m_mountpoint; LOG_INFO() << "about to unzip" << m_file << "to" << m_mountpoint;
emit logItem(tr("Extracting file."), LOGINFO); emit logItem(tr("Extracting file."), LOGINFO);
QCoreApplication::processEvents(); QCoreApplication::processEvents();
@ -159,7 +160,7 @@ void ZipInstaller::downloadDone(bool error)
else { else {
// only copy the downloaded file to the output location / name // only copy the downloaded file to the output location / name
emit logItem(tr("Installing file."), LOGINFO); emit logItem(tr("Installing file."), LOGINFO);
qDebug() << "[ZipInstall] saving downloaded file (no extraction)"; LOG_INFO() << "saving downloaded file (no extraction)";
m_downloadFile->open(); // copy fails if file is not opened (filename issue?) m_downloadFile->open(); // copy fails if file is not opened (filename issue?)
// make sure the required path is existing // make sure the required path is existing

View file

@ -26,6 +26,7 @@
#include "progressloggerinterface.h" #include "progressloggerinterface.h"
#include "httpget.h" #include "httpget.h"
#include "Logger.h"
class ZipInstaller : public QObject class ZipInstaller : public QObject
{ {
@ -40,9 +41,9 @@ public:
void setLogSection(QString name) {m_loglist = QStringList(name);} void setLogSection(QString name) {m_loglist = QStringList(name);}
void setLogSection(QStringList name) { m_loglist = name; } void setLogSection(QStringList name) { m_loglist = name; }
void setLogVersion(QString v = "") void setLogVersion(QString v = "")
{ m_verlist = QStringList(v); qDebug() << m_verlist;} { m_verlist = QStringList(v); LOG_INFO() << m_verlist;}
void setLogVersion(QStringList v) void setLogVersion(QStringList v)
{ m_verlist = v; qDebug() << m_verlist;} { m_verlist = v; LOG_INFO() << m_verlist;}
void setUnzip(bool i) { m_unzip = i; } void setUnzip(bool i) { m_unzip = i; }
void setTarget(QString t) { m_target = t; } void setTarget(QString t) { m_target = t; }
void setCache(QDir c) { m_cache = c; m_usecache = true; }; void setCache(QDir c) { m_cache = c; m_usecache = true; };

View file

@ -20,6 +20,7 @@
#include <QDebug> #include <QDebug>
#include "ziputil.h" #include "ziputil.h"
#include "progressloggerinterface.h" #include "progressloggerinterface.h"
#include "Logger.h"
#include "quazip/quazip.h" #include "quazip/quazip.h"
#include "quazip/quazipfile.h" #include "quazip/quazipfile.h"
@ -76,7 +77,7 @@ bool ZipUtil::close(void)
//! @return true on success, false otherwise //! @return true on success, false otherwise
bool ZipUtil::extractArchive(const QString& dest, QString file) bool ZipUtil::extractArchive(const QString& dest, QString file)
{ {
qDebug() << "[ZipUtil] extractArchive" << dest << file; LOG_INFO() << "extractArchive" << dest << file;
bool result = true; bool result = true;
if(!m_zip) { if(!m_zip) {
return false; return false;
@ -122,15 +123,15 @@ bool ZipUtil::extractArchive(const QString& dest, QString file)
if(!QDir().mkpath(QFileInfo(outfilename).absolutePath())) { if(!QDir().mkpath(QFileInfo(outfilename).absolutePath())) {
result = false; result = false;
emit logItem(tr("Creating output path failed"), LOGERROR); emit logItem(tr("Creating output path failed"), LOGERROR);
qDebug() << "[ZipUtil] creating output path failed for:" LOG_INFO() << "creating output path failed for:"
<< outfilename; << outfilename;
break; break;
} }
if(!outputFile.open(QFile::WriteOnly)) { if(!outputFile.open(QFile::WriteOnly)) {
result = false; result = false;
emit logItem(tr("Creating output file failed"), LOGERROR); emit logItem(tr("Creating output file failed"), LOGERROR);
qDebug() << "[ZipUtil] creating output file failed:" LOG_INFO() << "creating output file failed:"
<< outfilename; << outfilename;
break; break;
} }
currentFile->open(QIODevice::ReadOnly); currentFile->open(QIODevice::ReadOnly);
@ -138,8 +139,8 @@ bool ZipUtil::extractArchive(const QString& dest, QString file)
if(currentFile->getZipError() != UNZ_OK) { if(currentFile->getZipError() != UNZ_OK) {
result = false; result = false;
emit logItem(tr("Error during Zip operation"), LOGERROR); emit logItem(tr("Error during Zip operation"), LOGERROR);
qDebug() << "[ZipUtil] QuaZip error:" << currentFile->getZipError() LOG_INFO() << "QuaZip error:" << currentFile->getZipError()
<< "on file" << currentFile->getFileName(); << "on file" << currentFile->getFileName();
break; break;
} }
currentFile->close(); currentFile->close();
@ -162,7 +163,7 @@ bool ZipUtil::appendDirToArchive(QString& source, QString& basedir)
{ {
bool result = true; bool result = true;
if(!m_zip || !m_zip->isOpen()) { if(!m_zip || !m_zip->isOpen()) {
qDebug() << "[ZipUtil] Zip file not open!"; LOG_INFO() << "Zip file not open!";
return false; return false;
} }
// get a list of all files and folders. Needed for progress info and avoids // get a list of all files and folders. Needed for progress info and avoids
@ -176,14 +177,14 @@ bool ZipUtil::appendDirToArchive(QString& source, QString& basedir)
fileList.append(iterator.filePath()); fileList.append(iterator.filePath());
} }
} }
qDebug() << "[ZipUtil] Adding" << fileList.size() << "files to archive"; LOG_INFO() << "Adding" << fileList.size() << "files to archive";
int max = fileList.size(); int max = fileList.size();
for(int i = 0; i < max; i++) { for(int i = 0; i < max; i++) {
QString current = fileList.at(i); QString current = fileList.at(i);
if(!appendFileToArchive(current, basedir)) { if(!appendFileToArchive(current, basedir)) {
qDebug() << "[ZipUtil] Error appending file" << current LOG_ERROR() << "Error appending file" << current
<< "to archive" << m_zip->getZipName(); << "to archive" << m_zip->getZipName();
result = false; result = false;
break; break;
} }
@ -199,7 +200,7 @@ bool ZipUtil::appendFileToArchive(QString& file, QString& basedir)
{ {
bool result = true; bool result = true;
if(!m_zip || !m_zip->isOpen()) { if(!m_zip || !m_zip->isOpen()) {
qDebug() << "[ZipUtil] Zip file not open!"; LOG_ERROR() << "Zip file not open!";
return false; return false;
} }
// skip folders, we can't add them. // skip folders, we can't add them.
@ -215,12 +216,12 @@ bool ZipUtil::appendFileToArchive(QString& file, QString& basedir)
QFile fin(file); QFile fin(file);
if(!fin.open(QFile::ReadOnly)) { if(!fin.open(QFile::ReadOnly)) {
qDebug() << "[ZipUtil] Could not open file for reading:" << file; LOG_ERROR() << "Could not open file for reading:" << file;
return false; return false;
} }
if(!fout.open(QIODevice::WriteOnly, QuaZipNewInfo(newfile, infile))) { if(!fout.open(QIODevice::WriteOnly, QuaZipNewInfo(newfile, infile))) {
fin.close(); fin.close();
qDebug() << "[ZipUtil] Could not open file for writing:" << newfile; LOG_ERROR() << "Could not open file for writing:" << newfile;
return false; return false;
} }
@ -253,11 +254,11 @@ qint64 ZipUtil::totalUncompressedSize(unsigned int clustersize)
} }
} }
if(clustersize > 0) { if(clustersize > 0) {
qDebug() << "[ZipUtil] calculation rounded to cluster size for each file:" LOG_INFO() << "calculation rounded to cluster size for each file:"
<< clustersize; << clustersize;
} }
qDebug() << "[ZipUtil] size of archive files uncompressed:" LOG_INFO() << "size of archive files uncompressed:"
<< uncompressed; << uncompressed;
return uncompressed; return uncompressed;
} }
@ -281,7 +282,7 @@ QList<QuaZipFileInfo> ZipUtil::contentProperties()
{ {
QList<QuaZipFileInfo> items; QList<QuaZipFileInfo> items;
if(!m_zip || !m_zip->isOpen()) { if(!m_zip || !m_zip->isOpen()) {
qDebug() << "[ZipUtil] Zip file not open!"; LOG_ERROR() << "Zip file not open!";
return items; return items;
} }
QuaZipFileInfo info; QuaZipFileInfo info;
@ -290,8 +291,8 @@ QList<QuaZipFileInfo> ZipUtil::contentProperties()
{ {
currentFile.getFileInfo(&info); currentFile.getFileInfo(&info);
if(currentFile.getZipError() != UNZ_OK) { if(currentFile.getZipError() != UNZ_OK) {
qDebug() << "[ZipUtil] QuaZip error:" << currentFile.getZipError() LOG_ERROR() << "QuaZip error:" << currentFile.getZipError()
<< "on file" << currentFile.getFileName(); << "on file" << currentFile.getFileName();
return QList<QuaZipFileInfo>(); return QList<QuaZipFileInfo>();
} }
items.append(info); items.append(info);

View file

@ -13,5 +13,6 @@ Version 1.4
* Save proxy password differently in configuration file (better solution for FS#12166). * Save proxy password differently in configuration file (better solution for FS#12166).
* Add support for building Rockbox Utility with Qt5. * Add support for building Rockbox Utility with Qt5.
* Add Changelog window. * Add Changelog window.
* Rework System Trace functionality.

View file

@ -47,6 +47,7 @@
#include "rbutilqt.h" #include "rbutilqt.h"
#include "systrace.h" #include "systrace.h"
#include "Logger.h"
#define DEFAULT_LANG "English (en)" #define DEFAULT_LANG "English (en)"
#define DEFAULT_LANG_CODE "en" #define DEFAULT_LANG_CODE "en"
@ -125,7 +126,7 @@ Config::Config(QWidget *parent,int index) : QDialog(parent)
void Config::accept() void Config::accept()
{ {
qDebug() << "[Config] checking configuration"; LOG_INFO() << "checking configuration";
QString errormsg = tr("The following errors occurred:") + "<ul>"; QString errormsg = tr("The following errors occurred:") + "<ul>";
bool error = false; bool error = false;
@ -154,7 +155,7 @@ void Config::accept()
QUrl p = proxy; QUrl p = proxy;
p.setPassword(proxy.password().toUtf8().toBase64()); p.setPassword(proxy.password().toUtf8().toBase64());
RbSettings::setValue(RbSettings::Proxy, p.toString()); RbSettings::setValue(RbSettings::Proxy, p.toString());
qDebug() << "[Config] setting proxy to:" << proxy.toString(QUrl::RemovePassword); LOG_INFO() << "setting proxy to:" << proxy.toString(QUrl::RemovePassword);
// proxy type // proxy type
QString proxyType; QString proxyType;
if(ui.radioNoProxy->isChecked()) proxyType = "none"; if(ui.radioNoProxy->isChecked()) proxyType = "none";
@ -240,7 +241,7 @@ void Config::accept()
void Config::abort() void Config::abort()
{ {
qDebug() << "[Config] aborted."; LOG_INFO() << "aborted.";
this->close(); this->close();
} }
@ -334,7 +335,7 @@ void Config::showProxyPassword(bool show)
void Config::showDisabled(bool show) void Config::showDisabled(bool show)
{ {
qDebug() << "[Config] disabled targets shown:" << show; LOG_INFO() << "disabled targets shown:" << show;
if(show) if(show)
QMessageBox::warning(this, tr("Showing disabled targets"), QMessageBox::warning(this, tr("Showing disabled targets"),
tr("You just enabled showing targets that are marked disabled. " tr("You just enabled showing targets that are marked disabled. "
@ -349,7 +350,7 @@ void Config::setDevices()
{ {
// setup devices table // setup devices table
qDebug() << "[Config] setting up devices list"; LOG_INFO() << "setting up devices list";
QStringList platformList; QStringList platformList;
if(ui.showDisabled->isChecked()) if(ui.showDisabled->isChecked())
@ -393,7 +394,7 @@ void Config::setDevices()
SystemInfo::CurName).toString() + SystemInfo::CurName).toString() +
" (" +ServerInfo::platformValue(platformList.at(it), " (" +ServerInfo::platformValue(platformList.at(it),
ServerInfo::CurStatus).toString() +")"; ServerInfo::CurStatus).toString() +")";
qDebug() << "[Config] add supported device:" << brands.at(c) << curname; LOG_INFO() << "add supported device:" << brands.at(c) << curname;
w2 = new QTreeWidgetItem(w, QStringList(curname)); w2 = new QTreeWidgetItem(w, QStringList(curname));
w2->setData(0, Qt::UserRole, platformList.at(it)); w2->setData(0, Qt::UserRole, platformList.at(it));
@ -516,7 +517,7 @@ void Config::setSystemProxy(bool checked)
proxy.setPort(ui.proxyPort->text().toInt()); proxy.setPort(ui.proxyPort->text().toInt());
// show system values in input box // show system values in input box
QUrl envproxy = System::systemProxy(); QUrl envproxy = System::systemProxy();
qDebug() << "[Config] setting system proxy" << envproxy; LOG_INFO() << "setting system proxy" << envproxy;
ui.proxyHost->setText(envproxy.host()); ui.proxyHost->setText(envproxy.host());
ui.proxyPort->setText(QString("%1").arg(envproxy.port())); ui.proxyPort->setText(QString("%1").arg(envproxy.port()));
@ -524,7 +525,7 @@ void Config::setSystemProxy(bool checked)
ui.proxyPass->setText(envproxy.password()); ui.proxyPass->setText(envproxy.password());
if(envproxy.host().isEmpty() || envproxy.port() == -1) { if(envproxy.host().isEmpty() || envproxy.port() == -1) {
qDebug() << "[Config] sytem proxy is invalid."; LOG_WARNING() << "system proxy is invalid.";
QMessageBox::warning(this, tr("Proxy Detection"), QMessageBox::warning(this, tr("Proxy Detection"),
tr("The System Proxy settings are invalid!\n" tr("The System Proxy settings are invalid!\n"
"Rockbox Utility can't work with this proxy settings. " "Rockbox Utility can't work with this proxy settings. "
@ -571,7 +572,7 @@ QStringList Config::findLanguageFiles()
langs.append(a); langs.append(a);
} }
langs.sort(); langs.sort();
qDebug() << "[Config] available lang files:" << langs; LOG_INFO() << "available lang files:" << langs;
return langs; return langs;
} }
@ -592,7 +593,7 @@ QString Config::languageName(const QString &qmFile)
void Config::updateLanguage() void Config::updateLanguage()
{ {
qDebug() << "[Config] update selected language"; LOG_INFO() << "update selected language";
// remove all old translators // remove all old translators
for(int i = 0; i < RbUtilQt::translators.size(); ++i) { for(int i = 0; i < RbUtilQt::translators.size(); ++i) {
@ -603,7 +604,7 @@ void Config::updateLanguage()
QList<QListWidgetItem*> a = ui.listLanguages->selectedItems(); QList<QListWidgetItem*> a = ui.listLanguages->selectedItems();
if(a.size() > 0) if(a.size() > 0)
language = lang.value(a.at(0)->text()); language = lang.value(a.at(0)->text());
qDebug() << "[Config] new language:" << language; LOG_INFO() << "new language:" << language;
QString applang = QLocale::system().name(); QString applang = QLocale::system().name();
QTranslator *translator = new QTranslator(qApp); QTranslator *translator = new QTranslator(qApp);
@ -668,7 +669,7 @@ void Config::refreshMountpoint()
ui.mountPoint->addItem(QDir::toNativeSeparators(mps.at(i)), description); ui.mountPoint->addItem(QDir::toNativeSeparators(mps.at(i)), description);
} }
else { else {
qDebug() << "[Config] mountpoint not writable, skipping:" << mps.at(i); LOG_WARNING() << "mountpoint not writable, skipping:" << mps.at(i);
} }
} }
if(!mountpoint.isEmpty()) { if(!mountpoint.isEmpty()) {
@ -682,7 +683,7 @@ void Config::updateMountpoint(QString m)
{ {
if(!m.isEmpty()) { if(!m.isEmpty()) {
mountpoint = QDir::fromNativeSeparators(m); mountpoint = QDir::fromNativeSeparators(m);
qDebug() << "[Config] Mountpoint set to" << mountpoint; LOG_INFO() << "Mountpoint set to" << mountpoint;
} }
} }
@ -695,7 +696,7 @@ void Config::updateMountpoint(int idx)
QString mp = ui.mountPoint->itemText(idx); QString mp = ui.mountPoint->itemText(idx);
if(!mp.isEmpty()) { if(!mp.isEmpty()) {
mountpoint = QDir::fromNativeSeparators(mp); mountpoint = QDir::fromNativeSeparators(mp);
qDebug() << "[Config] Mountpoint set to" << mountpoint; LOG_INFO() << "Mountpoint set to" << mountpoint;
} }
} }
@ -715,7 +716,7 @@ void Config::setMountpoint(QString m)
ui.mountPoint->addItem(QDir::toNativeSeparators(m)); ui.mountPoint->addItem(QDir::toNativeSeparators(m));
ui.mountPoint->setCurrentIndex(ui.mountPoint->findText(m)); ui.mountPoint->setCurrentIndex(ui.mountPoint->findText(m));
} }
qDebug() << "[Config] Mountpoint set to" << mountpoint; LOG_INFO() << "Mountpoint set to" << mountpoint;
} }

View file

@ -23,6 +23,7 @@
#include "configure.h" #include "configure.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "systeminfo.h" #include "systeminfo.h"
#include "Logger.h"
CreateVoiceWindow::CreateVoiceWindow(QWidget *parent) : QDialog(parent) CreateVoiceWindow::CreateVoiceWindow(QWidget *parent) : QDialog(parent)
{ {
@ -88,7 +89,7 @@ void CreateVoiceWindow::updateSettings(void)
f = languages.value(uilang).at(0); f = languages.value(uilang).at(0);
} }
sel = ui.comboLanguage->findData(f); sel = ui.comboLanguage->findData(f);
qDebug() << "[CreateVoiceWindow] Selected language index:" << sel; LOG_INFO() << "Selected language index:" << sel;
} }
ui.comboLanguage->setCurrentIndex(sel); ui.comboLanguage->setCurrentIndex(sel);

View file

@ -32,6 +32,7 @@
#include <QCheckBox> #include <QCheckBox>
#include <QProgressDialog> #include <QProgressDialog>
#include "encttscfggui.h" #include "encttscfggui.h"
#include "Logger.h"
EncTtsCfgGui::EncTtsCfgGui(QDialog* parent, EncTtsSettingInterface* iface, QString name) EncTtsCfgGui::EncTtsCfgGui(QDialog* parent, EncTtsSettingInterface* iface, QString name)
: QDialog(parent) : QDialog(parent)
@ -174,7 +175,7 @@ QWidget* EncTtsCfgGui::createWidgets(EncTtsSetting* setting)
} }
default: default:
{ {
qDebug() << "Warning: unknown EncTTsSetting type" << setting->type(); LOG_WARNING() << "Warning: unknown EncTTsSetting type" << setting->type();
break; break;
} }
} }
@ -252,7 +253,7 @@ void EncTtsCfgGui::updateSetting()
} }
default: default:
{ {
qDebug() << "unknown Settingtype !!"; LOG_WARNING() << "unknown setting type!";
break; break;
} }
} }
@ -331,7 +332,7 @@ void EncTtsCfgGui::updateWidget()
} }
default: default:
{ {
qDebug() << "unknown EncTTsSetting"; LOG_WARNING() << "unknown EncTTsSetting";
break; break;
} }
} }

View file

@ -26,6 +26,7 @@
#include "progressloggergui.h" #include "progressloggergui.h"
#include "ziputil.h" #include "ziputil.h"
#include "rockboxinfo.h" #include "rockboxinfo.h"
#include "Logger.h"
class BackupSizeThread : public QThread class BackupSizeThread : public QThread
{ {
@ -42,14 +43,14 @@ class BackupSizeThread : public QThread
void BackupSizeThread::run(void) void BackupSizeThread::run(void)
{ {
qDebug() << "BackupSizeThread] Thread started, calculating" << m_path; LOG_INFO() << "Thread started, calculating" << m_path;
m_currentSize = 0; m_currentSize = 0;
QDirIterator it(m_path, QDirIterator::Subdirectories); QDirIterator it(m_path, QDirIterator::Subdirectories);
while(it.hasNext()) { while(it.hasNext()) {
m_currentSize += QFileInfo(it.next()).size(); m_currentSize += QFileInfo(it.next()).size();
} }
qDebug() << "[BackupSizeThread] Thread done, sum:" << m_currentSize; LOG_INFO() << "Thread done, sum:" << m_currentSize;
} }

View file

@ -20,6 +20,7 @@
#include <QDebug> #include <QDebug>
#include "infowidget.h" #include "infowidget.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "Logger.h"
InfoWidget::InfoWidget(QWidget *parent) : QWidget(parent) InfoWidget::InfoWidget(QWidget *parent) : QWidget(parent)
{ {
@ -35,7 +36,7 @@ InfoWidget::InfoWidget(QWidget *parent) : QWidget(parent)
void InfoWidget::updateInfo(void) void InfoWidget::updateInfo(void)
{ {
qDebug() << "[InfoWidget] updating server info"; LOG_INFO() << "updating server info";
QString mp = RbSettings::value(RbSettings::Mountpoint).toString(); QString mp = RbSettings::value(RbSettings::Mountpoint).toString();
QSettings log(mp + "/.rockbox/rbutil.log", QSettings::IniFormat, this); QSettings log(mp + "/.rockbox/rbutil.log", QSettings::IniFormat, this);

View file

@ -24,6 +24,7 @@
#include "rbsettings.h" #include "rbsettings.h"
#include "serverinfo.h" #include "serverinfo.h"
#include "systeminfo.h" #include "systeminfo.h"
#include "Logger.h"
ManualWidget::ManualWidget(QWidget *parent) : QWidget(parent) ManualWidget::ManualWidget(QWidget *parent) : QWidget(parent)
{ {
@ -36,7 +37,7 @@ ManualWidget::ManualWidget(QWidget *parent) : QWidget(parent)
void ManualWidget::updateManual() void ManualWidget::updateManual()
{ {
qDebug() << "[ManualWidget] updating manual URLs"; LOG_INFO() << "updating manual URLs";
m_platform = RbSettings::value(RbSettings::Platform).toString(); m_platform = RbSettings::value(RbSettings::Platform).toString();
if(!m_platform.isEmpty()) if(!m_platform.isEmpty())
{ {

View file

@ -30,6 +30,7 @@
#include "bootloaderinstallhelper.h" #include "bootloaderinstallhelper.h"
#include "themesinstallwindow.h" #include "themesinstallwindow.h"
#include "utils.h" #include "utils.h"
#include "Logger.h"
SelectiveInstallWidget::SelectiveInstallWidget(QWidget* parent) : QWidget(parent) SelectiveInstallWidget::SelectiveInstallWidget(QWidget* parent) : QWidget(parent)
{ {
@ -147,7 +148,7 @@ void SelectiveInstallWidget::updateVersion(void)
void SelectiveInstallWidget::saveSettings(void) void SelectiveInstallWidget::saveSettings(void)
{ {
qDebug() << "[SelectiveInstallWidget] saving current settings"; LOG_INFO() << "saving current settings";
RbSettings::setValue(RbSettings::InstallRockbox, ui.rockboxCheckbox->isChecked()); RbSettings::setValue(RbSettings::InstallRockbox, ui.rockboxCheckbox->isChecked());
RbSettings::setValue(RbSettings::InstallFonts, ui.fontsCheckbox->isChecked()); RbSettings::setValue(RbSettings::InstallFonts, ui.fontsCheckbox->isChecked());
@ -158,7 +159,7 @@ void SelectiveInstallWidget::saveSettings(void)
void SelectiveInstallWidget::startInstall(void) void SelectiveInstallWidget::startInstall(void)
{ {
qDebug() << "[SelectiveInstallWidget] starting installation"; LOG_INFO() << "starting installation";
saveSettings(); saveSettings();
m_installStage = 0; m_installStage = 0;
@ -191,15 +192,15 @@ void SelectiveInstallWidget::startInstall(void)
void SelectiveInstallWidget::continueInstall(bool error) void SelectiveInstallWidget::continueInstall(bool error)
{ {
qDebug() << "[SelectiveInstallWidget] continuing install with stage" << m_installStage; LOG_INFO() << "continuing install with stage" << m_installStage;
if(error) { if(error) {
qDebug() << "[SelectiveInstallWidget] Last part returned error."; LOG_ERROR() << "Last part returned error.";
m_logger->setFinished(); m_logger->setFinished();
m_installStage = 7; m_installStage = 7;
} }
m_installStage++; m_installStage++;
switch(m_installStage) { switch(m_installStage) {
case 0: qDebug() << "[SelectiveInstallWidget] Something wrong!"; break; case 0: LOG_ERROR() << "Something wrong!"; break;
case 1: installBootloader(); break; case 1: installBootloader(); break;
case 2: installRockbox(); break; case 2: installRockbox(); break;
case 3: installFonts(); break; case 3: installFonts(); break;
@ -210,7 +211,7 @@ void SelectiveInstallWidget::continueInstall(bool error)
} }
if(m_installStage > 6) { if(m_installStage > 6) {
qDebug() << "[SelectiveInstallWidget] All install stages done."; LOG_INFO() << "All install stages done.";
m_logger->setFinished(); m_logger->setFinished();
if(m_blmethod != "none") { if(m_blmethod != "none") {
// check if Rockbox is installed by looking after rockbox-info.txt. // check if Rockbox is installed by looking after rockbox-info.txt.
@ -225,7 +226,7 @@ void SelectiveInstallWidget::continueInstall(bool error)
void SelectiveInstallWidget::installBootloader(void) void SelectiveInstallWidget::installBootloader(void)
{ {
if(ui.bootloaderCheckbox->isChecked()) { if(ui.bootloaderCheckbox->isChecked()) {
qDebug() << "[SelectiveInstallWidget] installing bootloader"; LOG_INFO() << "installing bootloader";
QString platform = RbSettings::value(RbSettings::Platform).toString(); QString platform = RbSettings::value(RbSettings::Platform).toString();
QString backupDestination = ""; QString backupDestination = "";
@ -292,7 +293,7 @@ void SelectiveInstallWidget::installBootloader(void)
if(!backupDestination.isEmpty()) if(!backupDestination.isEmpty())
backupDestination += "/" + targetFolder; backupDestination += "/" + targetFolder;
qDebug() << "[RbUtil] backing up to" << backupDestination; LOG_INFO() << "backing up to" << backupDestination;
// backup needs to be done after the m_logger has been set up. // backup needs to be done after the m_logger has been set up.
} }
} }
@ -350,7 +351,7 @@ void SelectiveInstallWidget::installBootloader(void)
} }
else { else {
qDebug() << "[SelectiveInstallWidget] Bootloader install disabled."; LOG_INFO() << "Bootloader install disabled.";
emit installSkipped(false); emit installSkipped(false);
} }
} }
@ -372,7 +373,7 @@ void SelectiveInstallWidget::installBootloaderPost()
void SelectiveInstallWidget::installRockbox(void) void SelectiveInstallWidget::installRockbox(void)
{ {
if(ui.rockboxCheckbox->isChecked()) { if(ui.rockboxCheckbox->isChecked()) {
qDebug() << "[SelectiveInstallWidget] installing Rockbox"; LOG_INFO() << "installing Rockbox";
QString url; QString url;
QString selected = ui.selectedVersion->itemData(ui.selectedVersion->currentIndex()).toString(); QString selected = ui.selectedVersion->itemData(ui.selectedVersion->currentIndex()).toString();
@ -405,7 +406,7 @@ void SelectiveInstallWidget::installRockbox(void)
} }
else { else {
qDebug() << "[SelectiveInstallWidget] Rockbox install disabled."; LOG_INFO() << "Rockbox install disabled.";
emit installSkipped(false); emit installSkipped(false);
} }
} }
@ -414,7 +415,7 @@ void SelectiveInstallWidget::installRockbox(void)
void SelectiveInstallWidget::installFonts(void) void SelectiveInstallWidget::installFonts(void)
{ {
if(ui.fontsCheckbox->isChecked()) { if(ui.fontsCheckbox->isChecked()) {
qDebug() << "[SelectiveInstallWidget] installing Fonts"; LOG_INFO() << "installing Fonts";
RockboxInfo installInfo(m_mountpoint); RockboxInfo installInfo(m_mountpoint);
QString fontsurl; QString fontsurl;
@ -447,7 +448,7 @@ void SelectiveInstallWidget::installFonts(void)
m_zipinstaller->install(); m_zipinstaller->install();
} }
else { else {
qDebug() << "[SelectiveInstallWidget] Fonts install disabled."; LOG_INFO() << "Fonts install disabled.";
emit installSkipped(false); emit installSkipped(false);
} }
} }
@ -465,7 +466,7 @@ void SelectiveInstallWidget::customizeThemes(void)
void SelectiveInstallWidget::installThemes(void) void SelectiveInstallWidget::installThemes(void)
{ {
if(ui.themesCheckbox->isChecked()) { if(ui.themesCheckbox->isChecked()) {
qDebug() << "[SelectiveInstallWidget] installing themes"; LOG_INFO() << "installing themes";
if(m_themesinstaller == NULL) if(m_themesinstaller == NULL)
m_themesinstaller = new ThemesInstallWindow(this); m_themesinstaller = new ThemesInstallWindow(this);
@ -475,7 +476,7 @@ void SelectiveInstallWidget::installThemes(void)
m_themesinstaller->install(); m_themesinstaller->install();
} }
else { else {
qDebug() << "[SelectiveInstallWidget] Themes install disabled."; LOG_INFO() << "Themes install disabled.";
emit installSkipped(false); emit installSkipped(false);
} }
} }
@ -489,7 +490,7 @@ void SelectiveInstallWidget::installGamefiles(void)
m_logger->addItem(tr("Your installation doesn't require game files, skipping."), LOGINFO); m_logger->addItem(tr("Your installation doesn't require game files, skipping."), LOGINFO);
emit installSkipped(false); emit installSkipped(false);
} }
qDebug() << "[SelectiveInstallWidget] installing gamefiles"; LOG_INFO() << "installing gamefiles";
// create new zip installer // create new zip installer
if(m_zipinstaller != NULL) m_zipinstaller->deleteLater(); if(m_zipinstaller != NULL) m_zipinstaller->deleteLater();
m_zipinstaller = new ZipInstaller(this); m_zipinstaller = new ZipInstaller(this);
@ -507,7 +508,7 @@ void SelectiveInstallWidget::installGamefiles(void)
m_zipinstaller->install(); m_zipinstaller->install();
} }
else { else {
qDebug() << "[SelectiveInstallWidget] Gamefile install disabled."; LOG_INFO() << "Gamefile install disabled.";
emit installSkipped(false); emit installSkipped(false);
} }
} }

View file

@ -23,6 +23,7 @@
#include "configure.h" #include "configure.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "systeminfo.h" #include "systeminfo.h"
#include "Logger.h"
InstallTalkWindow::InstallTalkWindow(QWidget *parent) : QDialog(parent) InstallTalkWindow::InstallTalkWindow(QWidget *parent) : QDialog(parent)
{ {
@ -118,8 +119,8 @@ void InstallTalkWindow::accept()
connect(logger,SIGNAL(aborted()),talkcreator,SLOT(abort())); connect(logger,SIGNAL(aborted()),talkcreator,SLOT(abort()));
for(int i = 0; i < foldersToTalk.size(); i++) { for(int i = 0; i < foldersToTalk.size(); i++) {
qDebug() << "[InstallTalkWindow] creating talk files for folder" LOG_INFO() << "creating talk files for folder"
<< foldersToTalk.at(i); << foldersToTalk.at(i);
talkcreator->setDir(foldersToTalk.at(i)); talkcreator->setDir(foldersToTalk.at(i));
talkcreator->createTalkFiles(); talkcreator->createTalkFiles();
} }

View file

@ -0,0 +1,58 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
// Local
#include "AbstractAppender.h"
// Qt
#include <QMutexLocker>
AbstractAppender::AbstractAppender()
: m_detailsLevel(Logger::Debug)
{}
AbstractAppender::~AbstractAppender()
{}
Logger::LogLevel AbstractAppender::detailsLevel() const
{
QMutexLocker locker(&m_detailsLevelMutex);
return m_detailsLevel;
}
void AbstractAppender::setDetailsLevel(Logger::LogLevel level)
{
QMutexLocker locker(&m_detailsLevelMutex);
m_detailsLevel = level;
}
void AbstractAppender::setDetailsLevel(const QString& level)
{
setDetailsLevel(Logger::levelFromString(level));
}
void AbstractAppender::write(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line,
const char* function, const QString& message)
{
if (logLevel >= detailsLevel())
{
QMutexLocker locker(&m_writeMutex);
append(timeStamp, logLevel, file, line, function, message);
}
}

View file

@ -0,0 +1,125 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
#ifndef ABSTRACTAPPENDER_H
#define ABSTRACTAPPENDER_H
// Local
#include "CuteLogger_global.h"
#include <Logger.h>
// Qt
#include <QMutex>
//! The AbstractAppender class provides an abstract base class for writing a log entries.
/**
* The AbstractAppender class is the base interface class for all log appenders that could be used with Logger.
*
* AbstractAppender provides a common implementation for the thread safe, mutex-protected logging of application
* messages, such as ConsoleAppender, FileAppender or something else. AbstractAppender is abstract and can not be
* instantiated, but you can use any of its subclasses or create a custom log appender at your choice.
*
* Appenders are the logical devices that is aimed to be attached to Logger object by calling
* Logger::registerAppender(). On each log record call from the application Logger object sequentially calls write()
* function on all the appenders registered in it.
*
* You can subclass AbstractAppender to implement a logging target of any kind you like. It may be the external logging
* subsystem (for example, syslog in *nix), XML file, SQL database entries, D-Bus messages or anything else you can
* imagine.
*
* For the simple non-structured plain text logging (for example, to a plain text file or to the console output) you may
* like to subclass the AbstractStringAppender instead of AbstractAppender, which will give you a more convinient way to
* control the format of the log output.
*
* \sa AbstractStringAppender
* \sa Logger::registerAppender()
*/
class CUTELOGGERSHARED_EXPORT AbstractAppender
{
public:
//! Constructs a AbstractAppender object.
AbstractAppender();
//! Destructs the AbstractAppender object.
virtual ~AbstractAppender();
//! Returns the current details level of appender.
/**
* Log records with a log level lower than a current detailsLevel() will be silently ignored by appender and would not
* be sent to its append() function.
*
* It provides additional logging flexibility, allowing you to set the different severity levels for different types
* of logs.
*
* \note This function is thread safe.
*
* \sa setDetailsLevel()
* \sa Logger::LogLevel
*/
Logger::LogLevel detailsLevel() const;
//! Sets the current details level of appender.
/**
* \note This function is thread safe.
*
* \sa detalsLevel()
* \sa Logger::LogLevel
*/
void setDetailsLevel(Logger::LogLevel level);
//! Sets the current details level of appender
/**
* This function is provided for convinience, it behaves like an above function.
*
* \sa detalsLevel()
* \sa Logger::LogLevel
*/
void setDetailsLevel(const QString& level);
//! Tries to write the log record to this logger
/**
* This is the function called by Logger object to write a log message to the appender.
*
* \note This function is thread safe.
*
* \sa Logger::write()
* \sa detailsLevel()
*/
void write(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, const char* function,
const QString& message);
protected:
//! Writes the log record to the logger instance
/**
* This function is called every time when user tries to write a message to this AbstractAppender instance using
* the write() function. Write function works as proxy and transfers only the messages with log level more or equal
* to the current logLevel().
*
* Overload this function when you are implementing a custom appender.
*
* \note This function is not needed to be thread safe because it is never called directly by Logger object. The
* write() function works as a proxy and protects this function from concurrent access.
*
* \sa Logger::write()
*/
virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line,
const char* function, const QString& message) = 0;
private:
QMutex m_writeMutex;
Logger::LogLevel m_detailsLevel;
mutable QMutex m_detailsLevelMutex;
};
#endif // ABSTRACTAPPENDER_H

View file

@ -0,0 +1,161 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
// Local
#include "AbstractStringAppender.h"
// Qt
#include <QReadLocker>
#include <QWriteLocker>
#include <QDateTime>
#include <QRegExp>
const char formattingMarker = '%';
AbstractStringAppender::AbstractStringAppender()
: m_format(QLatin1String("%t{yyyy-MM-ddTHH:mm:ss.zzz} [%-7l] <%c> %m\n"))
{}
QString AbstractStringAppender::format() const
{
QReadLocker locker(&m_formatLock);
return m_format;
}
void AbstractStringAppender::setFormat(const QString& format)
{
QWriteLocker locker(&m_formatLock);
m_format = format;
}
QString AbstractStringAppender::stripFunctionName(const char* name)
{
QRegExp rx("^.+\\s((?:[\\w\\d]+::)+)?([\\w\\d\\<\\>~]+)(?:\\(.*\\)).*$"); // XXX: SLOW!
return QString::fromLatin1(name).replace(rx, QString(QLatin1String("\\1\\2")));
}
QString AbstractStringAppender::formattedString(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file,
int line, const char* function, const QString& message) const
{
QString f = format();
const int size = f.size();
QString result;
int i = 0;
while (i < f.size())
{
QChar c = f.at(i);
// We will silently ignore the broken % marker at the end of string
if (c != QLatin1Char(formattingMarker) || (i + 1) == size)
{
result.append(c);
}
else
{
QChar command = f.at(++i);
// Check for the padding instruction
int fieldWidth = 0;
if (command.isDigit() || command.category() == QChar::Punctuation_Dash)
{
int j = 1;
while ((i + j) < size && f.at(i + j).isDigit())
j++;
fieldWidth = f.mid(i, j).toInt();
i += j;
command = f.at(i);
}
// Log record chunk to insert instead of formatting instruction
QString chunk;
// Time stamp
if (command == QLatin1Char('t'))
{
if (f.at(i + 1) == QLatin1Char('{'))
{
int j = 1;
while ((i + 2 + j) < size && f.at(i + 2 + j) != QLatin1Char('}'))
j++;
if ((i + 2 + j) < size)
{
chunk = timeStamp.toString(f.mid(i + 2, j));
i += j;
i += 2;
}
}
if (chunk.isNull())
chunk = timeStamp.toString(QLatin1String("HH:mm:ss.zzz"));
}
// Log level
else if (command == QLatin1Char('l'))
chunk = Logger::levelToString(logLevel);
// Uppercased log level
else if (command == QLatin1Char('L'))
chunk = Logger::levelToString(logLevel).toUpper();
// Filename
else if (command == QLatin1Char('F'))
chunk = QLatin1String(file);
// Filename without a path
else if (command == QLatin1Char('f'))
chunk = QString(QLatin1String(file)).section('/', -1);
// Source line number
else if (command == QLatin1Char('i'))
chunk = QString::number(line);
// Function name, as returned by Q_FUNC_INFO
else if (command == QLatin1Char('C'))
chunk = QString::fromLatin1(function);
// Stripped function name
else if (command == QLatin1Char('c'))
chunk = stripFunctionName(function);
// Log message
else if (command == QLatin1Char('m'))
chunk = message;
// We simply replace the double formatting marker (%) with one
else if (command == QLatin1Char(formattingMarker))
chunk = QLatin1Char(formattingMarker);
// Do not process any unknown commands
else
{
chunk = QLatin1Char(formattingMarker);
chunk.append(command);
}
result.append(QString(QLatin1String("%1")).arg(chunk, fieldWidth));
}
++i;
}
return result;
}

View file

@ -0,0 +1,116 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
#ifndef ABSTRACTSTRINGAPPENDER_H
#define ABSTRACTSTRINGAPPENDER_H
// Local
#include "CuteLogger_global.h"
#include <AbstractAppender.h>
// Qt
#include <QReadWriteLock>
//! The AbstractStringAppender class provides a convinient base for appenders working with plain text formatted logs.
/**
* AbstractSringAppender is the simple extension of the AbstractAppender class providing the convinient way to create
* custom log appenders working with a plain text formatted log targets.
*
* It have the formattedString() protected function that formats the logging arguments according to a format set with
* setFormat().
*
* This class can not be directly instantiated because it contains pure virtual function inherited from AbstractAppender
* class.
*
* For more detailed description of customizing the log output format see the documentation on the setFormat() function.
*/
class CUTELOGGERSHARED_EXPORT AbstractStringAppender : public AbstractAppender
{
public:
//! Constructs a new string appender object
AbstractStringAppender();
//! Returns the current log format string.
/**
* The default format is set to "%t{yyyy-MM-ddTHH:mm:ss.zzz} [%-7l] <%C> %m\n". You can set a different log record
* format using the setFormat() function.
*
* \sa setFormat(const QString&)
*/
QString format() const;
//! Sets the logging format for writing strings to the log target with this appender.
/**
* The string format seems to be very common to those developers who have used a standart sprintf function.
*
* Log output format is a simple QString with the special markers (starting with % sign) which will be replaced with
* it's internal meaning when writing a log record.
*
* Controlling marker begins with the percent sign (%) which is followed by (optional) field width argument, the
* (necessary) single-letter command (which describes, what will be put to log record instead of marker, and an
* additional formatting argument (in the {} brackets) supported for some of the log commands.
*
* Field width argument works almost identically to the \c QString::arg() \c fieldWidth argument (and uses it
* internally). For example, \c "%-7l" will be replaced with the left padded debug level of the message
* (\c "Debug ") or something. For the more detailed description of it you may consider to look to the Qt
* Reference Documentation.
*
* Supported marker commands are:
* \arg \c %t - timestamp. You may specify your custom timestamp format using the {} brackets after the marker,
* timestamp format here will be similiar to those used in QDateTime::toString() function. For example,
* "%t{dd-MM-yyyy, HH:mm}" may be replaced with "17-12-2010, 20:17" depending on current date and time.
* The default format used here is "HH:mm:ss.zzz".
* \arg \c %l - Log level. Possible log levels are shown in the Logger::LogLevel enumerator.
* \arg \c %L - Uppercased log level.
* \arg \c %F - Full source file name (with path) of the file that requested log recording. Uses the \c __FILE__
* preprocessor macro.
* \arg \c %f - Short file name (with stripped path).
* \arg \c %i - Line number in the source file. Uses the \c __LINE__ preprocessor macro.
* \arg \c %C - Name of function that called on of the LOG_* macros. Uses the \c Q_FUNC_INFO macro provided with
* Qt.
* \arg \c %c - [EXPERIMENTAL] Similiar to the %C, but the function name is stripped using stripFunctionName
* \arg \c %m - The log message sent by the caller.
* \arg \c %% - Convinient marker that is replaced with the single \c % mark.
*
* \note Format doesn't add \c '\\n' to the end of the format line. Please consider adding it manually.
*
* \sa format()
* \sa stripFunctionName()
* \sa Logger::LogLevel
*/
void setFormat(const QString&);
//! Strips the long function signature (as added by Q_FUNC_INFO macro)
/**
* The string processing drops the returning type, arguments and template parameters of function. It is definitely
* useful for enchancing the log output readability.
* \return stripped function name
*/
static QString stripFunctionName(const char*);
protected:
//! Returns the string to record to the logging target, formatted according to the format().
/**
* \sa format()
* \sa setFormat(const QString&)
*/
QString formattedString(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line,
const char* function, const QString& message) const;
private:
QString m_format;
mutable QReadWriteLock m_formatLock;
};
#endif // ABSTRACTSTRINGAPPENDER_H

View file

@ -0,0 +1,25 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
// Local
#include "ConsoleAppender.h"
// STL
#include <iostream>
void ConsoleAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line,
const char* function, const QString& message)
{
std::cerr << qPrintable(formattedString(timeStamp, logLevel, file, line, function, message));
}

View file

@ -0,0 +1,32 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
#ifndef CONSOLEAPPENDER_H
#define CONSOLEAPPENDER_H
#include "CuteLogger_global.h"
#include <AbstractStringAppender.h>
//! ConsoleAppender is the simple appender that writes the log records to the std::cerr output stream.
class CUTELOGGERSHARED_EXPORT ConsoleAppender : public AbstractStringAppender
{
protected:
//! Writes the log record to the std::cerr stream.
/**
* \sa AbstractStringAppender::format()
*/
virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line,
const char* function, const QString& message);
};
#endif // CONSOLEAPPENDER_H

View file

@ -0,0 +1,12 @@
#ifndef CUTELOGGER_GLOBAL_H
#define CUTELOGGER_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(CUTELOGGER_LIBRARY)
# define CUTELOGGERSHARED_EXPORT Q_DECL_EXPORT
#else
# define CUTELOGGERSHARED_EXPORT Q_DECL_IMPORT
#endif
#endif // CUTELOGGER_GLOBAL_H

View file

@ -0,0 +1,85 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
// Local
#include "FileAppender.h"
// STL
#include <iostream>
FileAppender::FileAppender(const QString& fileName)
{
setFileName(fileName);
}
FileAppender::~FileAppender()
{
closeFile();
}
QString FileAppender::fileName() const
{
QMutexLocker locker(&m_logFileMutex);
return m_logFile.fileName();
}
void FileAppender::setFileName(const QString& s)
{
QMutexLocker locker(&m_logFileMutex);
if (m_logFile.isOpen())
m_logFile.close();
m_logFile.setFileName(s);
}
bool FileAppender::openFile()
{
bool isOpen = false;
if (!m_logFile.isOpen())
{
if (m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
m_logStream.setDevice(&m_logFile);
isOpen = true;
}
else
{
std::cerr << "<FileAppender::append> Cannot open the log file " << qPrintable(m_logFile.fileName()) << std::endl;
}
}
return isOpen;
}
void FileAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line,
const char* function, const QString& message)
{
QMutexLocker locker(&m_logFileMutex);
openFile();
m_logStream << formattedString(timeStamp, logLevel, file, line, function, message);
m_logStream.flush();
m_logFile.flush();
}
void FileAppender::closeFile()
{
QMutexLocker locker(&m_logFileMutex);
m_logFile.close();
}

View file

@ -0,0 +1,63 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
#ifndef FILEAPPENDER_H
#define FILEAPPENDER_H
// Logger
#include "CuteLogger_global.h"
#include <AbstractStringAppender.h>
// Qt
#include <QFile>
#include <QTextStream>
//! File is the simple appender that writes the log records to the plain text file.
class CUTELOGGERSHARED_EXPORT FileAppender : public AbstractStringAppender
{
public:
//! Constructs the new file appender assigned to file with the given name.
FileAppender(const QString& fileName = QString());
~FileAppender();
//! Returns the name set by setFileName() or to the FileAppender constructor.
/**
* \sa setFileName()
*/
QString fileName() const;
//! Sets the name of the file. The name can have no path, a relative path, or an absolute path.
/**
* \sa fileName()
*/
void setFileName(const QString&);
protected:
//! Write the log record to the file.
/**
* \sa fileName()
* \sa AbstractStringAppender::format()
*/
virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line,
const char* function, const QString& message);
bool openFile();
void closeFile();
private:
QFile m_logFile;
QTextStream m_logStream;
mutable QMutex m_logFileMutex;
};
#endif // FILEAPPENDER_H

View file

@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -0,0 +1,370 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
// Local
#include "Logger.h"
#include "AbstractAppender.h"
// Qt
#include <QCoreApplication>
#include <QReadWriteLock>
#include <QSemaphore>
#include <QDateTime>
#include <QIODevice>
#include <QTextCodec>
// STL
#include <iostream>
class LogDevice : public QIODevice
{
public:
LogDevice()
: m_semaphore(1)
{}
void lock(Logger::LogLevel logLevel, const char* file, int line, const char* function)
{
m_semaphore.acquire();
if (!isOpen())
open(QIODevice::WriteOnly);
m_logLevel = logLevel;
m_file = file;
m_line = line;
m_function = function;
}
protected:
qint64 readData(char*, qint64)
{
return 0;
}
qint64 writeData(const char* data, qint64 maxSize)
{
if (maxSize > 0)
Logger::write(m_logLevel, m_file, m_line, m_function, QString::fromLocal8Bit(QByteArray(data, maxSize)));
m_semaphore.release();
return maxSize;
}
private:
QSemaphore m_semaphore;
Logger::LogLevel m_logLevel;
const char* m_file;
int m_line;
const char* m_function;
};
// Forward declarations
static void cleanupLoggerPrivate();
#if QT_VERSION >= 0x050000
static void qtLoggerMessageHandler(QtMsgType, const QMessageLogContext& context, const QString& msg);
#else
static void qtLoggerMessageHandler(QtMsgType type, const char* msg);
#endif
/**
* \internal
*
* LoggerPrivate class implements the Singleton pattern in a thread-safe way. It uses a static pointer to itself
* protected by QReadWriteLock
*
* The appender list inside the LoggerPrivate class is also protected by QReadWriteLock so this class could be safely
* used in a multi-threaded application.
*/
class LoggerPrivate
{
public:
static LoggerPrivate* m_self;
static QReadWriteLock m_selfLock;
static LoggerPrivate* instance()
{
LoggerPrivate* result = 0;
{
QReadLocker locker(&m_selfLock);
result = m_self;
}
if (!result)
{
QWriteLocker locker(&m_selfLock);
m_self = new LoggerPrivate;
#if QT_VERSION >= 0x050000
qInstallMessageHandler(qtLoggerMessageHandler);
#else
qInstallMsgHandler(qtLoggerMessageHandler);
#endif
qAddPostRoutine(cleanupLoggerPrivate);
result = m_self;
}
return result;
}
LoggerPrivate()
: m_logDevice(0)
{}
~LoggerPrivate()
{
// Cleanup appenders
QReadLocker appendersLocker(&m_appendersLock);
foreach (AbstractAppender* appender, m_appenders)
delete appender;
// Cleanup device
QReadLocker deviceLocker(&m_logDeviceLock);
delete m_logDevice;
}
void registerAppender(AbstractAppender* appender)
{
QWriteLocker locker(&m_appendersLock);
if (!m_appenders.contains(appender))
m_appenders.append(appender);
else
std::cerr << "Trying to register appender that was already registered" << std::endl;
}
LogDevice* logDevice()
{
LogDevice* result = 0;
{
QReadLocker locker(&m_logDeviceLock);
result = m_logDevice;
}
if (!result)
{
QWriteLocker locker(&m_logDeviceLock);
m_logDevice = new LogDevice;
result = m_logDevice;
}
return result;
}
void write(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, const char* function,
const QString& message)
{
QReadLocker locker(&m_appendersLock);
if (!m_appenders.isEmpty())
{
foreach (AbstractAppender* appender, m_appenders)
appender->write(timeStamp, logLevel, file, line, function, message);
}
else
{
// Fallback
QString result = QString(QLatin1String("[%1] <%2> %3")).arg(Logger::levelToString(logLevel), -7)
.arg(function).arg(message);
std::cerr << qPrintable(result) << std::endl;
}
if (logLevel == Logger::Fatal)
abort();
}
void write(Logger::LogLevel logLevel, const char* file, int line, const char* function, const QString& message)
{
write(QDateTime::currentDateTime(), logLevel, file, line, function, message);
}
void write(Logger::LogLevel logLevel, const char* file, int line, const char* function, const char* message)
{
write(logLevel, file, line, function, QString(message));
}
QDebug write(Logger::LogLevel logLevel, const char* file, int line, const char* function)
{
LogDevice* d = logDevice();
d->lock(logLevel, file, line, function);
return QDebug(d);
}
void writeAssert(const char* file, int line, const char* function, const char* condition)
{
write(Logger::Fatal, file, line, function, QString("ASSERT: \"%1\"").arg(condition));
}
private:
QList<AbstractAppender*> m_appenders;
QReadWriteLock m_appendersLock;
LogDevice* m_logDevice;
QReadWriteLock m_logDeviceLock;
};
// Static fields initialization
LoggerPrivate* LoggerPrivate::m_self = 0;
QReadWriteLock LoggerPrivate::m_selfLock;
static void cleanupLoggerPrivate()
{
QWriteLocker locker(&LoggerPrivate::m_selfLock);
delete LoggerPrivate::m_self;
LoggerPrivate::m_self = 0;
}
#if QT_VERSION >= 0x050000
static void qtLoggerMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
Logger::LogLevel level;
switch (type)
{
case QtDebugMsg:
level = Logger::Debug;
break;
case QtWarningMsg:
level = Logger::Warning;
break;
case QtCriticalMsg:
level = Logger::Error;
break;
case QtFatalMsg:
level = Logger::Fatal;
break;
}
Logger::write(level, context.file, context.line, context.function, msg);
}
#else
static void qtLoggerMessageHandler(QtMsgType type, const char* msg)
{
switch (type)
{
case QtDebugMsg:
LOG_DEBUG(msg);
break;
case QtWarningMsg:
LOG_WARNING(msg);
break;
case QtCriticalMsg:
LOG_ERROR(msg);
break;
case QtFatalMsg:
LOG_FATAL(msg);
break;
}
}
#endif
QString Logger::levelToString(Logger::LogLevel logLevel)
{
switch (logLevel)
{
case Trace:
return QLatin1String("Trace");
case Debug:
return QLatin1String("Debug");
case Info:
return QLatin1String("Info");
case Warning:
return QLatin1String("Warning");
case Error:
return QLatin1String("Error");
case Fatal:
return QLatin1String("Fatal");
}
return QString();
}
Logger::LogLevel Logger::levelFromString(const QString& s)
{
QString str = s.trimmed().toLower();
LogLevel result = Debug;
if (str == QLatin1String("trace"))
result = Trace;
else if (str == QLatin1String("debug"))
result = Debug;
else if (str == QLatin1String("info"))
result = Info;
else if (str == QLatin1String("warning"))
result = Warning;
else if (str == QLatin1String("error"))
result = Error;
else if (str == QLatin1String("fatal"))
result = Fatal;
return result;
}
void Logger::registerAppender(AbstractAppender* appender)
{
LoggerPrivate::instance()->registerAppender(appender);
}
void Logger::write(const QDateTime& timeStamp, LogLevel logLevel, const char* file, int line, const char* function,
const QString& message)
{
LoggerPrivate::instance()->write(timeStamp, logLevel, file, line, function, message);
}
void Logger::write(LogLevel logLevel, const char* file, int line, const char* function, const QString& message)
{
LoggerPrivate::instance()->write(logLevel, file, line, function, message);
}
void Logger::write(LogLevel logLevel, const char* file, int line, const char* function, const char* message, ...)
{
va_list va;
va_start(va, message);
LoggerPrivate::instance()->write(logLevel, file, line, function, QString().vsprintf(message,va));
va_end(va);
}
QDebug Logger::write(LogLevel logLevel, const char* file, int line, const char* function)
{
return LoggerPrivate::instance()->write(logLevel, file, line, function);
}
void Logger::writeAssert(const char* file, int line, const char* function, const char* condition)
{
LoggerPrivate::instance()->writeAssert(file, line, function, condition);
}

View file

@ -0,0 +1,319 @@
/*
Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
#ifndef LOGGER_H
#define LOGGER_H
/**
* \file Logger.h
* \brief A file containing the description of Logger class and and additional useful macros for logging
*/
// Qt
#include <QString>
#include <QDebug>
class QDateTime;
// Local
#include "CuteLogger_global.h"
class AbstractAppender;
//! Writes the trace log record
/**
* This macro is the convinient way to call Logger::write(). It uses the common preprocessor macros \c __FILE__,
* \c __LINE__ and the standart Qt \c Q_FUNC_INFO macros to automatically determine the needed parameters to call
* Logger::write().
*
* \note This and other (LOG_INFO() etc...) macros uses the variadic macro arguments to give convinient usage form for
* the different versions of Logger::write() (using the QString or const char* argument or returning the QDebug class
* instance). Not all compilers will support this. Please, consider reviewing your compiler documentation to ensure
* it support __VA_ARGS__ macro.
*
* It is checked to work with GCC 4.4 or later.
*
* \sa Logger::LogLevel
* \sa Logger::write()
*/
#define LOG_TRACE(...) Logger::write(Logger::Trace, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__)
//! Writes the debug log record
/**
* This macro records the info log record using the Logger::write() function. It works identically to the LOG_TRACE()
* macro.
*
* \sa LOG_TRACE()
* \sa Logger::LogLevel
* \sa Logger::write()
*/
#define LOG_DEBUG(...) Logger::write(Logger::Debug, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__)
//! Write the info log record
/**
* This macro records the info log record using the Logger::write() function. It works identically to the LOG_TRACE()
* macro.
*
* \sa LOG_TRACE()
* \sa Logger::LogLevel
* \sa Logger::write()
*/
#define LOG_INFO(...) Logger::write(Logger::Info, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__)
//! Write the warning log record
/**
* This macro records the warning log record using the Logger::write() function. It works identically to the LOG_TRACE()
* macro.
*
* \sa LOG_TRACE()
* \sa Logger::LogLevel
* \sa Logger::write()
*/
#define LOG_WARNING(...) Logger::write(Logger::Warning, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__)
//! Write the error log record
/**
* This macro records the error log record using the Logger::write() function. It works identically to the LOG_TRACE()
* macro.
*
* \sa LOG_TRACE()
* \sa Logger::LogLevel
* \sa Logger::write()
*/
#define LOG_ERROR(...) Logger::write(Logger::Error, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__)
//! Write the fatal log record
/**
* This macro records the fatal log record using the Logger::write() function. It works identically to the LOG_TRACE()
* macro.
*
* \note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort()
* function, which will interrupt the running of your software and begin the writing of the core dump.
*
* \sa LOG_TRACE()
* \sa Logger::LogLevel
* \sa Logger::write()
*/
#define LOG_FATAL(...) Logger::write(Logger::Fatal, __FILE__, __LINE__, Q_FUNC_INFO, ##__VA_ARGS__)
//! Check the assertion
/**
* This macro is a convinient and recommended to use way to call Logger::writeAssert() function. It uses the
* preprocessor macros (as the LOG_DEBUG() does) to fill the necessary arguments of the Logger::writeAssert() call. It
* also uses undocumented but rather mature and stable \c qt_noop() function (which does nothing) when the assertion
* is true.
*
* Example:
* \code
* bool b = checkSomething();
* ...
* LOG_ASSERT(b == true);
* \endcode
*
* \sa Logger::writeAssert()
*/
#define LOG_ASSERT(cond) ((!(cond)) ? Logger::writeAssert(__FILE__, __LINE__, Q_FUNC_INFO, #cond) : qt_noop())
/**
* \mainpage
*
* Logger is a simple way to write the history of your application lifecycle to any target logging device (which is
* called Appender and may write to any target you will implement with it: console, text file, XML or something - you
* choose) and to map logging message to a class, function, source file and line of code which it is called from.
*
* Some simple appenders (which may be considered an examples) are provided with the logger itself: see ConsoleAppender
* and FileAppender documentation.
*
* It supports using it in a multithreaded applications, so ALL of its functions are thread safe.
*
* Simple usage example:
* \code
* #include <QCoreApplication>
*
* #include <Logger.h>
* #include <ConsoleAppender.h>
*
* int main(int argc, char* argv[])
* {
* QCoreApplication app(argc, argv);
* ...
* ConsoleAppender* consoleAppender = new ConsoleAppender();
* consoleAppender->setFormat("[%-7l] <%C> %m\n");
* Logger::registerAppender(consoleAppender);
* ...
* LOG_INFO("Starting the application");
* int result = app.exec();
* ...
* if (result)
* LOG_WARNING() << "Something went wrong." << "Result code is" << result;
*
* return result;
* }
* \endcode
*
* Logger internally uses the lazy-initialized singleton object and needs no definite initialization, but you may
* consider registering a log appender before calling any log recording functions or macros.
*
* The library design of Logger allows you to simply mass-replace all occurrences of qDebug and similiar calls with
* similiar Logger macros (e.g. LOG_DEBUG)
*
* \note Logger uses a singleton class which must live through all the application life cycle and cleans it on the
* destruction of the QCoreApplication (or QApplication) instance. It needs a QCoreApplication instance to be
* created before any of the Logger's functions are called.
*
* \sa AbstractAppender
* \sa LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL
* \sa LOG_ASSERT
*/
//! Very simple but rather powerful component which may be used for logging your application activities.
class CUTELOGGERSHARED_EXPORT Logger
{
public:
//! Describes the possible severity levels of the log records
enum LogLevel
{
Trace, //!< Trace level. Can be used for mostly unneeded records used for internal code tracing.
Debug, //!< Debug level. Useful for non-necessary records used for the debugging of the software.
Info, //!< Info level. Can be used for informational records, which may be interesting for not only developers.
Warning, //!< Warning. May be used to log some non-fatal warnings detected by your application.
Error, //!< Error. May be used for a big problems making your application work wrong but not crashing.
Fatal //!< Fatal. Used for unrecoverable errors, crashes the application right after the log record is written.
};
//! Converts the LogLevel enum value to its string representation
/**
* \param logLevel Log level to convert
*
* \sa LogLevel
* \sa levelFromString()
*/
static QString levelToString(LogLevel logLevel);
//! Converts the LogLevel string representation to enum value
/**
* Comparation of the strings is case independent. If the log level string provided cannot be understood
* Logger::Debug is returned.
*
* \param s String to be decoded
*
* \sa LogLevel
* \sa levelToString()
*/
static LogLevel levelFromString(const QString& s);
//! Registers the appender to write the log records to
/**
* On the log writing call (using one of the macros or the write() function) Logger traverses through the list of
* the appenders and writes a log records to the each of them. Please, look through the AbstractAppender
* documentation to understand the concept of appenders.
*
* If no appenders was added to Logger, it falls back to logging into the \c std::cerr STL stream.
*
* \param appender Appender to register in the Logger
*
* \note Logger takes ownership on the appender and it will delete it on the application exit. According to this,
* appenders must be created on heap to prevent double destruction of the appender.
*
* \sa AbstractAppender
*/
static void registerAppender(AbstractAppender* appender);
//! Writes the log record
/**
* Writes the log records with the supplied arguments to all the registered appenders.
*
* \note It is not recommended to call this function directly. Instead of this you can just call one of the macros
* (LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL) that will supply all the needed
* information to this function.
*
* \param timeStamp - the time stamp of the record
* \param logLevel - the log level of the record
* \param file - the name of the source file that requested the log record
* \param line - the line of the code of source file that requested the log record
* \param function - name of the function that requested the log record
* \param message - log message
*
* \note Recording of the log record using the Logger::Fatal log level will lead to calling the STL abort()
* function, which will interrupt the running of your software and begin the writing of the core dump.
*
* \sa LogLevel
* \sa LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL
* \sa AbstractAppender
*/
static void write(const QDateTime& timeStamp, LogLevel logLevel, const char* file, int line, const char* function,
const QString& message);
/**
* This is the overloaded function provided for the convinience. It behaves identically to the above function.
*
* This function uses the current timestamp obtained with \c QDateTime::currentDateTime().
*
* \sa write()
*/
static void write(LogLevel logLevel, const char* file, int line, const char* function, const QString& message);
/**
* This is the overloaded function provided for the convinience. It behaves identically to the above function.
*
* This function uses the current timestamp obtained with \c QDateTime::currentDateTime(). Also it supports writing
* <tt>const char*</tt> instead of \c QString and converts it internally using the \c QString::fromAscii(). If you
* want this function to support the non-ascii strings, you will need to setup the codec using the
* \c QTextCodec::setCodecForCStrings()
*
* \sa write()
*/
static void write(LogLevel logLevel, const char* file, int line, const char* function, const char* message, ...);
/**
* This is the overloaded function provided for the convinience. It behaves identically to the above function.
*
* This function doesn't accept any log message as argument. It returns the \c QDebug object that can be written
* using the stream functions. For example, you may like to write:
* \code
* LOG_DEBUG() << "This is the size" << size << "of the element" << elementName;
* \endcode
* instead of writing
* \code
* LOG_DEBUG(QString(QLatin1String("This is the size %1x%2 of the element %3"))
* .arg(size.x()).arg(size.y()).arg(elementName));
* \endcode
*
* Please consider reading the Qt Reference Documentation for the description of the QDebug class usage syntax.
*
* \note This overload is definitely more pleasant to use than the first write() overload, but it behaves definitely
* slower than all the above overloads.
*
* \sa write()
*/
static QDebug write(LogLevel logLevel, const char* file, int line, const char* function);
//! Writes the assertion
/**
* This function writes the assertion record using the write() function.
*
* The assertion record is always written using the Logger::Fatal log level which leads to the abortation of the
* program and generation of the core dump (if supported).
*
* The message written to the appenders will be identical to the \c condition argument prefixed with the
* <tt>ASSERT:</tt> notification.
*
* \note It is not recommended to call this function directly. Instead of this you can just call the LOG_ASSERT
* macro that will supply all the needed information to this function.
*
* \sa LOG_ASSERT
* \sa write()
*/
static void writeAssert(const char* file, int line, const char* function, const char* condition);
};
#endif // LOGGER_H

View file

@ -0,0 +1,31 @@
/*
Copyright (c) 2010 Karl-Heinz Reichel (khreichel at googlemail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
// Local
#include "OutputDebugAppender.h"
// STL
#include <windows.h>
void OutputDebugAppender::append(const QDateTime& timeStamp,
Logger::LogLevel logLevel,
const char* file,
int line,
const char* function,
const QString& message)
{
QString s = formattedString(timeStamp, logLevel, file, line, function, message);
OutputDebugStringW((LPCWSTR) s.utf16());
}

View file

@ -0,0 +1,33 @@
/*
Copyright (c) 2010 Karl-Heinz Reichel (khreichel at googlemail dot com)
This program 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 and appearing in the file
LICENSE.LGPL included in the packaging of this file.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*/
#ifndef OUTPUTDEBUGAPPENDER_H
#define OUTPUTDEBUGAPPENDER_H
#include "CuteLogger_global.h"
#include <AbstractStringAppender.h>
//! OutputDebugAppender is the appender that writes the log records to the Microsoft Debug Log
class CUTELOGGERSHARED_EXPORT OutputDebugAppender : public AbstractStringAppender
{
protected:
//! Writes the log record to the windows debug log.
/**
* \sa AbstractStringAppender::format()
*/
virtual void append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line,
const char* function, const QString& message);
};
#endif // OUTPUTDEBUGAPPENDER_H

View file

@ -0,0 +1,7 @@
This folder contains the cutelogger project for logging functionality.
These files are distributed under the LGPL v2 or later.
The source files have been last synced with the projects at
https://gitorious.org/cutelogger to commit
e3c2745c6c5f38896f87472e01ea2caf2d9e211b.

View file

@ -21,6 +21,9 @@
#include <QSettings> #include <QSettings>
#include "rbutilqt.h" #include "rbutilqt.h"
#include "systrace.h" #include "systrace.h"
#include "Logger.h"
#include "ConsoleAppender.h"
#include "FileAppender.h"
#ifdef STATIC #ifdef STATIC
#include <QtPlugin> #include <QtPlugin>
@ -28,14 +31,19 @@ Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif #endif
int main( int argc, char ** argv ) { int main( int argc, char ** argv ) {
#if QT_VERSION < 0x050000
qInstallMsgHandler(SysTrace::debug);
#else
qInstallMessageHandler(SysTrace::debug);
#endif
QApplication app( argc, argv ); QApplication app( argc, argv );
ConsoleAppender* consoleAppender = new ConsoleAppender();
consoleAppender->setFormat("[%f:%i %L] %m\n");
Logger::registerAppender(consoleAppender);
SysTrace::rotateTrace();
QString tracefile = QDir::tempPath() + "/rbutil-trace.log";
FileAppender* fileAppender = new FileAppender();
fileAppender->setFormat("[%f:%i %L] %m\n");
fileAppender->setFileName(tracefile);
Logger::registerAppender(fileAppender);
LOG_INFO() << "Starting trace at" << QDateTime::currentDateTime().toString(Qt::ISODate);
#if defined(Q_OS_MAC) #if defined(Q_OS_MAC)
QDir dir(QApplication::applicationDirPath()); QDir dir(QApplication::applicationDirPath());
dir.cdUp(); dir.cdUp();

View file

@ -142,9 +142,9 @@ void ProgressLoggerGui::show()
void ProgressLoggerGui::saveErrorLog() void ProgressLoggerGui::saveErrorLog()
{ {
QString filename = QFileDialog::getSaveFileName(downloadProgress, tr("Save system trace log"), QString filename = QFileDialog::getSaveFileName(downloadProgress,
QDir::homePath(), "*.log"); tr("Save system trace log"), QDir::homePath(), "*.log");
if(filename == "") if(filename.isEmpty())
return; return;
QFile file(filename); QFile file(filename);
@ -155,6 +155,7 @@ void ProgressLoggerGui::saveErrorLog()
QString loggerTexts = "\n*********************************************\n" QString loggerTexts = "\n*********************************************\n"
"*************** Logger *******************\n" "*************** Logger *******************\n"
"*********************************************\n"; "*********************************************\n";
file.write(loggerTexts.toUtf8(), loggerTexts.size()); file.write(loggerTexts.toUtf8(), loggerTexts.size());

View file

@ -49,6 +49,8 @@
#include "bootloaderinstallbase.h" #include "bootloaderinstallbase.h"
#include "bootloaderinstallhelper.h" #include "bootloaderinstallhelper.h"
#include "Logger.h"
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
#include <stdio.h> #include <stdio.h>
#endif #endif
@ -66,10 +68,10 @@ QList<QTranslator*> RbUtilQt::translators;
RbUtilQt::RbUtilQt(QWidget *parent) : QMainWindow(parent) RbUtilQt::RbUtilQt(QWidget *parent) : QMainWindow(parent)
{ {
// startup log // startup log
qDebug() << "======================================"; LOG_INFO() << "======================================";
qDebug() << "[System] Rockbox Utility " VERSION; LOG_INFO() << "Rockbox Utility" << VERSION;
qDebug() << "[System] Qt version:" << qVersion(); LOG_INFO() << "Qt version:" << qVersion();
qDebug() << "======================================"; LOG_INFO() << "======================================";
absolutePath = qApp->applicationDirPath(); absolutePath = qApp->applicationDirPath();
@ -110,7 +112,7 @@ RbUtilQt::RbUtilQt(QWidget *parent) : QMainWindow(parent)
"Please don't do this, running under Wine will fail. " "Please don't do this, running under Wine will fail. "
"Use the native Linux binary instead."), "Use the native Linux binary instead."),
QMessageBox::Ok, QMessageBox::Ok); QMessageBox::Ok, QMessageBox::Ok);
qDebug() << "[RbUtil] WINE DETECTED!"; LOG_WARNING() << "WINE DETECTED!";
RegCloseKey(hk); RegCloseKey(hk);
} }
#endif #endif
@ -181,15 +183,6 @@ RbUtilQt::RbUtilQt(QWidget *parent) : QMainWindow(parent)
void RbUtilQt::shutdown(void) void RbUtilQt::shutdown(void)
{ {
// restore default message handler to prevent trace accesses during
// object destruction -- the trace object could already be destroyed.
// Fixes segfaults on exit.
#if QT_VERSION < 0x050000
qInstallMsgHandler(0);
#else
qInstallMessageHandler(0);
#endif
SysTrace::save();
this->close(); this->close();
} }
@ -229,7 +222,7 @@ void RbUtilQt::downloadInfo()
connect(qApp, SIGNAL(lastWindowClosed()), daily, SLOT(abort())); connect(qApp, SIGNAL(lastWindowClosed()), daily, SLOT(abort()));
daily->setCache(false); daily->setCache(false);
ui.statusbar->showMessage(tr("Downloading build information, please wait ...")); ui.statusbar->showMessage(tr("Downloading build information, please wait ..."));
qDebug() << "[RbUtil] downloading build info"; LOG_INFO() << "downloading build info";
daily->setFile(&buildInfo); daily->setFile(&buildInfo);
daily->getFile(QUrl(SystemInfo::value(SystemInfo::BuildInfoUrl).toString())); daily->getFile(QUrl(SystemInfo::value(SystemInfo::BuildInfoUrl).toString()));
} }
@ -238,7 +231,7 @@ void RbUtilQt::downloadInfo()
void RbUtilQt::downloadDone(bool error) void RbUtilQt::downloadDone(bool error)
{ {
if(error) { if(error) {
qDebug() << "[RbUtil] network error:" << daily->errorString(); LOG_INFO() << "network error:" << daily->errorString();
ui.statusbar->showMessage(tr("Can't get version information!")); ui.statusbar->showMessage(tr("Can't get version information!"));
QMessageBox::critical(this, tr("Network error"), QMessageBox::critical(this, tr("Network error"),
tr("Can't get version information.\n" tr("Can't get version information.\n"
@ -246,7 +239,7 @@ void RbUtilQt::downloadDone(bool error)
.arg(daily->errorString())); .arg(daily->errorString()));
return; return;
} }
qDebug() << "[RbUtil] network status:" << daily->errorString(); LOG_INFO() << "network status:" << daily->errorString();
// read info into ServerInfo object // read info into ServerInfo object
buildInfo.open(); buildInfo.open();
@ -320,7 +313,7 @@ void RbUtilQt::configDialog()
void RbUtilQt::updateSettings() void RbUtilQt::updateSettings()
{ {
qDebug() << "[RbUtil] updating current settings"; LOG_INFO() << "updating current settings";
updateDevice(); updateDevice();
manual->updateManual(); manual->updateManual();
QString c = RbSettings::value(RbSettings::CachePath).toString(); QString c = RbSettings::value(RbSettings::CachePath).toString();
@ -409,7 +402,7 @@ void RbUtilQt::backup(void)
void RbUtilQt::installdone(bool error) void RbUtilQt::installdone(bool error)
{ {
qDebug() << "[RbUtil] install done"; LOG_INFO() << "install done";
m_installed = true; m_installed = true;
m_error = error; m_error = error;
} }
@ -464,7 +457,7 @@ void RbUtilQt::installVoice()
voiceurl.replace("%MODEL%", model); voiceurl.replace("%MODEL%", model);
voiceurl.replace("%RELVERSION%", relversion); voiceurl.replace("%RELVERSION%", relversion);
qDebug() << "[RbUtil] voicefile URL:" << voiceurl; LOG_INFO() << "voicefile URL:" << voiceurl;
// create logger // create logger
logger = new ProgressLoggerGui(this); logger = new ProgressLoggerGui(this);
@ -633,7 +626,7 @@ QUrl RbUtilQt::proxy()
else if(proxytype == "system") else if(proxytype == "system")
proxy = System::systemProxy(); proxy = System::systemProxy();
qDebug() << "[RbUtilQt] Proxy is" << proxy; LOG_INFO() << "Proxy is" << proxy;
return proxy; return proxy;
} }
@ -675,7 +668,7 @@ void RbUtilQt::checkUpdate(void)
void RbUtilQt::downloadUpdateDone(bool error) void RbUtilQt::downloadUpdateDone(bool error)
{ {
if(error) { if(error) {
qDebug() << "[RbUtil] network error:" << update->errorString(); LOG_INFO() << "network error:" << update->errorString();
} }
else { else {
QString toParse(update->readAll()); QString toParse(update->readAll());
@ -688,7 +681,7 @@ void RbUtilQt::downloadUpdateDone(bool error)
rbutilList << searchString.cap(1); rbutilList << searchString.cap(1);
pos += searchString.matchedLength(); pos += searchString.matchedLength();
} }
qDebug() << "[RbUtilQt] Checking for update"; LOG_INFO() << "Checking for update";
QString newVersion = ""; QString newVersion = "";
QString foundVersion = ""; QString foundVersion = "";

View file

@ -87,6 +87,11 @@ SOURCES += \
mspack/system-mspack.c \ mspack/system-mspack.c \
base/mspackutil.cpp \ base/mspackutil.cpp \
base/archiveutil.cpp \ base/archiveutil.cpp \
logger/AbstractAppender.cpp \
logger/AbstractStringAppender.cpp \
logger/ConsoleAppender.cpp \
logger/FileAppender.cpp \
logger/Logger.cpp \
HEADERS += \ HEADERS += \

View file

@ -110,6 +110,7 @@ INCLUDEPATH = $$_PRO_FILE_PWD_ $$_PRO_FILE_PWD_/irivertools \
$$_PRO_FILE_PWD_/zlib $$_PRO_FILE_PWD_/gui $$_PRO_FILE_PWD_/zlib $$_PRO_FILE_PWD_/gui
INCLUDEPATH += $$RBBASE_DIR/rbutil/ipodpatcher $$RBBASE_DIR/rbutil/sansapatcher \ INCLUDEPATH += $$RBBASE_DIR/rbutil/ipodpatcher $$RBBASE_DIR/rbutil/sansapatcher \
$$RBBASE_DIR/tools/rbspeex $$RBBASE_DIR/tools $$RBBASE_DIR/tools/rbspeex $$RBBASE_DIR/tools
INCLUDEPATH += logger
DEPENDPATH = $$INCLUDEPATH DEPENDPATH = $$INCLUDEPATH
@ -143,13 +144,11 @@ contains(QT_MAJOR_VERSION, 5) {
dbg { dbg {
CONFIG += debug thread qt warn_on CONFIG += debug thread qt warn_on
DEFINES -= QT_NO_DEBUG_OUTPUT
DEFINES += DBG DEFINES += DBG
message("debug") message("debug")
} }
!dbg { !dbg {
CONFIG += release thread qt CONFIG += release thread qt
DEFINES -= QT_NO_DEBUG_OUTPUT
DEFINES += NODEBUG DEFINES += NODEBUG
message("release") message("release")
} }

View file

@ -22,10 +22,8 @@
#include "ui_systracefrm.h" #include "ui_systracefrm.h"
#include "rbsettings.h" #include "rbsettings.h"
#include "Logger.h"
QString SysTrace::debugbuffer;
QString SysTrace::lastmessage;
unsigned int SysTrace::repeat = 0;
SysTrace::SysTrace(QWidget *parent) : QDialog(parent) SysTrace::SysTrace(QWidget *parent) : QDialog(parent)
{ {
@ -43,7 +41,28 @@ SysTrace::SysTrace(QWidget *parent) : QDialog(parent)
void SysTrace::refresh(void) void SysTrace::refresh(void)
{ {
int pos = ui.textTrace->verticalScrollBar()->value(); int pos = ui.textTrace->verticalScrollBar()->value();
flush();
QString debugbuffer;
QFile tracefile(QDir::tempPath() + "/rbutil-trace.log");
tracefile.open(QIODevice::ReadOnly);
QTextStream c(&tracefile);
QString line;
QString color;
while(!c.atEnd()) {
line = c.readLine();
if(line.contains("WARNING"))
color = "orange";
else if(line.contains("ERROR"))
color = "red";
#if 0
else if(line.contains("INFO"))
color = "green";
#endif
else
color = "black";
debugbuffer += QString("<div style='color:%1;'>%2</div>").arg(color, line);
}
tracefile.close();
ui.textTrace->setHtml("<pre>" + debugbuffer + "</pre>"); ui.textTrace->setHtml("<pre>" + debugbuffer + "</pre>");
ui.textTrace->verticalScrollBar()->setValue(pos); ui.textTrace->verticalScrollBar()->setValue(pos);
QString oldlog = RbSettings::value(RbSettings::CachePath).toString() QString oldlog = RbSettings::value(RbSettings::CachePath).toString()
@ -52,23 +71,26 @@ void SysTrace::refresh(void)
} }
QString SysTrace::getTrace(void)
{
QString debugbuffer;
QFile tracefile(QDir::tempPath() + "/rbutil-trace.log");
tracefile.open(QIODevice::ReadOnly);
QTextStream c(&tracefile);
debugbuffer = c.readAll();
tracefile.close();
return debugbuffer;
}
void SysTrace::save(QString filename) void SysTrace::save(QString filename)
{ {
if(filename.isEmpty()) if(filename.isEmpty())
filename = RbSettings::value(RbSettings::CachePath).toString()
+ "/rbutil-trace.log";
// make sure any repeat detection is flushed
flush();
// append save date to the trace. Append it directly instead of using
// qDebug() as the handler might have been unregistered.
debugbuffer.append("[SysTrace] saving trace at ");
debugbuffer.append(QDateTime::currentDateTime().toString(Qt::ISODate));
debugbuffer.append("\n");
QFile fh(filename);
if(!fh.open(QIODevice::WriteOnly))
return; return;
fh.write(debugbuffer.toUtf8(), debugbuffer.size()); LOG_INFO() << "saving trace at" << QDateTime::currentDateTime().toString(Qt::ISODate);
fh.close(); QFile::copy(QDir::tempPath() + "/rbutil-trace.log", filename);
} }
void SysTrace::saveCurrentTrace(void) void SysTrace::saveCurrentTrace(void)
@ -87,59 +109,19 @@ void SysTrace::savePreviousTrace(void)
if(fp.isEmpty()) if(fp.isEmpty())
return; return;
QString oldlog = RbSettings::value(RbSettings::CachePath).toString() QString oldlog = QDir::tempPath() + "/rbutil-trace.log.1";
+ "/rbutil-trace.log";
QFile::copy(oldlog, fp); QFile::copy(oldlog, fp);
return; return;
} }
#if QT_VERSION < 0x050000
void SysTrace::debug(QtMsgType type, const char* msg)
{
(void)type;
if(lastmessage != msg) {
lastmessage = msg;
flush();
debugbuffer.append(QString::fromLocal8Bit(msg) + "\n");
#if !defined(NODEBUG)
fprintf(stderr, "%s\n", msg);
#endif
repeat = 1;
}
else {
repeat++;
}
}
#else
void SysTrace::debug(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
(void)type;
(void)context;
QByteArray localMsg = msg.toLocal8Bit();
if(lastmessage != msg) {
lastmessage = msg;
flush();
debugbuffer.append(msg + "\n");
#if !defined(NODEBUG)
fprintf(stderr, "%s\n", localMsg.constData());
#endif
repeat = 1;
}
else {
repeat++;
}
}
#endif
void SysTrace::flush(void) void SysTrace::rotateTrace(void)
{ {
if(repeat > 1) { QString f = QDir::tempPath() + "/rbutil-trace.log.1";
debugbuffer.append( if(QFileInfo(f).exists()) {
QString(" (Last message repeated %1 times.)\n").arg(repeat)); QFile::remove(f);
#if !defined(NODEBUG)
fprintf(stderr, " (Last message repeated %i times.)\n", repeat);
#endif
} }
QFile::rename(QDir::tempPath() + "/rbutil-trace.log", f);
} }

View file

@ -29,20 +29,12 @@ class SysTrace : public QDialog
Q_OBJECT Q_OBJECT
public: public:
SysTrace(QWidget *parent); SysTrace(QWidget *parent);
#if QT_VERSION < 0x050000 static QString getTrace(void);
static void debug(QtMsgType type, const char* msg);
#else
static void debug(QtMsgType type, const QMessageLogContext &context, const QString &msg);
#endif
static QString getTrace() {return debugbuffer;}
static void save(QString filename = ""); static void save(QString filename = "");
static void rotateTrace(void);
private: private:
static void flush(void);
void changeEvent(QEvent *event); void changeEvent(QEvent *event);
Ui::SysTraceFrm ui; Ui::SysTraceFrm ui;
static QString debugbuffer;
static QString lastmessage;
static unsigned int repeat;
private slots: private slots:
void saveCurrentTrace(void); void saveCurrentTrace(void);

View file

@ -28,6 +28,7 @@
#include "systeminfo.h" #include "systeminfo.h"
#include "rockboxinfo.h" #include "rockboxinfo.h"
#include "version.h" #include "version.h"
#include "Logger.h"
ThemesInstallWindow::ThemesInstallWindow(QWidget *parent) : QDialog(parent) ThemesInstallWindow::ThemesInstallWindow(QWidget *parent) : QDialog(parent)
{ {
@ -79,7 +80,7 @@ void ThemesInstallWindow::downloadInfo()
= RockboxInfo(RbSettings::value(RbSettings::Mountpoint).toString()); = RockboxInfo(RbSettings::value(RbSettings::Mountpoint).toString());
themesInfo.open(); themesInfo.open();
qDebug() << "[Themes] downloading info to" << themesInfo.fileName(); LOG_INFO() << "downloading info to" << themesInfo.fileName();
themesInfo.close(); themesInfo.close();
QString infoUrl = SystemInfo::value(SystemInfo::ThemesInfoUrl).toString(); QString infoUrl = SystemInfo::value(SystemInfo::ThemesInfoUrl).toString();
@ -89,7 +90,7 @@ void ThemesInstallWindow::downloadInfo()
infoUrl.replace("%RELEASE%", installInfo.release()); infoUrl.replace("%RELEASE%", installInfo.release());
infoUrl.replace("%RBUTILVER%", VERSION); infoUrl.replace("%RBUTILVER%", VERSION);
QUrl url = QUrl(infoUrl); QUrl url = QUrl(infoUrl);
qDebug() << "[Themes] Info URL:" << url; LOG_INFO() << "Info URL:" << url;
getter->setFile(&themesInfo); getter->setFile(&themesInfo);
connect(getter, SIGNAL(done(bool)), this, SLOT(downloadDone(bool))); connect(getter, SIGNAL(done(bool)), this, SLOT(downloadDone(bool)));
@ -101,13 +102,13 @@ void ThemesInstallWindow::downloadInfo()
void ThemesInstallWindow::downloadDone(int id, bool error) void ThemesInstallWindow::downloadDone(int id, bool error)
{ {
downloadDone(error); downloadDone(error);
qDebug() << "[Themes] Download" << id << "done, error:" << error; LOG_INFO() << "Download" << id << "done, error:" << error;
} }
void ThemesInstallWindow::downloadDone(bool error) void ThemesInstallWindow::downloadDone(bool error)
{ {
qDebug() << "[Themes] Download done, error:" << error; LOG_INFO() << "Download done, error:" << error;
disconnect(logger, SIGNAL(aborted()), getter, SLOT(abort())); disconnect(logger, SIGNAL(aborted()), getter, SLOT(abort()));
disconnect(logger, SIGNAL(aborted()), this, SLOT(close())); disconnect(logger, SIGNAL(aborted()), this, SLOT(close()));
@ -115,10 +116,10 @@ void ThemesInstallWindow::downloadDone(bool error)
QSettings iniDetails(themesInfo.fileName(), QSettings::IniFormat, this); QSettings iniDetails(themesInfo.fileName(), QSettings::IniFormat, this);
QStringList tl = iniDetails.childGroups(); QStringList tl = iniDetails.childGroups();
qDebug() << "[Themes] Theme site result:" LOG_INFO() << "Theme site result:"
<< iniDetails.value("error/code").toString() << iniDetails.value("error/code").toString()
<< iniDetails.value("error/description").toString() << iniDetails.value("error/description").toString()
<< iniDetails.value("error/query").toString(); << iniDetails.value("error/query").toString();
if(error) { if(error) {
logger->addItem(tr("Network error: %1.\n" logger->addItem(tr("Network error: %1.\n"
@ -132,8 +133,8 @@ void ThemesInstallWindow::downloadDone(bool error)
} }
// handle possible error codes // handle possible error codes
if(iniDetails.value("error/code").toInt() != 0 || !iniDetails.contains("error/code")) { if(iniDetails.value("error/code").toInt() != 0 || !iniDetails.contains("error/code")) {
qDebug() << "[Themes] Theme site returned an error:" LOG_ERROR() << "Theme site returned an error:"
<< iniDetails.value("error/code"); << iniDetails.value("error/code");
logger->addItem(tr("the following error occured:\n%1") logger->addItem(tr("the following error occured:\n%1")
.arg(iniDetails.value("error/description", "unknown error").toString()), LOGERROR); .arg(iniDetails.value("error/description", "unknown error").toString()), LOGERROR);
logger->setFinished(); logger->setFinished();
@ -152,7 +153,7 @@ void ThemesInstallWindow::downloadDone(bool error)
iniDetails.endGroup(); iniDetails.endGroup();
continue; continue;
} }
qDebug() << "[Themes] adding to list:" << tl.at(i); LOG_INFO() << "adding to list:" << tl.at(i);
// convert to unicode and replace HTML-specific entities // convert to unicode and replace HTML-specific entities
QByteArray raw = iniDetails.value("name").toByteArray(); QByteArray raw = iniDetails.value("name").toByteArray();
QTextCodec* codec = QTextCodec::codecForHtml(raw); QTextCodec* codec = QTextCodec::codecForHtml(raw);
@ -175,7 +176,7 @@ void ThemesInstallWindow::downloadDone(bool error)
msg = iniDetails.value("status/msg." + lang).toString(); msg = iniDetails.value("status/msg." + lang).toString();
else else
msg = iniDetails.value("status/msg").toString(); msg = iniDetails.value("status/msg").toString();
qDebug() << "[Themes] MOTD" << msg; LOG_INFO() << "MOTD" << msg;
if(!msg.isEmpty()) if(!msg.isEmpty())
QMessageBox::information(this, tr("Information"), msg); QMessageBox::information(this, tr("Information"), msg);
} }
@ -240,7 +241,7 @@ void ThemesInstallWindow::updateDetails(QListWidgetItem* cur, QListWidgetItem* p
void ThemesInstallWindow::updateImage(bool error) void ThemesInstallWindow::updateImage(bool error)
{ {
qDebug() << "[Themes] Updating image:"<< !error; LOG_INFO() << "Updating image:"<< !error;
if(error) { if(error) {
ui.themePreview->clear(); ui.themePreview->clear();
@ -266,8 +267,7 @@ void ThemesInstallWindow::updateImage(bool error)
void ThemesInstallWindow::resizeEvent(QResizeEvent* e) void ThemesInstallWindow::resizeEvent(QResizeEvent* e)
{ {
qDebug() << "[Themes]" << e; (void)e;
QPixmap p, q; QPixmap p, q;
QSize img; QSize img;
img.setHeight(ui.themePreview->height()); img.setHeight(ui.themePreview->height());
@ -344,13 +344,13 @@ void ThemesInstallWindow::install()
QDate().currentDate().toString("yyyyMMdd")).toString()); QDate().currentDate().toString("yyyyMMdd")).toString());
iniDetails.endGroup(); iniDetails.endGroup();
} }
qDebug() << "[Themes] installing:" << themes; LOG_INFO() << "installing:" << themes;
if(logger == NULL) if(logger == NULL)
logger = new ProgressLoggerGui(this); logger = new ProgressLoggerGui(this);
logger->show(); logger->show();
QString mountPoint = RbSettings::value(RbSettings::Mountpoint).toString(); QString mountPoint = RbSettings::value(RbSettings::Mountpoint).toString();
qDebug() << "[Themes] mountpoint:" << mountPoint; LOG_INFO() << "mountpoint:" << mountPoint;
// show dialog with error if mount point is wrong // show dialog with error if mount point is wrong
if(!QFileInfo(mountPoint).isDir()) { if(!QFileInfo(mountPoint).isDir()) {
logger->addItem(tr("Mount point is wrong!"),LOGERROR); logger->addItem(tr("Mount point is wrong!"),LOGERROR);