additional step in rewriting commandline parameter handling

This commit is contained in:
csoler 2024-02-11 22:16:50 +01:00
parent 4f56c7dd2f
commit c5aface2cb
21 changed files with 878 additions and 688 deletions

View file

@ -142,7 +142,7 @@ void AboutWidget::updateTitle()
{ {
if (tWidget == NULL) if (tWidget == NULL)
{ {
setWindowTitle(QString("%1 %2").arg(tr("About RetroShare"), Rshare::retroshareVersion(true))); setWindowTitle(QString("%1 %2").arg(tr("About RetroShare"), RsApplication::retroshareVersion(true)));
} }
else else
{ {
@ -228,7 +228,7 @@ void AWidget::initImages()
#ifdef RS_ONLYHIDDENNODE #ifdef RS_ONLYHIDDENNODE
p.drawText(QPointF(10, 50), QString("%1 : %2 (With embedded Tor)").arg(tr("Retroshare version"), Rshare::retroshareVersion(true))); p.drawText(QPointF(10, 50), QString("%1 : %2 (With embedded Tor)").arg(tr("Retroshare version"), Rshare::retroshareVersion(true)));
#else #else
p.drawText(QPointF(10, 50), QString("%1 : %2").arg(tr("Retroshare version"), Rshare::retroshareVersion(true))); p.drawText(QPointF(10, 50), QString("%1 : %2").arg(tr("Retroshare version"), RsApplication::retroshareVersion(true)));
#endif #endif
/* Draw Qt's version number */ /* Draw Qt's version number */
@ -936,7 +936,7 @@ void AboutWidget::on_copy_button_clicked()
{ {
QString verInfo; QString verInfo;
QString rsVerString = "RetroShare Version: "; QString rsVerString = "RetroShare Version: ";
rsVerString+=Rshare::retroshareVersion(true); rsVerString+=RsApplication::retroshareVersion(true);
verInfo+=rsVerString; verInfo+=rsVerString;
#ifdef RS_ONLYHIDDENNODE #ifdef RS_ONLYHIDDENNODE
verInfo+=" " + tr("Only Hidden Node"); verInfo+=" " + tr("Only Hidden Node");

View file

@ -325,7 +325,7 @@ void SearchDialog::checkText(const QString& txt)
ui.searchButton->setDisabled(txt.length() < 3); ui.searchButton->setDisabled(txt.length() < 3);
ui.searchLineFrame->setProperty("valid", (txt.length() >= 3)); ui.searchLineFrame->setProperty("valid", (txt.length() >= 3));
ui.searchLineFrame->style()->unpolish(ui.searchLineFrame); ui.searchLineFrame->style()->unpolish(ui.searchLineFrame);
Rshare::refreshStyleSheet(ui.searchLineFrame, false); RsApplication::refreshStyleSheet(ui.searchLineFrame, false);
} }
void SearchDialog::initialiseFileTypeMappings() void SearchDialog::initialiseFileTypeMappings()

View file

@ -649,7 +649,7 @@ void GenCertDialog::genPerson()
{ {
/* complete the process */ /* complete the process */
RsInit::LoadPassword(sslPasswd); RsInit::LoadPassword(sslPasswd);
if (Rshare::loadCertificate(sslId, false)) { if (RsApplication::loadCertificate(sslId, false)) {
// Normally we should clear the cached passphrase as soon as possible. However,some other GUI components may still need it at start. // Normally we should clear the cached passphrase as soon as possible. However,some other GUI components may still need it at start.
// (csoler) This is really bad: we have to guess that 30 secs will be enough. I have no better way to do this. // (csoler) This is really bad: we have to guess that 30 secs will be enough. I have no better way to do this.

View file

@ -421,7 +421,7 @@ void GetStartedDialog::emailSupport()
sysVersion = "Linux"; sysVersion = "Linux";
#endif #endif
#endif #endif
text += QString("My RetroShare Configuration is: (%1, %2, %3)").arg(Rshare::retroshareVersion(true) text += QString("My RetroShare Configuration is: (%1, %2, %3)").arg(RsApplication::retroshareVersion(true)
, sysVersion , sysVersion
).arg(static_cast<typename std::underlying_type<RsConfigUserLvl>::type>(userLevel)) + "\n"; ).arg(static_cast<typename std::underlying_type<RsConfigUserLvl>::type>(userLevel)) + "\n";
text += "\n"; text += "\n";

View file

@ -80,7 +80,7 @@ HelpDialog::HelpDialog(QWidget *parent) :
ui->thanks->setHtml(in.readAll()); ui->thanks->setHtml(in.readAll());
} }
ui->version->setText(Rshare::retroshareVersion(true)); ui->version->setText(RsApplication::retroshareVersion(true));
/* Add version numbers of libretroshare */ /* Add version numbers of libretroshare */
std::list<RsLibraryInfo> libraries; std::list<RsLibraryInfo> libraries;

View file

@ -703,7 +703,7 @@ void IdEditDialog::updateInterface()
const QPixmap *pixmap = ui->avatarLabel->pixmap(); const QPixmap *pixmap = ui->avatarLabel->pixmap();
if (pixmap && !pixmap->isNull()) { if (pixmap && !pixmap->isNull()) {
ui->removeButton->setEnabled(true); ui->removeButton->setEnabled(true);
} else if (mEditGroup.mImage.mSize != NULL) { } else if (mEditGroup.mImage.mSize > 0) {
ui->removeButton->setEnabled(true); ui->removeButton->setEnabled(true);
} else { } else {
ui->removeButton->setEnabled(false); ui->removeButton->setEnabled(false);

View file

@ -32,6 +32,7 @@
#include <retroshare/rsplugin.h> #include <retroshare/rsplugin.h>
#include <retroshare/rsconfig.h> #include <retroshare/rsconfig.h>
#include <util/argstream.h>
#if defined(Q_OS_DARWIN) #if defined(Q_OS_DARWIN)
#include "gui/common/MacDockIconHandler.h" #include "gui/common/MacDockIconHandler.h"
@ -211,7 +212,7 @@ MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags)
hiddenmode = true; hiddenmode = true;
} }
setWindowTitle(tr("RetroShare %1 a secure decentralized communication platform").arg(Rshare::retroshareVersion(true)) + " - " + nameAndLocation); setWindowTitle(tr("RetroShare %1 a secure decentralized communication platform").arg(RsApplication::retroshareVersion(true)) + " - " + nameAndLocation);
connect(rApp, SIGNAL(newArgsReceived(QStringList)), this, SLOT(receiveNewArgs(QStringList))); connect(rApp, SIGNAL(newArgsReceived(QStringList)), this, SLOT(receiveNewArgs(QStringList)));
/* add url handler for RetroShare links */ /* add url handler for RetroShare links */
@ -1253,10 +1254,87 @@ void MainWindow::doQuit()
rApp->quit(); rApp->quit();
} }
// This method parses arguments passed by another process. All arguments
// except -r, -f, -o and lists of rscollection files and rslinks are discarded.
//
void MainWindow::receiveNewArgs(QStringList args) void MainWindow::receiveNewArgs(QStringList args)
{ {
Rshare::parseArguments(args, false); QString arg, argl, value;
processLastArgs(); std::vector<const char *> argv;
for(auto l:args)
argv.push_back((const char *)l.data());
// This class does all the job at once: validate arguments, and parses them.
std::vector<std::string> links_and_files;
argstream as(argv.size(),const_cast<char **>(argv.data()));
QString omValues = QString(";full;noturtle;gaming;minimal;");
std::string opModeStr;
std::string retroshare_link_url;
std::string rscollection_file;
as >> parameter('r',"rslink",retroshare_link_url,"Retroshare:// link","Retroshare link to open in Downloads " ,false)
>> parameter('f',"rsfile",rscollection_file,"file","File to open " ,false)
>> parameter('o',"opmode",opModeStr,"opmode","Set mode (Full, NoTurtle, Gaming, Minimal) " ,false)
>> values<std::string>(back_inserter(links_and_files),"links and files");
if(!as.isOk())
{
RsErr() << "Error while parsing arguments:" ;
RsErr() << as.errorLog() ;
return;
}
if(!opModeStr.empty() && omValues.contains(";"+QString::fromStdString(opModeStr).toLower()+";"))
{
QString opmode = QString::fromStdString(opModeStr).toLower();
//RsApplication::setOpMode(opModeStr.toLower()); // Do we need this??
if (opmode == "noturtle")
opModeStatus->setCurrentIndex(static_cast<typename std::underlying_type<RsOpMode>::type>(RsOpMode::NOTURTLE) - 1);
else if (opmode == "gaming")
opModeStatus->setCurrentIndex(static_cast<typename std::underlying_type<RsOpMode>::type>(RsOpMode::GAMING) - 1);
else if (opmode == "minimal")
opModeStatus->setCurrentIndex(static_cast<typename std::underlying_type<RsOpMode>::type>(RsOpMode::MINIMAL) - 1);
else if (opmode != "")
opModeStatus->setCurrentIndex(static_cast<typename std::underlying_type<RsOpMode>::type>(RsOpMode::FULL) - 1);
opModeStatus->setOpMode();
}
// Sort all collected arguments into rscollection files and retroshare links, accordingly
QStringList rscollection_files;
QList<RetroShareLink> rslinks;
auto sort = [&](const QString s) {
if(QFile(s).exists() && s.endsWith(".rscollection"))
rscollection_files.append(QString::fromUtf8(rscollection_file.c_str()));
else if(s.startsWith("retroshare://"))
{
RetroShareLink link(s);
if(link.valid())
rslinks.push_back(link);
}
};
sort(QString::fromUtf8(rscollection_file.c_str()));
sort(QString::fromUtf8(retroshare_link_url.c_str()));
for(auto s:links_and_files)
sort(QString::fromUtf8(s.c_str()));
// Now handle links and rscollection files.
for(auto file:rscollection_files)
if(file.endsWith(".rscollection"))
openRsCollection(file);
for(auto link:rslinks)
retroshareLinkActivated(link.toUrl());
} }
void MainWindow::displayErrorMessage(int /*a*/,int /*b*/,const QString& error_msg) void MainWindow::displayErrorMessage(int /*a*/,int /*b*/,const QString& error_msg)
@ -1633,35 +1711,6 @@ void MainWindow::openRsCollection(const QString &filename)
void MainWindow::processLastArgs() void MainWindow::processLastArgs()
{ {
while (!Rshare::links()->isEmpty()) {
std::cerr << "MainWindow::processLastArgs() : " << Rshare::links()->count() << std::endl;
/* Now use links from the command line, because no RetroShare was running */
RetroShareLink link(Rshare::links()->takeFirst());
if (link.valid()) {
retroshareLinkActivated(link.toUrl());
}
}
while (!Rshare::files()->isEmpty()) {
/* Now use files from the command line, because no RetroShare was running */
openRsCollection(Rshare::files()->takeFirst());
}
/* Handle the -opmode options. */
if (opModeStatus) {
QString opmode = Rshare::opmode().toLower();
if (opmode == "noturtle") {
opModeStatus->setCurrentIndex(static_cast<typename std::underlying_type<RsOpMode>::type>(RsOpMode::NOTURTLE) - 1);
} else if (opmode == "gaming") {
opModeStatus->setCurrentIndex(static_cast<typename std::underlying_type<RsOpMode>::type>(RsOpMode::GAMING) - 1);
} else if (opmode == "minimal") {
opModeStatus->setCurrentIndex(static_cast<typename std::underlying_type<RsOpMode>::type>(RsOpMode::MINIMAL) - 1);
} else if (opmode != "") {
opModeStatus->setCurrentIndex(static_cast<typename std::underlying_type<RsOpMode>::type>(RsOpMode::FULL) - 1);
}
opModeStatus->setOpMode();
} else {
std::cerr << "ERR: MainWindow::processLastArgs opModeStatus is not initialized.";
}
} }
void MainWindow::switchVisibilityStatus(StatusElement e,bool b) void MainWindow::switchVisibilityStatus(StatusElement e,bool b)

View file

@ -41,7 +41,7 @@
PluginManager::PluginManager() PluginManager::PluginManager()
{ {
baseFolder = //qApp->applicationDirPath()+"///plugins" ; baseFolder = //qApp->applicationDirPath()+"///plugins" ;
Rshare::dataDirectory() + "/plugins" ; RsApplication::dataDirectory() + "/plugins" ;
lastError = "No error."; lastError = "No error.";
viewWidget = 0; viewWidget = 0;

View file

@ -123,7 +123,7 @@ void StartDialog::loadPerson()
rsNotify->cachePgpPassphrase(ui.password_input->text().toUtf8().constData()) ; rsNotify->cachePgpPassphrase(ui.password_input->text().toUtf8().constData()) ;
rsNotify->setDisableAskPassword(true); rsNotify->setDisableAskPassword(true);
bool res = Rshare::loadCertificate(accountId, ui.autologin_checkbox->isChecked()) ; bool res = RsApplication::loadCertificate(accountId, ui.autologin_checkbox->isChecked()) ;
rsNotify->setDisableAskPassword(false); rsNotify->setDisableAskPassword(false);
rsNotify->clearPgpPassphrase(); rsNotify->clearPgpPassphrase();

View file

@ -121,7 +121,7 @@ void AvatarWidget::setFrameType(FrameType type)
//refreshAvatarImage(); //refreshAvatarImage();
refreshStatus(); refreshStatus();
Rshare::refreshStyleSheet(this, false); RsApplication::refreshStyleSheet(this, false);
} }
void AvatarWidget::setId(const ChatId &id) void AvatarWidget::setId(const ChatId &id)
{ {
@ -174,7 +174,7 @@ void AvatarWidget::refreshStatus()
case NO_FRAME: case NO_FRAME:
case NORMAL_FRAME: case NORMAL_FRAME:
{ {
Rshare::refreshStyleSheet(this, false); RsApplication::refreshStyleSheet(this, false);
break; break;
} }
case STATUS_FRAME: case STATUS_FRAME:
@ -252,7 +252,7 @@ void AvatarWidget::updateStatus(int status)
mPeerState = status; mPeerState = status;
setEnabled(((uint32_t) status == RS_STATUS_OFFLINE) ? false : true); setEnabled(((uint32_t) status == RS_STATUS_OFFLINE) ? false : true);
Rshare::refreshStyleSheet(this, false); RsApplication::refreshStyleSheet(this, false);
} }
void AvatarWidget::updateAvatar(const QString &peerId) void AvatarWidget::updateAvatar(const QString &peerId)

View file

@ -127,7 +127,7 @@ FriendSelectionWidget::FriendSelectionWidget(QWidget *parent)
ui->filterLineEdit->showFilterIcon(); ui->filterLineEdit->showFilterIcon();
/* Refresh style to have the correct text color */ /* Refresh style to have the correct text color */
Rshare::refreshStyleSheet(this, false); RsApplication::refreshStyleSheet(this, false);
mEventHandlerId_identities = 0; mEventHandlerId_identities = 0;
rsEvents->registerEventsHandler( [this](std::shared_ptr<const RsEvent> event) { rsEvents->registerEventsHandler( [this](std::shared_ptr<const RsEvent> event) {
@ -1225,7 +1225,7 @@ std::string FriendSelectionWidget::idFromItem(QTreeWidgetItem *item)
return item->data(COLUMN_DATA, ROLE_ID).toString().toStdString(); return item->data(COLUMN_DATA, ROLE_ID).toString().toStdString();
} }
void FriendSelectionWidget::sortByChecked(bool sort) void FriendSelectionWidget::sortByChecked(bool)
{ {
mCompareRole->clear(); mCompareRole->clear();
mCompareRole->setRole(COLUMN_NAME,ROLE_SORT_SELECTED); mCompareRole->setRole(COLUMN_NAME,ROLE_SORT_SELECTED);

View file

@ -117,7 +117,7 @@ HelpBrowser::~HelpBrowser()
QString QString
HelpBrowser::language() HelpBrowser::language()
{ {
QString lang = Rshare::language(); QString lang = RsApplication::language();
if (!QDir(":/help/" + lang).exists()) if (!QDir(":/help/" + lang).exists())
lang = "en"; lang = "en";
return lang; return lang;

View file

@ -54,7 +54,7 @@ HelpTextBrowser::loadResource(int type, const QUrl &name)
/* Fall back to English if there is no translation of the specified help /* Fall back to English if there is no translation of the specified help
* page in the current language. */ * page in the current language. */
if (!name.path().contains("/")) { if (!name.path().contains("/")) {
QString language = Rshare::language(); QString language = RsApplication::language();
if (!QDir(":/help/" + language).exists()) if (!QDir(":/help/" + language).exists())
language = "en"; language = "en";
helpPath += language + "/"; helpPath += language + "/";

View file

@ -45,13 +45,13 @@ ProfileWidget::ProfileWidget(QWidget *parent, Qt::WindowFlags flags)
connect(ui.CopyCertButton,SIGNAL(clicked()), this, SLOT(copyCert())); connect(ui.CopyCertButton,SIGNAL(clicked()), this, SLOT(copyCert()));
connect(ui.profile_Button,SIGNAL(clicked()), this, SLOT(profilemanager())); connect(ui.profile_Button,SIGNAL(clicked()), this, SLOT(profilemanager()));
ui.onLineSince->setText(DateTime::formatLongDateTime(Rshare::startupTime())); ui.onLineSince->setText(DateTime::formatLongDateTime(RsApplication::startupTime()));
} }
void ProfileWidget::showEvent ( QShowEvent * /*event*/ ) void ProfileWidget::showEvent ( QShowEvent * /*event*/ )
{ {
/* set retroshare version */ /* set retroshare version */
ui.version->setText(Rshare::retroshareVersion(true)); ui.version->setText(RsApplication::retroshareVersion(true));
RsPeerDetails detail; RsPeerDetails detail;
if (rsPeers->getPeerDetails(rsPeers->getOwnId(),detail)) if (rsPeers->getPeerDetails(rsPeers->getOwnId(),detail))

View file

@ -84,7 +84,7 @@ AppearancePage::AppearancePage(QWidget * parent, Qt::WindowFlags flags)
} }
QMap<QString, QString> styleSheets; QMap<QString, QString> styleSheets;
Rshare::getAvailableStyleSheets(styleSheets); RsApplication::getAvailableStyleSheets(styleSheets);
foreach (QString name, styleSheets.keys()) { foreach (QString name, styleSheets.keys()) {
ui.cmboStyleSheet->addItem(name, styleSheets[name]); ui.cmboStyleSheet->addItem(name, styleSheets[name]);
@ -136,7 +136,7 @@ void AppearancePage::updateInterfaceStyle()
#ifndef QT_NO_CURSOR #ifndef QT_NO_CURSOR
QApplication::setOverrideCursor(Qt::WaitCursor); QApplication::setOverrideCursor(Qt::WaitCursor);
#endif #endif
Rshare::setStyle(ui.cmboStyle->currentText()); RsApplication::setStyle(ui.cmboStyle->currentText());
Settings->setInterfaceStyle(ui.cmboStyle->currentText()); Settings->setInterfaceStyle(ui.cmboStyle->currentText());
#ifndef QT_NO_CURSOR #ifndef QT_NO_CURSOR
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
@ -152,7 +152,7 @@ void AppearancePage::loadStyleSheet(int index)
#ifndef QT_NO_CURSOR #ifndef QT_NO_CURSOR
QApplication::setOverrideCursor(Qt::WaitCursor); QApplication::setOverrideCursor(Qt::WaitCursor);
#endif #endif
Rshare::loadStyleSheet(ui.cmboStyleSheet->itemData(index).toString()); RsApplication::loadStyleSheet(ui.cmboStyleSheet->itemData(index).toString());
#ifndef QT_NO_CURSOR #ifndef QT_NO_CURSOR
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
#endif #endif
@ -251,7 +251,7 @@ void AppearancePage::updateCmboToolButtonSize()
// NotifyQt::getInstance()->notifySettingsChanged(); // NotifyQt::getInstance()->notifySettingsChanged();
// } // }
void AppearancePage::updateStyle() { Rshare::setStyle(ui.cmboStyle->currentText()); } void AppearancePage::updateStyle() { RsApplication::setStyle(ui.cmboStyle->currentText()); }
/** Loads the settings for this page */ /** Loads the settings for this page */
void AppearancePage::load() void AppearancePage::load()
@ -259,7 +259,7 @@ void AppearancePage::load()
int index = ui.cmboLanguage->findData(Settings->getLanguageCode()); int index = ui.cmboLanguage->findData(Settings->getLanguageCode());
whileBlocking(ui.cmboLanguage)->setCurrentIndex(index); whileBlocking(ui.cmboLanguage)->setCurrentIndex(index);
index = ui.cmboStyle->findData(Rshare::style().toLower()); index = ui.cmboStyle->findData(RsApplication::style().toLower());
whileBlocking(ui.cmboStyle)->setCurrentIndex(index); whileBlocking(ui.cmboStyle)->setCurrentIndex(index);
index = ui.cmboStyleSheet->findData(Settings->getSheetName()); index = ui.cmboStyleSheet->findData(Settings->getSheetName());

View file

@ -66,7 +66,7 @@ CryptoPage::CryptoPage(QWidget * parent, Qt::WindowFlags flags)
ui.retroshareId_content_LB->hide(); ui.retroshareId_content_LB->hide();
ui.stackPageCertificate->hide(); ui.stackPageCertificate->hide();
ui.onlinesince->setText(DateTime::formatLongDateTime(Rshare::startupTime())); ui.onlinesince->setText(DateTime::formatLongDateTime(RsApplication::startupTime()));
} }
#ifdef UNUSED_CODE #ifdef UNUSED_CODE
@ -111,7 +111,7 @@ void CryptoPage::showEvent ( QShowEvent * /*event*/ )
ui.retroshareId_content_LB->setText(QString::fromUtf8(invite.c_str())); ui.retroshareId_content_LB->setText(QString::fromUtf8(invite.c_str()));
/* set retroshare version */ /* set retroshare version */
ui.version->setText(Rshare::retroshareVersion(true)); ui.version->setText(RsApplication::retroshareVersion(true));
std::list<RsPgpId> ids; std::list<RsPgpId> ids;
ids.clear(); ids.clear();

View file

@ -910,7 +910,7 @@ void RshareSettings::setUseLocalServer(bool value)
{ {
if (value != getUseLocalServer()) { if (value != getUseLocalServer()) {
setValue("UseLocalServer", value); setValue("UseLocalServer", value);
Rshare::updateLocalServer(); RsApplication::updateLocalServer();
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -50,6 +50,7 @@
#include <lang/languagesupport.h> #include <lang/languagesupport.h>
#include <util/stringutil.h> #include <util/stringutil.h>
#include <util/argstream.h>
#include <retroshare/rsinit.h> #include <retroshare/rsinit.h>
#include <retroshare/rsversion.h> #include <retroshare/rsversion.h>
#include <retroshare/rsplugin.h> #include <retroshare/rsplugin.h>
@ -57,7 +58,7 @@
#include "rshare.h" #include "rshare.h"
/* Available command-line arguments. */ /* Available command-line arguments. */
#define ARG_RESET "reset" /**< Reset Rshare's saved settings. */ #define ARG_RESET "reset" /**< Reset RsApplication's saved settings. */
#define ARG_DATADIR "datadir" /**< Directory to use for data files. */ #define ARG_DATADIR "datadir" /**< Directory to use for data files. */
#define ARG_LOGFILE "logfile" /**< Location of our logfile. */ #define ARG_LOGFILE "logfile" /**< Location of our logfile. */
#define ARG_LOGLEVEL "loglevel" /**< Log verbosity. */ #define ARG_LOGLEVEL "loglevel" /**< Log verbosity. */
@ -86,19 +87,22 @@ static const char* const forwardableArgs[] = {
}; };
/* Static member variables */ /* Static member variables */
QMap<QString, QString> Rshare::_args; /**< List of command-line arguments. */ #ifdef TO_REMOVE
Log Rshare::_log; /**< Logs debugging messages to file or stdout. */ QMap<QString, QString> RsApplication::_args; /**< List of command-line arguments. */
QString Rshare::_style; /**< The current GUI style. */ QString RsApplication::_style; /**< The current GUI style. */
QString Rshare::_stylesheet; /**< The current GUI stylesheet. */ QString RsApplication::_stylesheet; /**< The current GUI stylesheet. */
QString Rshare::_language; /**< The current language. */ QString RsApplication::_language; /**< The current language. */
QString Rshare::_dateformat; /**< The format of dates in feed items etc. */ QString RsApplication::_dateformat; /**< The format of dates in feed items etc. */
QString Rshare::_opmode; /**< The operating mode passed by args. */ QString RsApplication::_opmode; /**< The operating mode passed by args. */
QStringList Rshare::_links; /**< List of links passed by arguments. */ QStringList RsApplication::_links; /**< List of links passed by arguments. */
QStringList Rshare::_files; /**< List of files passed by arguments. */ QStringList RsApplication::_files; /**< List of files passed by arguments. */
QDateTime Rshare::mStartupTime; bool RsApplication::useConfigDir;
bool Rshare::useConfigDir; QString RsApplication::configDir;
QString Rshare::configDir; #endif
QLocalServer* Rshare::localServer; Log RsApplication::log_output; /**< Logs debugging messages to file or stdout. */
RsGUIConfigOptions RsApplication::options;
QDateTime RsApplication::mStartupTime;
QLocalServer* RsApplication::localServer;
/** Catches debugging messages from Qt and sends them to RetroShare's logs. If Qt /** Catches debugging messages from Qt and sends them to RetroShare's logs. If Qt
* emits a QtFatalMsg, we will write the message to the log and then abort(). * emits a QtFatalMsg, we will write the message to the log and then abort().
@ -133,194 +137,177 @@ void qt_msg_handler(QtMsgType type, const char *msg)
} }
} }
static bool notifyRunningInstance() /** Constructor. Parses the command-line arguments, resets RsApplication's
{
// Connect to the Local Server of the main process to notify it
// that a new process had been started
QLocalSocket localSocket;
localSocket.connectToServer(QString(TARGET));
#ifdef DEBUG
std::cerr << "Rshare::Rshare waitForConnected to other instance." << std::endl;
#endif
if( localSocket.waitForConnected(100) )
{
#ifdef DEBUG
std::cerr << "Rshare::Rshare Connection etablished. Waiting for disconnection." << std::endl;
#endif
localSocket.waitForDisconnected(1000);
return true;
}
else
{
#ifdef DEBUG
std::cerr << "Rshare::Rshare failed to connect to other instance." << std::endl;
#endif
return false;
}
}
/** Constructor. Parses the command-line arguments, resets Rshare's
* configuration (if requested), and sets up the GUI style and language * configuration (if requested), and sets up the GUI style and language
* translation. */ * translation.
Rshare::Rshare(QStringList args, int &argc, char **argv, const QString &dir) * the const_cast below is truely horrible, but it allows to hide these unused argc/argv
: QApplication(argc, argv) * when initing RsApplication
*/
RsApplication::RsApplication(const RsGUIConfigOptions& conf)
: QApplication(const_cast<RsGUIConfigOptions*>(&conf)->argc,const_cast<RsGUIConfigOptions*>(&conf)->argv)
{ {
mStartupTime = QDateTime::currentDateTime(); mStartupTime = QDateTime::currentDateTime();
localServer = NULL; localServer = NULL;
options = conf;
//Initialize connection to LocalServer to know if other process runs. #ifdef TO_REMOVE
{ //Initialize connection to LocalServer to know if other process runs.
QString serverName = QString(TARGET);
// check if another instance is running
bool haveRunningInstance = notifyRunningInstance();
bool sendArgsToRunningInstance = haveRunningInstance;
if(args.empty())
sendArgsToRunningInstance = false;
// if we find non-forwardable args, start a new instance
for(int iCurs = 0; iCurs < args.size(); ++iCurs)
{ {
const char* const* argit = forwardableArgs; QString serverName = QString(TARGET);
bool found = false;
while(*argit && iCurs < args.size()) // check if another instance is running
{ bool haveRunningInstance = notifyRunningInstance();
if(args.value(iCurs) == "-"+QString(*argit) || args.value(iCurs) == "--"+QString(*argit))
{ bool sendArgsToRunningInstance = haveRunningInstance;
found = true; if(args.empty())
if(argNeedsValue(*argit))
iCurs++;
}
argit++;
}
if(!found)
sendArgsToRunningInstance = false; sendArgsToRunningInstance = false;
} // if we find non-forwardable args, start a new instance
for(int iCurs = 0; iCurs < args.size(); ++iCurs)
{
const char* const* argit = forwardableArgs;
bool found = false;
while(*argit && iCurs < args.size())
{
if(args.value(iCurs) == "-"+QString(*argit) || args.value(iCurs) == "--"+QString(*argit))
{
found = true;
if(argNeedsValue(*argit))
iCurs++;
}
argit++;
}
if(!found)
sendArgsToRunningInstance = false;
}
if (sendArgsToRunningInstance) { if (sendArgsToRunningInstance) {
// load into shared memory // load into shared memory
QBuffer buffer; QBuffer buffer;
buffer.open(QBuffer::ReadWrite); buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer); QDataStream out(&buffer);
out << args; out << args;
int size = buffer.size(); int size = buffer.size();
QSharedMemory newArgs; QSharedMemory newArgs;
newArgs.setKey(serverName + "_newArgs"); newArgs.setKey(serverName + "_newArgs");
if (newArgs.isAttached()) newArgs.detach(); if (newArgs.isAttached()) newArgs.detach();
if (!newArgs.create(size)) { if (!newArgs.create(size)) {
std::cerr << "(EE) Rshare::Rshare Unable to create shared memory segment of size:" std::cerr << "(EE) RsApplication::RsApplication Unable to create shared memory segment of size:"
<< size << " error:" << newArgs.errorString().toStdString() << "." << std::endl; << size << " error:" << newArgs.errorString().toStdString() << "." << std::endl;
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
std::cerr << "Look with `ipcs -m` for nattch==0 segment. And remove it with `ipcrm -m 'shmid'`." << std::endl; std::cerr << "Look with `ipcs -m` for nattch==0 segment. And remove it with `ipcrm -m 'shmid'`." << std::endl;
//No need for windows, as it removes shared segment directly even when crash. //No need for windows, as it removes shared segment directly even when crash.
#endif #endif
newArgs.detach(); newArgs.detach();
::exit(EXIT_FAILURE); ::exit(EXIT_FAILURE);
} }
newArgs.lock(); newArgs.lock();
char *to = (char*)newArgs.data(); char *to = (char*)newArgs.data();
const char *from = buffer.data().data(); const char *from = buffer.data().data();
memcpy(to, from, qMin(newArgs.size(), size)); memcpy(to, from, qMin(newArgs.size(), size));
newArgs.unlock(); newArgs.unlock();
std::cerr << "Rshare::Rshare waitForConnected to other instance." << std::endl; std::cerr << "RsApplication::RsApplication waitForConnected to other instance." << std::endl;
if(notifyRunningInstance()) if(notifyRunningInstance())
{ {
newArgs.detach(); newArgs.detach();
std::cerr << "Rshare::Rshare Arguments was sended." << std::endl std::cerr << "RsApplication::RsApplication Arguments was sended." << std::endl
<< " To disable it, in Options - General - Misc," << std::endl << " To disable it, in Options - General - Misc," << std::endl
<< " uncheck \"Use Local Server to get new Arguments\"." << std::endl; << " uncheck \"Use Local Server to get new Arguments\"." << std::endl;
::exit(EXIT_SUCCESS); // Terminate the program using STDLib's exit function ::exit(EXIT_SUCCESS); // Terminate the program using STDLib's exit function
} }
else else
std::cerr << "Rshare::Rshare failed to connect to other instance." << std::endl; std::cerr << "RsApplication::RsApplication failed to connect to other instance." << std::endl;
newArgs.detach(); newArgs.detach();
} }
if(!haveRunningInstance) if(!haveRunningInstance)
{ {
// No main process exists // No main process exists
// Or started without arguments // Or started without arguments
// So we start a Local Server to listen for connections from new process // So we start a Local Server to listen for connections from new process
localServer= new QLocalServer(); localServer= new QLocalServer();
QObject::connect(localServer, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished())); QObject::connect(localServer, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished()));
updateLocalServer(); updateLocalServer();
// clear out any old arguments (race condition?) // clear out any old arguments (race condition?)
QSharedMemory newArgs; QSharedMemory newArgs;
newArgs.setKey(QString(TARGET) + "_newArgs"); newArgs.setKey(QString(TARGET) + "_newArgs");
if(newArgs.attach(QSharedMemory::ReadWrite)) if(newArgs.attach(QSharedMemory::ReadWrite))
newArgs.detach(); newArgs.detach();
}
} }
} #endif
#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
qInstallMessageHandler(qt_msg_handler); qInstallMessageHandler(qt_msg_handler);
#else #else
qInstallMsgHandler(qt_msg_handler); qInstallMsgHandler(qt_msg_handler);
#endif #endif
#ifndef __APPLE__ #ifndef __APPLE__
/* set default window icon */ /* set default window icon */
setWindowIcon(FilesDefs::getIconFromQtResourcePath(":/icons/logo_128.png")); setWindowIcon(FilesDefs::getIconFromQtResourcePath(":/icons/logo_128.png"));
#endif #endif
mBlink = true; mBlink = true;
QTimer *timer = new QTimer(this); QTimer *timer = new QTimer(this);
timer->setInterval(500); timer->setInterval(500);
connect(timer, SIGNAL(timeout()), this, SLOT(blinkTimer())); connect(timer, SIGNAL(timeout()), this, SLOT(blinkTimer()));
timer->start(); timer->start();
timer = new QTimer(this); timer = new QTimer(this);
timer->setInterval(60000); timer->setInterval(60000);
connect(timer, SIGNAL(timeout()), this, SIGNAL(minuteTick())); connect(timer, SIGNAL(timeout()), this, SIGNAL(minuteTick()));
timer->start(); timer->start();
/* Read in all our command-line arguments. */ #ifdef TO_REMOVE
parseArguments(args); /* Read in all our command-line arguments. */
parseArguments(args);
#endif
/* Check if we're supposed to reset our config before proceeding. */ /* Check if we're supposed to reset our config before proceeding. */
if (_args.contains(ARG_RESET)) { if (options.optResetParams)
Settings->reset(); {
} RsInfo() << "Resetting Retroshare config parameters, as requested (option -R)";
Settings->reset();
/* Handle the -loglevel and -logfile options. */ }
if (_args.contains(ARG_LOGFILE))
_log.open(_args.value(ARG_LOGFILE));
if (_args.contains(ARG_LOGLEVEL)) {
_log.setLogLevel(Log::stringToLogLevel(
_args.value(ARG_LOGLEVEL)));
if (!_args.contains(ARG_LOGFILE))
_log.open(stdout);
}
if (!_args.contains(ARG_LOGLEVEL) &&
!_args.contains(ARG_LOGFILE))
_log.setLogLevel(Log::Off);
/* config directory */ /* Handle the -loglevel and -logfile options. */
useConfigDir = false; if (options.logLevel != "Off")
if (dir != "") {
{ if (!options.logFileName.isNull())
setConfigDirectory(dir); log_output.open(options.logFileName);
} else
log_output.open(stdout);
/** Initialize support for language translations. */ log_output.setLogLevel(Log::stringToLogLevel(options.logLevel));
//LanguageSupport::initialize(); }
resetLanguageAndStyle(); #ifdef TO_REMOVE
/* config directory */
useConfigDir = false;
if (!conf.optBaseDir.empty())
setConfigDirectory(QString::fromStdString(conf.optBaseDir));
#endif
/* Switch off auto shutdown */ /** Initialize support for language translations. */
setQuitOnLastWindowClosed ( false ); //LanguageSupport::initialize();
/* Initialize GxsIdDetails */ resetLanguageAndStyle();
GxsIdDetails::initialize();
/* Switch off auto shutdown */
setQuitOnLastWindowClosed ( false );
/* Initialize GxsIdDetails */
GxsIdDetails::initialize();
} }
/** Destructor */ /** Destructor */
Rshare::~Rshare() RsApplication::~RsApplication()
{ {
/* Cleanup GxsIdDetails */ /* Cleanup GxsIdDetails */
GxsIdDetails::cleanup(); GxsIdDetails::cleanup();
@ -334,7 +321,7 @@ Rshare::~Rshare()
/** /**
* @brief Executed when new instance connect command is sent to LocalServer * @brief Executed when new instance connect command is sent to LocalServer
*/ */
void Rshare::slotConnectionEstablished() void RsApplication::slotConnectionEstablished()
{ {
QSharedMemory newArgs; QSharedMemory newArgs;
newArgs.setKey(QString(TARGET) + "_newArgs"); newArgs.setKey(QString(TARGET) + "_newArgs");
@ -346,7 +333,7 @@ void Rshare::slotConnectionEstablished()
/* this is not an error. It just means we were notified to check /* this is not an error. It just means we were notified to check
newArgs, but none had been set yet. newArgs, but none had been set yet.
TODO: implement separate ping/take messages TODO: implement separate ping/take messages
std::cerr << "(EE) Rshare::slotConnectionEstablished() Unable to attach to shared memory segment." std::cerr << "(EE) RsApplication::slotConnectionEstablished() Unable to attach to shared memory segment."
<< newArgs.errorString().toStdString() << std::endl; << newArgs.errorString().toStdString() << std::endl;
*/ */
socket->close(); socket->close();
@ -371,22 +358,22 @@ void Rshare::slotConnectionEstablished()
emit newArgsReceived(args); emit newArgsReceived(args);
while (!args.empty()) while (!args.empty())
{ {
std::cerr << "Rshare::slotConnectionEstablished args:" << QString(args.takeFirst()).toStdString() << std::endl; std::cerr << "RsApplication::slotConnectionEstablished args:" << QString(args.takeFirst()).toStdString() << std::endl;
} }
} }
QString Rshare::retroshareVersion(bool) { return RS_HUMAN_READABLE_VERSION; } QString RsApplication::retroshareVersion(bool) { return RS_HUMAN_READABLE_VERSION; }
/** Enters the main event loop and waits until exit() is called. The signal /** Enters the main event loop and waits until exit() is called. The signal
* running() will be emitted when the event loop has started. */ * running() will be emitted when the event loop has started. */
int int
Rshare::run() RsApplication::run()
{ {
QTimer::singleShot(0, rApp, SLOT(onEventLoopStarted())); QTimer::singleShot(0, rApp, SLOT(onEventLoopStarted()));
return rApp->exec(); return rApp->exec();
} }
QDateTime Rshare::startupTime() QDateTime RsApplication::startupTime()
{ {
return mStartupTime; return mStartupTime;
} }
@ -395,14 +382,15 @@ QDateTime Rshare::startupTime()
* will emit the running() signal to indicate that the application's event * will emit the running() signal to indicate that the application's event
* loop is running. */ * loop is running. */
void void
Rshare::onEventLoopStarted() RsApplication::onEventLoopStarted()
{ {
emit running(); emit running();
} }
#ifdef TO_REMOVE
/** Display usage information regarding command-line arguments. */ /** Display usage information regarding command-line arguments. */
/*void /*void
Rshare::printUsage(QString errmsg) RsApplication::printUsage(QString errmsg)
{ {
QTextStream out(stdout);*/ QTextStream out(stdout);*/
@ -417,18 +405,18 @@ Rshare::printUsage(QString errmsg)
/* And available options */ /* And available options */
//out << endl << "Available Options:" << endl; //out << endl << "Available Options:" << endl;
//out << "\t-"ARG_RESET"\t\tResets ALL stored Rshare settings." << endl; //out << "\t-"ARG_RESET"\t\tResets ALL stored RsApplication settings." << endl;
//out << "\t-"ARG_DATADIR"\tSets the directory Rshare uses for data files"<< endl; //out << "\t-"ARG_DATADIR"\tSets the directory RsApplication uses for data files"<< endl;
//out << "\t-"ARG_GUISTYLE"\t\tSets Rshare's interface style." << endl; //out << "\t-"ARG_GUISTYLE"\t\tSets RsApplication's interface style." << endl;
//out << "\t-"ARG_GUISTYLESHEET"\t\tSets Rshare's stylesheet." << endl; //out << "\t-"ARG_GUISTYLESHEET"\t\tSets RsApplication's stylesheet." << endl;
//out << "\t\t\t[" << QStyleFactory::keys().join("|") << "]" << endl; //out << "\t\t\t[" << QStyleFactory::keys().join("|") << "]" << endl;
//out << "\t-"ARG_LANGUAGE"\t\tSets Rshare's language." << endl; //out << "\t-"ARG_LANGUAGE"\t\tSets RsApplication's language." << endl;
//out << "\t\t\t[" << LanguageSupport::languageCodes().join("|") << "]" << endl; //out << "\t\t\t[" << LanguageSupport::languageCodes().join("|") << "]" << endl;
//} //}
/** Displays usage information for command-line args. */ /** Displays usage information for command-line args. */
void void
Rshare::showUsageMessageBox() RsApplication::showUsageMessageBox()
{ {
QString usage; QString usage;
QTextStream out(&usage); QTextStream out(&usage);
@ -469,7 +457,7 @@ Rshare::showUsageMessageBox()
/** Returns true if the specified argument expects a value. */ /** Returns true if the specified argument expects a value. */
bool bool
Rshare::argNeedsValue(const QString &argName) RsApplication::argNeedsValue(const QString &argName)
{ {
return ( return (
argName == ARG_DATADIR || argName == ARG_DATADIR ||
@ -489,9 +477,12 @@ Rshare::argNeedsValue(const QString &argName)
/** Parses the list of command-line arguments for their argument names and /** Parses the list of command-line arguments for their argument names and
* values. */ * values. */
void void
Rshare::parseArguments(QStringList args, bool firstRun) RsApplication::parseArguments(QStringList args, bool firstRun)
{ {
QString arg, argl, value; QString arg, argl, value;
std::vector<const char *> argv;
for(auto l:args)
argv.push_back((const char *)l.data());
/* Loop through all command-line args/values and put them in a map */ /* Loop through all command-line args/values and put them in a map */
for (int iCurs = 0; iCurs < args.size(); ++iCurs) { for (int iCurs = 0; iCurs < args.size(); ++iCurs) {
@ -539,11 +530,12 @@ Rshare::parseArguments(QStringList args, bool firstRun)
_args.insert(arg, value); _args.insert(arg, value);
} }
} }
} }
/** Verifies that all specified arguments were valid. */ /** Verifies that all specified arguments were valid. */
bool bool
Rshare::validateArguments(QString &errmsg) RsApplication::validateArguments(QString &errmsg)
{ {
/* Check for a writable log file */ /* Check for a writable log file */
if (_args.contains(ARG_LOGFILE) && !_log.isOpen()) { if (_args.contains(ARG_LOGFILE) && !_log.isOpen()) {
@ -585,13 +577,14 @@ Rshare::validateArguments(QString &errmsg)
} }
return true; return true;
} }
#endif
/** Sets the translation RetroShare will use. If one was specified on the /** Sets the translation RetroShare will use. If one was specified on the
* command-line, we will use that. Otherwise, we'll check to see if one was * command-line, we will use that. Otherwise, we'll check to see if one was
* saved previously. If not, we'll default to one appropriate for the system * saved previously. If not, we'll default to one appropriate for the system
* locale. */ * locale. */
bool bool
Rshare::setLanguage(QString languageCode) RsApplication::setLanguage(QString languageCode)
{ {
/* If the language code is empty, use the previously-saved setting */ /* If the language code is empty, use the previously-saved setting */
if (languageCode.isEmpty()) { if (languageCode.isEmpty()) {
@ -599,7 +592,7 @@ Rshare::setLanguage(QString languageCode)
} }
/* Translate into the desired language */ /* Translate into the desired language */
if (LanguageSupport::translate(languageCode)) { if (LanguageSupport::translate(languageCode)) {
_language = languageCode; options.language = languageCode;
return true; return true;
} }
return false; return false;
@ -610,7 +603,7 @@ Rshare::setLanguage(QString languageCode)
* saved previously. If not, we'll default to the system * saved previously. If not, we'll default to the system
* locale. */ * locale. */
bool bool
Rshare::setLocale(QString languageCode) RsApplication::setLocale(QString languageCode)
{ {
bool retVal = false; bool retVal = false;
/* If the language code is empty, use the previously-saved setting */ /* If the language code is empty, use the previously-saved setting */
@ -626,20 +619,20 @@ Rshare::setLocale(QString languageCode)
} }
/** customize date format for feeds etc. */ /** customize date format for feeds etc. */
void Rshare::customizeDateFormat() void RsApplication::customizeDateFormat()
{ {
QLocale locale = QLocale(); // set to default locale QLocale locale = QLocale(); // set to default locale
/* get long date format without weekday */ /* get long date format without weekday */
_dateformat = locale.dateFormat(QLocale::LongFormat); options.dateformat = locale.dateFormat(QLocale::LongFormat);
_dateformat.replace(QRegExp("^dddd,*[^ ]* *('[^']+' )*"), ""); options.dateformat.replace(QRegExp("^dddd,*[^ ]* *('[^']+' )*"), "");
_dateformat.replace(QRegExp(",* *dddd"), ""); options.dateformat.replace(QRegExp(",* *dddd"), "");
_dateformat = _dateformat.trimmed(); options.dateformat = options.dateformat.trimmed();
} }
/** Get custom date format (defaultlongformat) */ /** Get custom date format (defaultlongformat) */
QString Rshare::customDateFormat() QString RsApplication::customDateFormat()
{ {
return _dateformat; return options.dateformat;
} }
/** Sets the GUI style RetroShare will use. If one was specified on the /** Sets the GUI style RetroShare will use. If one was specified on the
@ -647,49 +640,50 @@ QString Rshare::customDateFormat()
* saved previously. If not, we'll default to one appropriate for the * saved previously. If not, we'll default to one appropriate for the
* operating system. */ * operating system. */
bool bool
Rshare::setStyle(QString styleKey) RsApplication::setStyle(QString styleKey)
{ {
/* If no style was specified, use the previously-saved setting */ /* If no style was specified, use the previously-saved setting */
if (styleKey.isEmpty()) { if (styleKey.isEmpty()) {
styleKey = Settings->getInterfaceStyle(); styleKey = Settings->getInterfaceStyle();
} }
/* Apply the specified GUI style */ /* Apply the specified GUI style */
if (QApplication::setStyle(styleKey)) { if (QApplication::setStyle(styleKey))
_style = styleKey; {
options.guiStyle = styleKey;
return true; return true;
} }
return false; return false;
} }
bool bool
Rshare::setSheet(QString sheet) RsApplication::setSheet(QString sheet)
{ {
/* If no stylesheet was specified, use the previously-saved setting */ /* If no stylesheet was specified, use the previously-saved setting */
if (sheet.isEmpty()) { if (sheet.isEmpty()) {
sheet = Settings->getSheetName(); sheet = Settings->getSheetName();
} }
/* Apply the specified GUI stylesheet */ /* Apply the specified GUI stylesheet */
_stylesheet = sheet; options.guiStyleSheetFile = sheet;
/* load the StyleSheet*/ /* load the StyleSheet*/
loadStyleSheet(_stylesheet); loadStyleSheet(options.guiStyleSheetFile);
return true; return true;
} }
void Rshare::resetLanguageAndStyle() void RsApplication::resetLanguageAndStyle()
{ {
/** Translate the GUI to the appropriate language. */ /** Translate the GUI to the appropriate language. */
setLanguage(_args.value(ARG_LANGUAGE)); setLanguage(options.language);
/** Set the locale appropriately. */ /** Set the locale appropriately. */
setLocale(_args.value(ARG_LANGUAGE)); setLocale(options.language);
/** Set the GUI style appropriately. */ /** Set the GUI style appropriately. */
setStyle(_args.value(ARG_GUISTYLE)); setStyle(options.guiStyle);
/** Set the GUI stylesheet appropriately. */ /** Set the GUI stylesheet appropriately. */
setSheet(_args.value(ARG_GUISTYLESHEET)); setSheet(options.guiStyleSheetFile);
} }
// RetroShare: // RetroShare:
@ -714,7 +708,7 @@ void Rshare::resetLanguageAndStyle()
// Language depended stylesheet // Language depended stylesheet
// <Internal|External>_<locale>.lqss // <Internal|External>_<locale>.lqss
void Rshare::loadStyleSheet(const QString &sheetName) void RsApplication::loadStyleSheet(const QString &sheetName)
{ {
QString locale = QLocale().name(); QString locale = QLocale().name();
QString styleSheet; QString styleSheet;
@ -785,7 +779,7 @@ void Rshare::loadStyleSheet(const QString &sheetName)
} }
/** get list of available stylesheets **/ /** get list of available stylesheets **/
void Rshare::getAvailableStyleSheets(QMap<QString, QString> &styleSheets) void RsApplication::getAvailableStyleSheets(QMap<QString, QString> &styleSheets)
{ {
QFileInfoList fileInfoList = QDir(":/qss/stylesheet/").entryInfoList(QStringList("*.qss")); QFileInfoList fileInfoList = QDir(":/qss/stylesheet/").entryInfoList(QStringList("*.qss"));
QFileInfo fileInfo; QFileInfo fileInfo;
@ -813,7 +807,7 @@ void Rshare::getAvailableStyleSheets(QMap<QString, QString> &styleSheets)
} }
} }
void Rshare::refreshStyleSheet(QWidget *widget, bool processChildren) void RsApplication::refreshStyleSheet(QWidget *widget, bool processChildren)
{ {
if (widget != NULL) { if (widget != NULL) {
// force widget to recalculate valid style // force widget to recalculate valid style
@ -839,40 +833,35 @@ void Rshare::refreshStyleSheet(QWidget *widget, bool processChildren)
} }
/** Initialize plugins. */ /** Initialize plugins. */
void Rshare::initPlugins() void RsApplication::initPlugins()
{ {
loadStyleSheet(_stylesheet); loadStyleSheet(options.guiStyleSheetFile);
LanguageSupport::translatePlugins(_language); LanguageSupport::translatePlugins(options.language);
} }
/** Returns the directory RetroShare uses for its data files. */ /** Returns the directory RetroShare uses for its data files. */
QString QString RsApplication::dataDirectory()
Rshare::dataDirectory()
{ {
if (useConfigDir) if(!options.optBaseDir.empty())
{ return QString::fromUtf8(options.optBaseDir.c_str());
return configDir; else
} return defaultDataDirectory();
else if (_args.contains(ARG_DATADIR)) {
return _args.value(ARG_DATADIR);
}
return defaultDataDirectory();
} }
/** Returns the default location of RetroShare's data directory. */ /** Returns the default location of RetroShare's data directory. */
QString QString
Rshare::defaultDataDirectory() RsApplication::defaultDataDirectory()
{ {
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
return (win32_app_data_folder() + "\\RetroShare"); return (win32_app_data_folder() + "\\RetroShare");
#else #else
return (QDir::homePath() + "/.RetroShare"); return (QDir::homePath() + "/.retroshare");
#endif #endif
} }
/** Creates Rshare's data directory, if it doesn't already exist. */ /** Creates RsApplication's data directory, if it doesn't already exist. */
bool bool
Rshare::createDataDirectory(QString *errmsg) RsApplication::createDataDirectory(QString *errmsg)
{ {
QDir datadir(dataDirectory()); QDir datadir(dataDirectory());
if (!datadir.exists()) { if (!datadir.exists()) {
@ -885,33 +874,29 @@ Rshare::createDataDirectory(QString *errmsg)
return true; return true;
} }
/** Set Rshare's data directory - externally */ /** Set RsApplication's data directory - externally */
bool Rshare::setConfigDirectory(const QString& dir) bool RsApplication::setConfigDirectory(const QString& dir)
{ {
useConfigDir = true; options.optBaseDir = std::string(dir.toUtf8());
configDir = dir;
return true; return true;
} }
/** Writes <b>msg</b> with severity <b>level</b> to RetroShare's log. */ /** Writes <b>msg</b> with severity <b>level</b> to RetroShare's log. */
Log::LogMessage Log::LogMessage RsApplication::log(Log::LogLevel level, QString msg)
Rshare::log(Log::LogLevel level, QString msg)
{ {
return _log.log(level, msg); return log_output.log(level, msg);
} }
/** Creates and binds a shortcut such that when <b>key</b> is pressed in /** Creates and binds a shortcut such that when <b>key</b> is pressed in
* <b>sender</b>'s context, <b>receiver</b>'s <b>slot</b> will be called. */ * <b>sender</b>'s context, <b>receiver</b>'s <b>slot</b> will be called. */
void void RsApplication::createShortcut(const QKeySequence &key, QWidget *sender, QWidget *receiver, const char *slot)
Rshare::createShortcut(const QKeySequence &key, QWidget *sender,
QWidget *receiver, const char *slot)
{ {
QShortcut *s = new QShortcut(key, sender); QShortcut *s = new QShortcut(key, sender);
connect(s, SIGNAL(activated()), receiver, slot); connect(s, SIGNAL(activated()), receiver, slot);
} }
#ifdef __APPLE__ #ifdef __APPLE__
bool Rshare::event(QEvent *event) bool RsApplication::event(QEvent *event)
{ {
switch (event->type()) { switch (event->type()) {
case QEvent::FileOpen:{ case QEvent::FileOpen:{
@ -933,7 +918,7 @@ bool Rshare::event(QEvent *event)
} }
#endif #endif
void Rshare::blinkTimer() void RsApplication::blinkTimer()
{ {
mBlink = !mBlink; mBlink = !mBlink;
emit blink(mBlink); emit blink(mBlink);
@ -944,7 +929,7 @@ void Rshare::blinkTimer()
} }
} }
bool Rshare::loadCertificate(const RsPeerId &accountId, bool autoLogin) bool RsApplication::loadCertificate(const RsPeerId &accountId, bool autoLogin)
{ {
if (!RsAccounts::SelectAccount(accountId)) if (!RsAccounts::SelectAccount(accountId))
{ {
@ -985,14 +970,14 @@ bool Rshare::loadCertificate(const RsPeerId &accountId, bool autoLogin)
// QObject::tr("Login Failure"), // QObject::tr("Login Failure"),
// QObject::tr("Maybe password is wrong") ); // QObject::tr("Maybe password is wrong") );
return false; return false;
default: std::cerr << "Rshare::loadCertificate() unexpected switch value " << retVal << std::endl; default: std::cerr << "RsApplication::loadCertificate() unexpected switch value " << retVal << std::endl;
return false; return false;
} }
return true; return true;
} }
bool Rshare::updateLocalServer() bool RsApplication::updateLocalServer()
{ {
if (localServer) { if (localServer) {
QString serverName = QString(TARGET); QString serverName = QString(TARGET);

View file

@ -36,9 +36,10 @@
#include "util/log.h" #include "util/log.h"
#include "retroshare/rstypes.h" #include "retroshare/rstypes.h"
#include "retroshare/rsinit.h"
/** Pointer to this RetroShare application instance. */ /** Pointer to this RetroShare application instance. */
#define rApp (static_cast<Rshare *>(qApp)) #define rApp (static_cast<RsApplication *>(qApp))
#define rDebug(fmt) (rApp->log(Log::Debug, (fmt))) #define rDebug(fmt) (rApp->log(Log::Debug, (fmt)))
#define rInfo(fmt) (rApp->log(Log::Info, (fmt))) #define rInfo(fmt) (rApp->log(Log::Info, (fmt)))
@ -46,20 +47,39 @@
#define rWarn(fmt) (rApp->log(Log::Warn, (fmt))) #define rWarn(fmt) (rApp->log(Log::Warn, (fmt)))
#define rError(fmt) (rApp->log(Log::Error, (fmt))) #define rError(fmt) (rApp->log(Log::Error, (fmt)))
struct RsGUIConfigOptions: public RsConfigOptions
{
RsGUIConfigOptions()
: logLevel("Off"), argc(0)
{}
class Rshare : public QApplication QString dateformat; // The format for dates in feed items etc.
QString language; // The current language.
QString logFileName; // output filename for log
QString logLevel; // severity threshold for log output
QString guiStyle; // CSS Style for the GUI
QString guiStyleSheetFile; // CSS Style for the GUI
int argc ; // stores argc parameter. Only used by the creator of QApplication
char *argv[1] ; // stores argv parameter. Only used by the creator of QApplication
};
class RsApplication : public QApplication
{ {
Q_OBJECT Q_OBJECT
public: public:
/** Constructor. */ /** Constructor. */
Rshare(QStringList args, int &argc, char **argv, const QString &dir); RsApplication(const RsGUIConfigOptions& conf);
/** Destructor. */ /** Destructor. */
~Rshare(); ~RsApplication();
/** Return the version info */ /** Return the version info */
static QString retroshareVersion(bool=true); static QString retroshareVersion(bool=true);
#ifdef TO_REMOVE
/** Return the map of command-line arguments and values. */ /** Return the map of command-line arguments and values. */
static QMap<QString, QString> arguments() { return _args; } static QMap<QString, QString> arguments() { return _args; }
/** Parse the list of command-line arguments. */ /** Parse the list of command-line arguments. */
@ -72,6 +92,7 @@ public:
static void showUsageMessageBox(); static void showUsageMessageBox();
/** Returns true if the user wants to see usage information. */ /** Returns true if the user wants to see usage information. */
static bool showUsage(); static bool showUsage();
#endif
/** Sets the current language. */ /** Sets the current language. */
static bool setLanguage(QString languageCode = QString()); static bool setLanguage(QString languageCode = QString());
@ -105,17 +126,22 @@ public:
static void initPlugins(); static void initPlugins();
/** Returns the current GUI style. */ /** Returns the current GUI style. */
static QString style() { return _style; } static QString style() { return options.guiStyle; }
/** Returns the current GUI stylesheet. */ /** Returns the current GUI stylesheet. */
static QString stylesheet() { return _stylesheet; } static QString stylesheet() { return options.guiStyleSheetFile; }
/** Returns the current language. */ /** Returns the current language. */
static QString language() { return _language; } static QString language() { return options.language; }
/** Returns the operating mode. */
static QString opmode() { return _opmode; } /** Sets/Returns the operating mode. */
static void setOpMode(const QString& op ) { options.opModeStr = op.toStdString(); }
static QString opmode() { return QString::fromStdString(options.opModeStr); }
#ifdef TO_REMOVE
/** Returns links passed by arguments. */ /** Returns links passed by arguments. */
static QStringList* links() { return &_links; } static QStringList* links() { return &_links; }
/** Returns files passed by arguments. */ /** Returns files passed by arguments. */
static QStringList* files() {return &_files; } static QStringList* files() {return &_files; }
#endif
/** Returns Rshare's application startup time. */ /** Returns Rshare's application startup time. */
static QDateTime startupTime(); static QDateTime startupTime();
@ -176,24 +202,17 @@ private:
/** customize the date format (defaultlongformat) */ /** customize the date format (defaultlongformat) */
static void customizeDateFormat(); static void customizeDateFormat();
#ifdef TO_REMOVE
/** Returns true if the specified arguments wants a value. */ /** Returns true if the specified arguments wants a value. */
static bool argNeedsValue(const QString &argName); static bool argNeedsValue(const QString &argName);
#endif
static QMap<QString, QString> _args; /**< List of command-line arguments. */
static Log _log; /**< Logs debugging messages to file or stdout. */
static QString _style; /**< The current GUI style. */
static QString _stylesheet; /**< The current GUI stylesheet. */
static QString _language; /**< The current language. */
static QString _dateformat; /**< The format for dates in feed items etc. */
static QString _opmode; /**< The operating mode passed by args. */
static QStringList _links; /**< List of links passed by arguments. */
static QStringList _files; /**< List of files passed by arguments. */
static QDateTime mStartupTime; // startup time static QDateTime mStartupTime; // startup time
static bool useConfigDir;
static QString configDir;
bool mBlink; bool mBlink;
static QLocalServer* localServer; static QLocalServer* localServer;
static RsGUIConfigOptions options;
static Log log_output;
}; };
#endif #endif

View file

@ -30,7 +30,7 @@ QString DateTime::formatLongDate(time_t dateValue)
QString DateTime::formatLongDate(const QDate &dateValue) QString DateTime::formatLongDate(const QDate &dateValue)
{ {
QString customDateFormat = Rshare::customDateFormat(); QString customDateFormat = RsApplication::customDateFormat();
if (customDateFormat.isEmpty()) { if (customDateFormat.isEmpty()) {
return dateValue.toString(Qt::ISODate); return dateValue.toString(Qt::ISODate);