diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..28da532 --- /dev/null +++ b/.clang-format @@ -0,0 +1,25 @@ +Language: Cpp + +AccessModifierOffset: -4 +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: false +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: false +BasedOnStyle: Microsoft +BreakBeforeBraces: Allman +BreakConstructorInitializers: AfterColon +BreakInheritanceList: AfterColon +ColumnLimit: 200 +ConstructorInitializerAllOnOneLineOrOnePerLine: false +FixNamespaceComments: true +IndentCaseLabels: true +IndentWidth: 4 +IndentWrappedFunctionNames: true +IndentPPDirectives: AfterHash +IncludeBlocks: Preserve +NamespaceIndentation: Inner +SpacesBeforeTrailingComments: 2 +Standard: Auto +ReflowComments: false \ No newline at end of file diff --git a/src/AboutDialog.cpp b/src/AboutDialog.cpp index bbddce2..e2042ea 100644 --- a/src/AboutDialog.cpp +++ b/src/AboutDialog.cpp @@ -2,57 +2,55 @@ #include "ui_AboutDialog.h" #include -AboutDialog::AboutDialog(QWidget *parent, const QString &fossilVersion) : - QDialog(parent), - ui(new Ui::AboutDialog) +AboutDialog::AboutDialog(QWidget *parent, const QString &fossilVersion) : QDialog(parent), ui(new Ui::AboutDialog) { - ui->setupUi(this); - QString banner(QCoreApplication::applicationName() + " " + QCoreApplication::applicationVersion()); - banner += "\n" + ui->lblBanner->text(); - banner += "\nhttps://fuel-scm.org/"; - banner = banner.replace("\n", "
"); - ui->lblBanner->setText(banner); - ui->lblBanner->setOpenExternalLinks(true); - ui->lblBanner->setTextFormat(Qt::RichText); + ui->setupUi(this); + QString banner(QCoreApplication::applicationName() + " " + QCoreApplication::applicationVersion()); + banner += "\n" + ui->lblBanner->text(); + banner += "\nhttps://fuel-scm.org/"; + banner = banner.replace("\n", "
"); + ui->lblBanner->setText(banner); + ui->lblBanner->setOpenExternalLinks(true); + ui->lblBanner->setTextFormat(Qt::RichText); - ui->lblQtVersion->setText(tr("QT version %0").arg(QT_VERSION_STR)); + ui->lblQtVersion->setText(tr("QT version %0").arg(QT_VERSION_STR)); - if(!fossilVersion.isEmpty()) - ui->lblFossilVersion->setText(tr("Fossil version %0").arg(fossilVersion)); + if (!fossilVersion.isEmpty()) + ui->lblFossilVersion->setText(tr("Fossil version %0").arg(fossilVersion)); - QString revisiontxt; - QFile fmanifest(":/version/manifest"); - if(fmanifest.open(QFile::ReadOnly)) - { - QString revision = QString(fmanifest.readAll()).trimmed(); - revisiontxt = QString(tr("Fuel revision %0").arg("%0").arg(revision)); - ui->lblFuelRevision->setOpenExternalLinks(true); - ui->lblFuelRevision->setTextFormat(Qt::RichText); - fmanifest.close(); - } - ui->lblFuelRevision->setText(revisiontxt); + QString revisiontxt; + QFile fmanifest(":/version/manifest"); + if (fmanifest.open(QFile::ReadOnly)) + { + QString revision = QString(fmanifest.readAll()).trimmed(); + revisiontxt = QString(tr("Fuel revision %0").arg("%0").arg(revision)); + ui->lblFuelRevision->setOpenExternalLinks(true); + ui->lblFuelRevision->setTextFormat(Qt::RichText); + fmanifest.close(); + } + ui->lblFuelRevision->setText(revisiontxt); - QString additional; - QFile ftrans(":/docs/docs/Translators.txt"); - if(ftrans.open(QFile::ReadOnly)) - { - additional.append(tr("Translations with the help of:")+"\n"); - additional.append(ftrans.readAll()); - additional.append("\n\n"); - ftrans.close(); - } + QString additional; + QFile ftrans(":/docs/docs/Translators.txt"); + if (ftrans.open(QFile::ReadOnly)) + { + additional.append(tr("Translations with the help of:") + "\n"); + additional.append(ftrans.readAll()); + additional.append("\n\n"); + ftrans.close(); + } - QFile flicenses(":/docs/docs/Licenses.txt"); - if(flicenses.open(QFile::ReadOnly)) - { - additional.append(tr("This sofware uses the following open-source libraries and assets:")+"\n"); - additional.append(flicenses.readAll()); - flicenses.close(); - } - ui->txtAdditional->setText(additional); + QFile flicenses(":/docs/docs/Licenses.txt"); + if (flicenses.open(QFile::ReadOnly)) + { + additional.append(tr("This sofware uses the following open-source libraries and assets:") + "\n"); + additional.append(flicenses.readAll()); + flicenses.close(); + } + ui->txtAdditional->setText(additional); } AboutDialog::~AboutDialog() { - delete ui; + delete ui; } diff --git a/src/AboutDialog.h b/src/AboutDialog.h index 7a9b387..2d2a3c5 100644 --- a/src/AboutDialog.h +++ b/src/AboutDialog.h @@ -3,20 +3,21 @@ #include -namespace Ui { +namespace Ui +{ class AboutDialog; } class AboutDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit AboutDialog(QWidget *parent, const QString &fossilVersion); - ~AboutDialog(); + explicit AboutDialog(QWidget *parent, const QString &fossilVersion); + ~AboutDialog(); private: - Ui::AboutDialog *ui; + Ui::AboutDialog *ui; }; -#endif // ABOUTDIALOG_H +#endif // ABOUTDIALOG_H diff --git a/src/AppSettings.cpp b/src/AppSettings.cpp index d49476c..4d8b585 100644 --- a/src/AppSettings.cpp +++ b/src/AppSettings.cpp @@ -1,131 +1,129 @@ #include "AppSettings.h" -#include #include #include -#include #include +#include #include +#include /////////////////////////////////////////////////////////////////////////////// Settings::Settings(bool portableMode) : store(0) { - Mappings.insert(FOSSIL_SETTING_GDIFF_CMD, Setting("", Setting::TYPE_FOSSIL_GLOBAL)); - Mappings.insert(FOSSIL_SETTING_GMERGE_CMD, Setting("", Setting::TYPE_FOSSIL_GLOBAL)); - Mappings.insert(FOSSIL_SETTING_PROXY_URL, Setting("", Setting::TYPE_FOSSIL_GLOBAL)); - Mappings.insert(FOSSIL_SETTING_HTTP_PORT, Setting("", Setting::TYPE_FOSSIL_GLOBAL)); + Mappings.insert(FOSSIL_SETTING_GDIFF_CMD, Setting("", Setting::TYPE_FOSSIL_GLOBAL)); + Mappings.insert(FOSSIL_SETTING_GMERGE_CMD, Setting("", Setting::TYPE_FOSSIL_GLOBAL)); + Mappings.insert(FOSSIL_SETTING_PROXY_URL, Setting("", Setting::TYPE_FOSSIL_GLOBAL)); + Mappings.insert(FOSSIL_SETTING_HTTP_PORT, Setting("", Setting::TYPE_FOSSIL_GLOBAL)); - Mappings.insert(FOSSIL_SETTING_IGNORE_GLOB, Setting("", Setting::TYPE_FOSSIL_LOCAL)); - Mappings.insert(FOSSIL_SETTING_CRNL_GLOB, Setting("", Setting::TYPE_FOSSIL_LOCAL)); + Mappings.insert(FOSSIL_SETTING_IGNORE_GLOB, Setting("", Setting::TYPE_FOSSIL_LOCAL)); + Mappings.insert(FOSSIL_SETTING_CRNL_GLOB, Setting("", Setting::TYPE_FOSSIL_LOCAL)); - // Go into portable mode when explicitly requested or if a config file exists next to the executable - QString ini_path = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + QDir::separator() + QCoreApplication::applicationName() + ".ini"); - if( portableMode || QFile::exists(ini_path)) - store = new QSettings(ini_path, QSettings::IniFormat); - else - { - // Linux: ~/.config/organizationName/applicationName.conf - // Windows: HKEY_CURRENT_USER\Software\organizationName\Fuel - store = new QSettings(QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName()); - } - Q_ASSERT(store); + // Go into portable mode when explicitly requested or if a config file exists next to the executable + QString ini_path = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + QDir::separator() + QCoreApplication::applicationName() + ".ini"); + if (portableMode || QFile::exists(ini_path)) + store = new QSettings(ini_path, QSettings::IniFormat); + else + { + // Linux: ~/.config/organizationName/applicationName.conf + // Windows: HKEY_CURRENT_USER\Software\organizationName\Fuel + store = new QSettings(QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName()); + } + Q_ASSERT(store); - if(!HasValue(FUEL_SETTING_FILE_DBLCLICK)) - SetValue(FUEL_SETTING_FILE_DBLCLICK, 0); - if(!HasValue(FUEL_SETTING_LANGUAGE) && SupportsLang(QLocale::system().name())) - SetValue(FUEL_SETTING_LANGUAGE, QLocale::system().name()); - if(!HasValue(FUEL_SETTING_WEB_BROWSER)) - SetValue(FUEL_SETTING_WEB_BROWSER, 0); + if (!HasValue(FUEL_SETTING_FILE_DBLCLICK)) + SetValue(FUEL_SETTING_FILE_DBLCLICK, 0); + if (!HasValue(FUEL_SETTING_LANGUAGE) && SupportsLang(QLocale::system().name())) + SetValue(FUEL_SETTING_LANGUAGE, QLocale::system().name()); + if (!HasValue(FUEL_SETTING_WEB_BROWSER)) + SetValue(FUEL_SETTING_WEB_BROWSER, 0); + for (int i = 0; i < MAX_CUSTOM_ACTIONS; ++i) + { + CustomAction action; + action.Id = QObject::tr("Custom Action %0").arg(i + 1); + customActions.append(action); + } - for(int i=0; iremoveTranslator(&translator); - return true; - } + if (langId == "en_US") + { + QCoreApplication::instance()->removeTranslator(&translator); + return true; + } - QString locale_path = QString(":intl/%0.qm").arg(langId); - if(!translator.load(locale_path)) - return false; + QString locale_path = QString(":intl/%0.qm").arg(langId); + if (!translator.load(locale_path)) + return false; - Q_ASSERT(!translator.isEmpty()); - QCoreApplication::instance()->installTranslator(&translator); + Q_ASSERT(!translator.isEmpty()); + QCoreApplication::instance()->installTranslator(&translator); - - return true; + return true; } //----------------------------------------------------------------------------- bool Settings::HasValue(const QString &name) const { - return store->contains(name); + return store->contains(name); } //----------------------------------------------------------------------------- const QVariant Settings::GetValue(const QString &name) { - if(!HasValue(name)) - return QVariant(); - return store->value(name); + if (!HasValue(name)) + return QVariant(); + return store->value(name); } //----------------------------------------------------------------------------- void Settings::SetValue(const QString &name, const QVariant &value) { - store->setValue(name, value); + store->setValue(name, value); } //----------------------------------------------------------------------------- QVariant &Settings::GetFossilValue(const QString &name) { - mappings_t::iterator it=Mappings.find(name); - Q_ASSERT(it!=Mappings.end()); - return it.value().Value; + mappings_t::iterator it = Mappings.find(name); + Q_ASSERT(it != Mappings.end()); + return it.value().Value; } //----------------------------------------------------------------------------- void Settings::SetFossilValue(const QString &name, const QVariant &value) { - mappings_t::iterator it=Mappings.find(name); - Q_ASSERT(it!=Mappings.end()); - it->Value = value; + mappings_t::iterator it = Mappings.find(name); + Q_ASSERT(it != Mappings.end()); + it->Value = value; } //----------------------------------------------------------------------------- bool Settings::SupportsLang(const QString &langId) const { - QString locale_path = QString(":intl/intl/%0.qm").arg(langId); - QResource res(locale_path); - return res.isValid(); + QString locale_path = QString(":intl/intl/%0.qm").arg(langId); + QResource res(locale_path); + return res.isValid(); } diff --git a/src/AppSettings.h b/src/AppSettings.h index 1bf8811..d3ab3d3 100644 --- a/src/AppSettings.h +++ b/src/AppSettings.h @@ -2,125 +2,111 @@ #define APPSETTINGS_H #include -#include #include +#include #include -#define FUEL_SETTING_FOSSIL_PATH "FossilPath" -#define FUEL_SETTING_COMMIT_MSG "CommitMsgHistory" -#define FUEL_SETTING_FILE_DBLCLICK "FileDblClickAction" -#define FUEL_SETTING_LANGUAGE "Language" -#define FUEL_SETTING_WEB_BROWSER "WebBrowser" - -#define FOSSIL_SETTING_GDIFF_CMD "gdiff-command" -#define FOSSIL_SETTING_GMERGE_CMD "gmerge-command" -#define FOSSIL_SETTING_PROXY_URL "proxy" -#define FOSSIL_SETTING_IGNORE_GLOB "ignore-glob" -#define FOSSIL_SETTING_CRNL_GLOB "crnl-glob" -#define FOSSIL_SETTING_HTTP_PORT "http-port" +#define FUEL_SETTING_FOSSIL_PATH "FossilPath" +#define FUEL_SETTING_COMMIT_MSG "CommitMsgHistory" +#define FUEL_SETTING_FILE_DBLCLICK "FileDblClickAction" +#define FUEL_SETTING_LANGUAGE "Language" +#define FUEL_SETTING_WEB_BROWSER "WebBrowser" +#define FOSSIL_SETTING_GDIFF_CMD "gdiff-command" +#define FOSSIL_SETTING_GMERGE_CMD "gmerge-command" +#define FOSSIL_SETTING_PROXY_URL "proxy" +#define FOSSIL_SETTING_IGNORE_GLOB "ignore-glob" +#define FOSSIL_SETTING_CRNL_GLOB "crnl-glob" +#define FOSSIL_SETTING_HTTP_PORT "http-port" enum FileDblClickAction { - FILE_DLBCLICK_ACTION_DIFF, - FILE_DLBCLICK_ACTION_OPEN, - FILE_DLBCLICK_ACTION_OPENCONTAINING, - FILE_DLBCLICK_ACTION_CUSTOM, // Custom Action 1 - FILE_DLBCLICK_ACTION_MAX + FILE_DLBCLICK_ACTION_DIFF, + FILE_DLBCLICK_ACTION_OPEN, + FILE_DLBCLICK_ACTION_OPENCONTAINING, + FILE_DLBCLICK_ACTION_CUSTOM, // Custom Action 1 + FILE_DLBCLICK_ACTION_MAX }; - enum CustomActionContext { - ACTION_CONTEXT_FILES = 1 << 0, - ACTION_CONTEXT_FOLDERS = 1 << 1, - ACTION_CONTEXT_FILES_AND_FOLDERS = ACTION_CONTEXT_FILES|ACTION_CONTEXT_FOLDERS + ACTION_CONTEXT_FILES = 1 << 0, + ACTION_CONTEXT_FOLDERS = 1 << 1, + ACTION_CONTEXT_FILES_AND_FOLDERS = ACTION_CONTEXT_FILES | ACTION_CONTEXT_FOLDERS }; - enum { - MAX_CUSTOM_ACTIONS = 9 + MAX_CUSTOM_ACTIONS = 9 }; struct CustomAction { - QString Id; - QString Description; - QString Command; - CustomActionContext Context; - bool MultipleSelection; + QString Id; + QString Description; + QString Command; + CustomActionContext Context; + bool MultipleSelection; - CustomAction() - { - Clear(); - } + CustomAction() { Clear(); } - bool IsValid() const - { - return !(Description.isEmpty() || Command.isEmpty()); - } + bool IsValid() const { return !(Description.isEmpty() || Command.isEmpty()); } - bool IsActive(CustomActionContext context) const - { - return (Context & context) != 0; - } + bool IsActive(CustomActionContext context) const { return (Context & context) != 0; } - void Clear() - { - Description.clear(); - Command.clear(); - Context = ACTION_CONTEXT_FILES; - MultipleSelection = true; - } + void Clear() + { + Description.clear(); + Command.clear(); + Context = ACTION_CONTEXT_FILES; + MultipleSelection = true; + } }; struct Settings { - struct Setting - { - enum SettingType - { - TYPE_FOSSIL_GLOBAL, - TYPE_FOSSIL_LOCAL - }; + struct Setting + { + enum SettingType + { + TYPE_FOSSIL_GLOBAL, + TYPE_FOSSIL_LOCAL + }; - Setting(QVariant value, SettingType type) : Value(value), Type(type) - {} - QVariant Value; - SettingType Type; - }; - typedef QMap mappings_t; - typedef QVector custom_actions_t; + Setting(QVariant value, SettingType type) : Value(value), Type(type) {} + QVariant Value; + SettingType Type; + }; + typedef QMap mappings_t; + typedef QVector custom_actions_t; + Settings(bool portableMode = false); + ~Settings(); - Settings(bool portableMode = false); - ~Settings(); + void ApplyEnvironment(); - void ApplyEnvironment(); + // App configuration access + class QSettings *GetStore() { return store; } + bool HasValue(const QString &name) const; // store->contains(FUEL_SETTING_FOSSIL_PATH) + const QVariant GetValue(const QString &name); // settings.store->value + void SetValue(const QString &name, const QVariant &value); // settings.store->value - // App configuration access - class QSettings * GetStore() { return store; } - bool HasValue(const QString &name) const; // store->contains(FUEL_SETTING_FOSSIL_PATH) - const QVariant GetValue(const QString &name); // settings.store->value - void SetValue(const QString &name, const QVariant &value); // settings.store->value + // Fossil configuration access + QVariant &GetFossilValue(const QString &name); + void SetFossilValue(const QString &name, const QVariant &value); + mappings_t &GetMappings() { return Mappings; } - // Fossil configuration access - QVariant & GetFossilValue(const QString &name); - void SetFossilValue(const QString &name, const QVariant &value); - mappings_t & GetMappings() { return Mappings; } + bool SupportsLang(const QString &langId) const; + bool InstallLang(const QString &langId); - bool SupportsLang(const QString &langId) const; - bool InstallLang(const QString &langId); + custom_actions_t &GetCustomActions() { return customActions; } - custom_actions_t &GetCustomActions() { return customActions; } private: - mappings_t Mappings; - class QSettings *store; - QTranslator translator; + mappings_t Mappings; + class QSettings *store; + QTranslator translator; - custom_actions_t customActions; + custom_actions_t customActions; }; - -#endif // APPSETTINGS_H +#endif // APPSETTINGS_H diff --git a/src/BrowserWidget.cpp b/src/BrowserWidget.cpp index 6604a65..6b50c3f 100644 --- a/src/BrowserWidget.cpp +++ b/src/BrowserWidget.cpp @@ -1,73 +1,69 @@ -#include #include "BrowserWidget.h" #include "ui_BrowserWidget.h" +#include -BrowserWidget::BrowserWidget(QWidget *parent) : - QWidget(parent), - loading(false) +BrowserWidget::BrowserWidget(QWidget *parent) : QWidget(parent), loading(false) { - ui = new Ui::BrowserWidget; - ui->setupUi(this); - ui->toolBar->addWidget(ui->txtUrl); - connect(ui->txtUrl, SIGNAL(returnPressed()), this, SLOT(on_txtUrl_returnPressed()) ); - ui->actionBrowserStop->setVisible(false); + ui = new Ui::BrowserWidget; + ui->setupUi(this); + ui->toolBar->addWidget(ui->txtUrl); + connect(ui->txtUrl, SIGNAL(returnPressed()), this, SLOT(on_txtUrl_returnPressed())); + ui->actionBrowserStop->setVisible(false); } BrowserWidget::~BrowserWidget() { - delete ui; + delete ui; } void BrowserWidget::load(const QUrl &url) { - ui->webView->load(url); + ui->webView->load(url); } void BrowserWidget::on_webView_urlChanged(const QUrl &url) { - ui->txtUrl->setText(url.toString()); + ui->txtUrl->setText(url.toString()); } void BrowserWidget::on_webView_loadStarted() { - loading=true; - ui->actionBrowserRefresh->setVisible(false); - ui->actionBrowserStop->setVisible(true); + loading = true; + ui->actionBrowserRefresh->setVisible(false); + ui->actionBrowserStop->setVisible(true); } void BrowserWidget::on_webView_loadFinished(bool /*errorOccured*/) { - loading=false; - ui->actionBrowserRefresh->setVisible(true); - ui->actionBrowserStop->setVisible(false); + loading = false; + ui->actionBrowserRefresh->setVisible(true); + ui->actionBrowserStop->setVisible(false); } - void BrowserWidget::on_txtUrl_returnPressed() { - QUrl url(ui->txtUrl->text()); - if(url.scheme().isEmpty()) - url.setScheme("http"); - ui->webView->load(url); + QUrl url(ui->txtUrl->text()); + if (url.scheme().isEmpty()) + url.setScheme("http"); + ui->webView->load(url); } - void BrowserWidget::on_actionBrowserBack_triggered() { - ui->webView->back(); + ui->webView->back(); } void BrowserWidget::on_actionBrowserForward_triggered() { - ui->webView->forward(); + ui->webView->forward(); } void BrowserWidget::on_actionBrowserRefresh_triggered() { - ui->webView->reload(); + ui->webView->reload(); } void BrowserWidget::on_actionBrowserStop_triggered() { - ui->webView->stop(); + ui->webView->stop(); } diff --git a/src/BrowserWidget.h b/src/BrowserWidget.h index 263cab0..9312d62 100644 --- a/src/BrowserWidget.h +++ b/src/BrowserWidget.h @@ -1,37 +1,38 @@ #ifndef BROWSERWIDGET_H #define BROWSERWIDGET_H -#include #include +#include -namespace Ui { +namespace Ui +{ class BrowserWidget; } class BrowserWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit BrowserWidget(QWidget *parent = 0); - ~BrowserWidget(); + explicit BrowserWidget(QWidget *parent = 0); + ~BrowserWidget(); - void load(const QUrl &url); + void load(const QUrl &url); private slots: - void on_webView_urlChanged(const QUrl &url); - void on_webView_loadStarted(); - void on_webView_loadFinished(bool); - void on_actionBrowserBack_triggered(); - void on_actionBrowserForward_triggered(); - void on_actionBrowserRefresh_triggered(); - void on_txtUrl_returnPressed(); + void on_webView_urlChanged(const QUrl &url); + void on_webView_loadStarted(); + void on_webView_loadFinished(bool); + void on_actionBrowserBack_triggered(); + void on_actionBrowserForward_triggered(); + void on_actionBrowserRefresh_triggered(); + void on_txtUrl_returnPressed(); - void on_actionBrowserStop_triggered(); + void on_actionBrowserStop_triggered(); private: - Ui::BrowserWidget *ui; - bool loading; + Ui::BrowserWidget *ui; + bool loading; }; -#endif // BROWSERWIDGET_H +#endif // BROWSERWIDGET_H diff --git a/src/CloneDialog.cpp b/src/CloneDialog.cpp index c1f0cf2..4499b44 100644 --- a/src/CloneDialog.cpp +++ b/src/CloneDialog.cpp @@ -1,142 +1,134 @@ #include "CloneDialog.h" -#include "ui_CloneDialog.h" -#include -#include -#include -#include -#include #include "Utils.h" +#include "ui_CloneDialog.h" +#include +#include +#include +#include +#include //----------------------------------------------------------------------------- -CloneDialog::CloneDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::CloneDialog) +CloneDialog::CloneDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CloneDialog) { - ui->setupUi(this); + ui->setupUi(this); } //----------------------------------------------------------------------------- CloneDialog::~CloneDialog() { - delete ui; + delete ui; } //----------------------------------------------------------------------------- bool CloneDialog::run(QWidget *parent, QUrl &url, QString &repository, QUrl &urlProxy) { - CloneDialog dlg(parent); + CloneDialog dlg(parent); - // Try to parse a url from the clipboard - QClipboard *clipboard = QApplication::clipboard(); - if(clipboard) - { - QUrl nurl = QUrl::fromUserInput(clipboard->text()); + // Try to parse a url from the clipboard + QClipboard *clipboard = QApplication::clipboard(); + if (clipboard) + { + QUrl nurl = QUrl::fromUserInput(clipboard->text()); - // If we have a valid url - if(nurl.isValid() && !nurl.isEmpty()) - { - // Fill in dialog - dlg.ui->lineUserName->setText(nurl.userName()); - dlg.ui->linePassword->setText(nurl.password()); - nurl.setUserName(""); - nurl.setPassword(""); - dlg.ui->lineURL->setText(UrlToStringNoCredentials(nurl)); - } - } + // If we have a valid url + if (nurl.isValid() && !nurl.isEmpty()) + { + // Fill in dialog + dlg.ui->lineUserName->setText(nurl.userName()); + dlg.ui->linePassword->setText(nurl.password()); + nurl.setUserName(""); + nurl.setPassword(""); + dlg.ui->lineURL->setText(UrlToStringNoCredentials(nurl)); + } + } - if(dlg.exec() != QDialog::Accepted) - return false; + if (dlg.exec() != QDialog::Accepted) + return false; - QString urltext = dlg.ui->lineURL->text(); + QString urltext = dlg.ui->lineURL->text(); - // Check if the url is a local file - if(QFileInfo(urltext).exists()) - url = QUrl::fromLocalFile(urltext); - else - { - url = QUrl::fromUserInput(urltext); - if(url.isEmpty() || !url.isValid()) - { - QMessageBox::critical(parent, tr("Error"), tr("Invalid URL."), QMessageBox::Ok ); - return false; - } - } + // Check if the url is a local file + if (QFileInfo(urltext).exists()) + url = QUrl::fromLocalFile(urltext); + else + { + url = QUrl::fromUserInput(urltext); + if (url.isEmpty() || !url.isValid()) + { + QMessageBox::critical(parent, tr("Error"), tr("Invalid URL."), QMessageBox::Ok); + return false; + } + } - if(!dlg.ui->lineUserName->text().trimmed().isEmpty()) - url.setUserName(dlg.ui->lineUserName->text()); + if (!dlg.ui->lineUserName->text().trimmed().isEmpty()) + url.setUserName(dlg.ui->lineUserName->text()); - if(!dlg.ui->linePassword->text().trimmed().isEmpty()) - url.setPassword(dlg.ui->linePassword->text()); + if (!dlg.ui->linePassword->text().trimmed().isEmpty()) + url.setPassword(dlg.ui->linePassword->text()); - if(dlg.ui->lineTargetRepository->text().isEmpty()) - { - QMessageBox::critical(parent, tr("Error"), tr("Invalid Repository File."), QMessageBox::Ok ); - return false; - } + if (dlg.ui->lineTargetRepository->text().isEmpty()) + { + QMessageBox::critical(parent, tr("Error"), tr("Invalid Repository File."), QMessageBox::Ok); + return false; + } - urlProxy = QUrl::fromUserInput(dlg.ui->lineHttpProxyUrl->text()); - if(!urlProxy.isEmpty() && !urlProxy.isValid()) - { - QMessageBox::critical(parent, tr("Error"), tr("Invalid Proxy URL."), QMessageBox::Ok ); - return false; - } + urlProxy = QUrl::fromUserInput(dlg.ui->lineHttpProxyUrl->text()); + if (!urlProxy.isEmpty() && !urlProxy.isValid()) + { + QMessageBox::critical(parent, tr("Error"), tr("Invalid Proxy URL."), QMessageBox::Ok); + return false; + } - repository = dlg.ui->lineTargetRepository->text(); - return true; + repository = dlg.ui->lineTargetRepository->text(); + return true; } //----------------------------------------------------------------------------- void CloneDialog::GetRepositoryPath(QString &pathResult) { - QString filter(tr("Fossil Repository") + QString(" (*." FOSSIL_EXT ")")); + QString filter(tr("Fossil Repository") + QString(" (*." FOSSIL_EXT ")")); - pathResult = QFileDialog::getSaveFileName( - this, - tr("Select Fossil Repository"), - QDir::toNativeSeparators(pathResult), - filter, - &filter, - QFileDialog::DontConfirmOverwrite); + pathResult = QFileDialog::getSaveFileName(this, tr("Select Fossil Repository"), QDir::toNativeSeparators(pathResult), filter, &filter, QFileDialog::DontConfirmOverwrite); - // Ensure that it ends in the required extension (On GTK, Qt doesn't seem to add it automatically) - QFileInfo fi(pathResult); - QString ext = fi.suffix().toLower(); - if(ext != FOSSIL_EXT) - pathResult += "." FOSSIL_EXT; + // Ensure that it ends in the required extension (On GTK, Qt doesn't seem to add it automatically) + QFileInfo fi(pathResult); + QString ext = fi.suffix().toLower(); + if (ext != FOSSIL_EXT) + pathResult += "." FOSSIL_EXT; } //----------------------------------------------------------------------------- void CloneDialog::on_btnSelectSourceRepo_clicked() { - QString path = ui->lineURL->text(); - GetRepositoryPath(path); + QString path = ui->lineURL->text(); + GetRepositoryPath(path); - if(path.trimmed().isEmpty()) - return; + if (path.trimmed().isEmpty()) + return; - if(!QFile::exists(path)) - { - QMessageBox::critical(this, tr("Error"), tr("Invalid Repository File."), QMessageBox::Ok); - return; - } + if (!QFile::exists(path)) + { + QMessageBox::critical(this, tr("Error"), tr("Invalid Repository File."), QMessageBox::Ok); + return; + } - ui->lineURL->setText(QDir::toNativeSeparators(path)); + ui->lineURL->setText(QDir::toNativeSeparators(path)); } //----------------------------------------------------------------------------- void CloneDialog::on_btnSelectTargetRepo_clicked() { - QString path = ui->lineTargetRepository->text(); - GetRepositoryPath(path); + QString path = ui->lineTargetRepository->text(); + GetRepositoryPath(path); - if(path.trimmed().isEmpty()) - return; + if (path.trimmed().isEmpty()) + return; - if(QFile::exists(path)) - { - QMessageBox::critical(this, tr("Error"), tr("This repository file already exists."), QMessageBox::Ok); - return; - } + if (QFile::exists(path)) + { + QMessageBox::critical(this, tr("Error"), tr("This repository file already exists."), QMessageBox::Ok); + return; + } - ui->lineTargetRepository->setText(QDir::toNativeSeparators(path)); + ui->lineTargetRepository->setText(QDir::toNativeSeparators(path)); } diff --git a/src/CloneDialog.h b/src/CloneDialog.h index 884db5a..3980862 100644 --- a/src/CloneDialog.h +++ b/src/CloneDialog.h @@ -3,28 +3,29 @@ #include -namespace Ui { +namespace Ui +{ class CloneDialog; } class CloneDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit CloneDialog(QWidget *parent = 0); - ~CloneDialog(); + explicit CloneDialog(QWidget *parent = 0); + ~CloneDialog(); - static bool run(QWidget *parent, class QUrl &url, QString &repository, QUrl& urlProxy); + static bool run(QWidget *parent, class QUrl &url, QString &repository, QUrl &urlProxy); private slots: - void on_btnSelectSourceRepo_clicked(); - void on_btnSelectTargetRepo_clicked(); + void on_btnSelectSourceRepo_clicked(); + void on_btnSelectTargetRepo_clicked(); private: - void GetRepositoryPath(QString &pathResult); + void GetRepositoryPath(QString &pathResult); - Ui::CloneDialog *ui; + Ui::CloneDialog *ui; }; -#endif // CLONEDIALOG_H +#endif // CLONEDIALOG_H diff --git a/src/CommitDialog.cpp b/src/CommitDialog.cpp index f9d4b9c..aa3f7c4 100644 --- a/src/CommitDialog.cpp +++ b/src/CommitDialog.cpp @@ -1,171 +1,168 @@ #include "CommitDialog.h" +#include "MainWindow.h" // Ugly. I know. +#include "ui_CommitDialog.h" +#include #include #include -#include -#include "ui_CommitDialog.h" -#include "MainWindow.h" // Ugly. I know. -CommitDialog::CommitDialog(QWidget *parent, const QString &title, QStringList &files, const QStringList *history, bool stashMode) : - QDialog(parent, Qt::Sheet), - ui(new Ui::CommitDialog) +CommitDialog::CommitDialog(QWidget *parent, const QString &title, QStringList &files, const QStringList *history, bool stashMode) : QDialog(parent, Qt::Sheet), ui(new Ui::CommitDialog) { - ui->setupUi(this); - ui->plainTextEdit->clear(); - ui->listView->setModel(&itemModel); + ui->setupUi(this); + ui->plainTextEdit->clear(); + ui->listView->setModel(&itemModel); - setWindowTitle(title); + setWindowTitle(title); - // Activate the appropriate control based on mode - ui->plainTextEdit->setVisible(!stashMode); - ui->lineEdit->setVisible(stashMode); + // Activate the appropriate control based on mode + ui->plainTextEdit->setVisible(!stashMode); + ui->lineEdit->setVisible(stashMode); - // Activate the checkbox if we have some text - ui->chkRevertFiles->setVisible(stashMode); + // Activate the checkbox if we have some text + ui->chkRevertFiles->setVisible(stashMode); - ui->widgetBranchOptions->setVisible(!stashMode); + ui->widgetBranchOptions->setVisible(!stashMode); - // Activate the combo if we have history - ui->comboBox->setVisible(history!=0); - if(history) - { - // Generate the history combo - foreach(const QString msg, *history) - { - QString trimmed = msg.trimmed(); - if(trimmed.isEmpty()) - continue; + // Activate the combo if we have history + ui->comboBox->setVisible(history != 0); + if (history) + { + // Generate the history combo + foreach (const QString msg, *history) + { + QString trimmed = msg.trimmed(); + if (trimmed.isEmpty()) + continue; - commitMessages.append(trimmed); - QStringList lines = trimmed.split('\n'); - QString first_line; - if(!lines.empty()) - first_line = lines[0] + "..."; + commitMessages.append(trimmed); + QStringList lines = trimmed.split('\n'); + QString first_line; + if (!lines.empty()) + first_line = lines[0] + "..."; - ui->comboBox->addItem(first_line); - } - } + ui->comboBox->addItem(first_line); + } + } - // Populate file list - for(QStringList::const_iterator it=files.begin(); it!=files.end(); ++it) - { - QStandardItem *si = new QStandardItem(*it); - si->setCheckable(true); - si->setCheckState(Qt::Checked); - itemModel.appendRow(si); - } + // Populate file list + for (QStringList::const_iterator it = files.begin(); it != files.end(); ++it) + { + QStandardItem *si = new QStandardItem(*it); + si->setCheckable(true); + si->setCheckState(Qt::Checked); + itemModel.appendRow(si); + } + // Trigger commit with a Ctrl-Return from the comment box + QAction *action = new QAction(ui->plainTextEdit); + QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+Return"), ui->plainTextEdit); + action->setAutoRepeat(false); + connect(shortcut, SIGNAL(activated()), ui->buttonBox->button(QDialogButtonBox::Ok), SLOT(click())); - // Trigger commit with a Ctrl-Return from the comment box - QAction* action = new QAction(ui->plainTextEdit); - QShortcut* shortcut = new QShortcut(QKeySequence("Ctrl+Return"), ui->plainTextEdit); - action->setAutoRepeat(false); - connect(shortcut, SIGNAL(activated()), ui->buttonBox->button(QDialogButtonBox::Ok), SLOT(click())); - - // Abort commit with an Escape key from the comment box - action = new QAction(ui->plainTextEdit); - shortcut = new QShortcut(QKeySequence("Escape"), ui->plainTextEdit); - action->setAutoRepeat(false); - connect(shortcut, SIGNAL(activated()), ui->buttonBox->button(QDialogButtonBox::Cancel), SLOT(click())); + // Abort commit with an Escape key from the comment box + action = new QAction(ui->plainTextEdit); + shortcut = new QShortcut(QKeySequence("Escape"), ui->plainTextEdit); + action->setAutoRepeat(false); + connect(shortcut, SIGNAL(activated()), ui->buttonBox->button(QDialogButtonBox::Cancel), SLOT(click())); } //------------------------------------------------------------------------------ CommitDialog::~CommitDialog() { - delete ui; + delete ui; } //------------------------------------------------------------------------------ -bool CommitDialog::runCommit(QWidget* parent, QStringList& files, QString& commitMsg, const QStringList& commitMsgHistory, QString &branchName, bool &privateBranch) +bool CommitDialog::runCommit(QWidget *parent, QStringList &files, QString &commitMsg, const QStringList &commitMsgHistory, QString &branchName, bool &privateBranch) { - CommitDialog dlg(parent, tr("Commit Changes"), files, &commitMsgHistory, false); - int res = dlg.exec(); + CommitDialog dlg(parent, tr("Commit Changes"), files, &commitMsgHistory, false); + int res = dlg.exec(); - commitMsg = dlg.ui->plainTextEdit->toPlainText(); + commitMsg = dlg.ui->plainTextEdit->toPlainText(); - if(res!=QDialog::Accepted) - return false; + if (res != QDialog::Accepted) + return false; - files.clear(); - for(int i=0; icheckState()!=Qt::Checked) - continue; - files.append(si->text()); - } + files.clear(); + for (int i = 0; i < dlg.itemModel.rowCount(); ++i) + { + QStandardItem *si = dlg.itemModel.item(i); + if (si->checkState() != Qt::Checked) + continue; + files.append(si->text()); + } - branchName.clear(); - if(dlg.ui->chkNewBranch->isChecked()) - { - branchName = dlg.ui->lineBranchName->text().trimmed(); - privateBranch = dlg.ui->chkPrivateBranch->isChecked(); - } + branchName.clear(); + if (dlg.ui->chkNewBranch->isChecked()) + { + branchName = dlg.ui->lineBranchName->text().trimmed(); + privateBranch = dlg.ui->chkPrivateBranch->isChecked(); + } - return true; + return true; } //------------------------------------------------------------------------------ -bool CommitDialog::runStashNew(QWidget* parent, QStringList& stashedFiles, QString& stashName, bool& revertFiles) +bool CommitDialog::runStashNew(QWidget *parent, QStringList &stashedFiles, QString &stashName, bool &revertFiles) { - CommitDialog dlg(parent, tr("Stash Changes"), stashedFiles, NULL, true); - int res = dlg.exec(); + CommitDialog dlg(parent, tr("Stash Changes"), stashedFiles, NULL, true); + int res = dlg.exec(); - stashName = dlg.ui->lineEdit->text(); + stashName = dlg.ui->lineEdit->text(); - if(res!=QDialog::Accepted) - return false; + if (res != QDialog::Accepted) + return false; - stashedFiles.clear(); - for(int i=0; icheckState()!=Qt::Checked) - continue; - stashedFiles.append(si->text()); - } + stashedFiles.clear(); + for (int i = 0; i < dlg.itemModel.rowCount(); ++i) + { + QStandardItem *si = dlg.itemModel.item(i); + if (si->checkState() != Qt::Checked) + continue; + stashedFiles.append(si->text()); + } - revertFiles = dlg.ui->chkRevertFiles->checkState() == Qt::Checked; - return true; + revertFiles = dlg.ui->chkRevertFiles->checkState() == Qt::Checked; + return true; } //------------------------------------------------------------------------------ void CommitDialog::on_comboBox_activated(int index) { - Q_ASSERT(index < commitMessages.length()); + Q_ASSERT(index < commitMessages.length()); - if(ui->plainTextEdit->isVisible()) - ui->plainTextEdit->setPlainText(commitMessages[index]); + if (ui->plainTextEdit->isVisible()) + ui->plainTextEdit->setPlainText(commitMessages[index]); - if(ui->lineEdit->isVisible()) - ui->lineEdit->setText(commitMessages[index]); + if (ui->lineEdit->isVisible()) + ui->lineEdit->setText(commitMessages[index]); } //------------------------------------------------------------------------------ void CommitDialog::on_listView_doubleClicked(const QModelIndex &index) { - QVariant data = itemModel.data(index); - QString filename = data.toString(); - reinterpret_cast(parent())->diffFile(filename); + QVariant data = itemModel.data(index); + QString filename = data.toString(); + reinterpret_cast(parent())->diffFile(filename); } //------------------------------------------------------------------------------ void CommitDialog::on_listView_clicked(const QModelIndex &) { - int num_selected = 0; - for(int i=0; icheckState()==Qt::Checked) - ++num_selected; - } + int num_selected = 0; + for (int i = 0; i < itemModel.rowCount(); ++i) + { + QStandardItem *si = itemModel.item(i); + if (si->checkState() == Qt::Checked) + ++num_selected; + } - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(num_selected>0); + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(num_selected > 0); } //------------------------------------------------------------------------------ void CommitDialog::on_chkNewBranch_toggled(bool checked) { - ui->lblPrivateBranch->setEnabled(checked); - ui->chkPrivateBranch->setEnabled(checked); - ui->lineBranchName->setEnabled(checked); + ui->lblPrivateBranch->setEnabled(checked); + ui->chkPrivateBranch->setEnabled(checked); + ui->lineBranchName->setEnabled(checked); } diff --git a/src/CommitDialog.h b/src/CommitDialog.h index f52b928..c42efbf 100644 --- a/src/CommitDialog.h +++ b/src/CommitDialog.h @@ -4,31 +4,32 @@ #include #include -namespace Ui { - class CommitDialog; +namespace Ui +{ +class CommitDialog; } class CommitDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit CommitDialog(QWidget *parent, const QString &title, QStringList &files, const QStringList *history, bool stashMode); - ~CommitDialog(); + explicit CommitDialog(QWidget *parent, const QString &title, QStringList &files, const QStringList *history, bool stashMode); + ~CommitDialog(); - static bool runStashNew(QWidget* parent, QStringList& stashedFiles, QString& stashName, bool &revertFiles); - static bool runCommit(QWidget* parent, QStringList& files, QString& commitMsg, const QStringList &commitMsgHistory, QString& branchName, bool& privateBranch); + static bool runStashNew(QWidget *parent, QStringList &stashedFiles, QString &stashName, bool &revertFiles); + static bool runCommit(QWidget *parent, QStringList &files, QString &commitMsg, const QStringList &commitMsgHistory, QString &branchName, bool &privateBranch); private slots: - void on_comboBox_activated(int index); - void on_listView_doubleClicked(const QModelIndex &index); - void on_listView_clicked(const QModelIndex &index); - void on_chkNewBranch_toggled(bool checked); + void on_comboBox_activated(int index); + void on_listView_doubleClicked(const QModelIndex &index); + void on_listView_clicked(const QModelIndex &index); + void on_chkNewBranch_toggled(bool checked); private: - Ui::CommitDialog *ui; - QStandardItemModel itemModel; - QStringList commitMessages; + Ui::CommitDialog *ui; + QStandardItemModel itemModel; + QStringList commitMessages; }; -#endif // COMMITDIALOG_H +#endif // COMMITDIALOG_H diff --git a/src/CustomWebView.cpp b/src/CustomWebView.cpp index 682f561..6fafc84 100644 --- a/src/CustomWebView.cpp +++ b/src/CustomWebView.cpp @@ -1,19 +1,18 @@ #include "CustomWebView.h" #include -CustomWebView::CustomWebView(QWidget *parent) : - QWebEngineView(parent) +CustomWebView::CustomWebView(QWidget *parent) : QWebEngineView(parent) { - setUrl(QUrl("about:blank")); + setUrl(QUrl("about:blank")); } void CustomWebView::mousePressEvent(QMouseEvent *event) { - Qt::MouseButton but = event->button(); - if(but == Qt::XButton1) - back(); - else if(but == Qt::XButton2) - forward(); - else - QWebEngineView::mousePressEvent(event); + Qt::MouseButton but = event->button(); + if (but == Qt::XButton1) + back(); + else if (but == Qt::XButton2) + forward(); + else + QWebEngineView::mousePressEvent(event); } diff --git a/src/CustomWebView.h b/src/CustomWebView.h index 8e8c7a9..8328f56 100644 --- a/src/CustomWebView.h +++ b/src/CustomWebView.h @@ -5,17 +5,16 @@ class CustomWebView : public QWebEngineView { - Q_OBJECT + Q_OBJECT public: - explicit CustomWebView(QWidget *parent = 0); + explicit CustomWebView(QWidget *parent = 0); signals: public slots: protected: - virtual void mousePressEvent(QMouseEvent *event); - + virtual void mousePressEvent(QMouseEvent *event); }; -#endif // CUSTOMWEBVIEW_H +#endif // CUSTOMWEBVIEW_H diff --git a/src/FileActionDialog.cpp b/src/FileActionDialog.cpp index 66890d4..874f60d 100644 --- a/src/FileActionDialog.cpp +++ b/src/FileActionDialog.cpp @@ -1,64 +1,61 @@ -#include #include "FileActionDialog.h" #include "ui_FileActionDialog.h" +#include FileActionDialog::FileActionDialog(QWidget *parent, const QString &title, const QString &message, const QStringList &listData, const QString &checkBoxText, bool *checkBoxResult) : - QDialog(parent, Qt::Sheet), - ui(new Ui::FileActionDialog), - clickedButton(QDialogButtonBox::NoButton) + QDialog(parent, Qt::Sheet), ui(new Ui::FileActionDialog), clickedButton(QDialogButtonBox::NoButton) { ui->setupUi(this); - setWindowTitle(title); - ui->label->setText(message); - ui->listView->setModel(&itemModel); + setWindowTitle(title); + ui->label->setText(message); + ui->listView->setModel(&itemModel); - if(!checkBoxText.isEmpty() && checkBoxResult) - { - checkBox = new QCheckBox(this); - checkBox->setText(checkBoxText); - checkBox->setEnabled(true); - checkBox->setChecked(*checkBoxResult); - this->checkBoxResult = checkBoxResult; - ui->verticalLayout->insertWidget(2, checkBox); - } + if (!checkBoxText.isEmpty() && checkBoxResult) + { + checkBox = new QCheckBox(this); + checkBox->setText(checkBoxText); + checkBox->setEnabled(true); + checkBox->setChecked(*checkBoxResult); + this->checkBoxResult = checkBoxResult; + ui->verticalLayout->insertWidget(2, checkBox); + } - if(listData.empty()) - ui->listView->setVisible(false); - else - { - foreach(const QString &s, listData) - itemModel.appendRow(new QStandardItem(s)); - } + if (listData.empty()) + ui->listView->setVisible(false); + else + { + foreach (const QString &s, listData) + itemModel.appendRow(new QStandardItem(s)); + } } FileActionDialog::~FileActionDialog() { - delete ui; + delete ui; } bool FileActionDialog::run(QWidget *parent, const QString &title, const QString &message, const QStringList &listData, const QString &checkBoxText, bool *checkBoxResult) { - FileActionDialog dlg(parent, title, message, listData, checkBoxText, checkBoxResult); - int res = dlg.exec(); + FileActionDialog dlg(parent, title, message, listData, checkBoxText, checkBoxResult); + int res = dlg.exec(); - if(!checkBoxText.isEmpty() && checkBoxResult && dlg.checkBox) - *checkBoxResult = dlg.checkBox->isChecked(); + if (!checkBoxText.isEmpty() && checkBoxResult && dlg.checkBox) + *checkBoxResult = dlg.checkBox->isChecked(); - return res == QDialog::Accepted; + return res == QDialog::Accepted; } QDialogButtonBox::StandardButton FileActionDialog::runStandardButtons(QWidget *parent, StandardButtons buttons, const QString &title, const QString &message, const QStringList &listData) { - FileActionDialog dlg(parent, title, message, listData); - dlg.ui->buttonBox->setStandardButtons(buttons); + FileActionDialog dlg(parent, title, message, listData); + dlg.ui->buttonBox->setStandardButtons(buttons); - dlg.exec(); - return dlg.clickedButton; + dlg.exec(); + return dlg.clickedButton; } void FileActionDialog::on_buttonBox_clicked(QAbstractButton *button) { - // Retrieve the flag corresponding to the standard clicked - clickedButton = ui->buttonBox->standardButton(button); + // Retrieve the flag corresponding to the standard clicked + clickedButton = ui->buttonBox->standardButton(button); } - diff --git a/src/FileActionDialog.h b/src/FileActionDialog.h index f408619..6c8ac24 100644 --- a/src/FileActionDialog.h +++ b/src/FileActionDialog.h @@ -2,37 +2,37 @@ #define FILEACTIONDIALOG_H #include -#include #include +#include -namespace Ui { - class FileActionDialog; +namespace Ui +{ +class FileActionDialog; } class FileActionDialog : public QDialog { Q_OBJECT public: - explicit FileActionDialog(QWidget *parent, const QString &title, const QString &message, const QStringList &listData, const QString &checkBoxText=QString(), bool *checkBoxResult=0); + explicit FileActionDialog(QWidget *parent, const QString &title, const QString &message, const QStringList &listData, const QString &checkBoxText = QString(), bool *checkBoxResult = 0); ~FileActionDialog(); - static bool run(QWidget *parent, const QString &title, const QString &message, const QStringList &listData, const QString &checkBoxText=QString(), bool *checkBoxResult=0); + static bool run(QWidget *parent, const QString &title, const QString &message, const QStringList &listData, const QString &checkBoxText = QString(), bool *checkBoxResult = 0); - typedef QDialogButtonBox::StandardButton StandardButton; - typedef QDialogButtonBox::StandardButtons StandardButtons; - - static StandardButton runStandardButtons(QWidget *parent, StandardButtons, const QString &title, const QString &message, const QStringList &listData); + typedef QDialogButtonBox::StandardButton StandardButton; + typedef QDialogButtonBox::StandardButtons StandardButtons; + static StandardButton runStandardButtons(QWidget *parent, StandardButtons, const QString &title, const QString &message, const QStringList &listData); private slots: - void on_buttonBox_clicked(QAbstractButton *button); + void on_buttonBox_clicked(QAbstractButton *button); private: Ui::FileActionDialog *ui; - QStandardItemModel itemModel; - class QCheckBox *checkBox; - bool *checkBoxResult; - StandardButton clickedButton; + QStandardItemModel itemModel; + class QCheckBox *checkBox; + bool *checkBoxResult; + StandardButton clickedButton; }; -#endif // FILEACTIONDIALOG_H +#endif // FILEACTIONDIALOG_H diff --git a/src/FileTableView.cpp b/src/FileTableView.cpp index e35d0c8..5c77654 100644 --- a/src/FileTableView.cpp +++ b/src/FileTableView.cpp @@ -1,31 +1,27 @@ #include "FileTableView.h" -#include #include +#include -FileTableView::FileTableView(QWidget *parent) : - QTableView(parent) -{ -} +FileTableView::FileTableView(QWidget *parent) : QTableView(parent) {} //------------------------------------------------------------------------------ void FileTableView::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) - dragStartPos = event->pos(); + if (event->button() == Qt::LeftButton) + dragStartPos = event->pos(); - QTableView::mousePressEvent(event); + QTableView::mousePressEvent(event); } //------------------------------------------------------------------------------ void FileTableView::mouseMoveEvent(QMouseEvent *event) { - int distance = (event->pos() - dragStartPos).manhattanLength(); - if (event->buttons() & Qt::LeftButton && distance >= QApplication::startDragDistance()) - { - dragOutEvent(); - QTableView::mouseReleaseEvent(event); - } - else - QTableView::mouseMoveEvent(event); - + int distance = (event->pos() - dragStartPos).manhattanLength(); + if (event->buttons() & Qt::LeftButton && distance >= QApplication::startDragDistance()) + { + dragOutEvent(); + QTableView::mouseReleaseEvent(event); + } + else + QTableView::mouseMoveEvent(event); } diff --git a/src/FileTableView.h b/src/FileTableView.h index 5fc42fa..a3cfd9c 100644 --- a/src/FileTableView.h +++ b/src/FileTableView.h @@ -1,24 +1,24 @@ #ifndef FILETABLEVIEW_H #define FILETABLEVIEW_H -#include #include +#include class FileTableView : public QTableView { - Q_OBJECT + Q_OBJECT public: - explicit FileTableView(QWidget *parent = 0); - + explicit FileTableView(QWidget *parent = 0); + signals: - void dragOutEvent(); + void dragOutEvent(); private: - void mousePressEvent(QMouseEvent *event); - void mouseMoveEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); private: - QPoint dragStartPos; + QPoint dragStartPos; }; -#endif // FILETABLEVIEW_H +#endif // FILETABLEVIEW_H diff --git a/src/Fossil.cpp b/src/Fossil.cpp index 6c211b6..f63d8fb 100644 --- a/src/Fossil.cpp +++ b/src/Fossil.cpp @@ -1,571 +1,581 @@ #include "Fossil.h" -#include +#include "Utils.h" #include -#include #include #include +#include #include +#include #include -#include "Utils.h" -static const unsigned char UTF8_BOM[] = { 0xEF, 0xBB, 0xBF }; +static const unsigned char UTF8_BOM[] = {0xEF, 0xBB, 0xBF}; /////////////////////////////////////////////////////////////////////////////// -Fossil::Fossil() - : uiCallback(0) -{ -} +Fossil::Fossil() : uiCallback(0) {} /////////////////////////////////////////////////////////////////////////////// void Fossil::Init(UICallback *callback, const QString &exePath) { - uiCallback = callback; - fossilPath.clear(); - workspacePath.clear(); - setExePath(exePath); + uiCallback = callback; + fossilPath.clear(); + workspacePath.clear(); + setExePath(exePath); } //------------------------------------------------------------------------------ WorkspaceState Fossil::getWorkspaceState() { - QStringList res; - int exit_code = EXIT_FAILURE; + QStringList res; + int exit_code = EXIT_FAILURE; - // We need to determine the reason why fossil has failed - // so we delay processing of the exit_code - if(!runFossilRaw(QStringList() << "info", &res, &exit_code, RUNFLAGS_SILENT_ALL)) - return WORKSPACE_STATE_NOTFOUND; + // We need to determine the reason why fossil has failed + // so we delay processing of the exit_code + if (!runFossilRaw(QStringList() << "info", &res, &exit_code, RUNFLAGS_SILENT_ALL)) + return WORKSPACE_STATE_NOTFOUND; - bool run_ok = exit_code == EXIT_SUCCESS; + bool run_ok = exit_code == EXIT_SUCCESS; - activeTags.clear(); - for(QStringList::iterator it=res.begin(); it!=res.end(); ++it) - { - int col_index = it->indexOf(':'); - if(col_index==-1) - continue; + activeTags.clear(); + for (QStringList::iterator it = res.begin(); it != res.end(); ++it) + { + int col_index = it->indexOf(':'); + if (col_index == -1) + continue; - QString key = it->left(col_index).trimmed(); - QString value = it->mid(col_index+1).trimmed(); + QString key = it->left(col_index).trimmed(); + QString value = it->mid(col_index + 1).trimmed(); - if(key=="fossil") - { - if(value=="incorrect repository schema version") - return WORKSPACE_STATE_OLDSCHEMA; - else if(value=="not within an open checkout") - return WORKSPACE_STATE_NOTFOUND; - } + if (key == "fossil") + { + if (value == "incorrect repository schema version") + return WORKSPACE_STATE_OLDSCHEMA; + else if (value == "not within an open checkout") + return WORKSPACE_STATE_NOTFOUND; + } - if(run_ok) - { - if(key=="project-name") - projectName = value; - else if(key=="repository") - repositoryFile = value; - else if(key=="checkout") - { - // f2121dad5e4565f55ed9ef882484dd5934af565f 2015-04-26 17:27:39 UTC - QStringList tokens = value.split(' ', QString::SkipEmptyParts); - Q_ASSERT(tokens.length()>0); - currentRevision = tokens[0].trimmed(); - } - else if(key=="tags") - { - QStringList tokens = value.split(',', QString::SkipEmptyParts); - foreach(const QString &tag, tokens) - activeTags.append(tag); - activeTags.sort(); - } - } - } + if (run_ok) + { + if (key == "project-name") + projectName = value; + else if (key == "repository") + repositoryFile = value; + else if (key == "checkout") + { + // f2121dad5e4565f55ed9ef882484dd5934af565f 2015-04-26 17:27:39 UTC + QStringList tokens = value.split(' ', QString::SkipEmptyParts); + Q_ASSERT(tokens.length() > 0); + currentRevision = tokens[0].trimmed(); + } + else if (key == "tags") + { + QStringList tokens = value.split(',', QString::SkipEmptyParts); + foreach (const QString &tag, tokens) + activeTags.append(tag); + activeTags.sort(); + } + } + } - return run_ok ? WORKSPACE_STATE_OK : WORKSPACE_STATE_NOTFOUND; + return run_ok ? WORKSPACE_STATE_OK : WORKSPACE_STATE_NOTFOUND; } //------------------------------------------------------------------------------ -bool Fossil::createWorkspace(const QString& repositoryPath, const QString& workspacePath) +bool Fossil::createWorkspace(const QString &repositoryPath, const QString &workspacePath) { - QFileInfo fi(repositoryPath); + QFileInfo fi(repositoryPath); - if(!QDir::setCurrent(workspacePath) || !fi.isFile()) - return false; + if (!QDir::setCurrent(workspacePath) || !fi.isFile()) + return false; - QString abspath = fi.absoluteFilePath(); - setWorkspace(workspacePath); - setRepositoryFile(abspath); + QString abspath = fi.absoluteFilePath(); + setWorkspace(workspacePath); + setRepositoryFile(abspath); - if(!runFossil(QStringList() << "open" << QuotePath(abspath))) - return false; + if (!runFossil(QStringList() << "open" << QuotePath(abspath))) + return false; - return true; + return true; } //------------------------------------------------------------------------------ -bool Fossil::createRepository(const QString& repositoryPath) +bool Fossil::createRepository(const QString &repositoryPath) { - QFileInfo fi(repositoryPath); + QFileInfo fi(repositoryPath); - if(fi.exists()) - return false; + if (fi.exists()) + return false; - if(!runFossil(QStringList() << "new" << QuotePath(fi.absoluteFilePath()))) - return false; - return true; + if (!runFossil(QStringList() << "new" << QuotePath(fi.absoluteFilePath()))) + return false; + return true; } //------------------------------------------------------------------------------ bool Fossil::closeWorkspace(bool force) { - QStringList params; - params << "close"; + QStringList params; + params << "close"; - if(force) - params << "--force"; + if (force) + params << "--force"; - if(!runFossil(params)) - return false; + if (!runFossil(params)) + return false; - stopUI(); - setWorkspace(""); - return true; + stopUI(); + setWorkspace(""); + return true; } //------------------------------------------------------------------------------ void Fossil::setWorkspace(const QString &_workspacePath) { - workspacePath = _workspacePath; + workspacePath = _workspacePath; } //------------------------------------------------------------------------------ bool Fossil::listFiles(QStringList &files) { - return runFossil(QStringList() << "ls" << "-l", &files, RUNFLAGS_SILENT_ALL); + return runFossil(QStringList() << "ls" + << "-l", + &files, RUNFLAGS_SILENT_ALL); } //------------------------------------------------------------------------------ bool Fossil::statusWorkspace(QStringList &result) { - return runFossil(QStringList() << "status", &result, RUNFLAGS_SILENT_ALL); + return runFossil(QStringList() << "status", &result, RUNFLAGS_SILENT_ALL); } //------------------------------------------------------------------------------ bool Fossil::pushWorkspace(const QUrl &url) { - QStringList params; - params << "push"; + QStringList params; + params << "push"; - int runFlags=RUNFLAGS_NONE; + int runFlags = RUNFLAGS_NONE; - if(!url.isEmpty()) - { - params << UrlToString(url); - params << "--once"; + if (!url.isEmpty()) + { + params << UrlToString(url); + params << "--once"; - QStringList log_params = params; - if(!url.isLocalFile()) - log_params[1] = UrlToStringDisplay(url); + QStringList log_params = params; + if (!url.isLocalFile()) + log_params[1] = UrlToStringDisplay(url); - log_params.push_front("fossil"); + log_params.push_front("fossil"); - runFlags = RUNFLAGS_SILENT_INPUT; - log(">"+log_params.join(" ")+"
", true); - } + runFlags = RUNFLAGS_SILENT_INPUT; + log(">" + log_params.join(" ") + "
", true); + } - return runFossil(params, 0, runFlags); + return runFossil(params, 0, runFlags); } //------------------------------------------------------------------------------ bool Fossil::pullWorkspace(const QUrl &url) { - QStringList params; - params << "pull"; + QStringList params; + params << "pull"; - int runFlags=RUNFLAGS_NONE; + int runFlags = RUNFLAGS_NONE; - if(!url.isEmpty()) - { - params << UrlToString(url); - params << "--once"; + if (!url.isEmpty()) + { + params << UrlToString(url); + params << "--once"; - QStringList log_params = params; - if(!url.isLocalFile()) - log_params[1] = UrlToStringDisplay(url); + QStringList log_params = params; + if (!url.isLocalFile()) + log_params[1] = UrlToStringDisplay(url); - log_params.push_front("fossil"); + log_params.push_front("fossil"); - runFlags = RUNFLAGS_SILENT_INPUT; - log(">"+log_params.join(" ")+"
", true); - } + runFlags = RUNFLAGS_SILENT_INPUT; + log(">" + log_params.join(" ") + "
", true); + } - return runFossil(params, 0, runFlags); + return runFossil(params, 0, runFlags); } //------------------------------------------------------------------------------ -bool Fossil::cloneRepository(const QString& repository, const QUrl& url, const QUrl& proxyUrl) +bool Fossil::cloneRepository(const QString &repository, const QUrl &url, const QUrl &proxyUrl) { - // Actual command - QStringList cmd = QStringList() << "clone"; + // Actual command + QStringList cmd = QStringList() << "clone"; - // Log Command - QStringList logcmd = QStringList() << "fossil" << "clone"; + // Log Command + QStringList logcmd = QStringList() << "fossil" + << "clone"; - QString source = url.toString(); - QString logsource = url.toString(QUrl::RemovePassword); - if(url.isLocalFile()) - { - source = url.toLocalFile(); - logsource = source; - } - cmd << source << repository; - logcmd << logsource << repository; + QString source = url.toString(); + QString logsource = url.toString(QUrl::RemovePassword); + if (url.isLocalFile()) + { + source = url.toLocalFile(); + logsource = source; + } + cmd << source << repository; + logcmd << logsource << repository; - if(!proxyUrl.isEmpty()) - { - cmd << "--proxy" << proxyUrl.toString(); - logcmd << "--proxy" << proxyUrl.toString(QUrl::RemovePassword); - } + if (!proxyUrl.isEmpty()) + { + cmd << "--proxy" << proxyUrl.toString(); + logcmd << "--proxy" << proxyUrl.toString(QUrl::RemovePassword); + } - log(">"+logcmd.join(" ")+"
", true); + log(">" + logcmd.join(" ") + "
", true); - // Clone Repo - if(!runFossil(cmd, 0, RUNFLAGS_SILENT_INPUT)) - return false; + // Clone Repo + if (!runFossil(cmd, 0, RUNFLAGS_SILENT_INPUT)) + return false; - return true; + return true; } //------------------------------------------------------------------------------ -bool Fossil::getExeVersion(QString& version) +bool Fossil::getExeVersion(QString &version) { - QStringList res; - if(!runFossil(QStringList() << "version", &res, RUNFLAGS_SILENT_ALL) && res.length()==1) - return false; + QStringList res; + if (!runFossil(QStringList() << "version", &res, RUNFLAGS_SILENT_ALL) && res.length() == 1) + return false; - if(res.length()==0) - return false; + if (res.length() == 0) + return false; - int off = res[0].indexOf("version "); - if(off==-1) - return false; + int off = res[0].indexOf("version "); + if (off == -1) + return false; - version = res[0].mid(off+8); - return true; + version = res[0].mid(off + 8); + return true; } //------------------------------------------------------------------------------ bool Fossil::diffFile(const QString &repoFile, bool graphical) { - if(graphical) - { - // Run the diff detached - return runFossil(QStringList() << "gdiff" << QuotePath(repoFile), 0, RUNFLAGS_DETACHED); - } - else - return runFossil(QStringList() << "diff" << QuotePath(repoFile)); + if (graphical) + { + // Run the diff detached + return runFossil(QStringList() << "gdiff" << QuotePath(repoFile), 0, RUNFLAGS_DETACHED); + } + else + return runFossil(QStringList() << "diff" << QuotePath(repoFile)); } //------------------------------------------------------------------------------ -bool Fossil::commitFiles(const QStringList& fileList, const QString& comment, const QString &newBranchName, bool isPrivateBranch) +bool Fossil::commitFiles(const QStringList &fileList, const QString &comment, const QString &newBranchName, bool isPrivateBranch) { - // Do commit - QString comment_fname; - { - QTemporaryFile temp_file; - if(!temp_file.open()) - return false; + // Do commit + QString comment_fname; + { + QTemporaryFile temp_file; + if (!temp_file.open()) + return false; - comment_fname = temp_file.fileName(); - } + comment_fname = temp_file.fileName(); + } - QFile comment_file(comment_fname); - if(!comment_file.open(QIODevice::WriteOnly)) - return false; + QFile comment_file(comment_fname); + if (!comment_file.open(QIODevice::WriteOnly)) + return false; - // Write BOM - comment_file.write(reinterpret_cast(UTF8_BOM), sizeof(UTF8_BOM)); + // Write BOM + comment_file.write(reinterpret_cast(UTF8_BOM), sizeof(UTF8_BOM)); - // Write Comment - comment_file.write(comment.toUtf8()); - comment_file.close(); + // Write Comment + comment_file.write(comment.toUtf8()); + comment_file.close(); - // Generate fossil parameters. - QStringList params; - params << "commit" << "--message-file" << QuotePath(comment_fname); + // Generate fossil parameters. + QStringList params; + params << "commit" + << "--message-file" << QuotePath(comment_fname); - // Commit to new branch - if(!newBranchName.isEmpty()) - { - params << "--branch" << newBranchName.trimmed(); + // Commit to new branch + if (!newBranchName.isEmpty()) + { + params << "--branch" << newBranchName.trimmed(); - // Private branches are not synced with remotes - if(isPrivateBranch) - params << "--private"; - } + // Private branches are not synced with remotes + if (isPrivateBranch) + params << "--private"; + } - params << QuotePaths(fileList); + params << QuotePaths(fileList); - runFossil(params); - QFile::remove(comment_fname); - return true; + runFossil(params); + QFile::remove(comment_fname); + return true; } //------------------------------------------------------------------------------ -bool Fossil::addFiles(const QStringList& fileList) +bool Fossil::addFiles(const QStringList &fileList) { - if(fileList.empty()) - return false; + if (fileList.empty()) + return false; - // Do Add - return runFossil(QStringList() << "add" << QuotePaths(fileList)); + // Do Add + return runFossil(QStringList() << "add" << QuotePaths(fileList)); } //------------------------------------------------------------------------------ -bool Fossil::removeFiles(const QStringList& fileList, bool deleteLocal) +bool Fossil::removeFiles(const QStringList &fileList, bool deleteLocal) { - if(fileList.empty()) - return false; + if (fileList.empty()) + return false; - // Do Delete - if(!runFossil(QStringList() << "delete" << QuotePaths(fileList))) - return false; + // Do Delete + if (!runFossil(QStringList() << "delete" << QuotePaths(fileList))) + return false; - if(deleteLocal) - { - for(int i=0; i0) - url_str = out[0].trimmed(); + QString url_str; + if (out.length() > 0) + url_str = out[0].trimmed(); - if(url_str == "off") - url.clear(); - else - url.setUrl(url_str); + if (url_str == "off") + url.clear(); + else + url.setUrl(url_str); - return true; + return true; } //------------------------------------------------------------------------------ -bool Fossil::stashNew(const QStringList& fileList, const QString& name, bool revert) +bool Fossil::stashNew(const QStringList &fileList, const QString &name, bool revert) { - // Do Stash - // Snapshot just records the changes into the stash - QString command = "snapshot"; + // Do Stash + // Snapshot just records the changes into the stash + QString command = "snapshot"; - // Save also reverts the stashed files - if(revert) - command = "save"; + // Save also reverts the stashed files + if (revert) + command = "save"; - return runFossil(QStringList() << "stash" << command << "-m" << name << QuotePaths(fileList)); + return runFossil(QStringList() << "stash" << command << "-m" << name << QuotePaths(fileList)); } //------------------------------------------------------------------------------ -bool Fossil::stashList(stashmap_t& stashes) +bool Fossil::stashList(stashmap_t &stashes) { - stashes.clear(); - QStringList res; + stashes.clear(); + QStringList res; - if(!runFossil(QStringList() << "stash" << "ls", &res, RUNFLAGS_SILENT_ALL)) - return false; + if (!runFossil(QStringList() << "stash" + << "ls", + &res, RUNFLAGS_SILENT_ALL)) + return false; - // 19: [5c46757d4b9765] on 2012-04-22 04:41:15 - static const QRegExp REGEX_STASH("\\s*(\\d+):\\s+\\[(.*)\\] on (\\d+)-(\\d+)-(\\d+) (\\d+):(\\d+):(\\d+)", Qt::CaseInsensitive); + // 19: [5c46757d4b9765] on 2012-04-22 04:41:15 + static const QRegExp REGEX_STASH("\\s*(\\d+):\\s+\\[(.*)\\] on (\\d+)-(\\d+)-(\\d+) (\\d+):(\\d+):(\\d+)", Qt::CaseInsensitive); - for(QStringList::iterator line_it=res.begin(); line_it!=res.end(); ) - { - QString line = *line_it; + for (QStringList::iterator line_it = res.begin(); line_it != res.end();) + { + QString line = *line_it; - int index = REGEX_STASH.indexIn(line); - if(index==-1) - break; + int index = REGEX_STASH.indexIn(line); + if (index == -1) + break; - QString id = REGEX_STASH.cap(1); - ++line_it; + QString id = REGEX_STASH.cap(1); + ++line_it; - QString name; - // Finish at an anonymous stash or start of a new stash ? - if(line_it==res.end() || REGEX_STASH.indexIn(*line_it)!=-1) - name = line.trimmed(); - else // Named stash - { - // Parse stash name - name = (*line_it); - name = name.trimmed(); - ++line_it; - } + QString name; + // Finish at an anonymous stash or start of a new stash ? + if (line_it == res.end() || REGEX_STASH.indexIn(*line_it) != -1) + name = line.trimmed(); + else // Named stash + { + // Parse stash name + name = (*line_it); + name = name.trimmed(); + ++line_it; + } - stashes.insert(name, id); - } + stashes.insert(name, id); + } - return true; + return true; } //------------------------------------------------------------------------------ -bool Fossil::stashApply(const QString& name) +bool Fossil::stashApply(const QString &name) { - return runFossil(QStringList() << "stash" << "apply" << name); + return runFossil(QStringList() << "stash" + << "apply" << name); } //------------------------------------------------------------------------------ -bool Fossil::stashDrop(const QString& name) +bool Fossil::stashDrop(const QString &name) { - return runFossil(QStringList() << "stash" << "drop" << name); + return runFossil(QStringList() << "stash" + << "drop" << name); } //------------------------------------------------------------------------------ -bool Fossil::stashDiff(const QString& name) +bool Fossil::stashDiff(const QString &name) { - return runFossil(QStringList() << "stash" << "diff" << name, 0); + return runFossil(QStringList() << "stash" + << "diff" << name, + 0); } //------------------------------------------------------------------------------ -bool Fossil::tagList(QStringMap& tags) +bool Fossil::tagList(QStringMap &tags) { - tags.clear(); - QStringList tagnames; + tags.clear(); + QStringList tagnames; - if(!runFossil(QStringList() << "tag" << "ls", &tagnames, RUNFLAGS_SILENT_ALL)) - return false; + if (!runFossil(QStringList() << "tag" + << "ls", + &tagnames, RUNFLAGS_SILENT_ALL)) + return false; - QStringList info; - foreach(const QString &line, tagnames) - { - QString tag = line.trimmed(); + QStringList info; + foreach (const QString &line, tagnames) + { + QString tag = line.trimmed(); - if(tag.isEmpty()) - continue; + if (tag.isEmpty()) + continue; - info.clear(); + info.clear(); - // Use "whatis" instead of "info" to get extra information like the closed raw-tag - if(!runFossil(QStringList() << "whatis" << "tag:"+tag, &info, RUNFLAGS_SILENT_ALL)) - return false; + // Use "whatis" instead of "info" to get extra information like the closed raw-tag + if (!runFossil(QStringList() << "whatis" + << "tag:" + tag, + &info, RUNFLAGS_SILENT_ALL)) + return false; - /* + /* name: tag:refactor artifact: 54059126aee6bb232373c1f134cc07ea0a6f4cca size: 15831 bytes @@ -576,152 +586,158 @@ bool Fossil::tagList(QStringMap& tags) tableViewStash to stashTableView */ - QStringMap props; - ParseProperties(props, info, ':'); + QStringMap props; + ParseProperties(props, info, ':'); - bool closed = false; - if(props.contains("raw-tags")) - { - QString raw_tags = props["raw-tags"]; - closed = raw_tags.indexOf("closed") != -1; - } + bool closed = false; + if (props.contains("raw-tags")) + { + QString raw_tags = props["raw-tags"]; + closed = raw_tags.indexOf("closed") != -1; + } - // Skip closed tags, which are essentially closed branches. - // FIXME: Fossil treating listing all closed branches as active tags with a "closed" - // "raw-tag" seems weird. Maybe this will change at some point. Re-evaluate this - // behaviour in the future. - if(closed) - continue; + // Skip closed tags, which are essentially closed branches. + // FIXME: Fossil treating listing all closed branches as active tags with a "closed" + // "raw-tag" seems weird. Maybe this will change at some point. Re-evaluate this + // behaviour in the future. + if (closed) + continue; - Q_ASSERT(props.contains("artifact")); - QString revision = props["artifact"]; - Q_ASSERT(!revision.isEmpty()); + Q_ASSERT(props.contains("artifact")); + QString revision = props["artifact"]; + Q_ASSERT(!revision.isEmpty()); - tags.insert(tag, revision); - } - return true; + tags.insert(tag, revision); + } + return true; } //------------------------------------------------------------------------------ -bool Fossil::tagNew(const QString& name, const QString& revision) +bool Fossil::tagNew(const QString &name, const QString &revision) { - QStringList res; + QStringList res; - if(!runFossil(QStringList() << "tag" << "add" << name << revision, &res)) - return false; - return true; + if (!runFossil(QStringList() << "tag" + << "add" << name << revision, + &res)) + return false; + return true; } //------------------------------------------------------------------------------ -bool Fossil::tagDelete(const QString& name, const QString &revision) +bool Fossil::tagDelete(const QString &name, const QString &revision) { - QStringList res; + QStringList res; - if(!runFossil(QStringList() << "tag" << "cancel" << "tag:"+name << revision, &res)) - return false; + if (!runFossil(QStringList() << "tag" + << "cancel" + << "tag:" + name << revision, + &res)) + return false; - return true; + return true; } //------------------------------------------------------------------------------ -bool Fossil::branchList(QStringList& branches, QStringList& activeBranches) +bool Fossil::branchList(QStringList &branches, QStringList &activeBranches) { - branches.clear(); - activeBranches.clear(); - QStringList res; + branches.clear(); + activeBranches.clear(); + QStringList res; - if(!runFossil(QStringList() << "branch" , &res, RUNFLAGS_SILENT_ALL)) - return false; + if (!runFossil(QStringList() << "branch", &res, RUNFLAGS_SILENT_ALL)) + return false; - foreach(const QString &line, res) - { - QString name = line.trimmed(); + foreach (const QString &line, res) + { + QString name = line.trimmed(); - if(name.isEmpty()) - continue; + if (name.isEmpty()) + continue; - // Active branches start with a start - int active_index = name.indexOf('*'); - bool is_active = (active_index != -1) && active_index==0; + // Active branches start with a start + int active_index = name.indexOf('*'); + bool is_active = (active_index != -1) && active_index == 0; - // Strip - if(is_active) - { - name = name.mid(is_active+1).trimmed(); - activeBranches.append(name); - } - else - branches.append(name); - } + // Strip + if (is_active) + { + name = name.mid(is_active + 1).trimmed(); + activeBranches.append(name); + } + else + branches.append(name); + } - branches.sort(); - activeBranches.sort(); - return true; + branches.sort(); + activeBranches.sort(); + return true; } //------------------------------------------------------------------------------ -bool Fossil::branchNew(const QString& name, const QString& revisionBasis, bool isPrivate) +bool Fossil::branchNew(const QString &name, const QString &revisionBasis, bool isPrivate) { - QStringList params; + QStringList params; - params <<"branch" << "new" << name << revisionBasis; + params << "branch" + << "new" << name << revisionBasis; - if(isPrivate) - params << "--private"; + if (isPrivate) + params << "--private"; - QStringList res; + QStringList res; - if(!runFossil(params, &res)) - return false; - return true; + if (!runFossil(params, &res)) + return false; + return true; } //------------------------------------------------------------------------------ -bool Fossil::branchMerge(QStringList &res, const QString& revision, bool integrate, bool force, bool testOnly) +bool Fossil::branchMerge(QStringList &res, const QString &revision, bool integrate, bool force, bool testOnly) { - QStringList params; + QStringList params; - params <<"merge"; + params << "merge"; - if(integrate) - params << "--integrate"; + if (integrate) + params << "--integrate"; - if(force) - params << "--force"; + if (force) + params << "--force"; - if(testOnly) - params << "--dry-run"; + if (testOnly) + params << "--dry-run"; - params << revision; + params << revision; - if(!runFossil(params, &res)) - return false; - return true; + if (!runFossil(params, &res)) + return false; + return true; } //------------------------------------------------------------------------------ static QString ParseFossilQuery(QString line) { - // Extract question - int qend = line.lastIndexOf('('); - if(qend == -1) - qend = line.lastIndexOf('['); - Q_ASSERT(qend!=-1); - line = line.left(qend); - line = line.trimmed(); - line += "?"; - line[0]=QString(line[0]).toUpper()[0]; - return line; + // Extract question + int qend = line.lastIndexOf('('); + if (qend == -1) + qend = line.lastIndexOf('['); + Q_ASSERT(qend != -1); + line = line.left(qend); + line = line.trimmed(); + line += "?"; + line[0] = QString(line[0]).toUpper()[0]; + return line; } //------------------------------------------------------------------------------ bool Fossil::runFossil(const QStringList &args, QStringList *output, int runFlags) { - int exit_code = EXIT_FAILURE; - if(!runFossilRaw(args, output, &exit_code, runFlags)) - return false; + int exit_code = EXIT_FAILURE; + if (!runFossilRaw(args, output, &exit_code, runFlags)) + return false; - return exit_code == EXIT_SUCCESS; + return exit_code == EXIT_SUCCESS; } //------------------------------------------------------------------------------ @@ -729,133 +745,133 @@ bool Fossil::runFossil(const QStringList &args, QStringList *output, int runFlag // issued an error bool Fossil::runFossilRaw(const QStringList &args, QStringList *output, int *exitCode, int runFlags) { - bool silent_input = (runFlags & RUNFLAGS_SILENT_INPUT) != 0; - bool silent_output = (runFlags & RUNFLAGS_SILENT_OUTPUT) != 0; - bool detached = (runFlags & RUNFLAGS_DETACHED) != 0; + bool silent_input = (runFlags & RUNFLAGS_SILENT_INPUT) != 0; + bool silent_output = (runFlags & RUNFLAGS_SILENT_OUTPUT) != 0; + bool detached = (runFlags & RUNFLAGS_DETACHED) != 0; - if(!silent_input) - { - QString params; - foreach(QString p, args) - { - if(p.indexOf(' ')!=-1) - params += '"' + p + "\" "; - else - params += p + ' '; - } - log("> fossil "+params+"
", true); - } + if (!silent_input) + { + QString params; + foreach (QString p, args) + { + if (p.indexOf(' ') != -1) + params += '"' + p + "\" "; + else + params += p + ' '; + } + log("> fossil " + params + "
", true); + } - QString wkdir = getWorkspacePath(); + QString wkdir = getWorkspacePath(); - QString fossil = getFossilPath(); + QString fossil = getFossilPath(); - // Detached processes use the command-line only, to avoid having to wait - // for the temporary args file to be released before returing - if(detached) - { - bool started = QProcess::startDetached(fossil, args, wkdir); - if(exitCode) - *exitCode = started ? EXIT_SUCCESS : EXIT_FAILURE; - return started; - } + // Detached processes use the command-line only, to avoid having to wait + // for the temporary args file to be released before returing + if (detached) + { + bool started = QProcess::startDetached(fossil, args, wkdir); + if (exitCode) + *exitCode = started ? EXIT_SUCCESS : EXIT_FAILURE; + return started; + } - // Make status message - QString status_msg = QObject::tr("Running Fossil"); - if(args.length() > 0) - status_msg = QString("Fossil %0").arg(args[0].toCaseFolded()); - ScopedStatus status(uiCallback, status_msg); + // Make status message + QString status_msg = QObject::tr("Running Fossil"); + if (args.length() > 0) + status_msg = QString("Fossil %0").arg(args[0].toCaseFolded()); + ScopedStatus status(uiCallback, status_msg); - // Generate args file - const QStringList *final_args = &args; - QTemporaryFile args_file; - if(!args_file.open()) - { - log(QObject::tr("Could not generate command line file")); - return false; - } + // Generate args file + const QStringList *final_args = &args; + QTemporaryFile args_file; + if (!args_file.open()) + { + log(QObject::tr("Could not generate command line file")); + return false; + } - // Write BOM - args_file.write(reinterpret_cast(UTF8_BOM), sizeof(UTF8_BOM)); + // Write BOM + args_file.write(reinterpret_cast(UTF8_BOM), sizeof(UTF8_BOM)); - // Write Args - foreach(const QString &arg, args) - { - args_file.write(arg.toUtf8()); - args_file.write("\n"); - } - args_file.close(); + // Write Args + foreach (const QString &arg, args) + { + args_file.write(arg.toUtf8()); + args_file.write("\n"); + } + args_file.close(); - // Replace args with args filename - QStringList run_args; - run_args.append("--args"); - run_args.append(args_file.fileName()); - final_args = &run_args; + // Replace args with args filename + QStringList run_args; + run_args.append("--args"); + run_args.append(args_file.fileName()); + final_args = &run_args; - // Create fossil process - // FIXME: when we are sure this works delete this - // LoggedProcess process(parentWidget*/); - LoggedProcess process(0); + // Create fossil process + // FIXME: when we are sure this works delete this + // LoggedProcess process(parentWidget*/); + LoggedProcess process(0); - process.setWorkingDirectory(wkdir); + process.setWorkingDirectory(wkdir); - process.start(fossil, *final_args); - if(!process.waitForStarted()) - { - log(QObject::tr("Could not start Fossil executable '%0'").arg(fossil)+"\n"); - return false; - } - const QChar EOL_MARK('\n'); - QString ans_yes = 'y' + EOL_MARK; - QString ans_no = 'n' + EOL_MARK; - QString ans_always = 'a' + EOL_MARK; - QString ans_convert = 'c' + EOL_MARK; + process.start(fossil, *final_args); + if (!process.waitForStarted()) + { + log(QObject::tr("Could not start Fossil executable '%0'").arg(fossil) + "\n"); + return false; + } + const QChar EOL_MARK('\n'); + QString ans_yes = 'y' + EOL_MARK; + QString ans_no = 'n' + EOL_MARK; + QString ans_always = 'a' + EOL_MARK; + QString ans_convert = 'c' + EOL_MARK; - QString buffer; + QString buffer; #ifdef Q_OS_WIN - QTextCodec *codec = QTextCodec::codecForName("UTF-8"); + QTextCodec *codec = QTextCodec::codecForName("UTF-8"); #else - QTextCodec *codec = QTextCodec::codecForLocale(); + QTextCodec *codec = QTextCodec::codecForLocale(); #endif - Q_ASSERT(codec); - QTextDecoder *decoder = codec->makeDecoder(); - Q_ASSERT(decoder); + Q_ASSERT(codec); + QTextDecoder *decoder = codec->makeDecoder(); + Q_ASSERT(decoder); - Q_ASSERT(uiCallback); + Q_ASSERT(uiCallback); #ifdef QT_DEBUG - size_t input_index = 0; + size_t input_index = 0; #endif - while(true) - { - QProcess::ProcessState state = process.state(); - qint64 bytes_avail = process.logBytesAvailable(); + while (true) + { + QProcess::ProcessState state = process.state(); + qint64 bytes_avail = process.logBytesAvailable(); - if(state!=QProcess::Running && bytes_avail<1) - break; + if (state != QProcess::Running && bytes_avail < 1) + break; - if(uiCallback->processAborted()) - { - #ifdef Q_OS_WIN // Verify this is still true on Qt5 - process.kill(); // QT on windows cannot terminate console processes with QProcess::terminate - #else - process.terminate(); - #endif - break; - } + if (uiCallback->processAborted()) + { +#ifdef Q_OS_WIN // Verify this is still true on Qt5 + process.kill(); // QT on windows cannot terminate console processes with QProcess::terminate +#else + process.terminate(); +#endif + break; + } - QByteArray input; - process.getLogAndClear(input); + QByteArray input; + process.getLogAndClear(input); - #ifdef QT_DEBUG // Log fossil output in debug builds - if(!input.isEmpty() && (runFlags & RUNFLAGS_DEBUG) ) - qDebug() << "[" << ++input_index << "] '" << input.data() << "'\n"; - #endif +#ifdef QT_DEBUG // Log fossil output in debug builds + if (!input.isEmpty() && (runFlags & RUNFLAGS_DEBUG)) + qDebug() << "[" << ++input_index << "] '" << input.data() << "'\n"; +#endif - buffer += decoder->toUnicode(input); -#if 0 // Keep this for now to simulate bad parses + buffer += decoder->toUnicode(input); +#if 0 // Keep this for now to simulate bad parses if(runFlags & RUNFLAGS_DEBUG) { static int debug=1; @@ -877,324 +893,325 @@ bool Fossil::runFossilRaw(const QStringList &args, QStringList *output, int *exi buffer=""; } #endif - #ifdef QT_DEBUG // breakpoint - //if(buffer.indexOf("SQLITE_CANTOPEN")!=-1) - // qDebug() << "Breakpoint\n"; - #endif +#ifdef QT_DEBUG // breakpoint +//if(buffer.indexOf("SQLITE_CANTOPEN")!=-1) +// qDebug() << "Breakpoint\n"; +#endif - QCoreApplication::processEvents(QEventLoop::AllEvents, 500); // 500 ms + QCoreApplication::processEvents(QEventLoop::AllEvents, 500); // 500 ms - if(buffer.isEmpty()) - continue; + if (buffer.isEmpty()) + continue; - // Normalize line endings - buffer = buffer.replace("\r\n", "\n"); - buffer = buffer.replace("\r", "\n"); + // Normalize line endings + buffer = buffer.replace("\r\n", "\n"); + buffer = buffer.replace("\r", "\n"); - // Extract the last line - int last_line_start = buffer.lastIndexOf(EOL_MARK); + // Extract the last line + int last_line_start = buffer.lastIndexOf(EOL_MARK); - QString last_line; - QString before_last_line; - if(last_line_start != -1) - { - last_line = buffer.mid(last_line_start+1); // Including the EOL + QString last_line; + QString before_last_line; + if (last_line_start != -1) + { + last_line = buffer.mid(last_line_start + 1); // Including the EOL - // Detect previous line - if(last_line_start>0) - { - int before_last_line_start = buffer.lastIndexOf(EOL_MARK, last_line_start-1); + // Detect previous line + if (last_line_start > 0) + { + int before_last_line_start = buffer.lastIndexOf(EOL_MARK, last_line_start - 1); - // No new-line before ? - if(before_last_line_start==-1) - before_last_line_start = 0; // Use entire line - else - ++before_last_line_start; // Skip new-line + // No new-line before ? + if (before_last_line_start == -1) + before_last_line_start = 0; // Use entire line + else + ++before_last_line_start; // Skip new-line - // Extract previous line - before_last_line = buffer.mid(before_last_line_start, last_line_start-before_last_line_start); - } - } - else - last_line = buffer; + // Extract previous line + before_last_line = buffer.mid(before_last_line_start, last_line_start - before_last_line_start); + } + } + else + last_line = buffer; - last_line = last_line.trimmed(); + last_line = last_line.trimmed(); - // Check if we have a query - bool ends_qmark = !last_line.isEmpty() && last_line[last_line.length()-1]=='?'; - bool have_yn_query = last_line.toLower().indexOf("y/n")!=-1; - bool have_yna_query = last_line.toLower().indexOf("a=always/y/n")!=-1 || last_line.toLower().indexOf("yes/no/all")!=-1 || last_line.toLower().indexOf("a=all/y/n")!=-1; - bool have_an_query = last_line.toLower().indexOf("a=always/n")!=-1; - bool have_acyn_query = last_line.toLower().indexOf("a=all/c=convert/y/n")!=-1; + // Check if we have a query + bool ends_qmark = !last_line.isEmpty() && last_line[last_line.length() - 1] == '?'; + bool have_yn_query = last_line.toLower().indexOf("y/n") != -1; + bool have_yna_query = last_line.toLower().indexOf("a=always/y/n") != -1 || last_line.toLower().indexOf("yes/no/all") != -1 || last_line.toLower().indexOf("a=all/y/n") != -1; + bool have_an_query = last_line.toLower().indexOf("a=always/n") != -1; + bool have_acyn_query = last_line.toLower().indexOf("a=all/c=convert/y/n") != -1; - bool have_query = ends_qmark && (have_yn_query || have_yna_query || have_an_query || have_acyn_query); + bool have_query = ends_qmark && (have_yn_query || have_yna_query || have_an_query || have_acyn_query); - // Flush all complete lines to the log and output - QStringList log_lines = buffer.left(last_line_start).split(EOL_MARK); - for(int l=0; lappend(line); + if (output) + output->append(line); - if(!silent_output) - log(line+"\n"); - } + if (!silent_output) + log(line + "\n"); + } - // Remove everything we processed (including the EOL) - buffer = buffer.mid(last_line_start+1) ; + // Remove everything we processed (including the EOL) + buffer = buffer.mid(last_line_start + 1); - // Now process any query - if(have_query && (have_yna_query || have_acyn_query)) - { - log(last_line); - QString query = ParseFossilQuery(last_line); - QMessageBox::StandardButtons buttons = QMessageBox::YesToAll|QMessageBox::Yes|QMessageBox::No; + // Now process any query + if (have_query && (have_yna_query || have_acyn_query)) + { + log(last_line); + QString query = ParseFossilQuery(last_line); + QMessageBox::StandardButtons buttons = QMessageBox::YesToAll | QMessageBox::Yes | QMessageBox::No; - // Add any extra text available to the query - before_last_line = before_last_line.trimmed(); - if(!before_last_line.isEmpty()) - query = before_last_line + "\n" + query; + // Add any extra text available to the query + before_last_line = before_last_line.trimmed(); + if (!before_last_line.isEmpty()) + query = before_last_line + "\n" + query; - // Map the Convert option to the Apply button - if(have_acyn_query) - buttons |= QMessageBox::Apply; + // Map the Convert option to the Apply button + if (have_acyn_query) + buttons |= QMessageBox::Apply; - QMessageBox::StandardButton res = uiCallback->Query("Fossil", query, buttons); - if(res==QMessageBox::Yes) - { - process.write(ans_yes.toLatin1()); - log("Y\n"); - } - else if(res==QMessageBox::YesAll) - { - process.write(ans_always.toLatin1()); - log("A\n"); - } - else if(res==QMessageBox::Apply) - { - process.write(ans_convert.toLatin1()); - log("C\n"); - } - else - { - process.write(ans_no.toLatin1()); - log("N\n"); - } - buffer.clear(); - } - else if(have_query && have_yn_query) - { - log(last_line); - QString query = ParseFossilQuery(last_line); - QMessageBox::StandardButton res = uiCallback->Query("Fossil", query, QMessageBox::Yes|QMessageBox::No); + QMessageBox::StandardButton res = uiCallback->Query("Fossil", query, buttons); + if (res == QMessageBox::Yes) + { + process.write(ans_yes.toLatin1()); + log("Y\n"); + } + else if (res == QMessageBox::YesAll) + { + process.write(ans_always.toLatin1()); + log("A\n"); + } + else if (res == QMessageBox::Apply) + { + process.write(ans_convert.toLatin1()); + log("C\n"); + } + else + { + process.write(ans_no.toLatin1()); + log("N\n"); + } + buffer.clear(); + } + else if (have_query && have_yn_query) + { + log(last_line); + QString query = ParseFossilQuery(last_line); + QMessageBox::StandardButton res = uiCallback->Query("Fossil", query, QMessageBox::Yes | QMessageBox::No); - if(res==QMessageBox::Yes) - { - process.write(ans_yes.toLatin1()); - log("Y\n"); - } - else - { - process.write(ans_no.toLatin1()); - log("N\n"); - } + if (res == QMessageBox::Yes) + { + process.write(ans_yes.toLatin1()); + log("Y\n"); + } + else + { + process.write(ans_no.toLatin1()); + log("N\n"); + } - buffer.clear(); - } - else if(have_query && have_an_query) - { - log(last_line); - QString query = ParseFossilQuery(last_line); - QMessageBox::StandardButton res = uiCallback->Query("Fossil", query, QMessageBox::YesToAll|QMessageBox::No); - if(res==QMessageBox::YesAll) - { - process.write(ans_always.toLatin1()); - log("A\n"); - } - else - { - process.write(ans_no.toLatin1()); - log("N\n"); - } - buffer.clear(); - } - } + buffer.clear(); + } + else if (have_query && have_an_query) + { + log(last_line); + QString query = ParseFossilQuery(last_line); + QMessageBox::StandardButton res = uiCallback->Query("Fossil", query, QMessageBox::YesToAll | QMessageBox::No); + if (res == QMessageBox::YesAll) + { + process.write(ans_always.toLatin1()); + log("A\n"); + } + else + { + process.write(ans_no.toLatin1()); + log("N\n"); + } + buffer.clear(); + } + } - delete decoder; + delete decoder; - // Must be finished by now - process.waitForFinished(5000); // Wait for termination 5 secs maximum - Q_ASSERT(process.state()==QProcess::NotRunning); + // Must be finished by now + process.waitForFinished(5000); // Wait for termination 5 secs maximum + Q_ASSERT(process.state() == QProcess::NotRunning); - QProcess::ExitStatus es = process.exitStatus(); + QProcess::ExitStatus es = process.exitStatus(); - if(es!=QProcess::NormalExit || uiCallback->processAborted()) - return false; + if (es != QProcess::NormalExit || uiCallback->processAborted()) + return false; - if(exitCode) - *exitCode = process.exitCode(); + if (exitCode) + *exitCode = process.exitCode(); - return true; + return true; } //------------------------------------------------------------------------------ QString Fossil::getFossilPath() { - // Use the user-specified fossil if available - QString fossil_path = fossilPath; - if(!fossil_path.isEmpty()) - return QDir::toNativeSeparators(fossil_path); + // Use the user-specified fossil if available + QString fossil_path = fossilPath; + if (!fossil_path.isEmpty()) + return QDir::toNativeSeparators(fossil_path); - QString fossil_exe = "fossil"; + QString fossil_exe = "fossil"; #ifdef Q_OS_WIN - fossil_exe += ".exe"; + fossil_exe += ".exe"; #endif - // Use our fossil if available - QString fuel_fossil = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + QDir::separator() + fossil_exe); + // Use our fossil if available + QString fuel_fossil = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + QDir::separator() + fossil_exe); - if(QFile::exists(fuel_fossil)) - return fuel_fossil; + if (QFile::exists(fuel_fossil)) + return fuel_fossil; - // Otherwise assume there is a "fossil" executable in the path - return fossil_exe; + // Otherwise assume there is a "fossil" executable in the path + return fossil_exe; } //------------------------------------------------------------------------------ bool Fossil::isWorkspace(const QString &path) { - if(path.length()==0) - return false; + if (path.length() == 0) + return false; - QFileInfo fi(path); - QString wkspace = path; - wkspace = fi.absoluteDir().absolutePath(); - QString checkout_file1 = wkspace + PATH_SEPARATOR + FOSSIL_CHECKOUT1; - QString checkout_file2 = wkspace + PATH_SEPARATOR + FOSSIL_CHECKOUT2; + QFileInfo fi(path); + QString wkspace = path; + wkspace = fi.absoluteDir().absolutePath(); + QString checkout_file1 = wkspace + PATH_SEPARATOR + FOSSIL_CHECKOUT1; + QString checkout_file2 = wkspace + PATH_SEPARATOR + FOSSIL_CHECKOUT2; - return (QFileInfo(checkout_file1).exists() || QFileInfo(checkout_file2).exists()); + return (QFileInfo(checkout_file1).exists() || QFileInfo(checkout_file2).exists()); } //------------------------------------------------------------------------------ bool Fossil::uiRunning() const { - return fossilUI.state() == QProcess::Running; + return fossilUI.state() == QProcess::Running; } //------------------------------------------------------------------------------ bool Fossil::startUI(const QString &httpPort) { - if(uiRunning()) - { - log(QObject::tr("Fossil UI is already running")+"\n"); - return true; - } + if (uiRunning()) + { + log(QObject::tr("Fossil UI is already running") + "\n"); + return true; + } - fossilUI.setProcessChannelMode(QProcess::MergedChannels); - fossilUI.setWorkingDirectory(getWorkspacePath()); + fossilUI.setProcessChannelMode(QProcess::MergedChannels); + fossilUI.setWorkingDirectory(getWorkspacePath()); - log("> fossil ui
", true); - log(QObject::tr("Starting Fossil browser UI. Please wait.")+"\n"); - QString fossil = getFossilPath(); + log("> fossil ui
", true); + log(QObject::tr("Starting Fossil browser UI. Please wait.") + "\n"); + QString fossil = getFossilPath(); - QStringList params; - params << "server" << "--localauth"; + QStringList params; + params << "server" + << "--localauth"; - if(!httpPort.isEmpty()) - params << "-P" << httpPort; + if (!httpPort.isEmpty()) + params << "-P" << httpPort; - fossilUI.start(getFossilPath(), params); + fossilUI.start(getFossilPath(), params); - if(!fossilUI.waitForStarted() || fossilUI.state()!=QProcess::Running) - { - log(QObject::tr("Could not start Fossil executable '%s'").arg(fossil)+"\n"); - return false; - } + if (!fossilUI.waitForStarted() || fossilUI.state() != QProcess::Running) + { + log(QObject::tr("Could not start Fossil executable '%s'").arg(fossil) + "\n"); + return false; + } #ifdef Q_OS_WIN - QTextCodec *codec = QTextCodec::codecForName("UTF-8"); + QTextCodec *codec = QTextCodec::codecForName("UTF-8"); #else - QTextCodec *codec = QTextCodec::codecForLocale(); + QTextCodec *codec = QTextCodec::codecForLocale(); #endif - Q_ASSERT(codec); - QTextDecoder *decoder = codec->makeDecoder(); - Q_ASSERT(decoder); + Q_ASSERT(codec); + QTextDecoder *decoder = codec->makeDecoder(); + Q_ASSERT(decoder); - fossilUIPort.clear(); + fossilUIPort.clear(); - // Listening for HTTP requests on TCP port 8081 - static const QRegExp REGEX_PORT(".*TCP port ([0-9]+)\\n", Qt::CaseSensitive); + // Listening for HTTP requests on TCP port 8081 + static const QRegExp REGEX_PORT(".*TCP port ([0-9]+)\\n", Qt::CaseSensitive); - // Wait for fossil to report the http port - QString buffer; - while(true) - { - QProcess::ProcessState state = fossilUI.state(); - qint64 bytes_avail = fossilUI.logBytesAvailable(); + // Wait for fossil to report the http port + QString buffer; + while (true) + { + QProcess::ProcessState state = fossilUI.state(); + qint64 bytes_avail = fossilUI.logBytesAvailable(); - if(state!=QProcess::Running && bytes_avail<1) - break; + if (state != QProcess::Running && bytes_avail < 1) + break; - QByteArray input; - fossilUI.getLogAndClear(input); + QByteArray input; + fossilUI.getLogAndClear(input); - buffer += decoder->toUnicode(input); + buffer += decoder->toUnicode(input); - // Normalize line endings - buffer = buffer.replace("\r\n", "\n"); - buffer = buffer.replace("\r", "\n"); + // Normalize line endings + buffer = buffer.replace("\r\n", "\n"); + buffer = buffer.replace("\r", "\n"); - int index = REGEX_PORT.indexIn(buffer); - if(index==-1) - { - QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); - continue; - } + int index = REGEX_PORT.indexIn(buffer); + if (index == -1) + { + QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); + continue; + } - // Extract port - fossilUIPort = REGEX_PORT.cap(1).trimmed(); + // Extract port + fossilUIPort = REGEX_PORT.cap(1).trimmed(); - // Done parsing - break; - } - return true; + // Done parsing + break; + } + return true; } //------------------------------------------------------------------------------ void Fossil::stopUI() { - if(uiRunning()) - { + if (uiRunning()) + { #ifdef Q_WS_WIN - fossilUI.kill(); // QT on windows cannot terminate console processes with QProcess::terminate + fossilUI.kill(); // QT on windows cannot terminate console processes with QProcess::terminate #else - fossilUI.terminate(); + fossilUI.terminate(); #endif - } - fossilUI.close(); - fossilUIPort.clear(); + } + fossilUI.close(); + fossilUIPort.clear(); } //------------------------------------------------------------------------------ QString Fossil::getUIHttpAddress() const { - if(fossilUIPort.isEmpty()) - return QString(); - return "http://127.0.0.1:"+fossilUIPort; + if (fossilUIPort.isEmpty()) + return QString(); + return "http://127.0.0.1:" + fossilUIPort; } diff --git a/src/Fossil.h b/src/Fossil.h index 71a4aa7..886abc1 100644 --- a/src/Fossil.h +++ b/src/Fossil.h @@ -2,121 +2,119 @@ #define FOSSIL_H class QStringList; -#include -#include -#include #include "LoggedProcess.h" #include "Utils.h" #include "WorkspaceCommon.h" +#include +#include +#include class Fossil { public: + Fossil(); + void Init(UICallback *callback, const QString &exePath); - Fossil(); - void Init(UICallback *callback, const QString &exePath); + // Repositories + bool createRepository(const QString &repositoryPath); + bool cloneRepository(const QString &repository, const QUrl &url, const QUrl &proxyUrl); - // Repositories - bool createRepository(const QString &repositoryPath); - bool cloneRepository(const QString &repository, const QUrl &url, const QUrl &proxyUrl); + // Workspace + bool createWorkspace(const QString &repositoryPath, const QString &workspacePath); + bool closeWorkspace(bool force = false); + void setWorkspace(const QString &_workspacePath); + bool pushWorkspace(const QUrl &url); + bool pullWorkspace(const QUrl &url); + bool undoWorkspace(QStringList &result, bool explainOnly); + bool updateWorkspace(QStringList &result, const QString &revision, bool explainOnly); + bool statusWorkspace(QStringList &result); + WorkspaceState getWorkspaceState(); + static bool isWorkspace(const QString &path); - // Workspace - bool createWorkspace(const QString &repositoryPath, const QString& workspacePath); - bool closeWorkspace(bool force=false); - void setWorkspace(const QString &_workspacePath); - bool pushWorkspace(const QUrl& url); - bool pullWorkspace(const QUrl& url); - bool undoWorkspace(QStringList& result, bool explainOnly); - bool updateWorkspace(QStringList& result, const QString& revision, bool explainOnly); - bool statusWorkspace(QStringList& result); - WorkspaceState getWorkspaceState(); - static bool isWorkspace(const QString &path); + // Workspace Information + const QString &getProjectName() const { return projectName; } + const QString &getRepositoryFile() const { return repositoryFile; } + const QString &getWorkspacePath() const { return workspacePath; } - // Workspace Information - const QString &getProjectName() const { return projectName; } - const QString &getRepositoryFile() const { return repositoryFile; } - const QString &getWorkspacePath() const { return workspacePath; } + // Files + bool listFiles(QStringList &files); + bool diffFile(const QString &repoFile, bool graphical); + bool commitFiles(const QStringList &fileList, const QString &comment, const QString &newBranchName, bool isPrivateBranch); + bool addFiles(const QStringList &fileList); + bool removeFiles(const QStringList &fileList, bool deleteLocal); + bool revertFiles(const QStringList &fileList); + bool renameFile(const QString &beforePath, const QString &afterPath, bool renameLocal); - // Files - bool listFiles(QStringList &files); - bool diffFile(const QString &repoFile, bool graphical); - bool commitFiles(const QStringList &fileList, const QString &comment, const QString& newBranchName, bool isPrivateBranch); - bool addFiles(const QStringList& fileList); - bool removeFiles(const QStringList& fileList, bool deleteLocal); - bool revertFiles(const QStringList& fileList); - bool renameFile(const QString& beforePath, const QString& afterPath, bool renameLocal); + // Settings + bool getSettings(QStringList &result); + bool setSetting(const QString &name, const QString &value, bool global); - // Settings - bool getSettings(QStringList& result); - bool setSetting(const QString &name, const QString &value, bool global); + // Remotes + bool setRemoteUrl(const QUrl &url); + bool getRemoteUrl(QUrl &url); - // Remotes - bool setRemoteUrl(const QUrl& url); - bool getRemoteUrl(QUrl &url); + // Stashes + bool stashNew(const QStringList &fileList, const QString &name, bool revert); + bool stashList(stashmap_t &stashes); + bool stashApply(const QString &name); + bool stashDrop(const QString &name); + bool stashDiff(const QString &name); - // Stashes - bool stashNew(const QStringList& fileList, const QString& name, bool revert); - bool stashList(stashmap_t &stashes); - bool stashApply(const QString& name); - bool stashDrop(const QString& name); - bool stashDiff(const QString& name); + // Tags + bool tagList(QStringMap &tags); + bool tagNew(const QString &name, const QString &revision); + bool tagDelete(const QString &name, const QString &revision); - // Tags - bool tagList(QStringMap& tags); - bool tagNew(const QString& name, const QString& revision); - bool tagDelete(const QString& name, const QString& revision); + // Branches + bool branchList(QStringList &branches, QStringList &activeBranches); + bool branchNew(const QString &name, const QString &revisionBasis, bool isPrivate = false); + bool branchMerge(QStringList &res, const QString &revision, bool integrate, bool force, bool testOnly); - // Branches - bool branchList(QStringList& branches, QStringList& activeBranches); - bool branchNew(const QString& name, const QString& revisionBasis, bool isPrivate=false); - bool branchMerge(QStringList& res, const QString& revision, bool integrate, bool force, bool testOnly); + const QString &getCurrentRevision() const { return currentRevision; } + const QStringList &getActiveTags() const { return activeTags; } - const QString &getCurrentRevision() const { return currentRevision; } - const QStringList &getActiveTags() const { return activeTags; } + // UI + bool uiRunning() const; + bool startUI(const QString &httpPort); + void stopUI(); + const QString &getUIHttpPort() const { return fossilUIPort; } + QString getUIHttpAddress() const; - // UI - bool uiRunning() const; - bool startUI(const QString &httpPort); - void stopUI(); - const QString &getUIHttpPort() const { return fossilUIPort; } - QString getUIHttpAddress() const; - - // Fossil executable - void setExePath(const QString &path) { fossilPath = path; } - bool getExeVersion(QString &version); + // Fossil executable + void setExePath(const QString &path) { fossilPath = path; } + bool getExeVersion(QString &version); private: - enum RunFlags - { - RUNFLAGS_NONE = 0<<0, - RUNFLAGS_SILENT_INPUT = 1<<0, - RUNFLAGS_SILENT_OUTPUT = 1<<1, - RUNFLAGS_SILENT_ALL = RUNFLAGS_SILENT_INPUT | RUNFLAGS_SILENT_OUTPUT, - RUNFLAGS_DETACHED = 1<<2, - RUNFLAGS_DEBUG = 1<<3, - }; + enum RunFlags + { + RUNFLAGS_NONE = 0 << 0, + RUNFLAGS_SILENT_INPUT = 1 << 0, + RUNFLAGS_SILENT_OUTPUT = 1 << 1, + RUNFLAGS_SILENT_ALL = RUNFLAGS_SILENT_INPUT | RUNFLAGS_SILENT_OUTPUT, + RUNFLAGS_DETACHED = 1 << 2, + RUNFLAGS_DEBUG = 1 << 3, + }; - void setRepositoryFile(const QString &filename) { repositoryFile = filename; } - bool runFossil(const QStringList &args, QStringList *output=0, int runFlags=RUNFLAGS_NONE); - bool runFossilRaw(const QStringList &args, QStringList *output, int *exitCode, int runFlags); - QString getFossilPath(); + void setRepositoryFile(const QString &filename) { repositoryFile = filename; } + bool runFossil(const QStringList &args, QStringList *output = 0, int runFlags = RUNFLAGS_NONE); + bool runFossilRaw(const QStringList &args, QStringList *output, int *exitCode, int runFlags); + QString getFossilPath(); - void log(const QString &text, bool isHTML=false) - { - if(uiCallback) - uiCallback->logText(text, isHTML); - } + void log(const QString &text, bool isHTML = false) + { + if (uiCallback) + uiCallback->logText(text, isHTML); + } - UICallback *uiCallback; - QString workspacePath; - QString fossilPath; // The value from the settings - QString repositoryFile; - QString projectName; - QString currentRevision; - QStringList activeTags; - LoggedProcess fossilUI; - QString fossilUIPort; + UICallback *uiCallback; + QString workspacePath; + QString fossilPath; // The value from the settings + QString repositoryFile; + QString projectName; + QString currentRevision; + QStringList activeTags; + LoggedProcess fossilUI; + QString fossilUIPort; }; - -#endif // FOSSIL_H +#endif // FOSSIL_H diff --git a/src/FslSettingsDialog.cpp b/src/FslSettingsDialog.cpp index 021dc6d..08034a6 100644 --- a/src/FslSettingsDialog.cpp +++ b/src/FslSettingsDialog.cpp @@ -1,70 +1,66 @@ #include "FslSettingsDialog.h" -#include "ui_FslSettingsDialog.h" #include "Utils.h" +#include "ui_FslSettingsDialog.h" #include /////////////////////////////////////////////////////////////////////////////// -FslSettingsDialog::FslSettingsDialog(QWidget *parent, Settings &_settings) : - QDialog(parent, Qt::Sheet), - ui(new Ui::FslSettingsDialog), - settings(&_settings) +FslSettingsDialog::FslSettingsDialog(QWidget *parent, Settings &_settings) : QDialog(parent, Qt::Sheet), ui(new Ui::FslSettingsDialog), settings(&_settings) { - ui->setupUi(this); + ui->setupUi(this); - ui->lineUIPort->setText(settings->GetFossilValue(FOSSIL_SETTING_HTTP_PORT).toString()); + ui->lineUIPort->setText(settings->GetFossilValue(FOSSIL_SETTING_HTTP_PORT).toString()); - // Global Settings - ui->lineGDiffCommand->setText(settings->GetFossilValue(FOSSIL_SETTING_GDIFF_CMD).toString()); - ui->lineGMergeCommand->setText(settings->GetFossilValue(FOSSIL_SETTING_GMERGE_CMD).toString()); - ui->lineProxy->setText(settings->GetFossilValue(FOSSIL_SETTING_PROXY_URL).toString()); + // Global Settings + ui->lineGDiffCommand->setText(settings->GetFossilValue(FOSSIL_SETTING_GDIFF_CMD).toString()); + ui->lineGMergeCommand->setText(settings->GetFossilValue(FOSSIL_SETTING_GMERGE_CMD).toString()); + ui->lineProxy->setText(settings->GetFossilValue(FOSSIL_SETTING_PROXY_URL).toString()); - // Repository Settings - ui->lineIgnore->setText(settings->GetFossilValue(FOSSIL_SETTING_IGNORE_GLOB).toString()); - ui->lineIgnoreCRNL->setText(settings->GetFossilValue(FOSSIL_SETTING_CRNL_GLOB).toString()); + // Repository Settings + ui->lineIgnore->setText(settings->GetFossilValue(FOSSIL_SETTING_IGNORE_GLOB).toString()); + ui->lineIgnoreCRNL->setText(settings->GetFossilValue(FOSSIL_SETTING_CRNL_GLOB).toString()); } //----------------------------------------------------------------------------- FslSettingsDialog::~FslSettingsDialog() { - delete ui; + delete ui; } //----------------------------------------------------------------------------- bool FslSettingsDialog::run(QWidget *parent, Settings &settings) { - FslSettingsDialog dlg(parent, settings); - return dlg.exec() == QDialog::Accepted; + FslSettingsDialog dlg(parent, settings); + return dlg.exec() == QDialog::Accepted; } //----------------------------------------------------------------------------- void FslSettingsDialog::on_buttonBox_accepted() { - settings->SetFossilValue(FOSSIL_SETTING_HTTP_PORT, ui->lineUIPort->text()); + settings->SetFossilValue(FOSSIL_SETTING_HTTP_PORT, ui->lineUIPort->text()); - settings->SetFossilValue(FOSSIL_SETTING_GDIFF_CMD, ui->lineGDiffCommand->text()); - settings->SetFossilValue(FOSSIL_SETTING_GMERGE_CMD, ui->lineGMergeCommand->text()); - settings->SetFossilValue(FOSSIL_SETTING_PROXY_URL, ui->lineProxy->text()); + settings->SetFossilValue(FOSSIL_SETTING_GDIFF_CMD, ui->lineGDiffCommand->text()); + settings->SetFossilValue(FOSSIL_SETTING_GMERGE_CMD, ui->lineGMergeCommand->text()); + settings->SetFossilValue(FOSSIL_SETTING_PROXY_URL, ui->lineProxy->text()); - settings->SetFossilValue(FOSSIL_SETTING_IGNORE_GLOB, ui->lineIgnore->text()); - settings->SetFossilValue(FOSSIL_SETTING_CRNL_GLOB, ui->lineIgnoreCRNL->text()); + settings->SetFossilValue(FOSSIL_SETTING_IGNORE_GLOB, ui->lineIgnore->text()); + settings->SetFossilValue(FOSSIL_SETTING_CRNL_GLOB, ui->lineIgnoreCRNL->text()); - settings->ApplyEnvironment(); + settings->ApplyEnvironment(); } //----------------------------------------------------------------------------- void FslSettingsDialog::on_btnSelectFossilGDiff_clicked() { - QString path = SelectExe(this, tr("Select Graphical Diff application")); - if(!path.isEmpty()) - ui->lineGDiffCommand->setText(QDir::toNativeSeparators(path)); + QString path = SelectExe(this, tr("Select Graphical Diff application")); + if (!path.isEmpty()) + ui->lineGDiffCommand->setText(QDir::toNativeSeparators(path)); } //----------------------------------------------------------------------------- void FslSettingsDialog::on_btnSelectGMerge_clicked() { - QString path = SelectExe(this, tr("Select Graphical Merge application")); - if(!path.isEmpty()) - ui->lineGMergeCommand->setText(path); + QString path = SelectExe(this, tr("Select Graphical Merge application")); + if (!path.isEmpty()) + ui->lineGMergeCommand->setText(path); } - diff --git a/src/FslSettingsDialog.h b/src/FslSettingsDialog.h index f61c35d..fbc10d8 100644 --- a/src/FslSettingsDialog.h +++ b/src/FslSettingsDialog.h @@ -1,33 +1,32 @@ #ifndef FSLSETTINGSDIALOG_H #define FSLSETTINGSDIALOG_H -#include #include "AppSettings.h" +#include -namespace Ui { - class FslSettingsDialog; +namespace Ui +{ +class FslSettingsDialog; } class FslSettingsDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit FslSettingsDialog(QWidget *parent, Settings &_settings); - ~FslSettingsDialog(); - - static bool run(QWidget *parent, Settings &_settings); + explicit FslSettingsDialog(QWidget *parent, Settings &_settings); + ~FslSettingsDialog(); + static bool run(QWidget *parent, Settings &_settings); private slots: - void on_buttonBox_accepted(); - void on_btnSelectFossilGDiff_clicked(); - void on_btnSelectGMerge_clicked(); + void on_buttonBox_accepted(); + void on_btnSelectFossilGDiff_clicked(); + void on_btnSelectGMerge_clicked(); private: - - Ui::FslSettingsDialog *ui; - Settings *settings; + Ui::FslSettingsDialog *ui; + Settings *settings; }; -#endif // FSLSETTINGSDIALOG_H +#endif // FSLSETTINGSDIALOG_H diff --git a/src/LoggedProcess.cpp b/src/LoggedProcess.cpp index 73b1376..8f46056 100644 --- a/src/LoggedProcess.cpp +++ b/src/LoggedProcess.cpp @@ -3,20 +3,19 @@ /////////////////////////////////////////////////////////////////////////////// LoggedProcess::LoggedProcess(QObject *parent) : QProcess(parent) { - setProcessChannelMode(QProcess::MergedChannels); - connect(this, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadyReadStandardOutput())); + setProcessChannelMode(QProcess::MergedChannels); + connect(this, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadyReadStandardOutput())); } void LoggedProcess::getLogAndClear(QByteArray &buffer) { - QMutexLocker lck(&mutex); - buffer = log; - log.clear(); + QMutexLocker lck(&mutex); + buffer = log; + log.clear(); } void LoggedProcess::onReadyReadStandardOutput() { - QMutexLocker lck(&mutex); - log.append(readAllStandardOutput()); + QMutexLocker lck(&mutex); + log.append(readAllStandardOutput()); } - diff --git a/src/LoggedProcess.h b/src/LoggedProcess.h index 225bfc8..f409d1a 100644 --- a/src/LoggedProcess.h +++ b/src/LoggedProcess.h @@ -1,24 +1,24 @@ #ifndef LOGGEDPROCESS_H #define LOGGEDPROCESS_H -#include #include +#include class LoggedProcess : public QProcess { - Q_OBJECT + Q_OBJECT public: - explicit LoggedProcess(QObject *parent = 0); - void getLogAndClear(QByteArray &buffer); - bool isLogEmpty() const { return log.isEmpty(); } - qint64 logBytesAvailable() const { return log.size(); } + explicit LoggedProcess(QObject *parent = 0); + void getLogAndClear(QByteArray &buffer); + bool isLogEmpty() const { return log.isEmpty(); } + qint64 logBytesAvailable() const { return log.size(); } private slots: - void onReadyReadStandardOutput(); + void onReadyReadStandardOutput(); private: - QMutex mutex; - QByteArray log; + QMutex mutex; + QByteArray log; }; -#endif // LOGGEDPROCESS_H +#endif // LOGGEDPROCESS_H diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index e53d61a..f94e0a5 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -1,4 +1,14 @@ #include "MainWindow.h" +#include "AboutDialog.h" +#include "CloneDialog.h" +#include "CommitDialog.h" +#include "FileActionDialog.h" +#include "FslSettingsDialog.h" +#include "RemoteDialog.h" +#include "RevisionDialog.h" +#include "SearchBox.h" +#include "SettingsDialog.h" +#include "Utils.h" #include "ui_MainWindow.h" #include #include @@ -7,374 +17,341 @@ #include #include #include +#include #include #include -#include -#include #include #include -#include "SettingsDialog.h" -#include "FslSettingsDialog.h" -#include "SearchBox.h" -#include "CommitDialog.h" -#include "FileActionDialog.h" -#include "CloneDialog.h" -#include "RevisionDialog.h" -#include "RemoteDialog.h" -#include "AboutDialog.h" -#include "Utils.h" +#include //----------------------------------------------------------------------------- enum { - COLUMN_STATUS, - COLUMN_FILENAME, - COLUMN_EXTENSION, - COLUMN_MODIFIED, - COLUMN_PATH + COLUMN_STATUS, + COLUMN_FILENAME, + COLUMN_EXTENSION, + COLUMN_MODIFIED, + COLUMN_PATH }; enum { - TAB_LOG, - TAB_BROWSER + TAB_LOG, + TAB_BROWSER }; enum { - ROLE_WORKSPACE_ITEM = Qt::UserRole+1 + ROLE_WORKSPACE_ITEM = Qt::UserRole + 1 }; struct WorkspaceItem { - enum - { - TYPE_UNKNOWN, - TYPE_WORKSPACE, - TYPE_FOLDER, - TYPE_STASHES, - TYPE_STASH, - TYPE_BRANCHES, - TYPE_BRANCH, - TYPE_TAGS, - TYPE_TAG, - TYPE_REMOTES, - TYPE_REMOTE, - }; + enum + { + TYPE_UNKNOWN, + TYPE_WORKSPACE, + TYPE_FOLDER, + TYPE_STASHES, + TYPE_STASH, + TYPE_BRANCHES, + TYPE_BRANCH, + TYPE_TAGS, + TYPE_TAG, + TYPE_REMOTES, + TYPE_REMOTE, + }; - enum - { - STATE_DEFAULT, - STATE_UNCHANGED, - STATE_MODIFIED, - STATE_UNKNOWN - }; + enum + { + STATE_DEFAULT, + STATE_UNCHANGED, + STATE_MODIFIED, + STATE_UNKNOWN + }; + WorkspaceItem() : Type(TYPE_UNKNOWN), State(STATE_DEFAULT) {} - WorkspaceItem() - : Type(TYPE_UNKNOWN) - , State(STATE_DEFAULT) - { - } + WorkspaceItem(int type, const QString &value, int state = STATE_DEFAULT) : Type(type), State(state), Value(value) {} - WorkspaceItem(int type, const QString &value, int state=STATE_DEFAULT) - : Type(type), State(state), Value(value) - { - } + WorkspaceItem(const WorkspaceItem &other) + { + Type = other.Type; + State = other.State; + Value = other.Value; + } - WorkspaceItem(const WorkspaceItem &other) - { - Type = other.Type; - State = other.State; - Value = other.Value; - } + int Type; + int State; + QString Value; - int Type; - int State; - QString Value; - - - operator QVariant() const - { - return QVariant::fromValue(*this); - } + operator QVariant() const { return QVariant::fromValue(*this); } }; Q_DECLARE_METATYPE(WorkspaceItem) /////////////////////////////////////////////////////////////////////////////// -MainWindow::MainWindow(Settings &_settings, QWidget *parent, QString *workspacePath) : - QMainWindow(parent), - ui(new Ui::MainWindow), - settings(_settings) +MainWindow::MainWindow(Settings &_settings, QWidget *parent, QString *workspacePath) : QMainWindow(parent), ui(new Ui::MainWindow), settings(_settings) { - ui->setupUi(this); + ui->setupUi(this); - QAction *separator = new QAction(this); - separator->setSeparator(true); + QAction *separator = new QAction(this); + separator->setSeparator(true); - fileActionSeparator = new QAction(this); - fileActionSeparator->setSeparator(true); + fileActionSeparator = new QAction(this); + fileActionSeparator->setSeparator(true); - workspaceActionSeparator = new QAction(this); - workspaceActionSeparator->setSeparator(true); + workspaceActionSeparator = new QAction(this); + workspaceActionSeparator->setSeparator(true); - // fileTableView - ui->fileTableView->setModel(&getWorkspace().getFileModel()); + // fileTableView + ui->fileTableView->setModel(&getWorkspace().getFileModel()); - ui->fileTableView->addAction(ui->actionDiff); - ui->fileTableView->addAction(ui->actionHistory); - ui->fileTableView->addAction(ui->actionOpenFile); - ui->fileTableView->addAction(ui->actionOpenContaining); - ui->fileTableView->addAction(separator); - ui->fileTableView->addAction(ui->actionAdd); - ui->fileTableView->addAction(ui->actionRevert); - ui->fileTableView->addAction(ui->actionRename); - ui->fileTableView->addAction(ui->actionDelete); + ui->fileTableView->addAction(ui->actionDiff); + ui->fileTableView->addAction(ui->actionHistory); + ui->fileTableView->addAction(ui->actionOpenFile); + ui->fileTableView->addAction(ui->actionOpenContaining); + ui->fileTableView->addAction(separator); + ui->fileTableView->addAction(ui->actionAdd); + ui->fileTableView->addAction(ui->actionRevert); + ui->fileTableView->addAction(ui->actionRename); + ui->fileTableView->addAction(ui->actionDelete); - connect( ui->fileTableView, - SIGNAL( dragOutEvent() ), - SLOT( onFileViewDragOut() ), - Qt::DirectConnection ); + connect(ui->fileTableView, SIGNAL(dragOutEvent()), SLOT(onFileViewDragOut()), Qt::DirectConnection); - QStringList header; - header << tr("Status") << tr("File") << tr("Extension") << tr("Modified") << tr("Path"); - getWorkspace().getFileModel().setHorizontalHeaderLabels(header); - getWorkspace().getFileModel().horizontalHeaderItem(COLUMN_STATUS)->setTextAlignment(Qt::AlignCenter); + QStringList header; + header << tr("Status") << tr("File") << tr("Extension") << tr("Modified") << tr("Path"); + getWorkspace().getFileModel().setHorizontalHeaderLabels(header); + getWorkspace().getFileModel().horizontalHeaderItem(COLUMN_STATUS)->setTextAlignment(Qt::AlignCenter); - // Needed on OSX as the preset value from the GUI editor is not always reflected - ui->fileTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); + // Needed on OSX as the preset value from the GUI editor is not always reflected + ui->fileTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) - ui->fileTableView->horizontalHeader()->setMovable(true); + ui->fileTableView->horizontalHeader()->setMovable(true); #else - ui->fileTableView->horizontalHeader()->setSectionsMovable(true); + ui->fileTableView->horizontalHeader()->setSectionsMovable(true); #endif - ui->fileTableView->horizontalHeader()->setStretchLastSection(true); + ui->fileTableView->horizontalHeader()->setStretchLastSection(true); - // workspaceTreeView - ui->workspaceTreeView->setModel(&getWorkspace().getTreeModel()); + // workspaceTreeView + ui->workspaceTreeView->setModel(&getWorkspace().getTreeModel()); - header.clear(); - header << tr("Workspace"); - getWorkspace().getTreeModel().setHorizontalHeaderLabels(header); + header.clear(); + header << tr("Workspace"); + getWorkspace().getTreeModel().setHorizontalHeaderLabels(header); - connect( ui->workspaceTreeView->selectionModel(), - SIGNAL( selectionChanged(const QItemSelection &, const QItemSelection &) ), - SLOT( onWorkspaceTreeViewSelectionChanged(const QItemSelection &, const QItemSelection &) ), - Qt::DirectConnection ); + connect(ui->workspaceTreeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), + SLOT(onWorkspaceTreeViewSelectionChanged(const QItemSelection &, const QItemSelection &)), Qt::DirectConnection); - // Workspace Menus - menuWorkspace = new QMenu(this); - menuWorkspace->addAction(ui->actionCommit); - menuWorkspace->addAction(ui->actionOpenFolder); - menuWorkspace->addAction(ui->actionAdd); - menuWorkspace->addAction(ui->actionRevert); - menuWorkspace->addAction(ui->actionDelete); - menuWorkspace->addAction(separator); - menuWorkspace->addAction(ui->actionRenameFolder); - menuWorkspace->addAction(ui->actionOpenFolder); + // Workspace Menus + menuWorkspace = new QMenu(this); + menuWorkspace->addAction(ui->actionCommit); + menuWorkspace->addAction(ui->actionOpenFolder); + menuWorkspace->addAction(ui->actionAdd); + menuWorkspace->addAction(ui->actionRevert); + menuWorkspace->addAction(ui->actionDelete); + menuWorkspace->addAction(separator); + menuWorkspace->addAction(ui->actionRenameFolder); + menuWorkspace->addAction(ui->actionOpenFolder); - // StashMenu - menuStashes = new QMenu(this); - menuStashes->addAction(ui->actionCreateStash); - menuStashes->addAction(separator); - menuStashes->addAction(ui->actionApplyStash); - menuStashes->addAction(ui->actionDiffStash); - menuStashes->addAction(ui->actionDeleteStash); + // StashMenu + menuStashes = new QMenu(this); + menuStashes->addAction(ui->actionCreateStash); + menuStashes->addAction(separator); + menuStashes->addAction(ui->actionApplyStash); + menuStashes->addAction(ui->actionDiffStash); + menuStashes->addAction(ui->actionDeleteStash); - // TagsMenu - menuTags = new QMenu(this); - menuTags->addAction(ui->actionCreateTag); - menuTags->addAction(separator); - menuTags->addAction(ui->actionDeleteTag); - menuTags->addAction(ui->actionUpdate); + // TagsMenu + menuTags = new QMenu(this); + menuTags->addAction(ui->actionCreateTag); + menuTags->addAction(separator); + menuTags->addAction(ui->actionDeleteTag); + menuTags->addAction(ui->actionUpdate); - // BranchesMenu - menuBranches = new QMenu(this); - menuBranches->addAction(ui->actionCreateBranch); - menuBranches->addAction(separator); - menuBranches->addAction(ui->actionMergeBranch); - menuBranches->addAction(ui->actionUpdate); + // BranchesMenu + menuBranches = new QMenu(this); + menuBranches->addAction(ui->actionCreateBranch); + menuBranches->addAction(separator); + menuBranches->addAction(ui->actionMergeBranch); + menuBranches->addAction(ui->actionUpdate); - // RemotesMenu - menuRemotes = new QMenu(this); - menuRemotes->addAction(ui->actionPushRemote); - menuRemotes->addAction(ui->actionPullRemote); - menuRemotes->addAction(separator); - menuRemotes->addAction(ui->actionAddRemote); - menuRemotes->addAction(ui->actionDeleteRemote); - menuRemotes->addAction(ui->actionEditRemote); - menuRemotes->addAction(ui->actionSetDefaultRemote); + // RemotesMenu + menuRemotes = new QMenu(this); + menuRemotes->addAction(ui->actionPushRemote); + menuRemotes->addAction(ui->actionPullRemote); + menuRemotes->addAction(separator); + menuRemotes->addAction(ui->actionAddRemote); + menuRemotes->addAction(ui->actionDeleteRemote); + menuRemotes->addAction(ui->actionEditRemote); + menuRemotes->addAction(ui->actionSetDefaultRemote); - // Recent Workspaces - // Locate a sequence of two separator actions in file menu - QList file_actions = ui->menuFile->actions(); - QAction *recent_sep=0; - for(int i=0; iisSeparator() && i>0 && file_actions[i-1]->isSeparator()) - { - recent_sep = act; - break; - } - } - Q_ASSERT(recent_sep); - for(int i = 0; i < MAX_RECENT; ++i) - { - recentWorkspaceActs[i] = new QAction(this); - recentWorkspaceActs[i]->setVisible(false); - connect(recentWorkspaceActs[i], SIGNAL(triggered()), this, SLOT(onOpenRecent())); - ui->menuFile->insertAction(recent_sep, recentWorkspaceActs[i]); - } + // Recent Workspaces + // Locate a sequence of two separator actions in file menu + QList file_actions = ui->menuFile->actions(); + QAction *recent_sep = 0; + for (int i = 0; i < file_actions.size(); ++i) + { + QAction *act = file_actions[i]; + if (act->isSeparator() && i > 0 && file_actions[i - 1]->isSeparator()) + { + recent_sep = act; + break; + } + } + Q_ASSERT(recent_sep); + for (int i = 0; i < MAX_RECENT; ++i) + { + recentWorkspaceActs[i] = new QAction(this); + recentWorkspaceActs[i]->setVisible(false); + connect(recentWorkspaceActs[i], SIGNAL(triggered()), this, SLOT(onOpenRecent())); + ui->menuFile->insertAction(recent_sep, recentWorkspaceActs[i]); + } - // Custom Actions - for(int i = 0; i < settings.GetCustomActions().size(); ++i) - { - customActions[i] = new QAction(this); - customActions[i]->setVisible(false); - connect(customActions[i], SIGNAL(triggered()), this, SLOT(onCustomActionTriggered())); - customActions[i]->setData(i); - customActions[i]->setShortcut(QKeySequence(QString("Ctrl+%0").arg(i+1))); - } + // Custom Actions + for (int i = 0; i < settings.GetCustomActions().size(); ++i) + { + customActions[i] = new QAction(this); + customActions[i]->setVisible(false); + connect(customActions[i], SIGNAL(triggered()), this, SLOT(onCustomActionTriggered())); + customActions[i]->setData(i); + customActions[i]->setShortcut(QKeySequence(QString("Ctrl+%0").arg(i + 1))); + } - // TabWidget - ui->tabWidget->setCurrentIndex(TAB_LOG); + // TabWidget + ui->tabWidget->setCurrentIndex(TAB_LOG); - // Tags Label - lblTags = new QLabel(); - ui->statusBar->insertPermanentWidget(0, lblTags); - lblTags->setVisible(true); + // Tags Label + lblTags = new QLabel(); + ui->statusBar->insertPermanentWidget(0, lblTags); + lblTags->setVisible(true); - // Create Progress Bar - progressBar = new QProgressBar(); - progressBar->setMinimum(0); - progressBar->setMaximum(0); - progressBar->setMaximumSize(170, 16); - progressBar->setAlignment(Qt::AlignCenter); - progressBar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); - ui->statusBar->insertPermanentWidget(1, progressBar); - progressBar->setVisible(false); + // Create Progress Bar + progressBar = new QProgressBar(); + progressBar->setMinimum(0); + progressBar->setMaximum(0); + progressBar->setMaximumSize(170, 16); + progressBar->setAlignment(Qt::AlignCenter); + progressBar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); + ui->statusBar->insertPermanentWidget(1, progressBar); + progressBar->setVisible(false); - // Create Abort Button - abortButton = new QToolButton(ui->statusBar); - abortButton->setAutoRaise(true); - abortButton->setIcon(getCachedIcon(":/icons/icon-action-stop")); - abortButton->setVisible(false); - abortButton->setArrowType(Qt::NoArrow); - abortButton->setToolButtonStyle(Qt::ToolButtonIconOnly); - abortButton->setDefaultAction(ui->actionAbortOperation); - ui->statusBar->insertPermanentWidget(2, abortButton); - ui->actionAbortOperation->setEnabled(false); + // Create Abort Button + abortButton = new QToolButton(ui->statusBar); + abortButton->setAutoRaise(true); + abortButton->setIcon(getCachedIcon(":/icons/icon-action-stop")); + abortButton->setVisible(false); + abortButton->setArrowType(Qt::NoArrow); + abortButton->setToolButtonStyle(Qt::ToolButtonIconOnly); + abortButton->setDefaultAction(ui->actionAbortOperation); + ui->statusBar->insertPermanentWidget(2, abortButton); + ui->actionAbortOperation->setEnabled(false); #ifdef Q_OS_MACX - // Native applications on OSX don't have menu icons - foreach(QAction *a, ui->menuBar->actions()) - a->setIconVisibleInMenu(false); - foreach(QAction *a, ui->menuFile->actions()) - a->setIconVisibleInMenu(false); + // Native applications on OSX don't have menu icons + foreach (QAction *a, ui->menuBar->actions()) + a->setIconVisibleInMenu(false); + foreach (QAction *a, ui->menuFile->actions()) + a->setIconVisibleInMenu(false); - // For some unknown reason on OSX the treeview gets a focus rect. So disable it - ui->workspaceTreeView->setAttribute(Qt::WA_MacShowFocusRect, false); + // For some unknown reason on OSX the treeview gets a focus rect. So disable it + ui->workspaceTreeView->setAttribute(Qt::WA_MacShowFocusRect, false); - // Tighen-up the sizing of the main widgets to look slightly more consistent with the OSX style - ui->centralWidget->layout()->setContentsMargins(0, 0, 0, 0); - ui->workspaceTreeView->setFrameShape(QFrame::NoFrame); - ui->fileTableView->setFrameShape(QFrame::NoFrame); - ui->splitterVertical->setHandleWidth(1); - ui->splitterHorizontal->setHandleWidth(1); + // Tighen-up the sizing of the main widgets to look slightly more consistent with the OSX style + ui->centralWidget->layout()->setContentsMargins(0, 0, 0, 0); + ui->workspaceTreeView->setFrameShape(QFrame::NoFrame); + ui->fileTableView->setFrameShape(QFrame::NoFrame); + ui->splitterVertical->setHandleWidth(1); + ui->splitterHorizontal->setHandleWidth(1); - // Wrong color scheme on Yosemite but better than the standard TabWidget - ui->tabWidget->setDocumentMode(true); + // Wrong color scheme on Yosemite but better than the standard TabWidget + ui->tabWidget->setDocumentMode(true); #endif - // Searchbox - // Add spacer to pad to right - QWidget* spacer = new QWidget(); - spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - ui->mainToolBar->addWidget(spacer); + // Searchbox + // Add spacer to pad to right + QWidget *spacer = new QWidget(); + spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + ui->mainToolBar->addWidget(spacer); - // Search shortcut - searchShortcut = new QShortcut(QKeySequence(QKeySequence::Find), this); - searchShortcut->setContext(Qt::ApplicationShortcut); - searchShortcut->setEnabled(true); - connect(searchShortcut, SIGNAL(activated()), this, SLOT(onSearch())); + // Search shortcut + searchShortcut = new QShortcut(QKeySequence(QKeySequence::Find), this); + searchShortcut->setContext(Qt::ApplicationShortcut); + searchShortcut->setEnabled(true); + connect(searchShortcut, SIGNAL(activated()), this, SLOT(onSearch())); - // Create SearchBox - searchBox = new SearchBox(this); - searchBox->setPlaceholderText(tr("Filter (%0)").arg(searchShortcut->key().toString(QKeySequence::NativeText))); - searchBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - searchBox->setMinimumWidth(230); - ui->mainToolBar->addWidget(searchBox); + // Create SearchBox + searchBox = new SearchBox(this); + searchBox->setPlaceholderText(tr("Filter (%0)").arg(searchShortcut->key().toString(QKeySequence::NativeText))); + searchBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + searchBox->setMinimumWidth(230); + ui->mainToolBar->addWidget(searchBox); - connect( searchBox, - SIGNAL( textChanged(const QString&)), - SLOT( onSearchBoxTextChanged(const QString&)), - Qt::DirectConnection ); + connect(searchBox, SIGNAL(textChanged(const QString &)), SLOT(onSearchBoxTextChanged(const QString &)), Qt::DirectConnection); - // Add another spacer to the right - spacer = new QWidget(); - spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); - spacer->setMinimumWidth(3); - ui->mainToolBar->addWidget(spacer); + // Add another spacer to the right + spacer = new QWidget(); + spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); + spacer->setMinimumWidth(3); + ui->mainToolBar->addWidget(spacer); - viewMode = VIEWMODE_TREE; + viewMode = VIEWMODE_TREE; - uiCallback.init(this); + uiCallback.init(this); - // Need to be before applySettings which sets the last workspace - getWorkspace().Init(&uiCallback, settings.GetValue(FUEL_SETTING_FOSSIL_PATH).toString()); + // Need to be before applySettings which sets the last workspace + getWorkspace().Init(&uiCallback, settings.GetValue(FUEL_SETTING_FOSSIL_PATH).toString()); - applySettings(); + applySettings(); - // Apply any explicit workspace path if available - if(workspacePath && !workspacePath->isEmpty()) - openWorkspace(*workspacePath); + // Apply any explicit workspace path if available + if (workspacePath && !workspacePath->isEmpty()) + openWorkspace(*workspacePath); - operationAborted = false; + operationAborted = false; - rebuildRecent(); + rebuildRecent(); } //------------------------------------------------------------------------------ MainWindow::~MainWindow() { - stopUI(); - getWorkspace().storeWorkspace(*settings.GetStore()); - updateSettings(); + stopUI(); + getWorkspace().storeWorkspace(*settings.GetStore()); + updateSettings(); - delete ui; + delete ui; } //----------------------------------------------------------------------------- void MainWindow::setCurrentWorkspace(const QString &workspace) { - if(!getWorkspace().switchWorkspace(workspace, *settings.GetStore())) - QMessageBox::critical(this, tr("Error"), tr("Could not change current directory to '%0'").arg(workspace), QMessageBox::Ok ); - else - addWorkspaceHistory(getWorkspace().getPath()); + if (!getWorkspace().switchWorkspace(workspace, *settings.GetStore())) + QMessageBox::critical(this, tr("Error"), tr("Could not change current directory to '%0'").arg(workspace), QMessageBox::Ok); + else + addWorkspaceHistory(getWorkspace().getPath()); } //------------------------------------------------------------------------------ void MainWindow::addWorkspaceHistory(const QString &dir) { - if(dir.isEmpty()) - return; + if (dir.isEmpty()) + return; - QDir d(dir); - QString new_workspace = d.absolutePath(); + QDir d(dir); + QString new_workspace = d.absolutePath(); - // Do not add the workspace if it exists already - if(workspaceHistory.indexOf(new_workspace)!=-1) - return; + // Do not add the workspace if it exists already + if (workspaceHistory.indexOf(new_workspace) != -1) + return; - workspaceHistory.append(new_workspace); - rebuildRecent(); + workspaceHistory.append(new_workspace); + rebuildRecent(); } //------------------------------------------------------------------------------ void MainWindow::on_actionRefresh_triggered() { - refresh(); + refresh(); } //------------------------------------------------------------------------------ @@ -382,2654 +359,2599 @@ void MainWindow::on_actionRefresh_triggered() // open the fossil file. bool MainWindow::openWorkspace(const QString &path) { - QFileInfo fi(path); - QString wkspace = path; + QFileInfo fi(path); + QString wkspace = path; - if(fi.isFile()) - { - wkspace = fi.absoluteDir().absolutePath(); - QString checkout_file1 = wkspace + PATH_SEPARATOR + FOSSIL_CHECKOUT1; - QString checkout_file2 = wkspace + PATH_SEPARATOR + FOSSIL_CHECKOUT2; + if (fi.isFile()) + { + wkspace = fi.absoluteDir().absolutePath(); + QString checkout_file1 = wkspace + PATH_SEPARATOR + FOSSIL_CHECKOUT1; + QString checkout_file2 = wkspace + PATH_SEPARATOR + FOSSIL_CHECKOUT2; - if(!(QFileInfo(checkout_file1).exists() || QFileInfo(checkout_file2).exists()) ) - { - if(QMessageBox::Yes !=DialogQuery(this, tr("Open Workspace"), tr("A workspace does not exist in this folder.\nWould you like to create one here?"))) - { - wkspace = QFileDialog::getExistingDirectory( - this, - tr("Select Workspace Folder"), - wkspace); + if (!(QFileInfo(checkout_file1).exists() || QFileInfo(checkout_file2).exists())) + { + if (QMessageBox::Yes != DialogQuery(this, tr("Open Workspace"), tr("A workspace does not exist in this folder.\nWould you like to create one here?"))) + { + wkspace = QFileDialog::getExistingDirectory(this, tr("Select Workspace Folder"), wkspace); - if(wkspace.isEmpty() || !QDir(wkspace).exists()) - return false; - } + if (wkspace.isEmpty() || !QDir(wkspace).exists()) + return false; + } - // Ok open the repository file - if(!getWorkspace().create(fi.absoluteFilePath(), wkspace)) - { - QMessageBox::critical(this, tr("Error"), tr("Could not open repository."), QMessageBox::Ok ); - return false; - } + // Ok open the repository file + if (!getWorkspace().create(fi.absoluteFilePath(), wkspace)) + { + QMessageBox::critical(this, tr("Error"), tr("Could not open repository."), QMessageBox::Ok); + return false; + } + } + else + { + if (!QDir(wkspace).exists()) + { + QMessageBox::critical(this, tr("Error"), tr("Could not open repository."), QMessageBox::Ok); + return false; + } + setCurrentWorkspace(wkspace); + } + } + else + { + if (!QDir(wkspace).exists()) + { + QMessageBox::critical(this, tr("Error"), tr("Could not open repository."), QMessageBox::Ok); + return false; + } + setCurrentWorkspace(wkspace); + } - } - else - { - if(!QDir(wkspace).exists()) - { - QMessageBox::critical(this, tr("Error"), tr("Could not open repository."), QMessageBox::Ok ); - return false; - } - setCurrentWorkspace(wkspace); - } - } - else - { - if(!QDir(wkspace).exists()) - { - QMessageBox::critical(this, tr("Error"), tr("Could not open repository."), QMessageBox::Ok ); - return false; - } - setCurrentWorkspace(wkspace); - } + on_actionClearLog_triggered(); + stopUI(); - on_actionClearLog_triggered(); - stopUI(); + // If this repository is not valid, remove it from the history + if (!refresh()) + { + setCurrentWorkspace(""); + workspaceHistory.removeAll(path); + rebuildRecent(); + return false; + } - // If this repository is not valid, remove it from the history - if(!refresh()) - { - setCurrentWorkspace(""); - workspaceHistory.removeAll(path); - rebuildRecent(); - return false; - } - - // Select the Root of the tree to update the file view - selectRootDir(); - searchBox->clear(); - return true; + // Select the Root of the tree to update the file view + selectRootDir(); + searchBox->clear(); + return true; } //------------------------------------------------------------------------------ void MainWindow::on_actionOpenRepository_triggered() { - QString filter(tr("Fossil Files") + QString(" (*." FOSSIL_EXT " " FOSSIL_CHECKOUT1 " " FOSSIL_CHECKOUT2 ")" )); + QString filter(tr("Fossil Files") + QString(" (*." FOSSIL_EXT " " FOSSIL_CHECKOUT1 " " FOSSIL_CHECKOUT2 ")")); - QString path = QFileDialog::getOpenFileName( - this, - tr("Open Fossil Repository"), - QDir::currentPath(), - filter, - &filter); + QString path = QFileDialog::getOpenFileName(this, tr("Open Fossil Repository"), QDir::currentPath(), filter, &filter); - if(path.isEmpty()) - return; + if (path.isEmpty()) + return; - openWorkspace(path); + openWorkspace(path); } //------------------------------------------------------------------------------ void MainWindow::on_actionNewRepository_triggered() { - QString filter(tr("Fossil Repositories") + QString(" (*." FOSSIL_EXT ")")); + QString filter(tr("Fossil Repositories") + QString(" (*." FOSSIL_EXT ")")); - // Get Repository file - QString repo_path = QFileDialog::getSaveFileName( - this, - tr("New Fossil Repository"), - QDir::currentPath(), - filter, - &filter); + // Get Repository file + QString repo_path = QFileDialog::getSaveFileName(this, tr("New Fossil Repository"), QDir::currentPath(), filter, &filter); - if(repo_path.isEmpty()) - return; + if (repo_path.isEmpty()) + return; - if(QFile::exists(repo_path)) - { - QMessageBox::critical(this, tr("Error"), tr("A repository file already exists.\nRepository creation aborted."), QMessageBox::Ok ); - return; - } + if (QFile::exists(repo_path)) + { + QMessageBox::critical(this, tr("Error"), tr("A repository file already exists.\nRepository creation aborted."), QMessageBox::Ok); + return; + } - QFileInfo repo_path_info(repo_path); - Q_ASSERT(repo_path_info.dir().exists()); + QFileInfo repo_path_info(repo_path); + Q_ASSERT(repo_path_info.dir().exists()); - // Get Workspace path - QString wkdir = repo_path_info.absoluteDir().absolutePath(); - if(QMessageBox::Yes != DialogQuery(this, tr("Create Workspace"), tr("Would you like to create a workspace in the same folder?"))) - { - wkdir = QFileDialog::getExistingDirectory( - this, - tr("Select Workspace Folder"), - wkdir); + // Get Workspace path + QString wkdir = repo_path_info.absoluteDir().absolutePath(); + if (QMessageBox::Yes != DialogQuery(this, tr("Create Workspace"), tr("Would you like to create a workspace in the same folder?"))) + { + wkdir = QFileDialog::getExistingDirectory(this, tr("Select Workspace Folder"), wkdir); - if(wkdir.isEmpty() || !QDir(wkdir).exists()) - return; - } + if (wkdir.isEmpty() || !QDir(wkdir).exists()) + return; + } - stopUI(); - on_actionClearLog_triggered(); + stopUI(); + on_actionClearLog_triggered(); - // Create repository - QString repo_abs_path = repo_path_info.absoluteFilePath(); + // Create repository + QString repo_abs_path = repo_path_info.absoluteFilePath(); - if(!getWorkspace().createRepository(repo_abs_path)) - { - QMessageBox::critical(this, tr("Error"), tr("Could not create repository."), QMessageBox::Ok ); - return; - } + if (!getWorkspace().createRepository(repo_abs_path)) + { + QMessageBox::critical(this, tr("Error"), tr("Could not create repository."), QMessageBox::Ok); + return; + } - if(!getWorkspace().create(repo_abs_path, wkdir)) - { - QMessageBox::critical(this, tr("Error"), tr("Could not open repository."), QMessageBox::Ok ); - return; - } + if (!getWorkspace().create(repo_abs_path, wkdir)) + { + QMessageBox::critical(this, tr("Error"), tr("Could not open repository."), QMessageBox::Ok); + return; + } - // Disable unknown file filter - if(!ui->actionViewUnknown->isChecked()) - ui->actionViewUnknown->setChecked(true); + // Disable unknown file filter + if (!ui->actionViewUnknown->isChecked()) + ui->actionViewUnknown->setChecked(true); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionCloseRepository_triggered() { - if(getWorkspace().getState()!=WORKSPACE_STATE_OK) - return; + if (getWorkspace().getState() != WORKSPACE_STATE_OK) + return; - if(QMessageBox::Yes !=DialogQuery(this, tr("Close Workspace"), tr("Are you sure you want to close this workspace?"))) - return; + if (QMessageBox::Yes != DialogQuery(this, tr("Close Workspace"), tr("Are you sure you want to close this workspace?"))) + return; - // Close Repo - bool success = getWorkspace().close(); + // Close Repo + bool success = getWorkspace().close(); - if(!success) - { - if(QMessageBox::Yes !=DialogQuery(this, tr("Close Workspace"), - tr("Could not close the workspace.\n" - "Perhaps there are uncommitted changes available\n" - "Would you like to force closing this workspace?"))) - { - refresh(); - return; - } + if (!success) + { + if (QMessageBox::Yes != DialogQuery(this, tr("Close Workspace"), + tr("Could not close the workspace.\n" + "Perhaps there are uncommitted changes available\n" + "Would you like to force closing this workspace?"))) + { + refresh(); + return; + } - success = getWorkspace().close(true); - } + success = getWorkspace().close(true); + } - if(!success) - { - QMessageBox::critical(this, tr("Error"), tr("Could not close the workspace."), QMessageBox::Ok); - refresh(); - return; - } + if (!success) + { + QMessageBox::critical(this, tr("Error"), tr("Could not close the workspace."), QMessageBox::Ok); + refresh(); + return; + } - stopUI(); - setCurrentWorkspace(""); - refresh(); + stopUI(); + setCurrentWorkspace(""); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionCloneRepository_triggered() { - QUrl url, url_proxy; - QString repository; + QUrl url, url_proxy; + QString repository; - if(!CloneDialog::run(this, url, repository, url_proxy)) - return; + if (!CloneDialog::run(this, url, repository, url_proxy)) + return; - stopUI(); + stopUI(); - if(!getWorkspace().cloneRepository(repository, url, url_proxy)) - { - QMessageBox::critical(this, tr("Error"), tr("Could not clone the repository"), QMessageBox::Ok); - return; - } + if (!getWorkspace().cloneRepository(repository, url, url_proxy)) + { + QMessageBox::critical(this, tr("Error"), tr("Could not clone the repository"), QMessageBox::Ok); + return; + } - if(!openWorkspace(repository)) - return; + if (!openWorkspace(repository)) + return; - // Store credentials - if(!url.isLocalFile()) - { - KeychainDelete(this, url, *settings.GetStore()); + // Store credentials + if (!url.isLocalFile()) + { + KeychainDelete(this, url, *settings.GetStore()); - if(!KeychainSet(this, url, *settings.GetStore())) - QMessageBox::critical(this, tr("Error"), tr("Could not store information to keychain."), QMessageBox::Ok ); - } + if (!KeychainSet(this, url, *settings.GetStore())) + QMessageBox::critical(this, tr("Error"), tr("Could not store information to keychain."), QMessageBox::Ok); + } - // Create Remote - url.setPassword(""); + // Create Remote + url.setPassword(""); - QString name = UrlToStringNoCredentials(url); - getWorkspace().addRemote(url, name); - getWorkspace().setRemoteDefault(url); - updateWorkspaceView(); + QString name = UrlToStringNoCredentials(url); + getWorkspace().addRemote(url, name); + getWorkspace().setRemoteDefault(url); + updateWorkspaceView(); } //------------------------------------------------------------------------------ void MainWindow::rebuildRecent() { - for(int i = 0; i < MAX_RECENT; ++i) - recentWorkspaceActs[i]->setVisible(false); + for (int i = 0; i < MAX_RECENT; ++i) + recentWorkspaceActs[i]->setVisible(false); - int enabled_acts = qMin(MAX_RECENT, workspaceHistory.size()); + int enabled_acts = qMin(MAX_RECENT, workspaceHistory.size()); - for(int i = 0; i < enabled_acts; ++i) - { - QString text = QString("&%1 %2").arg(i + 1).arg(QDir::toNativeSeparators(workspaceHistory[i])); + for (int i = 0; i < enabled_acts; ++i) + { + QString text = QString("&%1 %2").arg(i + 1).arg(QDir::toNativeSeparators(workspaceHistory[i])); - recentWorkspaceActs[i]->setText(text); - recentWorkspaceActs[i]->setData(workspaceHistory[i]); - recentWorkspaceActs[i]->setVisible(true); - } + recentWorkspaceActs[i]->setText(text); + recentWorkspaceActs[i]->setData(workspaceHistory[i]); + recentWorkspaceActs[i]->setVisible(true); + } } //------------------------------------------------------------------------------ void MainWindow::onOpenRecent() { - QAction *action = qobject_cast(sender()); - if(!action) - return; + QAction *action = qobject_cast(sender()); + if (!action) + return; - QString workspace = action->data().toString(); + QString workspace = action->data().toString(); - openWorkspace(workspace); + openWorkspace(workspace); } - //------------------------------------------------------------------------------ void MainWindow::enableActions(bool on) { - QAction *actions[] = { - ui->actionCloseRepository, - ui->actionCommit, - ui->actionDiff, - ui->actionAdd, - ui->actionDelete, - ui->actionPush, - ui->actionPull, - ui->actionRename, - ui->actionHistory, - ui->actionFossilUI, - ui->actionRevert, - ui->actionTimeline, - ui->actionOpenFile, - ui->actionOpenContaining, - ui->actionUndo, - ui->actionUpdate, - ui->actionOpenFolder, - ui->actionRenameFolder, - ui->actionCreateStash, - ui->actionDeleteStash, - ui->actionDiffStash, - ui->actionApplyStash, - ui->actionDeleteStash, - ui->actionCreateTag, - ui->actionDeleteTag, - ui->actionCreateBranch, - ui->actionMergeBranch, - ui->actionFossilSettings, - ui->actionViewAll, - ui->actionViewAsFolders, - ui->actionViewAsList, - ui->actionViewIgnored, - ui->actionViewModifedOnly, - ui->actionViewModified, - ui->actionViewUnchanged, - ui->actionViewUnknown - }; + QAction *actions[] = {ui->actionCloseRepository, ui->actionCommit, ui->actionDiff, ui->actionAdd, + ui->actionDelete, ui->actionPush, ui->actionPull, ui->actionRename, + ui->actionHistory, ui->actionFossilUI, ui->actionRevert, ui->actionTimeline, + ui->actionOpenFile, ui->actionOpenContaining, ui->actionUndo, ui->actionUpdate, + ui->actionOpenFolder, ui->actionRenameFolder, ui->actionCreateStash, ui->actionDeleteStash, + ui->actionDiffStash, ui->actionApplyStash, ui->actionDeleteStash, ui->actionCreateTag, + ui->actionDeleteTag, ui->actionCreateBranch, ui->actionMergeBranch, ui->actionFossilSettings, + ui->actionViewAll, ui->actionViewAsFolders, ui->actionViewAsList, ui->actionViewIgnored, + ui->actionViewModifedOnly, ui->actionViewModified, ui->actionViewUnchanged, ui->actionViewUnknown}; - for(size_t i=0; isetEnabled(on); + for (size_t i = 0; i < COUNTOF(actions); ++i) + actions[i]->setEnabled(on); } //------------------------------------------------------------------------------ bool MainWindow::refresh() { - QString title = "Fuel"; + QString title = "Fuel"; - loadFossilSettings(); + loadFossilSettings(); - bool valid = scanWorkspace(); - if(valid) - { - const QString &project_name = getWorkspace().getProjectName(); - if(!project_name.isEmpty()) - title += " - " + project_name; - } + bool valid = scanWorkspace(); + if (valid) + { + const QString &project_name = getWorkspace().getProjectName(); + if (!project_name.isEmpty()) + title += " - " + project_name; + } - enableActions(valid); - setWindowTitle(title); - return valid; + enableActions(valid); + setWindowTitle(title); + return valid; } //------------------------------------------------------------------------------ bool MainWindow::scanWorkspace() { - setBusy(true); - bool valid = true; + setBusy(true); + bool valid = true; - // Load repository info - WorkspaceState st = getWorkspace().getState(); - QString status; + // Load repository info + WorkspaceState st = getWorkspace().getState(); + QString status; - if(st==WORKSPACE_STATE_NOTFOUND) - { - status = tr("No workspace detected."); - valid = false; - } - else if(st==WORKSPACE_STATE_OLDSCHEMA) - { - status = tr("Old repository schema detected. Consider running 'fossil rebuild'"); - valid = false; - } + if (st == WORKSPACE_STATE_NOTFOUND) + { + status = tr("No workspace detected."); + valid = false; + } + else if (st == WORKSPACE_STATE_OLDSCHEMA) + { + status = tr("Old repository schema detected. Consider running 'fossil rebuild'"); + valid = false; + } - versionList.clear(); - selectedTags.clear(); - selectedBranches.clear(); + versionList.clear(); + selectedTags.clear(); + selectedBranches.clear(); - if(valid) - { - // Determine ignored file patterns - QStringList ignore_patterns; - { - static const QRegExp REGEX_GLOB_LIST(",|\\n", Qt::CaseSensitive); + if (valid) + { + // Determine ignored file patterns + QStringList ignore_patterns; + { + static const QRegExp REGEX_GLOB_LIST(",|\\n", Qt::CaseSensitive); - QString ignore_list = settings.GetFossilValue(FOSSIL_SETTING_IGNORE_GLOB).toString().trimmed(); + QString ignore_list = settings.GetFossilValue(FOSSIL_SETTING_IGNORE_GLOB).toString().trimmed(); - // Read patterns from versionable file if it exists - QFile ignored_file(getWorkspace().getPath() + PATH_SEPARATOR ".fossil-settings" PATH_SEPARATOR "ignore-glob"); + // Read patterns from versionable file if it exists + QFile ignored_file(getWorkspace().getPath() + PATH_SEPARATOR ".fossil-settings" PATH_SEPARATOR "ignore-glob"); - if(ignored_file.open(QFile::ReadOnly)) - { - ignore_list = ignored_file.readAll(); - ignored_file.close(); - } + if (ignored_file.open(QFile::ReadOnly)) + { + ignore_list = ignored_file.readAll(); + ignored_file.close(); + } - if(!ignore_list.isEmpty()) - ignore_patterns = ignore_list.split(REGEX_GLOB_LIST, QString::SkipEmptyParts); + if (!ignore_list.isEmpty()) + ignore_patterns = ignore_list.split(REGEX_GLOB_LIST, QString::SkipEmptyParts); - TrimStringList(ignore_patterns); - } + TrimStringList(ignore_patterns); + } - getWorkspace().scanWorkspace(ui->actionViewUnknown->isChecked(), - ui->actionViewIgnored->isChecked(), - ui->actionViewModified->isChecked(), - ui->actionViewUnchanged->isChecked(), - ignore_patterns, - uiCallback - ); + getWorkspace().scanWorkspace(ui->actionViewUnknown->isChecked(), ui->actionViewIgnored->isChecked(), ui->actionViewModified->isChecked(), ui->actionViewUnchanged->isChecked(), ignore_patterns, + uiCallback); - // Build default versions list - versionList += getWorkspace().getBranches(); - versionList += getWorkspace().getTags().keys(); - lblTags->setText(" " + getWorkspace().getActiveTags().join(" ") + " "); - } + // Build default versions list + versionList += getWorkspace().getBranches(); + versionList += getWorkspace().getTags().keys(); + lblTags->setText(" " + getWorkspace().getActiveTags().join(" ") + " "); + } - updateWorkspaceView(); - updateFileView(); + updateWorkspaceView(); + updateFileView(); - setStatus(status); - lblTags->setVisible(valid); + setStatus(status); + lblTags->setVisible(valid); - setBusy(false); - return valid; + setBusy(false); + return valid; } //------------------------------------------------------------------------------ -static void addPathToTree(QStandardItem &root, const QString &path, const QIcon &iconDefault, const QIcon &iconUnchanged, const QIcon &iconModified, const QIcon &iconUnknown, const pathstate_map_t &pathState) +static void addPathToTree(QStandardItem &root, const QString &path, const QIcon &iconDefault, const QIcon &iconUnchanged, const QIcon &iconModified, const QIcon &iconUnknown, + const pathstate_map_t &pathState) { - QStringList dirs = path.split(PATH_SEPARATOR); - QStandardItem *parent = &root; + QStringList dirs = path.split(PATH_SEPARATOR); + QStandardItem *parent = &root; - QString fullpath; - for(QStringList::iterator it = dirs.begin(); it!=dirs.end(); ++it) - { - const QString &dir = *it; - fullpath += dir; + QString fullpath; + for (QStringList::iterator it = dirs.begin(); it != dirs.end(); ++it) + { + const QString &dir = *it; + fullpath += dir; - // Find the child that matches this subdirectory - bool found = false; - for(int r=0; rrowCount(); ++r) - { - QStandardItem *child = parent->child(r, 0); - Q_ASSERT(child); - if(child->text() == dir) - { - parent = child; - found = true; - } - } + // Find the child that matches this subdirectory + bool found = false; + for (int r = 0; r < parent->rowCount(); ++r) + { + QStandardItem *child = parent->child(r, 0); + Q_ASSERT(child); + if (child->text() == dir) + { + parent = child; + found = true; + } + } - if(!found) // Generate it - { - int state = WorkspaceItem::STATE_DEFAULT; + if (!found) // Generate it + { + int state = WorkspaceItem::STATE_DEFAULT; - pathstate_map_t::const_iterator state_it = pathState.find(fullpath); - if(state_it != pathState.end()) - { - WorkspaceFile::Type type = state_it.value(); + pathstate_map_t::const_iterator state_it = pathState.find(fullpath); + if (state_it != pathState.end()) + { + WorkspaceFile::Type type = state_it.value(); - if(type & (WorkspaceFile::TYPE_MODIFIED)) - state = WorkspaceItem::STATE_MODIFIED; - else if(type == WorkspaceFile::TYPE_UNKNOWN) - state = WorkspaceItem::STATE_UNKNOWN; - else - state = WorkspaceItem::STATE_UNCHANGED; - } + if (type & (WorkspaceFile::TYPE_MODIFIED)) + state = WorkspaceItem::STATE_MODIFIED; + else if (type == WorkspaceFile::TYPE_UNKNOWN) + state = WorkspaceItem::STATE_UNKNOWN; + else + state = WorkspaceItem::STATE_UNCHANGED; + } - QStandardItem *child = new QStandardItem(dir); - child->setData(WorkspaceItem(WorkspaceItem::TYPE_FOLDER, fullpath, state), ROLE_WORKSPACE_ITEM); + QStandardItem *child = new QStandardItem(dir); + child->setData(WorkspaceItem(WorkspaceItem::TYPE_FOLDER, fullpath, state), ROLE_WORKSPACE_ITEM); - QString tooltip = fullpath; + QString tooltip = fullpath; - if(state == WorkspaceItem::STATE_UNCHANGED) - { - child->setIcon(iconUnchanged); - tooltip += " " + QObject::tr("Unchanged"); - } - else if(state == WorkspaceItem::STATE_MODIFIED) - { - child->setIcon(iconModified); - tooltip += " " + QObject::tr("Modified"); - } - else if(state == WorkspaceItem::STATE_UNKNOWN) - { - child->setIcon(iconUnknown); - tooltip += " " + QObject::tr("Unknown"); - } - else - child->setIcon(iconDefault); + if (state == WorkspaceItem::STATE_UNCHANGED) + { + child->setIcon(iconUnchanged); + tooltip += " " + QObject::tr("Unchanged"); + } + else if (state == WorkspaceItem::STATE_MODIFIED) + { + child->setIcon(iconModified); + tooltip += " " + QObject::tr("Modified"); + } + else if (state == WorkspaceItem::STATE_UNKNOWN) + { + child->setIcon(iconUnknown); + tooltip += " " + QObject::tr("Unknown"); + } + else + child->setIcon(iconDefault); - child->setToolTip(tooltip); + child->setToolTip(tooltip); - parent->appendRow(child); - parent = child; - } + parent->appendRow(child); + parent = child; + } - fullpath += PATH_SEPARATOR; - } + fullpath += PATH_SEPARATOR; + } } //------------------------------------------------------------------------------ void MainWindow::updateWorkspaceView() { - // Record expanded tree-node names, and selection - name_modelindex_map_t name_map; - BuildNameToModelIndex(name_map, getWorkspace().getTreeModel()); - stringset_t expanded_items; - stringset_t selected_items; + // Record expanded tree-node names, and selection + name_modelindex_map_t name_map; + BuildNameToModelIndex(name_map, getWorkspace().getTreeModel()); + stringset_t expanded_items; + stringset_t selected_items; - const QItemSelection selection = ui->workspaceTreeView->selectionModel()->selection(); + const QItemSelection selection = ui->workspaceTreeView->selectionModel()->selection(); - for(name_modelindex_map_t::const_iterator it=name_map.begin(); it!=name_map.end(); ++it) - { - const QModelIndex mi = it.value(); - if(ui->workspaceTreeView->isExpanded(mi)) - expanded_items.insert(it.key()); + for (name_modelindex_map_t::const_iterator it = name_map.begin(); it != name_map.end(); ++it) + { + const QModelIndex mi = it.value(); + if (ui->workspaceTreeView->isExpanded(mi)) + expanded_items.insert(it.key()); - if(selection.contains(mi)) - selected_items.insert(it.key()); - } + if (selection.contains(mi)) + selected_items.insert(it.key()); + } - // Clear content except headers - getWorkspace().getTreeModel().removeRows(0, getWorkspace().getTreeModel().rowCount()); + // Clear content except headers + getWorkspace().getTreeModel().removeRows(0, getWorkspace().getTreeModel().rowCount()); - QStandardItem *workspace = new QStandardItem(getCachedIcon(":icons/icon-item-folder"), tr("Files") ); - workspace->setData(WorkspaceItem(WorkspaceItem::TYPE_WORKSPACE, ""), ROLE_WORKSPACE_ITEM); - workspace->setEditable(false); + QStandardItem *workspace = new QStandardItem(getCachedIcon(":icons/icon-item-folder"), tr("Files")); + workspace->setData(WorkspaceItem(WorkspaceItem::TYPE_WORKSPACE, ""), ROLE_WORKSPACE_ITEM); + workspace->setEditable(false); - getWorkspace().getTreeModel().appendRow(workspace); - if(viewMode == VIEWMODE_TREE) - { - // FIXME: Change paths to map to allow for automatic sorting - QStringList paths = getWorkspace().getPaths().toList(); - paths.sort(); + getWorkspace().getTreeModel().appendRow(workspace); + if (viewMode == VIEWMODE_TREE) + { + // FIXME: Change paths to map to allow for automatic sorting + QStringList paths = getWorkspace().getPaths().toList(); + paths.sort(); - foreach(const QString &dir, paths) - { - if(dir.isEmpty()) - continue; + foreach (const QString &dir, paths) + { + if (dir.isEmpty()) + continue; - addPathToTree(*workspace, dir, - getCachedIcon(":icons/icon-item-folder"), - getCachedIcon(":icons/icon-item-folder-unchanged"), - getCachedIcon(":icons/icon-item-folder-modified"), - getCachedIcon(":icons/icon-item-folder-unknown"), - getWorkspace().getPathState()); - } + addPathToTree(*workspace, dir, getCachedIcon(":icons/icon-item-folder"), getCachedIcon(":icons/icon-item-folder-unchanged"), getCachedIcon(":icons/icon-item-folder-modified"), + getCachedIcon(":icons/icon-item-folder-unknown"), getWorkspace().getPathState()); + } - // Expand root folder - ui->workspaceTreeView->setExpanded(workspace->index(), true); - } + // Expand root folder + ui->workspaceTreeView->setExpanded(workspace->index(), true); + } - // Branches - QStandardItem *branches = new QStandardItem(getCachedIcon(":icons/icon-item-branch"), tr("Branches")); - branches->setData(WorkspaceItem(WorkspaceItem::TYPE_BRANCHES, ""), ROLE_WORKSPACE_ITEM); - branches->setEditable(false); - getWorkspace().getTreeModel().appendRow(branches); - foreach(const QString &branch_name, getWorkspace().getBranches()) - { - QStandardItem *branch = new QStandardItem(getCachedIcon(":icons/icon-item-branch"), branch_name); - branch->setData(WorkspaceItem(WorkspaceItem::TYPE_BRANCH, branch_name), ROLE_WORKSPACE_ITEM); + // Branches + QStandardItem *branches = new QStandardItem(getCachedIcon(":icons/icon-item-branch"), tr("Branches")); + branches->setData(WorkspaceItem(WorkspaceItem::TYPE_BRANCHES, ""), ROLE_WORKSPACE_ITEM); + branches->setEditable(false); + getWorkspace().getTreeModel().appendRow(branches); + foreach (const QString &branch_name, getWorkspace().getBranches()) + { + QStandardItem *branch = new QStandardItem(getCachedIcon(":icons/icon-item-branch"), branch_name); + branch->setData(WorkspaceItem(WorkspaceItem::TYPE_BRANCH, branch_name), ROLE_WORKSPACE_ITEM); - bool active = getWorkspace().getActiveTags().contains(branch_name); - if(active) - { - QFont font = branch->font(); - font.setBold(true); - branch->setFont(font); - } - branches->appendRow(branch); - } + bool active = getWorkspace().getActiveTags().contains(branch_name); + if (active) + { + QFont font = branch->font(); + font.setBold(true); + branch->setFont(font); + } + branches->appendRow(branch); + } - // Tags - QStandardItem *tags = new QStandardItem(getCachedIcon(":icons/icon-item-tag"), tr("Tags")); - tags->setData(WorkspaceItem(WorkspaceItem::TYPE_TAGS, ""), ROLE_WORKSPACE_ITEM); - tags->setEditable(false); - getWorkspace().getTreeModel().appendRow(tags); - for(QStringMap::const_iterator it=getWorkspace().getTags().begin(); it!=getWorkspace().getTags().end(); ++it) - { - const QString &tag_name = it.key(); + // Tags + QStandardItem *tags = new QStandardItem(getCachedIcon(":icons/icon-item-tag"), tr("Tags")); + tags->setData(WorkspaceItem(WorkspaceItem::TYPE_TAGS, ""), ROLE_WORKSPACE_ITEM); + tags->setEditable(false); + getWorkspace().getTreeModel().appendRow(tags); + for (QStringMap::const_iterator it = getWorkspace().getTags().begin(); it != getWorkspace().getTags().end(); ++it) + { + const QString &tag_name = it.key(); - QStandardItem *tag = new QStandardItem(getCachedIcon(":icons/icon-item-tag"), tag_name); - tag->setData(WorkspaceItem(WorkspaceItem::TYPE_TAG, tag_name), ROLE_WORKSPACE_ITEM); + QStandardItem *tag = new QStandardItem(getCachedIcon(":icons/icon-item-tag"), tag_name); + tag->setData(WorkspaceItem(WorkspaceItem::TYPE_TAG, tag_name), ROLE_WORKSPACE_ITEM); - bool active = getWorkspace().getActiveTags().contains(tag_name); - if(active) - { - QFont font = tag->font(); - font.setBold(true); - tag->setFont(font); - } - tags->appendRow(tag); - } + bool active = getWorkspace().getActiveTags().contains(tag_name); + if (active) + { + QFont font = tag->font(); + font.setBold(true); + tag->setFont(font); + } + tags->appendRow(tag); + } - // Stashes - QStandardItem *stashes = new QStandardItem(getCachedIcon(":icons/icon-action-repo-open"), tr("Stashes")); - stashes->setData(WorkspaceItem(WorkspaceItem::TYPE_STASHES, ""), ROLE_WORKSPACE_ITEM); - stashes->setEditable(false); - getWorkspace().getTreeModel().appendRow(stashes); - for(stashmap_t::const_iterator it= getWorkspace().getStashes().begin(); it!=getWorkspace().getStashes().end(); ++it) - { - QStandardItem *stash = new QStandardItem(getCachedIcon(":icons/icon-action-repo-open"), it.key()); - stash->setData(WorkspaceItem(WorkspaceItem::TYPE_STASH, it.value()), ROLE_WORKSPACE_ITEM); - stashes->appendRow(stash); - } + // Stashes + QStandardItem *stashes = new QStandardItem(getCachedIcon(":icons/icon-action-repo-open"), tr("Stashes")); + stashes->setData(WorkspaceItem(WorkspaceItem::TYPE_STASHES, ""), ROLE_WORKSPACE_ITEM); + stashes->setEditable(false); + getWorkspace().getTreeModel().appendRow(stashes); + for (stashmap_t::const_iterator it = getWorkspace().getStashes().begin(); it != getWorkspace().getStashes().end(); ++it) + { + QStandardItem *stash = new QStandardItem(getCachedIcon(":icons/icon-action-repo-open"), it.key()); + stash->setData(WorkspaceItem(WorkspaceItem::TYPE_STASH, it.value()), ROLE_WORKSPACE_ITEM); + stashes->appendRow(stash); + } - // Remotes - QStandardItem *remotes = new QStandardItem(getCachedIcon(":icons/icon-item-remote"), tr("Remotes")); - remotes->setData(WorkspaceItem(WorkspaceItem::TYPE_REMOTES, ""), ROLE_WORKSPACE_ITEM); - remotes->setEditable(false); - getWorkspace().getTreeModel().appendRow(remotes); - for(remote_map_t::const_iterator it=getWorkspace().getRemotes().begin(); it!=getWorkspace().getRemotes().end(); ++it) - { - QStandardItem *remote_item = new QStandardItem(getCachedIcon(":icons/icon-item-remote"), it->name); - remote_item->setData(WorkspaceItem(WorkspaceItem::TYPE_REMOTE, it->url.toString()), ROLE_WORKSPACE_ITEM); + // Remotes + QStandardItem *remotes = new QStandardItem(getCachedIcon(":icons/icon-item-remote"), tr("Remotes")); + remotes->setData(WorkspaceItem(WorkspaceItem::TYPE_REMOTES, ""), ROLE_WORKSPACE_ITEM); + remotes->setEditable(false); + getWorkspace().getTreeModel().appendRow(remotes); + for (remote_map_t::const_iterator it = getWorkspace().getRemotes().begin(); it != getWorkspace().getRemotes().end(); ++it) + { + QStandardItem *remote_item = new QStandardItem(getCachedIcon(":icons/icon-item-remote"), it->name); + remote_item->setData(WorkspaceItem(WorkspaceItem::TYPE_REMOTE, it->url.toString()), ROLE_WORKSPACE_ITEM); - remote_item->setToolTip(UrlToStringDisplay(it->url)); + remote_item->setToolTip(UrlToStringDisplay(it->url)); - // Mark the default url as bold - if(it->isDefault) - { - QFont font = remote_item->font(); - font.setBold(true); - remote_item->setFont(font); - } - remotes->appendRow(remote_item); - } + // Mark the default url as bold + if (it->isDefault) + { + QFont font = remote_item->font(); + font.setBold(true); + remote_item->setFont(font); + } + remotes->appendRow(remote_item); + } - // Expand previously selected nodes - name_map.clear(); - BuildNameToModelIndex(name_map, getWorkspace().getTreeModel()); + // Expand previously selected nodes + name_map.clear(); + BuildNameToModelIndex(name_map, getWorkspace().getTreeModel()); - for(stringset_t::const_iterator it=expanded_items.begin(); it!=expanded_items.end(); ++it) - { - name_modelindex_map_t::const_iterator mi_it = name_map.find(*it); - if(mi_it!=name_map.end()) - ui->workspaceTreeView->setExpanded(mi_it.value(), true); - } + for (stringset_t::const_iterator it = expanded_items.begin(); it != expanded_items.end(); ++it) + { + name_modelindex_map_t::const_iterator mi_it = name_map.find(*it); + if (mi_it != name_map.end()) + ui->workspaceTreeView->setExpanded(mi_it.value(), true); + } - // Select previous selected item - for(stringset_t::const_iterator it=selected_items.begin(); it!=selected_items.end(); ++it) - { - name_modelindex_map_t::const_iterator mi_it = name_map.find(*it); - if(mi_it!=name_map.end()) - { - const QModelIndex &mi = mi_it.value(); - ui->workspaceTreeView->selectionModel()->select(mi, QItemSelectionModel::Select); - } - } + // Select previous selected item + for (stringset_t::const_iterator it = selected_items.begin(); it != selected_items.end(); ++it) + { + name_modelindex_map_t::const_iterator mi_it = name_map.find(*it); + if (mi_it != name_map.end()) + { + const QModelIndex &mi = mi_it.value(); + ui->workspaceTreeView->selectionModel()->select(mi, QItemSelectionModel::Select); + } + } } //------------------------------------------------------------------------------ void MainWindow::updateFileView() { - // Clear content except headers - getWorkspace().getFileModel().removeRows(0, getWorkspace().getFileModel().rowCount()); + // Clear content except headers + getWorkspace().getFileModel().removeRows(0, getWorkspace().getFileModel().rowCount()); - struct { WorkspaceFile::Type type; QString text; const char *icon; } - stats[] = - { - { WorkspaceFile::TYPE_EDITTED, tr("Edited"), ":icons/icon-item-edited" }, - { WorkspaceFile::TYPE_UNCHANGED, tr("Unchanged"), ":icons/icon-item-unchanged" }, - { WorkspaceFile::TYPE_ADDED, tr("Added"), ":icons/icon-item-added" }, - { WorkspaceFile::TYPE_DELETED, tr("Deleted"), ":icons/icon-item-deleted" }, - { WorkspaceFile::TYPE_RENAMED, tr("Renamed"), ":icons/icon-item-renamed" }, - { WorkspaceFile::TYPE_MISSING, tr("Missing"), ":icons/icon-item-missing" }, - { WorkspaceFile::TYPE_CONFLICTED, tr("Conflicted"), ":icons/icon-item-conflicted" }, - { WorkspaceFile::TYPE_MERGED, tr("Merged"), ":icons/icon-item-edited" }, - }; + struct + { + WorkspaceFile::Type type; + QString text; + const char *icon; + } stats[] = { + {WorkspaceFile::TYPE_EDITTED, tr("Edited"), ":icons/icon-item-edited"}, + {WorkspaceFile::TYPE_UNCHANGED, tr("Unchanged"), ":icons/icon-item-unchanged"}, + {WorkspaceFile::TYPE_ADDED, tr("Added"), ":icons/icon-item-added"}, + {WorkspaceFile::TYPE_DELETED, tr("Deleted"), ":icons/icon-item-deleted"}, + {WorkspaceFile::TYPE_RENAMED, tr("Renamed"), ":icons/icon-item-renamed"}, + {WorkspaceFile::TYPE_MISSING, tr("Missing"), ":icons/icon-item-missing"}, + {WorkspaceFile::TYPE_CONFLICTED, tr("Conflicted"), ":icons/icon-item-conflicted"}, + {WorkspaceFile::TYPE_MERGED, tr("Merged"), ":icons/icon-item-edited"}, + }; - bool display_path = viewMode==VIEWMODE_LIST || selectedDirs.count() > 1; + bool display_path = viewMode == VIEWMODE_LIST || selectedDirs.count() > 1; - const QString &status_unknown = QString(tr("Unknown")); - const QString &search_text = searchBox->text(); + const QString &status_unknown = QString(tr("Unknown")); + const QString &search_text = searchBox->text(); - size_t item_id=0; - for(filemap_t::iterator it = getWorkspace().getFiles().begin(); it!=getWorkspace().getFiles().end(); ++it) - { - const WorkspaceFile &e = *it.value(); - const QString &path = e.getPath(); - const QString &file_path = e.getFilePath(); - QString native_file_path = QDir::toNativeSeparators(file_path); + size_t item_id = 0; + for (filemap_t::iterator it = getWorkspace().getFiles().begin(); it != getWorkspace().getFiles().end(); ++it) + { + const WorkspaceFile &e = *it.value(); + const QString &path = e.getPath(); + const QString &file_path = e.getFilePath(); + QString native_file_path = QDir::toNativeSeparators(file_path); - // Apply filter if available - if(!search_text.isEmpty() && !native_file_path.contains(search_text, Qt::CaseInsensitive)) - continue; + // Apply filter if available + if (!search_text.isEmpty() && !native_file_path.contains(search_text, Qt::CaseInsensitive)) + continue; - // In Tree mode, filter all items not included in the current dir - if(viewMode==VIEWMODE_TREE && !selectedDirs.contains(path)) - continue; + // In Tree mode, filter all items not included in the current dir + if (viewMode == VIEWMODE_TREE && !selectedDirs.contains(path)) + continue; - // Status Column - const QString *status_text = &status_unknown; - const char *status_icon_path= ":icons/icon-item-unknown"; // Default icon + // Status Column + const QString *status_text = &status_unknown; + const char *status_icon_path = ":icons/icon-item-unknown"; // Default icon - for(size_t t=0; tsetToolTip(*status_text); - getWorkspace().getFileModel().setItem(item_id, COLUMN_STATUS, status); + QStandardItem *status = new QStandardItem(getCachedIcon(status_icon_path), *status_text); + status->setToolTip(*status_text); + getWorkspace().getFileModel().setItem(item_id, COLUMN_STATUS, status); - QFileInfo finfo = e.getFileInfo(); + QFileInfo finfo = e.getFileInfo(); - const QIcon *icon = &getCachedFileIcon(finfo); + const QIcon *icon = &getCachedFileIcon(finfo); - QStandardItem *filename_item = 0; - getWorkspace().getFileModel().setItem(item_id, COLUMN_PATH, new QStandardItem(path)); + QStandardItem *filename_item = 0; + getWorkspace().getFileModel().setItem(item_id, COLUMN_PATH, new QStandardItem(path)); - if(display_path) - filename_item = new QStandardItem(*icon, native_file_path); - else - filename_item = new QStandardItem(*icon, e.getFilename()); + if (display_path) + filename_item = new QStandardItem(*icon, native_file_path); + else + filename_item = new QStandardItem(*icon, e.getFilename()); - Q_ASSERT(filename_item); - // Keep the path in the user data - filename_item->setData(file_path); - getWorkspace().getFileModel().setItem(item_id, COLUMN_FILENAME, filename_item); + Q_ASSERT(filename_item); + // Keep the path in the user data + filename_item->setData(file_path); + getWorkspace().getFileModel().setItem(item_id, COLUMN_FILENAME, filename_item); - getWorkspace().getFileModel().setItem(item_id, COLUMN_EXTENSION, new QStandardItem(finfo.suffix())); - getWorkspace().getFileModel().setItem(item_id, COLUMN_MODIFIED, new QStandardItem(finfo.lastModified().toString(Qt::SystemLocaleShortDate))); + getWorkspace().getFileModel().setItem(item_id, COLUMN_EXTENSION, new QStandardItem(finfo.suffix())); + getWorkspace().getFileModel().setItem(item_id, COLUMN_MODIFIED, new QStandardItem(finfo.lastModified().toString(Qt::SystemLocaleShortDate))); - ++item_id; - } + ++item_id; + } - ui->fileTableView->resizeRowsToContents(); + ui->fileTableView->resizeRowsToContents(); } //------------------------------------------------------------------------------ void MainWindow::log(const QString &text, bool isHTML) { - QTextCursor c = ui->textBrowser->textCursor(); - c.movePosition(QTextCursor::End); - ui->textBrowser->setTextCursor(c); + QTextCursor c = ui->textBrowser->textCursor(); + c.movePosition(QTextCursor::End); + ui->textBrowser->setTextCursor(c); - if(isHTML) - ui->textBrowser->insertHtml(text); - else - ui->textBrowser->insertPlainText(text); + if (isHTML) + ui->textBrowser->insertHtml(text); + else + ui->textBrowser->insertPlainText(text); } //------------------------------------------------------------------------------ void MainWindow::setStatus(const QString &text) { - ui->statusBar->showMessage(text); + ui->statusBar->showMessage(text); } //------------------------------------------------------------------------------ void MainWindow::on_actionClearLog_triggered() { - ui->textBrowser->clear(); + ui->textBrowser->clear(); } //------------------------------------------------------------------------------ void MainWindow::applySettings() { - QSettings *store = settings.GetStore(); - QString active_workspace; + QSettings *store = settings.GetStore(); + QString active_workspace; - int num_wks = store->beginReadArray("Workspaces"); - for(int i=0; isetArrayIndex(i); - QString wk = store->value("Path").toString(); + int num_wks = store->beginReadArray("Workspaces"); + for (int i = 0; i < num_wks; ++i) + { + store->setArrayIndex(i); + QString wk = store->value("Path").toString(); - // Skip invalid workspaces - if(wk.isEmpty() || !QDir(wk).exists()) - continue; + // Skip invalid workspaces + if (wk.isEmpty() || !QDir(wk).exists()) + continue; - addWorkspaceHistory(wk); + addWorkspaceHistory(wk); - if(store->contains("Active") && store->value("Active").toBool()) - active_workspace = wk; - } - store->endArray(); + if (store->contains("Active") && store->value("Active").toBool()) + active_workspace = wk; + } + store->endArray(); - store->beginReadArray("FileColumns"); - for(int i=0; isetArrayIndex(i); - if(store->contains("Width")) - { - int width = store->value("Width").toInt(); - ui->fileTableView->setColumnWidth(i, width); - } + store->beginReadArray("FileColumns"); + for (int i = 0; i < getWorkspace().getFileModel().columnCount(); ++i) + { + store->setArrayIndex(i); + if (store->contains("Width")) + { + int width = store->value("Width").toInt(); + ui->fileTableView->setColumnWidth(i, width); + } - if(store->contains("Index")) - { - int index = store->value("Index").toInt(); - int cur_index = ui->fileTableView->horizontalHeader()->visualIndex(i); - ui->fileTableView->horizontalHeader()->moveSection(cur_index, index); - } + if (store->contains("Index")) + { + int index = store->value("Index").toInt(); + int cur_index = ui->fileTableView->horizontalHeader()->visualIndex(i); + ui->fileTableView->horizontalHeader()->moveSection(cur_index, index); + } + } + store->endArray(); - } - store->endArray(); + if (store->contains("WindowX") && store->contains("WindowY")) + { + QPoint _pos; + _pos.setX(store->value("WindowX").toInt()); + _pos.setY(store->value("WindowY").toInt()); + move(_pos); + } + if (store->contains("WindowWidth") && store->contains("WindowHeight")) + { + QSize _size; + _size.setWidth(store->value("WindowWidth").toInt()); + _size.setHeight(store->value("WindowHeight").toInt()); + resize(_size); + } - if(store->contains("WindowX") && store->contains("WindowY")) - { - QPoint _pos; - _pos.setX(store->value("WindowX").toInt()); - _pos.setY(store->value("WindowY").toInt()); - move(_pos); - } + if (store->contains("ViewUnknown")) + ui->actionViewUnknown->setChecked(store->value("ViewUnknown").toBool()); + if (store->contains("ViewModified")) + ui->actionViewModified->setChecked(store->value("ViewModified").toBool()); + if (store->contains("ViewUnchanged")) + ui->actionViewUnchanged->setChecked(store->value("ViewUnchanged").toBool()); + if (store->contains("ViewIgnored")) + ui->actionViewIgnored->setChecked(store->value("ViewIgnored").toBool()); + if (store->contains("ViewAsList")) + { + ui->actionViewAsList->setChecked(store->value("ViewAsList").toBool()); + ui->actionViewAsFolders->setChecked(!store->value("ViewAsList").toBool()); + viewMode = store->value("ViewAsList").toBool() ? VIEWMODE_LIST : VIEWMODE_TREE; + } - if(store->contains("WindowWidth") && store->contains("WindowHeight")) - { - QSize _size; - _size.setWidth(store->value("WindowWidth").toInt()); - _size.setHeight(store->value("WindowHeight").toInt()); - resize(_size); - } + // Set the workspace after loading the settings, since it may trigger a remote info storage + if (!active_workspace.isEmpty()) + setCurrentWorkspace(active_workspace); - if(store->contains("ViewUnknown")) - ui->actionViewUnknown->setChecked(store->value("ViewUnknown").toBool()); - if(store->contains("ViewModified")) - ui->actionViewModified->setChecked(store->value("ViewModified").toBool()); - if(store->contains("ViewUnchanged")) - ui->actionViewUnchanged->setChecked(store->value("ViewUnchanged").toBool()); - if(store->contains("ViewIgnored")) - ui->actionViewIgnored->setChecked(store->value("ViewIgnored").toBool()); - if(store->contains("ViewAsList")) - { - ui->actionViewAsList->setChecked(store->value("ViewAsList").toBool()); - ui->actionViewAsFolders->setChecked(!store->value("ViewAsList").toBool()); - viewMode = store->value("ViewAsList").toBool()? VIEWMODE_LIST : VIEWMODE_TREE; - } + // Custom Actions + for (int i = 0; i < MAX_CUSTOM_ACTIONS; ++i) + settings.GetCustomActions()[i].Clear(); - // Set the workspace after loading the settings, since it may trigger a remote info storage - if(!active_workspace.isEmpty()) - setCurrentWorkspace(active_workspace); + int num_actions = store->beginReadArray("CustomActions"); + int last_action = 0; + for (int i = 0; i < num_actions; ++i) + { + store->setArrayIndex(i); + CustomAction &action = settings.GetCustomActions()[last_action]; + QString descr; + if (store->contains("Description")) + descr = store->value("Description").toString(); - // Custom Actions - for(int i=0; ibeginReadArray("CustomActions"); - int last_action = 0; - for(int i=0; isetArrayIndex(i); - CustomAction &action = settings.GetCustomActions()[last_action]; + if (store->contains("Command")) + action.Command = store->value("Command").toString(); + if (store->contains("Context")) + action.Context = static_cast(store->value("Context").toInt()); + if (store->contains("MultipleSelection")) + action.MultipleSelection = store->value("MultipleSelection").toBool(); - QString descr; - if(store->contains("Description")) - descr = store->value("Description").toString(); + ++last_action; + } + store->endArray(); - if(descr.isEmpty()) - continue; - action.Description = descr; - - if(store->contains("Command")) - action.Command = store->value("Command").toString(); - if(store->contains("Context")) - action.Context = static_cast(store->value("Context").toInt()); - if(store->contains("MultipleSelection")) - action.MultipleSelection = store->value("MultipleSelection").toBool(); - - ++last_action; - } - store->endArray(); - - updateCustomActions(); + updateCustomActions(); } //------------------------------------------------------------------------------ void MainWindow::updateSettings() { - QSettings *store = settings.GetStore(); + QSettings *store = settings.GetStore(); - store->beginWriteArray("Workspaces", workspaceHistory.size()); - for(int i=0; isetArrayIndex(i); - store->setValue("Path", workspaceHistory[i]); - if(getWorkspace().getPath() == workspaceHistory[i]) - store->setValue("Active", true); - else - store->remove("Active"); - } - store->endArray(); + store->beginWriteArray("Workspaces", workspaceHistory.size()); + for (int i = 0; i < workspaceHistory.size(); ++i) + { + store->setArrayIndex(i); + store->setValue("Path", workspaceHistory[i]); + if (getWorkspace().getPath() == workspaceHistory[i]) + store->setValue("Active", true); + else + store->remove("Active"); + } + store->endArray(); - store->beginWriteArray("FileColumns", getWorkspace().getFileModel().columnCount()); - for(int i=0; isetArrayIndex(i); - store->setValue("Width", ui->fileTableView->columnWidth(i)); - int index = ui->fileTableView->horizontalHeader()->visualIndex(i); - store->setValue("Index", index); - } - store->endArray(); + store->beginWriteArray("FileColumns", getWorkspace().getFileModel().columnCount()); + for (int i = 0; i < getWorkspace().getFileModel().columnCount(); ++i) + { + store->setArrayIndex(i); + store->setValue("Width", ui->fileTableView->columnWidth(i)); + int index = ui->fileTableView->horizontalHeader()->visualIndex(i); + store->setValue("Index", index); + } + store->endArray(); - store->setValue("WindowX", x()); - store->setValue("WindowY", y()); - store->setValue("WindowWidth", width()); - store->setValue("WindowHeight", height()); - store->setValue("ViewUnknown", ui->actionViewUnknown->isChecked()); - store->setValue("ViewModified", ui->actionViewModified->isChecked()); - store->setValue("ViewUnchanged", ui->actionViewUnchanged->isChecked()); - store->setValue("ViewIgnored", ui->actionViewIgnored->isChecked()); - store->setValue("ViewAsList", ui->actionViewAsList->isChecked()); + store->setValue("WindowX", x()); + store->setValue("WindowY", y()); + store->setValue("WindowWidth", width()); + store->setValue("WindowHeight", height()); + store->setValue("ViewUnknown", ui->actionViewUnknown->isChecked()); + store->setValue("ViewModified", ui->actionViewModified->isChecked()); + store->setValue("ViewUnchanged", ui->actionViewUnchanged->isChecked()); + store->setValue("ViewIgnored", ui->actionViewIgnored->isChecked()); + store->setValue("ViewAsList", ui->actionViewAsList->isChecked()); - // Custom Actions - Settings::custom_actions_t &actions = settings.GetCustomActions(); - store->beginWriteArray("CustomActions", actions.size()); - int active_actions = 0; - for(int i=0; isetArrayIndex(active_actions); + // Custom Actions + Settings::custom_actions_t &actions = settings.GetCustomActions(); + store->beginWriteArray("CustomActions", actions.size()); + int active_actions = 0; + for (int i = 0; i < actions.size(); ++i) + { + CustomAction &action = actions[i]; + if (!action.IsValid()) + continue; + store->setArrayIndex(active_actions); - store->setValue("Description", action.Description); - store->setValue("Command", action.Command); - store->setValue("Context", static_cast(action.Context)); - store->setValue("MultipleSelection", action.MultipleSelection); - ++active_actions; - } - store->endArray(); + store->setValue("Description", action.Description); + store->setValue("Command", action.Command); + store->setValue("Context", static_cast(action.Context)); + store->setValue("MultipleSelection", action.MultipleSelection); + ++active_actions; + } + store->endArray(); } //------------------------------------------------------------------------------ void MainWindow::selectRootDir() { - // FIXME: KKK - if(viewMode==VIEWMODE_TREE) - { - QModelIndex root_index = ui->workspaceTreeView->model()->index(0, 0); - ui->workspaceTreeView->selectionModel()->select(root_index, QItemSelectionModel::Select); - } + // FIXME: KKK + if (viewMode == VIEWMODE_TREE) + { + QModelIndex root_index = ui->workspaceTreeView->model()->index(0, 0); + ui->workspaceTreeView->selectionModel()->select(root_index, QItemSelectionModel::Select); + } } //------------------------------------------------------------------------------ void MainWindow::fossilBrowse(const QString &fossilUrl) { - if(!uiRunning()) - ui->actionFossilUI->activate(QAction::Trigger); + if (!uiRunning()) + ui->actionFossilUI->activate(QAction::Trigger); - bool use_internal = settings.GetValue(FUEL_SETTING_WEB_BROWSER).toInt() == 1; + bool use_internal = settings.GetValue(FUEL_SETTING_WEB_BROWSER).toInt() == 1; - QUrl url = QUrl(getWorkspace().fossil().getUIHttpAddress()+fossilUrl); + QUrl url = QUrl(getWorkspace().fossil().getUIHttpAddress() + fossilUrl); - if(use_internal) - { - ui->webView->load(url); - ui->tabWidget->setCurrentIndex(TAB_BROWSER); - } - else - QDesktopServices::openUrl(url); + if (use_internal) + { + ui->webView->load(url); + ui->tabWidget->setCurrentIndex(TAB_BROWSER); + } + else + QDesktopServices::openUrl(url); } //------------------------------------------------------------------------------ void MainWindow::getSelectionFilenames(QStringList &filenames, int includeMask, bool allIfEmpty) { - if(QApplication::focusWidget() == ui->workspaceTreeView) - getDirViewSelection(filenames, includeMask, allIfEmpty); - else - getFileViewSelection(filenames, includeMask, allIfEmpty); + if (QApplication::focusWidget() == ui->workspaceTreeView) + getDirViewSelection(filenames, includeMask, allIfEmpty); + else + getFileViewSelection(filenames, includeMask, allIfEmpty); } //------------------------------------------------------------------------------ void MainWindow::getSelectionPaths(stringset_t &paths) { - // Determine the directories selected - QModelIndexList selection = ui->workspaceTreeView->selectionModel()->selectedIndexes(); - foreach(const QModelIndex &mi, selection) - { - QVariant data = mi.model()->data(mi, ROLE_WORKSPACE_ITEM); - Q_ASSERT(data.isValid()); + // Determine the directories selected + QModelIndexList selection = ui->workspaceTreeView->selectionModel()->selectedIndexes(); + foreach (const QModelIndex &mi, selection) + { + QVariant data = mi.model()->data(mi, ROLE_WORKSPACE_ITEM); + Q_ASSERT(data.isValid()); - WorkspaceItem tv = data.value(); - if(tv.Type != WorkspaceItem::TYPE_FOLDER && tv.Type != WorkspaceItem::TYPE_WORKSPACE) - continue; + WorkspaceItem tv = data.value(); + if (tv.Type != WorkspaceItem::TYPE_FOLDER && tv.Type != WorkspaceItem::TYPE_WORKSPACE) + continue; - paths.insert(tv.Value); - } + paths.insert(tv.Value); + } } //------------------------------------------------------------------------------ // Select all workspace files that match the includeMask void MainWindow::getAllFilenames(QStringList &filenames, int includeMask) { - for(filemap_t::iterator it=getWorkspace().getFiles().begin(); it!=getWorkspace().getFiles().end(); ++it) - { - const WorkspaceFile &e = *(*it); + for (filemap_t::iterator it = getWorkspace().getFiles().begin(); it != getWorkspace().getFiles().end(); ++it) + { + const WorkspaceFile &e = *(*it); - // Skip unwanted file types - if(!(includeMask & e.getType())) - continue; + // Skip unwanted file types + if (!(includeMask & e.getType())) + continue; - filenames.append(e.getFilePath()); - } + filenames.append(e.getFilePath()); + } } //------------------------------------------------------------------------------ void MainWindow::getDirViewSelection(QStringList &filenames, int includeMask, bool allIfEmpty) { - // Determine the directories selected - stringset_t paths; + // Determine the directories selected + stringset_t paths; - QModelIndexList selection = ui->workspaceTreeView->selectionModel()->selectedIndexes(); - if(!(selection.empty() && allIfEmpty)) - { - getSelectionPaths(paths); - } + QModelIndexList selection = ui->workspaceTreeView->selectionModel()->selectedIndexes(); + if (!(selection.empty() && allIfEmpty)) + { + getSelectionPaths(paths); + } - // Select the actual files form the selected directories - for(filemap_t::iterator it=getWorkspace().getFiles().begin(); it!=getWorkspace().getFiles().end(); ++it) - { - const WorkspaceFile &e = *(*it); + // Select the actual files form the selected directories + for (filemap_t::iterator it = getWorkspace().getFiles().begin(); it != getWorkspace().getFiles().end(); ++it) + { + const WorkspaceFile &e = *(*it); - // Skip unwanted file types - if(!(includeMask & e.getType())) - continue; + // Skip unwanted file types + if (!(includeMask & e.getType())) + continue; - bool include = true; + bool include = true; - // If we have a limited set of paths to filter, check them - if(!paths.empty()) - include = false; + // If we have a limited set of paths to filter, check them + if (!paths.empty()) + include = false; - for(stringset_t::iterator p_it=paths.begin(); p_it!=paths.end(); ++p_it) - { - const QString &path = *p_it; - // An empty path is the root folder, so it includes all files - // If the file's path starts with this, we include id - if(path.isEmpty() || e.getPath().indexOf(path)==0) - { - include = true; - break; - } - } + for (stringset_t::iterator p_it = paths.begin(); p_it != paths.end(); ++p_it) + { + const QString &path = *p_it; + // An empty path is the root folder, so it includes all files + // If the file's path starts with this, we include id + if (path.isEmpty() || e.getPath().indexOf(path) == 0) + { + include = true; + break; + } + } - if(!include) - continue; - - filenames.append(e.getFilePath()); - } + if (!include) + continue; + filenames.append(e.getFilePath()); + } } //------------------------------------------------------------------------------ void MainWindow::getFileViewSelection(QStringList &filenames, int includeMask, bool allIfEmpty) { - QModelIndexList selection = ui->fileTableView->selectionModel()->selectedIndexes(); - if(selection.empty() && allIfEmpty) - { - ui->fileTableView->selectAll(); - selection = ui->fileTableView->selectionModel()->selectedIndexes(); - ui->fileTableView->clearSelection(); - } + QModelIndexList selection = ui->fileTableView->selectionModel()->selectedIndexes(); + if (selection.empty() && allIfEmpty) + { + ui->fileTableView->selectAll(); + selection = ui->fileTableView->selectionModel()->selectedIndexes(); + ui->fileTableView->clearSelection(); + } - for(QModelIndexList::iterator mi_it = selection.begin(); mi_it!=selection.end(); ++mi_it) - { - const QModelIndex &mi = *mi_it; + for (QModelIndexList::iterator mi_it = selection.begin(); mi_it != selection.end(); ++mi_it) + { + const QModelIndex &mi = *mi_it; - // FIXME: we are being called once per cell of each row - // but we only need column 1. There must be a better way - if(mi.column()!=COLUMN_FILENAME) - continue; + // FIXME: we are being called once per cell of each row + // but we only need column 1. There must be a better way + if (mi.column() != COLUMN_FILENAME) + continue; - QVariant data = getWorkspace().getFileModel().data(mi, Qt::UserRole+1); - QString filename = data.toString(); - filemap_t::iterator e_it = getWorkspace().getFiles().find(filename); - Q_ASSERT(e_it!=getWorkspace().getFiles().end()); - const WorkspaceFile &e = *e_it.value(); + QVariant data = getWorkspace().getFileModel().data(mi, Qt::UserRole + 1); + QString filename = data.toString(); + filemap_t::iterator e_it = getWorkspace().getFiles().find(filename); + Q_ASSERT(e_it != getWorkspace().getFiles().end()); + const WorkspaceFile &e = *e_it.value(); - // Skip unwanted files - if(!(includeMask & e.getType())) - continue; + // Skip unwanted files + if (!(includeMask & e.getType())) + continue; - filenames.append(filename); - } + filenames.append(filename); + } } //------------------------------------------------------------------------------ void MainWindow::getSelectionStashes(QStringList &stashNames) { - QModelIndexList selection = ui->workspaceTreeView->selectionModel()->selectedIndexes(); + QModelIndexList selection = ui->workspaceTreeView->selectionModel()->selectedIndexes(); - foreach(const QModelIndex &mi, selection) - { - QVariant data = mi.model()->data(mi, ROLE_WORKSPACE_ITEM); - Q_ASSERT(data.isValid()); - WorkspaceItem tv = data.value(); + foreach (const QModelIndex &mi, selection) + { + QVariant data = mi.model()->data(mi, ROLE_WORKSPACE_ITEM); + Q_ASSERT(data.isValid()); + WorkspaceItem tv = data.value(); - if(tv.Type != WorkspaceItem::TYPE_STASH) - continue; + if (tv.Type != WorkspaceItem::TYPE_STASH) + continue; - QString name = mi.model()->data(mi, Qt::DisplayRole).toString(); - stashNames.append(name); - } + QString name = mi.model()->data(mi, Qt::DisplayRole).toString(); + stashNames.append(name); + } } //------------------------------------------------------------------------------ void MainWindow::getSelectionRemotes(QStringList &remoteUrls) { - QModelIndexList selection = ui->workspaceTreeView->selectionModel()->selectedIndexes(); + QModelIndexList selection = ui->workspaceTreeView->selectionModel()->selectedIndexes(); - foreach(const QModelIndex &mi, selection) - { - QVariant data = mi.model()->data(mi, ROLE_WORKSPACE_ITEM); - Q_ASSERT(data.isValid()); - WorkspaceItem tv = data.value(); + foreach (const QModelIndex &mi, selection) + { + QVariant data = mi.model()->data(mi, ROLE_WORKSPACE_ITEM); + Q_ASSERT(data.isValid()); + WorkspaceItem tv = data.value(); - if(tv.Type != WorkspaceItem::TYPE_REMOTE) - continue; + if (tv.Type != WorkspaceItem::TYPE_REMOTE) + continue; - QString url = tv.Value; - remoteUrls.append(url); - } + QString url = tv.Value; + remoteUrls.append(url); + } } //------------------------------------------------------------------------------ bool MainWindow::diffFile(const QString &repoFile) { - const QString &gdiff = settings.GetFossilValue(FOSSIL_SETTING_GDIFF_CMD).toString(); - if(!gdiff.isEmpty()) - return getWorkspace().diffFile(repoFile, true); - else - return getWorkspace().diffFile(repoFile, false); + const QString &gdiff = settings.GetFossilValue(FOSSIL_SETTING_GDIFF_CMD).toString(); + if (!gdiff.isEmpty()) + return getWorkspace().diffFile(repoFile, true); + else + return getWorkspace().diffFile(repoFile, false); } //------------------------------------------------------------------------------ void MainWindow::on_actionDiff_triggered() { - QStringList selection; - getSelectionFilenames(selection, WorkspaceFile::TYPE_REPO); + QStringList selection; + getSelectionFilenames(selection, WorkspaceFile::TYPE_REPO); - for(QStringList::iterator it = selection.begin(); it!=selection.end(); ++it) - if(!diffFile(*it)) - return; + for (QStringList::iterator it = selection.begin(); it != selection.end(); ++it) + if (!diffFile(*it)) + return; } //------------------------------------------------------------------------------ bool MainWindow::startUI() { - bool started = getWorkspace().fossil().startUI(""); - ui->actionFossilUI->setChecked(started); - return started; + bool started = getWorkspace().fossil().startUI(""); + ui->actionFossilUI->setChecked(started); + return started; } //------------------------------------------------------------------------------ void MainWindow::stopUI() { - getWorkspace().fossil().stopUI(); - ui->webView->load(QUrl("about:blank")); - ui->actionFossilUI->setChecked(false); + getWorkspace().fossil().stopUI(); + ui->webView->load(QUrl("about:blank")); + ui->actionFossilUI->setChecked(false); } //------------------------------------------------------------------------------ bool MainWindow::uiRunning() const { - return getWorkspace().fossil().uiRunning(); + return getWorkspace().fossil().uiRunning(); } //------------------------------------------------------------------------------ void MainWindow::on_actionFossilUI_triggered() { - if(!uiRunning() && ui->actionFossilUI->isChecked()) - { - startUI(); - fossilBrowse(""); - } - else - stopUI(); + if (!uiRunning() && ui->actionFossilUI->isChecked()) + { + startUI(); + fossilBrowse(""); + } + else + stopUI(); } //------------------------------------------------------------------------------ void MainWindow::on_actionQuit_triggered() { - close(); + close(); } //------------------------------------------------------------------------------ void MainWindow::on_actionTimeline_triggered() { - fossilBrowse("/timeline"); + fossilBrowse("/timeline"); } //------------------------------------------------------------------------------ void MainWindow::on_actionHistory_triggered() { - QStringList selection; - getSelectionFilenames(selection); + QStringList selection; + getSelectionFilenames(selection); - for(QStringList::iterator it = selection.begin(); it!=selection.end(); ++it) - fossilBrowse("/finfo?name="+*it); + for (QStringList::iterator it = selection.begin(); it != selection.end(); ++it) + fossilBrowse("/finfo?name=" + *it); } //------------------------------------------------------------------------------ -void MainWindow::on_fileTableView_doubleClicked(const QModelIndex &/*index*/) +void MainWindow::on_fileTableView_doubleClicked(const QModelIndex & /*index*/) { - int action = settings.GetValue(FUEL_SETTING_FILE_DBLCLICK).toInt(); - if(action==FILE_DLBCLICK_ACTION_DIFF) - on_actionDiff_triggered(); - else if(action==FILE_DLBCLICK_ACTION_OPEN) - on_actionOpenFile_triggered(); - else if(action==FILE_DLBCLICK_ACTION_OPENCONTAINING) - on_actionOpenContaining_triggered(); - else if(action==FILE_DLBCLICK_ACTION_CUSTOM) - invokeCustomAction(0); + int action = settings.GetValue(FUEL_SETTING_FILE_DBLCLICK).toInt(); + if (action == FILE_DLBCLICK_ACTION_DIFF) + on_actionDiff_triggered(); + else if (action == FILE_DLBCLICK_ACTION_OPEN) + on_actionOpenFile_triggered(); + else if (action == FILE_DLBCLICK_ACTION_OPENCONTAINING) + on_actionOpenContaining_triggered(); + else if (action == FILE_DLBCLICK_ACTION_CUSTOM) + invokeCustomAction(0); } //------------------------------------------------------------------------------ void MainWindow::on_actionOpenFile_triggered() { - QStringList selection; - getSelectionFilenames(selection); + QStringList selection; + getSelectionFilenames(selection); - for(QStringList::iterator it = selection.begin(); it!=selection.end(); ++it) - { - QDesktopServices::openUrl(QUrl::fromLocalFile(getWorkspace().getPath()+QDir::separator()+*it)); - } + for (QStringList::iterator it = selection.begin(); it != selection.end(); ++it) + { + QDesktopServices::openUrl(QUrl::fromLocalFile(getWorkspace().getPath() + QDir::separator() + *it)); + } } //------------------------------------------------------------------------------ void MainWindow::on_actionCommit_triggered() { - QStringList commit_files; - getSelectionFilenames(commit_files, WorkspaceFile::TYPE_MODIFIED, true); + QStringList commit_files; + getSelectionFilenames(commit_files, WorkspaceFile::TYPE_MODIFIED, true); - if(commit_files.empty() && !getWorkspace().otherChanges()) - return; + if (commit_files.empty() && !getWorkspace().otherChanges()) + return; - QStringList commit_msgs = settings.GetValue(FUEL_SETTING_COMMIT_MSG).toStringList(); + QStringList commit_msgs = settings.GetValue(FUEL_SETTING_COMMIT_MSG).toStringList(); - QString msg; - QString branch_name=""; - bool private_branch = false; - bool aborted = !CommitDialog::runCommit(this, commit_files, msg, commit_msgs, branch_name, private_branch); + QString msg; + QString branch_name = ""; + bool private_branch = false; + bool aborted = !CommitDialog::runCommit(this, commit_files, msg, commit_msgs, branch_name, private_branch); - // Aborted or not we always keep the commit messages. - // (This has saved me way too many times on TortoiseSVN) - if(commit_msgs.indexOf(msg)==-1) - { - commit_msgs.push_front(msg); - settings.SetValue(FUEL_SETTING_COMMIT_MSG, commit_msgs); - } + // Aborted or not we always keep the commit messages. + // (This has saved me way too many times on TortoiseSVN) + if (commit_msgs.indexOf(msg) == -1) + { + commit_msgs.push_front(msg); + settings.SetValue(FUEL_SETTING_COMMIT_MSG, commit_msgs); + } - if(aborted) - return; + if (aborted) + return; - // Since via the commit dialog the user can deselect all files - if(commit_files.empty() && !getWorkspace().otherChanges()) - return; + // Since via the commit dialog the user can deselect all files + if (commit_files.empty() && !getWorkspace().otherChanges()) + return; - // Do commit - QStringList files; + // Do commit + QStringList files; - // When a subset of files has been selected, explicitely specify each file. - // Otherwise all files will be implicitly committed by fossil. This is necessary - // when committing after a merge where fossil thinks that we are trying to do - // a partial commit which is not permitted. - QStringList all_modified_files; - getAllFilenames(all_modified_files, WorkspaceFile::TYPE_MODIFIED); + // When a subset of files has been selected, explicitely specify each file. + // Otherwise all files will be implicitly committed by fossil. This is necessary + // when committing after a merge where fossil thinks that we are trying to do + // a partial commit which is not permitted. + QStringList all_modified_files; + getAllFilenames(all_modified_files, WorkspaceFile::TYPE_MODIFIED); - if(commit_files.size() != all_modified_files.size()) - files = commit_files; + if (commit_files.size() != all_modified_files.size()) + files = commit_files; - if(!getWorkspace().commitFiles(files, msg, branch_name, private_branch)) - QMessageBox::critical(this, tr("Error"), tr("Could not commit changes."), QMessageBox::Ok); + if (!getWorkspace().commitFiles(files, msg, branch_name, private_branch)) + QMessageBox::critical(this, tr("Error"), tr("Could not commit changes."), QMessageBox::Ok); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionAdd_triggered() { - // Get unknown files only - QStringList selection; - getSelectionFilenames(selection, WorkspaceFile::TYPE_UNKNOWN); + // Get unknown files only + QStringList selection; + getSelectionFilenames(selection, WorkspaceFile::TYPE_UNKNOWN); - if(selection.empty()) - return; + if (selection.empty()) + return; - if(!FileActionDialog::run(this, tr("Add files"), tr("The following files will be added.")+"\n"+tr("Are you sure?"), selection)) - return; + if (!FileActionDialog::run(this, tr("Add files"), tr("The following files will be added.") + "\n" + tr("Are you sure?"), selection)) + return; - // Do Add - if(!getWorkspace().addFiles(selection)) - QMessageBox::critical(this, tr("Error"), tr("Could not add files."), QMessageBox::Ok); + // Do Add + if (!getWorkspace().addFiles(selection)) + QMessageBox::critical(this, tr("Error"), tr("Could not add files."), QMessageBox::Ok); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionDelete_triggered() { - QStringList repo_files; - getSelectionFilenames(repo_files, WorkspaceFile::TYPE_REPO); + QStringList repo_files; + getSelectionFilenames(repo_files, WorkspaceFile::TYPE_REPO); - QStringList unknown_files; - getSelectionFilenames(unknown_files, WorkspaceFile::TYPE_UNKNOWN); + QStringList unknown_files; + getSelectionFilenames(unknown_files, WorkspaceFile::TYPE_UNKNOWN); - QStringList all_files = repo_files+unknown_files; + QStringList all_files = repo_files + unknown_files; - if(all_files.empty()) - return; + if (all_files.empty()) + return; - bool remove_local = false; + bool remove_local = false; - if(!FileActionDialog::run(this, tr("Remove files"), tr("The following files will be removed from the repository.")+"\n"+tr("Are you sure?"), all_files, tr("Also delete the local files"), &remove_local )) - return; + if (!FileActionDialog::run(this, tr("Remove files"), tr("The following files will be removed from the repository.") + "\n" + tr("Are you sure?"), all_files, tr("Also delete the local files"), + &remove_local)) + return; - // Remove repository files - if(!repo_files.empty()) - { - if(!getWorkspace().removeFiles(repo_files, remove_local)) - QMessageBox::critical(this, tr("Error"), tr("Could not remove files."), QMessageBox::Ok); - } + // Remove repository files + if (!repo_files.empty()) + { + if (!getWorkspace().removeFiles(repo_files, remove_local)) + QMessageBox::critical(this, tr("Error"), tr("Could not remove files."), QMessageBox::Ok); + } - // Remove unknown local files if selected - if(remove_local) - { - for(int i=0; i0 && res[0]=="No undo or redo is available") - return; + if (res.length() > 0 && res[0] == "No undo or redo is available") + return; - if(!FileActionDialog::run(this, tr("Undo"), tr("The following actions will be undone.")+"\n"+tr("Are you sure?"), res)) - return; + if (!FileActionDialog::run(this, tr("Undo"), tr("The following actions will be undone.") + "\n" + tr("Are you sure?"), res)) + return; - // Do Undo - if(!getWorkspace().undo(res, false)) - QMessageBox::critical(this, tr("Error"), tr("Could not undo changes."), QMessageBox::Ok); + // Do Undo + if (!getWorkspace().undo(res, false)) + QMessageBox::critical(this, tr("Error"), tr("Could not undo changes."), QMessageBox::Ok); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionAbout_triggered() { - QString version; - getWorkspace().getInterfaceVersion(version); + QString version; + getWorkspace().getInterfaceVersion(version); - AboutDialog dlg(this, version); - dlg.exec(); + AboutDialog dlg(this, version); + dlg.exec(); } //------------------------------------------------------------------------------ void MainWindow::on_actionUpdate_triggered() { - QStringList selected = selectedBranches + selectedTags; + QStringList selected = selectedBranches + selectedTags; - QString revision; - if(!selected.isEmpty()) - revision = selected.first(); + QString revision; + if (!selected.isEmpty()) + revision = selected.first(); - updateRevision(revision); + updateRevision(revision); } //------------------------------------------------------------------------------ void MainWindow::loadFossilSettings() { - // Also retrieve the fossil global settings - QStringList out; + // Also retrieve the fossil global settings + QStringList out; - if(!getWorkspace().fossil().getSettings(out)) - return; + if (!getWorkspace().fossil().getSettings(out)) + return; - QStringMap kv; - ParseProperties(kv, out); + QStringMap kv; + ParseProperties(kv, out); - for(Settings::mappings_t::iterator it=settings.GetMappings().begin(); it!=settings.GetMappings().end(); ++it) - { - const QString &name = it.key(); - Settings::Setting::SettingType type = it->Type; + for (Settings::mappings_t::iterator it = settings.GetMappings().begin(); it != settings.GetMappings().end(); ++it) + { + const QString &name = it.key(); + Settings::Setting::SettingType type = it->Type; - Q_ASSERT(type == Settings::Setting::TYPE_FOSSIL_GLOBAL || type == Settings::Setting::TYPE_FOSSIL_LOCAL); - Q_UNUSED(type); + Q_ASSERT(type == Settings::Setting::TYPE_FOSSIL_GLOBAL || type == Settings::Setting::TYPE_FOSSIL_LOCAL); + Q_UNUSED(type); - // Otherwise it must be a fossil setting - if(!kv.contains(name)) - continue; + // Otherwise it must be a fossil setting + if (!kv.contains(name)) + continue; - QString value = kv[name]; - if(value.indexOf("(global)") != -1 || value.indexOf("(local)") != -1) - { - int i = value.indexOf(" "); - Q_ASSERT(i!=-1); - value = value.mid(i).trimmed(); + QString value = kv[name]; + if (value.indexOf("(global)") != -1 || value.indexOf("(local)") != -1) + { + int i = value.indexOf(" "); + Q_ASSERT(i != -1); + value = value.mid(i).trimmed(); - // Remove quotes if any - if(value.length()>=2 && value.at(0)=='\"' && value.at(value.length()-1)=='\"') - value = value.mid(1, value.length()-2); + // Remove quotes if any + if (value.length() >= 2 && value.at(0) == '\"' && value.at(value.length() - 1) == '\"') + value = value.mid(1, value.length() - 2); - it.value().Value = value; - } - } + it.value().Value = value; + } + } } //------------------------------------------------------------------------------ void MainWindow::on_actionSettings_triggered() { - // Run the dialog - if(!SettingsDialog::run(this, settings)) - return; + // Run the dialog + if (!SettingsDialog::run(this, settings)) + return; - getWorkspace().fossil().setExePath(settings.GetValue(FUEL_SETTING_FOSSIL_PATH).toString()); - updateCustomActions(); + getWorkspace().fossil().setExePath(settings.GetValue(FUEL_SETTING_FOSSIL_PATH).toString()); + updateCustomActions(); } //------------------------------------------------------------------------------ void MainWindow::on_actionFossilSettings_triggered() { - loadFossilSettings(); + loadFossilSettings(); - // Run the dialog - if(!FslSettingsDialog::run(this, settings)) - return; + // Run the dialog + if (!FslSettingsDialog::run(this, settings)) + return; - // Apply settings - for(Settings::mappings_t::iterator it=settings.GetMappings().begin(); it!=settings.GetMappings().end(); ++it) - { - const QString &name = it.key(); - Settings::Setting::SettingType type = it.value().Type; + // Apply settings + for (Settings::mappings_t::iterator it = settings.GetMappings().begin(); it != settings.GetMappings().end(); ++it) + { + const QString &name = it.key(); + Settings::Setting::SettingType type = it.value().Type; - Q_ASSERT(type == Settings::Setting::TYPE_FOSSIL_GLOBAL || type == Settings::Setting::TYPE_FOSSIL_LOCAL); + Q_ASSERT(type == Settings::Setting::TYPE_FOSSIL_GLOBAL || type == Settings::Setting::TYPE_FOSSIL_LOCAL); - QString value = it.value().Value.toString(); - getWorkspace().fossil().setSetting(name, value, type == Settings::Setting::TYPE_FOSSIL_GLOBAL); - } + QString value = it.value().Value.toString(); + getWorkspace().fossil().setSetting(name, value, type == Settings::Setting::TYPE_FOSSIL_GLOBAL); + } } //------------------------------------------------------------------------------ void MainWindow::on_actionViewModified_triggered() { - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionViewUnchanged_triggered() { - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionViewUnknown_triggered() { - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionViewIgnored_triggered() { - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionViewAll_triggered() { - ui->actionViewModified->setChecked(true); - ui->actionViewUnchanged->setChecked(true); - ui->actionViewUnknown->setChecked(true); - ui->actionViewIgnored->setChecked(true); - refresh(); + ui->actionViewModified->setChecked(true); + ui->actionViewUnchanged->setChecked(true); + ui->actionViewUnknown->setChecked(true); + ui->actionViewIgnored->setChecked(true); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionViewModifedOnly_triggered() { - ui->actionViewModified->setChecked(true); - ui->actionViewUnchanged->setChecked(false); - ui->actionViewUnknown->setChecked(false); - ui->actionViewIgnored->setChecked(false); - refresh(); + ui->actionViewModified->setChecked(true); + ui->actionViewUnchanged->setChecked(false); + ui->actionViewUnknown->setChecked(false); + ui->actionViewIgnored->setChecked(false); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionViewAsList_triggered() { - ui->actionViewAsFolders->setChecked(!ui->actionViewAsList->isChecked()); - viewMode = ui->actionViewAsList->isChecked() ? VIEWMODE_LIST : VIEWMODE_TREE; + ui->actionViewAsFolders->setChecked(!ui->actionViewAsList->isChecked()); + viewMode = ui->actionViewAsList->isChecked() ? VIEWMODE_LIST : VIEWMODE_TREE; - updateWorkspaceView(); - updateFileView(); + updateWorkspaceView(); + updateFileView(); } //------------------------------------------------------------------------------ void MainWindow::on_actionViewAsFolders_triggered() { - ui->actionViewAsList->setChecked(!ui->actionViewAsFolders->isChecked()); - viewMode = ui->actionViewAsList->isChecked() ? VIEWMODE_LIST : VIEWMODE_TREE; - updateWorkspaceView(); - updateFileView(); + ui->actionViewAsList->setChecked(!ui->actionViewAsFolders->isChecked()); + viewMode = ui->actionViewAsList->isChecked() ? VIEWMODE_LIST : VIEWMODE_TREE; + updateWorkspaceView(); + updateFileView(); } //------------------------------------------------------------------------------ -void MainWindow::onWorkspaceTreeViewSelectionChanged(const QItemSelection &/*selected*/, const QItemSelection &/*deselected*/) +void MainWindow::onWorkspaceTreeViewSelectionChanged(const QItemSelection & /*selected*/, const QItemSelection & /*deselected*/) { - QModelIndexList indices = ui->workspaceTreeView->selectionModel()->selectedIndexes(); + QModelIndexList indices = ui->workspaceTreeView->selectionModel()->selectedIndexes(); - // Do not modify the selection if nothing is selected - if(indices.empty()) - return; + // Do not modify the selection if nothing is selected + if (indices.empty()) + return; - stringset_t new_dirs; - selectedTags.clear(); - selectedBranches.clear(); + stringset_t new_dirs; + selectedTags.clear(); + selectedBranches.clear(); - foreach(const QModelIndex &id, indices) - { - QVariant data = id.model()->data(id, ROLE_WORKSPACE_ITEM); - Q_ASSERT(data.isValid()); - WorkspaceItem tv = data.value(); + foreach (const QModelIndex &id, indices) + { + QVariant data = id.model()->data(id, ROLE_WORKSPACE_ITEM); + Q_ASSERT(data.isValid()); + WorkspaceItem tv = data.value(); - if(tv.Type == WorkspaceItem::TYPE_FOLDER || tv.Type == WorkspaceItem::TYPE_WORKSPACE) - new_dirs.insert(tv.Value); - else if(tv.Type == WorkspaceItem::TYPE_TAG) - selectedTags.append(tv.Value); - else if(tv.Type == WorkspaceItem::TYPE_BRANCH) - selectedBranches.append(tv.Value); - } + if (tv.Type == WorkspaceItem::TYPE_FOLDER || tv.Type == WorkspaceItem::TYPE_WORKSPACE) + new_dirs.insert(tv.Value); + else if (tv.Type == WorkspaceItem::TYPE_TAG) + selectedTags.append(tv.Value); + else if (tv.Type == WorkspaceItem::TYPE_BRANCH) + selectedBranches.append(tv.Value); + } - // Update the selection if we have any new folders - if(!new_dirs.empty() && viewMode == VIEWMODE_TREE) - { - selectedDirs = new_dirs; - updateFileView(); - } + // Update the selection if we have any new folders + if (!new_dirs.empty() && viewMode == VIEWMODE_TREE) + { + selectedDirs = new_dirs; + updateFileView(); + } } //------------------------------------------------------------------------------ void MainWindow::on_actionOpenFolder_triggered() { - const QItemSelection &selection = ui->workspaceTreeView->selectionModel()->selection(); + const QItemSelection &selection = ui->workspaceTreeView->selectionModel()->selection(); - if(selection.indexes().count()!=1) - return; + if (selection.indexes().count() != 1) + return; - QModelIndex index = selection.indexes().at(0); - on_workspaceTreeView_doubleClicked(index); + QModelIndex index = selection.indexes().at(0); + on_workspaceTreeView_doubleClicked(index); } //------------------------------------------------------------------------------ void MainWindow::on_workspaceTreeView_doubleClicked(const QModelIndex &index) { - QVariant data = index.model()->data(index, ROLE_WORKSPACE_ITEM); - Q_ASSERT(data.isValid()); - WorkspaceItem tv = data.value(); + QVariant data = index.model()->data(index, ROLE_WORKSPACE_ITEM); + Q_ASSERT(data.isValid()); + WorkspaceItem tv = data.value(); - if(tv.Type==WorkspaceItem::TYPE_FOLDER || tv.Type==WorkspaceItem::TYPE_WORKSPACE) - { - QString target = getWorkspace().getPath() + PATH_SEPARATOR + tv.Value; - QUrl url = QUrl::fromLocalFile(target); - QDesktopServices::openUrl(url); - } - else if(tv.Type==WorkspaceItem::TYPE_REMOTE) - { - on_actionEditRemote_triggered(); - } + if (tv.Type == WorkspaceItem::TYPE_FOLDER || tv.Type == WorkspaceItem::TYPE_WORKSPACE) + { + QString target = getWorkspace().getPath() + PATH_SEPARATOR + tv.Value; + QUrl url = QUrl::fromLocalFile(target); + QDesktopServices::openUrl(url); + } + else if (tv.Type == WorkspaceItem::TYPE_REMOTE) + { + on_actionEditRemote_triggered(); + } } //------------------------------------------------------------------------------ void MainWindow::on_actionRenameFolder_triggered() { - stringset_t paths; - getSelectionPaths(paths); + stringset_t paths; + getSelectionPaths(paths); - if(paths.size()!=1) - return; + if (paths.size() != 1) + return; - QString old_path = *paths.begin(); + QString old_path = *paths.begin(); - // Root Node? - if(old_path.isEmpty()) - { - // Cannot change the project name via command line - // so unsupported - return; - } + // Root Node? + if (old_path.isEmpty()) + { + // Cannot change the project name via command line + // so unsupported + return; + } - int dir_start = old_path.lastIndexOf(PATH_SEPARATOR); - if(dir_start==-1) - dir_start = 0; - else - ++dir_start; + int dir_start = old_path.lastIndexOf(PATH_SEPARATOR); + if (dir_start == -1) + dir_start = 0; + else + ++dir_start; - QString old_name = old_path.mid(dir_start); + QString old_name = old_path.mid(dir_start); - bool ok = false; - QString new_name = QInputDialog::getText(this, tr("Rename Folder"), tr("New name"), QLineEdit::Normal, old_name, &ok, Qt::Sheet); - if(!ok || old_name==new_name) - return; + bool ok = false; + QString new_name = QInputDialog::getText(this, tr("Rename Folder"), tr("New name"), QLineEdit::Normal, old_name, &ok, Qt::Sheet); + if (!ok || old_name == new_name) + return; - const char* invalid_tokens[] = { - "/", "\\", "\\\\", ":", ">", "<", "*", "?", "|", "\"", ".." - }; + const char *invalid_tokens[] = {"/", "\\", "\\\\", ":", ">", "<", "*", "?", "|", "\"", ".."}; - for(size_t i=0; igetPath().indexOf(old_path)!=0) - continue; + // Collect the files to be moved + filelist_t files_to_move; + QStringList new_paths; + QStringList operations; + foreach (WorkspaceFile *r, getWorkspace().getFiles()) + { + if (r->getPath().indexOf(old_path) != 0) + continue; - files_to_move.append(r); - QString new_dir = new_path + r->getPath().mid(old_path.length()); - new_paths.append(new_dir); - QString new_file_path = new_dir + PATH_SEPARATOR + r->getFilename(); - operations.append(r->getFilePath() + " -> " + new_file_path); - } + files_to_move.append(r); + QString new_dir = new_path + r->getPath().mid(old_path.length()); + new_paths.append(new_dir); + QString new_file_path = new_dir + PATH_SEPARATOR + r->getFilename(); + operations.append(r->getFilePath() + " -> " + new_file_path); + } - if(files_to_move.empty()) - return; + if (files_to_move.empty()) + return; - bool move_local = false; - if(!FileActionDialog::run(this, tr("Rename Folder"), tr("Renaming folder '%0' to '%1'\n" - "The following files will be moved in the repository.").arg(old_path, new_path)+"\n"+tr("Are you sure?"), - operations, - tr("Also move the workspace files"), &move_local)) { - return; - } + bool move_local = false; + if (!FileActionDialog::run(this, tr("Rename Folder"), + tr("Renaming folder '%0' to '%1'\n" + "The following files will be moved in the repository.") + .arg(old_path, new_path) + + "\n" + tr("Are you sure?"), + operations, tr("Also move the workspace files"), &move_local)) + { + return; + } - // Rename files in fossil - Q_ASSERT(files_to_move.length() == new_paths.length()); - for(int i=0; igetFilename(); + // Rename files in fossil + Q_ASSERT(files_to_move.length() == new_paths.length()); + for (int i = 0; i < files_to_move.length(); ++i) + { + WorkspaceFile *r = files_to_move[i]; + const QString &new_file_path = new_paths[i] + PATH_SEPARATOR + r->getFilename(); - if(!getWorkspace().renameFile(r->getFilePath(), new_file_path, false)) - { - log(tr("Move aborted due to errors")+"\n"); - goto _exit; - } - } + if (!getWorkspace().renameFile(r->getFilePath(), new_file_path, false)) + { + log(tr("Move aborted due to errors") + "\n"); + goto _exit; + } + } - if(!move_local) - goto _exit; + if (!move_local) + goto _exit; - // First ensure that the target directories exist, and if not make them - for(int i=0; igetFilename(); + // Now that target directories exist copy files + for (int i = 0; i < files_to_move.length(); ++i) + { + WorkspaceFile *r = files_to_move[i]; + QString new_file_path = new_paths[i] + PATH_SEPARATOR + r->getFilename(); - if(QFile::exists(new_file_path)) - { - QMessageBox::critical(this, tr("Error"), tr("Target file '%0' exists already").arg(new_file_path)); - goto _exit; - } + if (QFile::exists(new_file_path)) + { + QMessageBox::critical(this, tr("Error"), tr("Target file '%0' exists already").arg(new_file_path)); + goto _exit; + } - log(tr("Copying file '%0' to '%1'").arg(r->getFilePath(), new_file_path)+"\n"); + log(tr("Copying file '%0' to '%1'").arg(r->getFilePath(), new_file_path) + "\n"); - if(!QFile::copy(r->getFilePath(), new_file_path)) - { - QMessageBox::critical(this, tr("Error"), tr("Cannot copy file '%0' to '%1'").arg(r->getFilePath(), new_file_path)); - goto _exit; - } - } + if (!QFile::copy(r->getFilePath(), new_file_path)) + { + QMessageBox::critical(this, tr("Error"), tr("Cannot copy file '%0' to '%1'").arg(r->getFilePath(), new_file_path)); + goto _exit; + } + } - // Finally delete old files - for(int i=0; igetFilePath())+"\n"); + log(tr("Removing old file '%0'").arg(r->getFilePath()) + "\n"); - if(!QFile::exists(r->getFilePath())) - { - QMessageBox::critical(this, tr("Error"), tr("Source file '%0' does not exist").arg(r->getFilePath())); - goto _exit; - } + if (!QFile::exists(r->getFilePath())) + { + QMessageBox::critical(this, tr("Error"), tr("Source file '%0' does not exist").arg(r->getFilePath())); + goto _exit; + } - if(!QFile::remove(r->getFilePath())) - { - QMessageBox::critical(this, tr("Error"), tr("Cannot remove file '%0'").arg(r->getFilePath())); - goto _exit; - } - } + if (!QFile::remove(r->getFilePath())) + { + QMessageBox::critical(this, tr("Error"), tr("Cannot remove file '%0'").arg(r->getFilePath())); + goto _exit; + } + } - log(tr("Folder renamed completed. Don't forget to commit!")+"\n"); + log(tr("Folder renamed completed. Don't forget to commit!") + "\n"); _exit: - refresh(); + refresh(); } //------------------------------------------------------------------------------ -QMenu * MainWindow::createPopupMenu() +QMenu *MainWindow::createPopupMenu() { - return NULL; + return NULL; } //------------------------------------------------------------------------------ -const QIcon &MainWindow::getCachedIcon(const char* name) +const QIcon &MainWindow::getCachedIcon(const char *name) { - if(!iconCache.contains(name)) - iconCache.insert(name, QIcon(name)); + if (!iconCache.contains(name)) + iconCache.insert(name, QIcon(name)); - return iconCache[name]; + return iconCache[name]; } //------------------------------------------------------------------------------ const QIcon &MainWindow::getCachedFileIcon(const QFileInfo &finfo) { - QString icon_type = iconProvider.type(finfo); + QString icon_type = iconProvider.type(finfo); - // Exe files have varying icons, so key on path - if(icon_type == "exe File") - icon_type = finfo.absoluteFilePath(); + // Exe files have varying icons, so key on path + if (icon_type == "exe File") + icon_type = finfo.absoluteFilePath(); - if(!iconCache.contains(icon_type)) - iconCache.insert(icon_type, iconProvider.icon(finfo)); + if (!iconCache.contains(icon_type)) + iconCache.insert(icon_type, iconProvider.icon(finfo)); - return iconCache[icon_type]; + return iconCache[icon_type]; } //------------------------------------------------------------------------------ void MainWindow::on_actionCreateStash_triggered() { - QStringList stashed_files; - getSelectionFilenames(stashed_files, WorkspaceFile::TYPE_MODIFIED, true); + QStringList stashed_files; + getSelectionFilenames(stashed_files, WorkspaceFile::TYPE_MODIFIED, true); - if(stashed_files.empty()) - return; + if (stashed_files.empty()) + return; - QString stash_name; - bool revert = false; + QString stash_name; + bool revert = false; - if(!CommitDialog::runStashNew(this, stashed_files, stash_name, revert) || stashed_files.empty()) - return; + if (!CommitDialog::runStashNew(this, stashed_files, stash_name, revert) || stashed_files.empty()) + return; - stash_name = stash_name.trimmed(); + stash_name = stash_name.trimmed(); - if(stash_name.indexOf("\"")!=-1 || stash_name.isEmpty()) - { - QMessageBox::critical(this, tr("Error"), tr("Invalid stash name")); - return; - } + if (stash_name.indexOf("\"") != -1 || stash_name.isEmpty()) + { + QMessageBox::critical(this, tr("Error"), tr("Invalid stash name")); + return; + } - // Check that this stash does not exist - for(stashmap_t::iterator it=getWorkspace().getStashes().begin(); it!=getWorkspace().getStashes().end(); ++it) - { - if(stash_name == it.key()) - { - QMessageBox::critical(this, tr("Error"), tr("This stash already exists")); - return; - } - } + // Check that this stash does not exist + for (stashmap_t::iterator it = getWorkspace().getStashes().begin(); it != getWorkspace().getStashes().end(); ++it) + { + if (stash_name == it.key()) + { + QMessageBox::critical(this, tr("Error"), tr("This stash already exists")); + return; + } + } - // Do Stash - if(!getWorkspace().stashNew(stashed_files, stash_name, revert)) - QMessageBox::critical(this, tr("Error"), tr("Could not create stash."), QMessageBox::Ok); + // Do Stash + if (!getWorkspace().stashNew(stashed_files, stash_name, revert)) + QMessageBox::critical(this, tr("Error"), tr("Could not create stash."), QMessageBox::Ok); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionApplyStash_triggered() { - QStringList stashes; - getSelectionStashes(stashes); + QStringList stashes; + getSelectionStashes(stashes); - if(stashes.empty()) - return; + if (stashes.empty()) + return; - bool delete_stashes = false; - if(!FileActionDialog::run(this, tr("Apply Stash"), tr("The following stashes will be applied.")+"\n"+tr("Are you sure?"), stashes, tr("Delete after applying"), &delete_stashes)) - return; + bool delete_stashes = false; + if (!FileActionDialog::run(this, tr("Apply Stash"), tr("The following stashes will be applied.") + "\n" + tr("Are you sure?"), stashes, tr("Delete after applying"), &delete_stashes)) + return; - // Apply stashes - for(QStringList::iterator it=stashes.begin(); it!=stashes.end(); ++it) - { - stashmap_t::iterator id_it = getWorkspace().getStashes().find(*it); - Q_ASSERT(id_it!=getWorkspace().getStashes().end()); + // Apply stashes + for (QStringList::iterator it = stashes.begin(); it != stashes.end(); ++it) + { + stashmap_t::iterator id_it = getWorkspace().getStashes().find(*it); + Q_ASSERT(id_it != getWorkspace().getStashes().end()); - if(!getWorkspace().stashApply(*id_it)) - { - log(tr("Stash application aborted due to errors")+"\n"); - QMessageBox::critical(this, tr("Error"), tr("Could not apply stash."), QMessageBox::Ok); - return; - } - } + if (!getWorkspace().stashApply(*id_it)) + { + log(tr("Stash application aborted due to errors") + "\n"); + QMessageBox::critical(this, tr("Error"), tr("Could not apply stash."), QMessageBox::Ok); + return; + } + } - // Delete stashes - for(QStringList::iterator it=stashes.begin(); delete_stashes && it!=stashes.end(); ++it) - { - stashmap_t::iterator id_it = getWorkspace().getStashes().find(*it); - Q_ASSERT(id_it!=getWorkspace().getStashes().end()); + // Delete stashes + for (QStringList::iterator it = stashes.begin(); delete_stashes && it != stashes.end(); ++it) + { + stashmap_t::iterator id_it = getWorkspace().getStashes().find(*it); + Q_ASSERT(id_it != getWorkspace().getStashes().end()); - if(!getWorkspace().stashDrop(*id_it)) - { - log(tr("Stash deletion aborted due to errors")+"\n"); - QMessageBox::critical(this, tr("Error"), tr("Could not delete stash."), QMessageBox::Ok); - return; - } - } + if (!getWorkspace().stashDrop(*id_it)) + { + log(tr("Stash deletion aborted due to errors") + "\n"); + QMessageBox::critical(this, tr("Error"), tr("Could not delete stash."), QMessageBox::Ok); + return; + } + } - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionDeleteStash_triggered() { - QStringList stashes; - getSelectionStashes(stashes); + QStringList stashes; + getSelectionStashes(stashes); - if(stashes.empty()) - return; + if (stashes.empty()) + return; - if(!FileActionDialog::run(this, tr("Delete Stashes"), tr("The following stashes will be deleted.")+"\n"+tr("Are you sure?"), stashes)) - return; + if (!FileActionDialog::run(this, tr("Delete Stashes"), tr("The following stashes will be deleted.") + "\n" + tr("Are you sure?"), stashes)) + return; - // Delete stashes - for(QStringList::iterator it=stashes.begin(); it!=stashes.end(); ++it) - { - stashmap_t::iterator id_it = getWorkspace().getStashes().find(*it); - Q_ASSERT(id_it!=getWorkspace().getStashes().end()); + // Delete stashes + for (QStringList::iterator it = stashes.begin(); it != stashes.end(); ++it) + { + stashmap_t::iterator id_it = getWorkspace().getStashes().find(*it); + Q_ASSERT(id_it != getWorkspace().getStashes().end()); - if(!getWorkspace().stashDrop(*id_it)) - { - log(tr("Stash deletion aborted due to errors")+"\n"); - QMessageBox::critical(this, tr("Error"), tr("Could not delete stash."), QMessageBox::Ok); - return; - } - } + if (!getWorkspace().stashDrop(*id_it)) + { + log(tr("Stash deletion aborted due to errors") + "\n"); + QMessageBox::critical(this, tr("Error"), tr("Could not delete stash."), QMessageBox::Ok); + return; + } + } - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionDiffStash_triggered() { - QStringList stashes; - getSelectionStashes(stashes); + QStringList stashes; + getSelectionStashes(stashes); - if(stashes.length() != 1) - return; + if (stashes.length() != 1) + return; - stashmap_t::iterator id_it = getWorkspace().getStashes().find(*stashes.begin()); - Q_ASSERT(id_it!=getWorkspace().getStashes().end()); + stashmap_t::iterator id_it = getWorkspace().getStashes().find(*stashes.begin()); + Q_ASSERT(id_it != getWorkspace().getStashes().end()); - // Run diff - if(!getWorkspace().stashDiff(*id_it)) - QMessageBox::critical(this, tr("Error"), tr("Could not diff stash."), QMessageBox::Ok); + // Run diff + if (!getWorkspace().stashDiff(*id_it)) + QMessageBox::critical(this, tr("Error"), tr("Could not diff stash."), QMessageBox::Ok); } //------------------------------------------------------------------------------ void MainWindow::onFileViewDragOut() { - QStringList filenames; - getFileViewSelection(filenames); + QStringList filenames; + getFileViewSelection(filenames); - if(filenames.isEmpty()) - return; + if (filenames.isEmpty()) + return; - QList urls; - foreach(QString f, filenames) - urls.append(QUrl::fromLocalFile(getWorkspace().getPath()+QDir::separator()+f)); + QList urls; + foreach (QString f, filenames) + urls.append(QUrl::fromLocalFile(getWorkspace().getPath() + QDir::separator() + f)); - QMimeData *mime_data = new QMimeData; - mime_data->setUrls(urls); + QMimeData *mime_data = new QMimeData; + mime_data->setUrls(urls); - QDrag *drag = new QDrag(this); - drag->setMimeData(mime_data); - drag->exec(Qt::CopyAction); + QDrag *drag = new QDrag(this); + drag->setMimeData(mime_data); + drag->exec(Qt::CopyAction); } //------------------------------------------------------------------------------ void MainWindow::on_textBrowser_customContextMenuRequested(const QPoint &pos) { - QMenu *menu = ui->textBrowser->createStandardContextMenu(); - menu->addSeparator(); - menu->addAction(ui->actionClearLog); - menu->popup(ui->textBrowser->mapToGlobal(pos)); + QMenu *menu = ui->textBrowser->createStandardContextMenu(); + menu->addSeparator(); + menu->addAction(ui->actionClearLog); + menu->popup(ui->textBrowser->mapToGlobal(pos)); } //------------------------------------------------------------------------------ void MainWindow::on_fileTableView_customContextMenuRequested(const QPoint &pos) { - QPoint gpos = QCursor::pos() + QPoint(1, 1); + QPoint gpos = QCursor::pos() + QPoint(1, 1); #ifdef Q_OS_WIN - if(qApp->keyboardModifiers() & Qt::SHIFT) - { - ui->fileTableView->selectionModel()->select(ui->fileTableView->indexAt(pos), QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows); - QStringList fnames; - getSelectionFilenames(fnames); + if (qApp->keyboardModifiers() & Qt::SHIFT) + { + ui->fileTableView->selectionModel()->select(ui->fileTableView->indexAt(pos), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); + QStringList fnames; + getSelectionFilenames(fnames); - if(fnames.size()==1) - { - QString fname = getWorkspace().getPath() + PATH_SEPARATOR + fnames[0]; - fname = QDir::toNativeSeparators(fname); - if(ShowExplorerMenu((HWND)winId(), fname, gpos)) - refresh(); - } - } - else + if (fnames.size() == 1) + { + QString fname = getWorkspace().getPath() + PATH_SEPARATOR + fnames[0]; + fname = QDir::toNativeSeparators(fname); + if (ShowExplorerMenu((HWND)winId(), fname, gpos)) + refresh(); + } + } + else #else - Q_UNUSED(pos); + Q_UNUSED(pos); #endif - { - QMenu *menu = new QMenu(this); - menu->addActions(ui->fileTableView->actions()); - menu->popup(gpos); - } - + { + QMenu *menu = new QMenu(this); + menu->addActions(ui->fileTableView->actions()); + menu->popup(gpos); + } } //------------------------------------------------------------------------------ void MainWindow::on_workspaceTreeView_customContextMenuRequested(const QPoint &pos) { - ui->workspaceTreeView->selectionModel()->select(ui->workspaceTreeView->indexAt(pos), QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows); - QModelIndexList indices = ui->workspaceTreeView->selectionModel()->selectedIndexes(); + ui->workspaceTreeView->selectionModel()->select(ui->workspaceTreeView->indexAt(pos), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); + QModelIndexList indices = ui->workspaceTreeView->selectionModel()->selectedIndexes(); - if(indices.empty()) - return; + if (indices.empty()) + return; - QPoint gpos = QCursor::pos() + QPoint(1, 1); - QMenu *menu = 0; + QPoint gpos = QCursor::pos() + QPoint(1, 1); + QMenu *menu = 0; - // Get first selected item - const QModelIndex &mi = indices.first(); - QVariant data = getWorkspace().getTreeModel().data(mi, ROLE_WORKSPACE_ITEM); - Q_ASSERT(data.isValid()); - WorkspaceItem tv = data.value(); + // Get first selected item + const QModelIndex &mi = indices.first(); + QVariant data = getWorkspace().getTreeModel().data(mi, ROLE_WORKSPACE_ITEM); + Q_ASSERT(data.isValid()); + WorkspaceItem tv = data.value(); - if(tv.Type == WorkspaceItem::TYPE_FOLDER || tv.Type == WorkspaceItem::TYPE_WORKSPACE) - { - #ifdef Q_OS_WIN - if(qApp->keyboardModifiers() & Qt::SHIFT) - { - QString fname = getWorkspace().getPath() + PATH_SEPARATOR + tv.Value; - fname = QDir::toNativeSeparators(fname); - ShowExplorerMenu((HWND)winId(), fname, gpos); - } - else - #endif - { - menu = menuWorkspace; - } - } - else if (tv.Type == WorkspaceItem::TYPE_STASH || tv.Type == WorkspaceItem::TYPE_STASHES) - menu = menuStashes; - else if (tv.Type == WorkspaceItem::TYPE_TAG || tv.Type == WorkspaceItem::TYPE_TAGS) - menu = menuTags; - else if (tv.Type == WorkspaceItem::TYPE_BRANCH || tv.Type == WorkspaceItem::TYPE_BRANCHES) - menu = menuBranches; - else if (tv.Type == WorkspaceItem::TYPE_REMOTE || tv.Type == WorkspaceItem::TYPE_REMOTES) - menu = menuRemotes; + if (tv.Type == WorkspaceItem::TYPE_FOLDER || tv.Type == WorkspaceItem::TYPE_WORKSPACE) + { +#ifdef Q_OS_WIN + if (qApp->keyboardModifiers() & Qt::SHIFT) + { + QString fname = getWorkspace().getPath() + PATH_SEPARATOR + tv.Value; + fname = QDir::toNativeSeparators(fname); + ShowExplorerMenu((HWND)winId(), fname, gpos); + } + else +#endif + { + menu = menuWorkspace; + } + } + else if (tv.Type == WorkspaceItem::TYPE_STASH || tv.Type == WorkspaceItem::TYPE_STASHES) + menu = menuStashes; + else if (tv.Type == WorkspaceItem::TYPE_TAG || tv.Type == WorkspaceItem::TYPE_TAGS) + menu = menuTags; + else if (tv.Type == WorkspaceItem::TYPE_BRANCH || tv.Type == WorkspaceItem::TYPE_BRANCHES) + menu = menuBranches; + else if (tv.Type == WorkspaceItem::TYPE_REMOTE || tv.Type == WorkspaceItem::TYPE_REMOTES) + menu = menuRemotes; - if(menu) - menu->popup(gpos); + if (menu) + menu->popup(gpos); } //------------------------------------------------------------------------------ void MainWindow::dragEnterEvent(QDragEnterEvent *event) { - // Ignore drops from the same window - if(event->source() != this) - event->acceptProposedAction(); + // Ignore drops from the same window + if (event->source() != this) + event->acceptProposedAction(); } //------------------------------------------------------------------------------ void MainWindow::dropEvent(QDropEvent *event) { - QList urls = event->mimeData()->urls(); + QList urls = event->mimeData()->urls(); - if(urls.length()==0) - return; + if (urls.length() == 0) + return; - // When dropping a folder or a checkout file, open the associated worksspace - QFileInfo finfo(urls.first().toLocalFile()); - if(finfo.isDir() || finfo.suffix() == FOSSIL_EXT || finfo.fileName() == FOSSIL_CHECKOUT1 || finfo.fileName() == FOSSIL_CHECKOUT2 ) - { - event->acceptProposedAction(); - openWorkspace(finfo.absoluteFilePath()); - } - else // Otherwise if not a workspace file and within a workspace, add - { - QStringList newfiles; + // When dropping a folder or a checkout file, open the associated worksspace + QFileInfo finfo(urls.first().toLocalFile()); + if (finfo.isDir() || finfo.suffix() == FOSSIL_EXT || finfo.fileName() == FOSSIL_CHECKOUT1 || finfo.fileName() == FOSSIL_CHECKOUT2) + { + event->acceptProposedAction(); + openWorkspace(finfo.absoluteFilePath()); + } + else // Otherwise if not a workspace file and within a workspace, add + { + QStringList newfiles; - Q_FOREACH(const QUrl &url, urls) - { - QFileInfo finfo(url.toLocalFile()); - QString abspath = finfo.absoluteFilePath(); + Q_FOREACH (const QUrl &url, urls) + { + QFileInfo finfo(url.toLocalFile()); + QString abspath = finfo.absoluteFilePath(); - // Within the current workspace ? - if(abspath.indexOf(getWorkspace().getPath())!=0) - continue; // skip + // Within the current workspace ? + if (abspath.indexOf(getWorkspace().getPath()) != 0) + continue; // skip - // Remove workspace from full path - QString wkpath = abspath.right(abspath.length()-getWorkspace().getPath().length()-1); + // Remove workspace from full path + QString wkpath = abspath.right(abspath.length() - getWorkspace().getPath().length() - 1); - newfiles.append(wkpath); - } + newfiles.append(wkpath); + } - // Any files to add? - if(!newfiles.empty()) - { - if(!FileActionDialog::run(this, tr("Add files"), tr("The following files will be added.")+"\n"+tr("Are you sure?"), newfiles)) - return; + // Any files to add? + if (!newfiles.empty()) + { + if (!FileActionDialog::run(this, tr("Add files"), tr("The following files will be added.") + "\n" + tr("Are you sure?"), newfiles)) + return; - // Do Add - if(!getWorkspace().addFiles(newfiles)) - QMessageBox::critical(this, tr("Error"), tr("Could not add files."), QMessageBox::Ok); + // Do Add + if (!getWorkspace().addFiles(newfiles)) + QMessageBox::critical(this, tr("Error"), tr("Could not add files."), QMessageBox::Ok); - refresh(); - } - } + refresh(); + } + } } //------------------------------------------------------------------------------ void MainWindow::setBusy(bool busy) { - if(busy) - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - else - QApplication::restoreOverrideCursor(); + if (busy) + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + else + QApplication::restoreOverrideCursor(); - ui->actionAbortOperation->setEnabled(busy); - bool enabled = !busy; - ui->menuBar->setEnabled(enabled); - ui->mainToolBar->setEnabled(enabled); - ui->centralWidget->setEnabled(enabled); + ui->actionAbortOperation->setEnabled(busy); + bool enabled = !busy; + ui->menuBar->setEnabled(enabled); + ui->mainToolBar->setEnabled(enabled); + ui->centralWidget->setEnabled(enabled); } //------------------------------------------------------------------------------ void MainWindow::on_actionAbortOperation_triggered() { - operationAborted = true; - uiCallback.abortProcess(); - log("
* "+tr("Operation Aborted")+" *
", true); + operationAborted = true; + uiCallback.abortProcess(); + log("
* " + tr("Operation Aborted") + " *
", true); } //------------------------------------------------------------------------------ void MainWindow::fullRefresh() { - refresh(); - // Select the Root of the tree to update the file view - selectRootDir(); + refresh(); + // Select the Root of the tree to update the file view + selectRootDir(); } //------------------------------------------------------------------------------ -void MainWindow::MainWinUICallback::logText(const QString& text, bool isHTML) +void MainWindow::MainWinUICallback::logText(const QString &text, bool isHTML) { - Q_ASSERT(mainWindow); - mainWindow->log(text, isHTML); + Q_ASSERT(mainWindow); + mainWindow->log(text, isHTML); } //------------------------------------------------------------------------------ -void MainWindow::MainWinUICallback::beginProcess(const QString& text) +void MainWindow::MainWinUICallback::beginProcess(const QString &text) { - Q_ASSERT(mainWindow); - aborted = false; - mainWindow->ui->statusBar->showMessage(text); - mainWindow->lblTags->setHidden(true); - mainWindow->progressBar->setHidden(false); - mainWindow->abortButton->setHidden(false); - mainWindow->ui->actionAbortOperation->setEnabled(true); - QCoreApplication::processEvents(); + Q_ASSERT(mainWindow); + aborted = false; + mainWindow->ui->statusBar->showMessage(text); + mainWindow->lblTags->setHidden(true); + mainWindow->progressBar->setHidden(false); + mainWindow->abortButton->setHidden(false); + mainWindow->ui->actionAbortOperation->setEnabled(true); + QCoreApplication::processEvents(); } //------------------------------------------------------------------------------ -void MainWindow::MainWinUICallback::updateProcess(const QString& text) +void MainWindow::MainWinUICallback::updateProcess(const QString &text) { - Q_ASSERT(mainWindow); - mainWindow->ui->statusBar->showMessage(text); - QCoreApplication::processEvents(); + Q_ASSERT(mainWindow); + mainWindow->ui->statusBar->showMessage(text); + QCoreApplication::processEvents(); } //------------------------------------------------------------------------------ void MainWindow::MainWinUICallback::endProcess() { - Q_ASSERT(mainWindow); - mainWindow->ui->statusBar->clearMessage(); - mainWindow->lblTags->setHidden(false); - mainWindow->progressBar->setHidden(true); - mainWindow->abortButton->setHidden(true); - mainWindow->ui->actionAbortOperation->setEnabled(false); - QCoreApplication::processEvents(); + Q_ASSERT(mainWindow); + mainWindow->ui->statusBar->clearMessage(); + mainWindow->lblTags->setHidden(false); + mainWindow->progressBar->setHidden(true); + mainWindow->abortButton->setHidden(true); + mainWindow->ui->actionAbortOperation->setEnabled(false); + QCoreApplication::processEvents(); } //------------------------------------------------------------------------------ QMessageBox::StandardButton MainWindow::MainWinUICallback::Query(const QString &title, const QString &query, QMessageBox::StandardButtons buttons) { - return DialogQuery(mainWindow, title, query, buttons); + return DialogQuery(mainWindow, title, query, buttons); } //------------------------------------------------------------------------------ void MainWindow::updateRevision(const QString &revision) { - const QString latest = tr(""); - QString defaultval = latest; + const QString latest = tr(""); + QString defaultval = latest; - if(!revision.isEmpty()) - defaultval = revision; + if (!revision.isEmpty()) + defaultval = revision; - // Also include our "Latest Revision" to the version list - QStringList versions = versionList; - versions.push_front(latest); + // Also include our "Latest Revision" to the version list + QStringList versions = versionList; + versions.push_front(latest); - QString selected_revision = RevisionDialog::runUpdate(this, tr("Update workspace"), versions, defaultval).trimmed(); + QString selected_revision = RevisionDialog::runUpdate(this, tr("Update workspace"), versions, defaultval).trimmed(); - // Nothing selected ? - if(selected_revision.isEmpty()) - return; - else if(selected_revision == latest) - selected_revision = ""; // Empty revision is "latest" + // Nothing selected ? + if (selected_revision.isEmpty()) + return; + else if (selected_revision == latest) + selected_revision = ""; // Empty revision is "latest" - QStringList res; + QStringList res; - // Do test update - if(!getWorkspace().update(res, selected_revision, true)) - { - QMessageBox::critical(this, tr("Error"), tr("Could not update the repository."), QMessageBox::Ok); - return; - } + // Do test update + if (!getWorkspace().update(res, selected_revision, true)) + { + QMessageBox::critical(this, tr("Error"), tr("Could not update the repository."), QMessageBox::Ok); + return; + } - if(res.length()==0) - return; + if (res.length() == 0) + return; - QStringMap kv; - ParseProperties(kv, res, ':'); + QStringMap kv; + ParseProperties(kv, res, ':'); - // If no changes exit - if(kv.contains("changes") && kv["changes"].indexOf("None.")!=-1) - return; + // If no changes exit + if (kv.contains("changes") && kv["changes"].indexOf("None.") != -1) + return; - if(!FileActionDialog::run(this, tr("Update"), tr("The following files will be updated.")+"\n"+tr("Are you sure?"), res)) - return; + if (!FileActionDialog::run(this, tr("Update"), tr("The following files will be updated.") + "\n" + tr("Are you sure?"), res)) + return; - // Do update - if(!getWorkspace().update(res, selected_revision, false)) - QMessageBox::critical(this, tr("Error"), tr("Could not update the repository."), QMessageBox::Ok); + // Do update + if (!getWorkspace().update(res, selected_revision, false)) + QMessageBox::critical(this, tr("Error"), tr("Could not update the repository."), QMessageBox::Ok); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionCreateTag_triggered() { - // Default to current revision - QString revision = getWorkspace().getCurrentRevision(); + // Default to current revision + QString revision = getWorkspace().getCurrentRevision(); - QString name; - if(!RevisionDialog::runNewTag(this, tr("Create Tag"), versionList, revision, revision, name)) - return; + QString name; + if (!RevisionDialog::runNewTag(this, tr("Create Tag"), versionList, revision, revision, name)) + return; - if(name.isEmpty() || getWorkspace().getTags().contains(name) || getWorkspace().getBranches().contains(name)) - { - QMessageBox::critical(this, tr("Error"), tr("Invalid name."), QMessageBox::Ok); - return; - } + if (name.isEmpty() || getWorkspace().getTags().contains(name) || getWorkspace().getBranches().contains(name)) + { + QMessageBox::critical(this, tr("Error"), tr("Invalid name."), QMessageBox::Ok); + return; + } - if(!getWorkspace().tagNew(name, revision)) - QMessageBox::critical(this, tr("Error"), tr("Could not create tag."), QMessageBox::Ok); + if (!getWorkspace().tagNew(name, revision)) + QMessageBox::critical(this, tr("Error"), tr("Could not create tag."), QMessageBox::Ok); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionDeleteTag_triggered() { - if(selectedTags.size()!=1) - return; + if (selectedTags.size() != 1) + return; - const QString &tagname = selectedTags.first(); + const QString &tagname = selectedTags.first(); - if(QMessageBox::Yes != DialogQuery(this, tr("Delete Tag"), tr("Are you sure want to delete the tag '%0' ?").arg(tagname))) - return; + if (QMessageBox::Yes != DialogQuery(this, tr("Delete Tag"), tr("Are you sure want to delete the tag '%0' ?").arg(tagname))) + return; - Q_ASSERT(getWorkspace().getTags().contains(tagname)); + Q_ASSERT(getWorkspace().getTags().contains(tagname)); - const QString &revision = getWorkspace().getTags()[tagname]; + const QString &revision = getWorkspace().getTags()[tagname]; - if(!getWorkspace().tagDelete(tagname, revision)) - QMessageBox::critical(this, tr("Error"), tr("Could not delete tag."), QMessageBox::Ok); + if (!getWorkspace().tagDelete(tagname, revision)) + QMessageBox::critical(this, tr("Error"), tr("Could not delete tag."), QMessageBox::Ok); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionCreateBranch_triggered() { - // Default to current revision - QString revision = getWorkspace().getCurrentRevision(); + // Default to current revision + QString revision = getWorkspace().getCurrentRevision(); - QString branch_name; - if(!RevisionDialog::runNewTag(this, tr("Create Branch"), versionList, revision, revision, branch_name)) - return; + QString branch_name; + if (!RevisionDialog::runNewTag(this, tr("Create Branch"), versionList, revision, revision, branch_name)) + return; - if(branch_name.isEmpty() || getWorkspace().getTags().contains(branch_name) || getWorkspace().getBranches().contains(branch_name)) - { - QMessageBox::critical(this, tr("Error"), tr("Invalid name."), QMessageBox::Ok); - return; - } + if (branch_name.isEmpty() || getWorkspace().getTags().contains(branch_name) || getWorkspace().getBranches().contains(branch_name)) + { + QMessageBox::critical(this, tr("Error"), tr("Invalid name."), QMessageBox::Ok); + return; + } - if(!getWorkspace().branchNew(branch_name, revision, false)) - { - QMessageBox::critical(this, tr("Error"), tr("Could not create branch."), QMessageBox::Ok); - return; - } + if (!getWorkspace().branchNew(branch_name, revision, false)) + { + QMessageBox::critical(this, tr("Error"), tr("Could not create branch."), QMessageBox::Ok); + return; + } - // Update to this branch. - updateRevision(branch_name); + // Update to this branch. + updateRevision(branch_name); } //------------------------------------------------------------------------------ void MainWindow::mergeRevision(const QString &defaultRevision) { - QStringList res; - QString revision = defaultRevision; + QStringList res; + QString revision = defaultRevision; - bool integrate = false; - bool force = false; - revision = RevisionDialog::runMerge(this, tr("Merge Branch"), versionList, revision, integrate, force); + bool integrate = false; + bool force = false; + revision = RevisionDialog::runMerge(this, tr("Merge Branch"), versionList, revision, integrate, force); - if(revision.isEmpty()) - return; + if (revision.isEmpty()) + return; - // Do test merge - if(!getWorkspace().branchMerge(res, revision, integrate, force, true)) - { - QMessageBox::critical(this, tr("Error"), tr("Merge failed."), QMessageBox::Ok); - return; - } + // Do test merge + if (!getWorkspace().branchMerge(res, revision, integrate, force, true)) + { + QMessageBox::critical(this, tr("Error"), tr("Merge failed."), QMessageBox::Ok); + return; + } - if(!FileActionDialog::run(this, tr("Merge"), tr("The following changes will be applied.")+"\n"+tr("Are you sure?"), res)) - return; + if (!FileActionDialog::run(this, tr("Merge"), tr("The following changes will be applied.") + "\n" + tr("Are you sure?"), res)) + return; - // Do update - if(!getWorkspace().branchMerge(res, revision, integrate, force, false)) - QMessageBox::critical(this, tr("Error"), tr("Merge failed."), QMessageBox::Ok); - else - log(tr("Merge completed. Don't forget to commit!")+"\n"); + // Do update + if (!getWorkspace().branchMerge(res, revision, integrate, force, false)) + QMessageBox::critical(this, tr("Error"), tr("Merge failed."), QMessageBox::Ok); + else + log(tr("Merge completed. Don't forget to commit!") + "\n"); - refresh(); + refresh(); } //------------------------------------------------------------------------------ void MainWindow::on_actionMergeBranch_triggered() { - QString revision; + QString revision; - if(!selectedBranches.isEmpty()) - revision = selectedBranches.first(); - mergeRevision(revision); + if (!selectedBranches.isEmpty()) + revision = selectedBranches.first(); + mergeRevision(revision); } //------------------------------------------------------------------------------ void MainWindow::onSearchBoxTextChanged(const QString &) { - updateFileView(); + updateFileView(); } //------------------------------------------------------------------------------ void MainWindow::onSearch() { - searchBox->selectAll(); - searchBox->setFocus(); + searchBox->selectAll(); + searchBox->setFocus(); } //------------------------------------------------------------------------------ void MainWindow::on_actionEditRemote_triggered() { - QStringList remotes; - getSelectionRemotes(remotes); - if(remotes.empty()) - return; + QStringList remotes; + getSelectionRemotes(remotes); + if (remotes.empty()) + return; - QUrl old_url(remotes.first()); + QUrl old_url(remotes.first()); - QString name; - Remote *remote = getWorkspace().findRemote(old_url); - if(remote) - name = remote->name; + QString name; + Remote *remote = getWorkspace().findRemote(old_url); + if (remote) + name = remote->name; - bool exists = KeychainGet(this, old_url, *settings.GetStore()); + bool exists = KeychainGet(this, old_url, *settings.GetStore()); - QUrl new_url = old_url; - if(!RemoteDialog::run(this, new_url, name)) - return; + QUrl new_url = old_url; + if (!RemoteDialog::run(this, new_url, name)) + return; - if(!new_url.isLocalFile()) - { - if(exists) - KeychainDelete(this, new_url, *settings.GetStore()); + if (!new_url.isLocalFile()) + { + if (exists) + KeychainDelete(this, new_url, *settings.GetStore()); - if(!KeychainSet(this, new_url, *settings.GetStore())) - QMessageBox::critical(this, tr("Error"), tr("Could not store information to keychain."), QMessageBox::Ok ); - } + if (!KeychainSet(this, new_url, *settings.GetStore())) + QMessageBox::critical(this, tr("Error"), tr("Could not store information to keychain."), QMessageBox::Ok); + } - // Remove password - new_url.setPassword(""); - old_url.setPassword(""); - // Url changed? - if(new_url != old_url) - { - getWorkspace().removeRemote(old_url); - getWorkspace().addRemote(new_url, name); - } - else // Just data changed - remote->name = name; + // Remove password + new_url.setPassword(""); + old_url.setPassword(""); + // Url changed? + if (new_url != old_url) + { + getWorkspace().removeRemote(old_url); + getWorkspace().addRemote(new_url, name); + } + else // Just data changed + remote->name = name; - updateWorkspaceView(); + updateWorkspaceView(); } //------------------------------------------------------------------------------ void MainWindow::on_actionPushRemote_triggered() { - QStringList remotes; - getSelectionRemotes(remotes); - if(remotes.empty()) - return; + QStringList remotes; + getSelectionRemotes(remotes); + if (remotes.empty()) + return; - QUrl url(remotes.first()); + QUrl url(remotes.first()); - // Retrieve password from keychain - if(!url.isLocalFile()) - KeychainGet(this, url, *settings.GetStore()); + // Retrieve password from keychain + if (!url.isLocalFile()) + KeychainGet(this, url, *settings.GetStore()); - if(!getWorkspace().push(url)) - QMessageBox::critical(this, tr("Error"), tr("Could not push to the remote repository."), QMessageBox::Ok); + if (!getWorkspace().push(url)) + QMessageBox::critical(this, tr("Error"), tr("Could not push to the remote repository."), QMessageBox::Ok); } //------------------------------------------------------------------------------ void MainWindow::on_actionPullRemote_triggered() { - QStringList remotes; - getSelectionRemotes(remotes); - if(remotes.empty()) - return; + QStringList remotes; + getSelectionRemotes(remotes); + if (remotes.empty()) + return; - QUrl url(remotes.first()); + QUrl url(remotes.first()); - // Retrieve password from keychain - if(!url.isLocalFile()) - KeychainGet(this, url, *settings.GetStore()); + // Retrieve password from keychain + if (!url.isLocalFile()) + KeychainGet(this, url, *settings.GetStore()); - if(!getWorkspace().pull(url)) - QMessageBox::critical(this, tr("Error"), tr("Could not pull from the remote repository."), QMessageBox::Ok); + if (!getWorkspace().pull(url)) + QMessageBox::critical(this, tr("Error"), tr("Could not pull from the remote repository."), QMessageBox::Ok); } //------------------------------------------------------------------------------ void MainWindow::on_actionPush_triggered() { - QUrl url = getWorkspace().getRemoteDefault(); + QUrl url = getWorkspace().getRemoteDefault(); - if(url.isEmpty()) - { - QMessageBox::critical(this, tr("Error"), tr("A default remote repository has not been specified."), QMessageBox::Ok); - return; - } + if (url.isEmpty()) + { + QMessageBox::critical(this, tr("Error"), tr("A default remote repository has not been specified."), QMessageBox::Ok); + return; + } - // Retrieve password from keychain - if(!url.isLocalFile()) - KeychainGet(this, url, *settings.GetStore()); + // Retrieve password from keychain + if (!url.isLocalFile()) + KeychainGet(this, url, *settings.GetStore()); - if(!getWorkspace().push(url)) - QMessageBox::critical(this, tr("Error"), tr("Could not push to the remote repository."), QMessageBox::Ok); + if (!getWorkspace().push(url)) + QMessageBox::critical(this, tr("Error"), tr("Could not push to the remote repository."), QMessageBox::Ok); } //------------------------------------------------------------------------------ void MainWindow::on_actionPull_triggered() { - QUrl url = getWorkspace().getRemoteDefault(); + QUrl url = getWorkspace().getRemoteDefault(); - if(url.isEmpty()) - { - QMessageBox::critical(this, tr("Error"), tr("A default remote repository has not been specified."), QMessageBox::Ok); - return; - } + if (url.isEmpty()) + { + QMessageBox::critical(this, tr("Error"), tr("A default remote repository has not been specified."), QMessageBox::Ok); + return; + } - // Retrieve password from keychain - if(!url.isLocalFile()) - KeychainGet(this, url, *settings.GetStore()); + // Retrieve password from keychain + if (!url.isLocalFile()) + KeychainGet(this, url, *settings.GetStore()); - if(!getWorkspace().pull(url)) - QMessageBox::critical(this, tr("Error"), tr("Could not pull from the remote repository."), QMessageBox::Ok); + if (!getWorkspace().pull(url)) + QMessageBox::critical(this, tr("Error"), tr("Could not pull from the remote repository."), QMessageBox::Ok); } //------------------------------------------------------------------------------ void MainWindow::on_actionSetDefaultRemote_triggered() { - QStringList remotes; - getSelectionRemotes(remotes); - if(remotes.empty()) - return; + QStringList remotes; + getSelectionRemotes(remotes); + if (remotes.empty()) + return; - QUrl url(remotes.first()); + QUrl url(remotes.first()); - if(getWorkspace().setRemoteDefault(url)) - { - if(!url.isLocalFile()) - KeychainGet(this, url, *settings.GetStore()); + if (getWorkspace().setRemoteDefault(url)) + { + if (!url.isLocalFile()) + KeychainGet(this, url, *settings.GetStore()); - // FIXME: Fossil currently ignores the password in "remote-url" - // which breaks commits due to a missing password when autosync is enabled - // so only set the remote url when there is no password set - if(url.password().isEmpty()) - { - if(!getWorkspace().fossil().setRemoteUrl(url)) - QMessageBox::critical(this, tr("Error"), tr("Could not set the remote repository."), QMessageBox::Ok); - } - } + // FIXME: Fossil currently ignores the password in "remote-url" + // which breaks commits due to a missing password when autosync is enabled + // so only set the remote url when there is no password set + if (url.password().isEmpty()) + { + if (!getWorkspace().fossil().setRemoteUrl(url)) + QMessageBox::critical(this, tr("Error"), tr("Could not set the remote repository."), QMessageBox::Ok); + } + } - updateWorkspaceView(); + updateWorkspaceView(); } //------------------------------------------------------------------------------ void MainWindow::on_actionAddRemote_triggered() { - QUrl url; - QString name; - if(!RemoteDialog::run(this, url, name)) - return; + QUrl url; + QString name; + if (!RemoteDialog::run(this, url, name)) + return; - if(!url.isLocalFile()) - { - KeychainDelete(this, url, *settings.GetStore()); + if (!url.isLocalFile()) + { + KeychainDelete(this, url, *settings.GetStore()); - if(!KeychainSet(this, url, *settings.GetStore())) - QMessageBox::critical(this, tr("Error"), tr("Could not store information to keychain."), QMessageBox::Ok); - } + if (!KeychainSet(this, url, *settings.GetStore())) + QMessageBox::critical(this, tr("Error"), tr("Could not store information to keychain."), QMessageBox::Ok); + } - url.setPassword(""); + url.setPassword(""); - getWorkspace().addRemote(url, name); - updateWorkspaceView(); + getWorkspace().addRemote(url, name); + updateWorkspaceView(); } //------------------------------------------------------------------------------ void MainWindow::on_actionDeleteRemote_triggered() { - QStringList remotes; - getSelectionRemotes(remotes); - if(remotes.empty()) - return; + QStringList remotes; + getSelectionRemotes(remotes); + if (remotes.empty()) + return; - QUrl url(remotes.first()); + QUrl url(remotes.first()); - Remote *remote = getWorkspace().findRemote(url); - Q_ASSERT(remote); + Remote *remote = getWorkspace().findRemote(url); + Q_ASSERT(remote); - if(QMessageBox::Yes != DialogQuery(this, tr("Delete Remote"), tr("Are you sure want to delete the remote '%0' ?").arg(remote->name))) - return; + if (QMessageBox::Yes != DialogQuery(this, tr("Delete Remote"), tr("Are you sure want to delete the remote '%0' ?").arg(remote->name))) + return; - getWorkspace().removeRemote(url); - updateWorkspaceView(); + getWorkspace().removeRemote(url); + updateWorkspaceView(); } //------------------------------------------------------------------------------ void MainWindow::updateCustomActions() { - Settings::custom_actions_t custom_actions = settings.GetCustomActions(); - Q_ASSERT(MAX_CUSTOM_ACTIONS == custom_actions.size()); + Settings::custom_actions_t custom_actions = settings.GetCustomActions(); + Q_ASSERT(MAX_CUSTOM_ACTIONS == custom_actions.size()); - // Remove All Actions - for(int i = 0; i < custom_actions.size(); ++i) - { - QAction *action = customActions[i]; - ui->fileTableView->removeAction(action); - menuWorkspace->removeAction(action); - } - ui->fileTableView->removeAction(fileActionSeparator); - menuWorkspace->removeAction(workspaceActionSeparator); + // Remove All Actions + for (int i = 0; i < custom_actions.size(); ++i) + { + QAction *action = customActions[i]; + ui->fileTableView->removeAction(action); + menuWorkspace->removeAction(action); + } + ui->fileTableView->removeAction(fileActionSeparator); + menuWorkspace->removeAction(workspaceActionSeparator); - // Add them to the top - ui->fileTableView->addAction(fileActionSeparator); - menuWorkspace->addAction(workspaceActionSeparator); + // Add them to the top + ui->fileTableView->addAction(fileActionSeparator); + menuWorkspace->addAction(workspaceActionSeparator); - bool has_file_actions = false; - bool has_folder_actions = false; + bool has_file_actions = false; + bool has_folder_actions = false; - for(int i = 0; i < custom_actions.size(); ++i) - { - CustomAction &cust_act = custom_actions[i]; - QAction *action = customActions[i]; - action->setVisible(cust_act.IsValid()); - action->setText(cust_act.Description); + for (int i = 0; i < custom_actions.size(); ++i) + { + CustomAction &cust_act = custom_actions[i]; + QAction *action = customActions[i]; + action->setVisible(cust_act.IsValid()); + action->setText(cust_act.Description); - if(!cust_act.IsValid()) - continue; + if (!cust_act.IsValid()) + continue; - // Attempt to extract an icon - QString cmd, extra_params; - SplitCommandLine(cust_act.Command, cmd, extra_params); - QFileInfo fi(cmd); - if(fi.isFile()) - action->setIcon(getCachedFileIcon(fi)); + // Attempt to extract an icon + QString cmd, extra_params; + SplitCommandLine(cust_act.Command, cmd, extra_params); + QFileInfo fi(cmd); + if (fi.isFile()) + action->setIcon(getCachedFileIcon(fi)); - if(cust_act.IsActive(ACTION_CONTEXT_FILES)) - { - ui->fileTableView->addAction(action); - has_file_actions = true; - } + if (cust_act.IsActive(ACTION_CONTEXT_FILES)) + { + ui->fileTableView->addAction(action); + has_file_actions = true; + } - if(cust_act.IsActive(ACTION_CONTEXT_FOLDERS)) - { - menuWorkspace->addAction(action); - has_folder_actions = true; - } - } + if (cust_act.IsActive(ACTION_CONTEXT_FOLDERS)) + { + menuWorkspace->addAction(action); + has_folder_actions = true; + } + } - if(!has_file_actions) - ui->fileTableView->removeAction(fileActionSeparator); + if (!has_file_actions) + ui->fileTableView->removeAction(fileActionSeparator); - if(!has_folder_actions) - menuWorkspace->removeAction(workspaceActionSeparator); + if (!has_folder_actions) + menuWorkspace->removeAction(workspaceActionSeparator); } //------------------------------------------------------------------------------ void MainWindow::invokeCustomAction(int actionId) { - Q_ASSERT(actionId < settings.GetCustomActions().size()); - CustomAction &cust_action = settings.GetCustomActions()[actionId]; - Q_ASSERT(cust_action.IsValid()); + Q_ASSERT(actionId < settings.GetCustomActions().size()); + CustomAction &cust_action = settings.GetCustomActions()[actionId]; + Q_ASSERT(cust_action.IsValid()); - Q_ASSERT(!cust_action.Command.isEmpty()); + Q_ASSERT(!cust_action.Command.isEmpty()); - QStringList file_selection; - if(cust_action.IsActive(ACTION_CONTEXT_FILES)) - getSelectionFilenames(file_selection, WorkspaceFile::TYPE_ALL); + QStringList file_selection; + if (cust_action.IsActive(ACTION_CONTEXT_FILES)) + getSelectionFilenames(file_selection, WorkspaceFile::TYPE_ALL); - stringset_t path_selection; - if(cust_action.IsActive(ACTION_CONTEXT_FOLDERS)) - getSelectionPaths(path_selection); + stringset_t path_selection; + if (cust_action.IsActive(ACTION_CONTEXT_FOLDERS)) + getSelectionPaths(path_selection); - // Trim excess items for single selection - if(!cust_action.MultipleSelection) - { - if(!file_selection.empty()) - { - QString item = *file_selection.begin(); - file_selection.clear(); - file_selection.push_back(item); - path_selection.clear(); - } - else if(!path_selection.empty()) - { - QString item = *path_selection.begin(); - path_selection.clear(); - path_selection.insert(item); - } - } + // Trim excess items for single selection + if (!cust_action.MultipleSelection) + { + if (!file_selection.empty()) + { + QString item = *file_selection.begin(); + file_selection.clear(); + file_selection.push_back(item); + path_selection.clear(); + } + else if (!path_selection.empty()) + { + QString item = *path_selection.begin(); + path_selection.clear(); + path_selection.insert(item); + } + } - const QString &wkdir = getWorkspace().getPath(); + const QString &wkdir = getWorkspace().getPath(); - SpawnExternalProcess(this, cust_action.Command, file_selection, path_selection, wkdir, uiCallback); + SpawnExternalProcess(this, cust_action.Command, file_selection, path_selection, wkdir, uiCallback); } //------------------------------------------------------------------------------ void MainWindow::onCustomActionTriggered() { - QAction *action = qobject_cast(sender()); - if(!action) - return; + QAction *action = qobject_cast(sender()); + if (!action) + return; - int action_id = action->data().toInt(); - invokeCustomAction(action_id); + int action_id = action->data().toInt(); + invokeCustomAction(action_id); } diff --git a/src/MainWindow.h b/src/MainWindow.h index ccadbca..6f5416d 100644 --- a/src/MainWindow.h +++ b/src/MainWindow.h @@ -1,14 +1,15 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include -#include -#include #include "AppSettings.h" #include "Workspace.h" +#include +#include +#include -namespace Ui { - class MainWindow; +namespace Ui +{ +class MainWindow; } ////////////////////////////////////////////////////////////////////////// @@ -16,195 +17,190 @@ namespace Ui { ////////////////////////////////////////////////////////////////////////// class MainWindow : public QMainWindow { - Q_OBJECT + Q_OBJECT public: - explicit MainWindow(Settings &_settings, QWidget *parent = 0, QString *workspacePath = 0); - ~MainWindow(); - bool diffFile(const QString& repoFile); - void fullRefresh(); + explicit MainWindow(Settings &_settings, QWidget *parent = 0, QString *workspacePath = 0); + ~MainWindow(); + bool diffFile(const QString &repoFile); + void fullRefresh(); private: - bool refresh(); - bool scanWorkspace(); - void applySettings(); - void updateSettings(); - void updateRevision(const QString& revision); - void setCurrentWorkspace(const QString &workspace); - void log(const QString &text, bool isHTML=false); - void setStatus(const QString &text); - bool uiRunning() const; - void getSelectionFilenames(QStringList &filenames, int includeMask=WorkspaceFile::TYPE_ALL, bool allIfEmpty=false); - void getFileViewSelection(QStringList &filenames, int includeMask=WorkspaceFile::TYPE_ALL, bool allIfEmpty=false); - void getDirViewSelection(QStringList &filenames, int includeMask=WorkspaceFile::TYPE_ALL, bool allIfEmpty=false); - void getSelectionStashes(QStringList &stashNames); - void getSelectionPaths(stringset_t &paths); - void getSelectionRemotes(QStringList& remoteUrls); - void getAllFilenames(QStringList &filenames, int includeMask=WorkspaceFile::TYPE_ALL); - bool startUI(); - void stopUI(); - void enableActions(bool on); - void addWorkspaceHistory(const QString &dir); - void rebuildRecent(); - bool openWorkspace(const QString &path); - void loadFossilSettings(); - void updateWorkspaceView(); - void updateFileView(); - void selectRootDir(); - void mergeRevision(const QString& defaultRevision); - void updateCustomActions(); - void invokeCustomAction(int actionId); + bool refresh(); + bool scanWorkspace(); + void applySettings(); + void updateSettings(); + void updateRevision(const QString &revision); + void setCurrentWorkspace(const QString &workspace); + void log(const QString &text, bool isHTML = false); + void setStatus(const QString &text); + bool uiRunning() const; + void getSelectionFilenames(QStringList &filenames, int includeMask = WorkspaceFile::TYPE_ALL, bool allIfEmpty = false); + void getFileViewSelection(QStringList &filenames, int includeMask = WorkspaceFile::TYPE_ALL, bool allIfEmpty = false); + void getDirViewSelection(QStringList &filenames, int includeMask = WorkspaceFile::TYPE_ALL, bool allIfEmpty = false); + void getSelectionStashes(QStringList &stashNames); + void getSelectionPaths(stringset_t &paths); + void getSelectionRemotes(QStringList &remoteUrls); + void getAllFilenames(QStringList &filenames, int includeMask = WorkspaceFile::TYPE_ALL); + bool startUI(); + void stopUI(); + void enableActions(bool on); + void addWorkspaceHistory(const QString &dir); + void rebuildRecent(); + bool openWorkspace(const QString &path); + void loadFossilSettings(); + void updateWorkspaceView(); + void updateFileView(); + void selectRootDir(); + void mergeRevision(const QString &defaultRevision); + void updateCustomActions(); + void invokeCustomAction(int actionId); - void fossilBrowse(const QString &fossilUrl); - void dragEnterEvent(class QDragEnterEvent *event); - void dropEvent(class QDropEvent *event); - void setBusy(bool busy); - virtual QMenu *createPopupMenu(); - const QIcon& getCachedIcon(const char *name); - const QIcon& getCachedFileIcon(const QFileInfo &finfo); + void fossilBrowse(const QString &fossilUrl); + void dragEnterEvent(class QDragEnterEvent *event); + void dropEvent(class QDropEvent *event); + void setBusy(bool busy); + virtual QMenu *createPopupMenu(); + const QIcon &getCachedIcon(const char *name); + const QIcon &getCachedFileIcon(const QFileInfo &finfo); - enum ViewMode - { - VIEWMODE_LIST, - VIEWMODE_TREE - }; + enum ViewMode + { + VIEWMODE_LIST, + VIEWMODE_TREE + }; private slots: - // Manual slots. - // Use a different naming scheme to prevent warnings from Qt's automatic signaling - void onOpenRecent(); - void onWorkspaceTreeViewSelectionChanged(const class QItemSelection &selected, const class QItemSelection &deselected); - void onFileViewDragOut(); - void onSearchBoxTextChanged(const QString &text); - void onSearch(); - void onCustomActionTriggered(); + // Manual slots. + // Use a different naming scheme to prevent warnings from Qt's automatic signaling + void onOpenRecent(); + void onWorkspaceTreeViewSelectionChanged(const class QItemSelection &selected, const class QItemSelection &deselected); + void onFileViewDragOut(); + void onSearchBoxTextChanged(const QString &text); + void onSearch(); + void onCustomActionTriggered(); - // Designer slots - void on_actionRefresh_triggered(); - void on_actionDiff_triggered(); - void on_actionFossilUI_triggered(); - void on_actionQuit_triggered(); - void on_actionTimeline_triggered(); - void on_actionHistory_triggered(); - void on_actionClearLog_triggered(); - void on_fileTableView_doubleClicked(const QModelIndex &index); - void on_workspaceTreeView_doubleClicked(const QModelIndex &index); - void on_actionOpenFile_triggered(); - void on_actionPush_triggered(); - void on_actionPull_triggered(); - void on_actionPushRemote_triggered(); - void on_actionPullRemote_triggered(); - void on_actionCommit_triggered(); - void on_actionAdd_triggered(); - void on_actionDelete_triggered(); - void on_actionRevert_triggered(); - void on_actionOpenContaining_triggered(); - void on_actionRename_triggered(); - void on_actionUndo_triggered(); - void on_actionAbout_triggered(); - void on_actionUpdate_triggered(); - void on_actionSettings_triggered(); - void on_actionFossilSettings_triggered(); - void on_actionViewUnchanged_triggered(); - void on_actionViewModified_triggered(); - void on_actionViewUnknown_triggered(); - void on_actionViewIgnored_triggered(); - void on_actionViewAll_triggered(); - void on_actionViewModifedOnly_triggered(); - void on_actionViewAsList_triggered(); - void on_actionViewAsFolders_triggered(); - void on_actionOpenFolder_triggered(); - void on_actionRenameFolder_triggered(); - void on_actionNewRepository_triggered(); - void on_actionOpenRepository_triggered(); - void on_actionCloseRepository_triggered(); - void on_actionCloneRepository_triggered(); - void on_actionCreateStash_triggered(); - void on_actionApplyStash_triggered(); - void on_actionDeleteStash_triggered(); - void on_actionDiffStash_triggered(); - void on_textBrowser_customContextMenuRequested(const QPoint &pos); - void on_fileTableView_customContextMenuRequested(const QPoint &pos); - void on_workspaceTreeView_customContextMenuRequested(const QPoint &pos); - void on_actionCreateTag_triggered(); - void on_actionDeleteTag_triggered(); - void on_actionCreateBranch_triggered(); - void on_actionMergeBranch_triggered(); - void on_actionEditRemote_triggered(); - void on_actionSetDefaultRemote_triggered(); - void on_actionAddRemote_triggered(); - void on_actionDeleteRemote_triggered(); - void on_actionAbortOperation_triggered(); + // Designer slots + void on_actionRefresh_triggered(); + void on_actionDiff_triggered(); + void on_actionFossilUI_triggered(); + void on_actionQuit_triggered(); + void on_actionTimeline_triggered(); + void on_actionHistory_triggered(); + void on_actionClearLog_triggered(); + void on_fileTableView_doubleClicked(const QModelIndex &index); + void on_workspaceTreeView_doubleClicked(const QModelIndex &index); + void on_actionOpenFile_triggered(); + void on_actionPush_triggered(); + void on_actionPull_triggered(); + void on_actionPushRemote_triggered(); + void on_actionPullRemote_triggered(); + void on_actionCommit_triggered(); + void on_actionAdd_triggered(); + void on_actionDelete_triggered(); + void on_actionRevert_triggered(); + void on_actionOpenContaining_triggered(); + void on_actionRename_triggered(); + void on_actionUndo_triggered(); + void on_actionAbout_triggered(); + void on_actionUpdate_triggered(); + void on_actionSettings_triggered(); + void on_actionFossilSettings_triggered(); + void on_actionViewUnchanged_triggered(); + void on_actionViewModified_triggered(); + void on_actionViewUnknown_triggered(); + void on_actionViewIgnored_triggered(); + void on_actionViewAll_triggered(); + void on_actionViewModifedOnly_triggered(); + void on_actionViewAsList_triggered(); + void on_actionViewAsFolders_triggered(); + void on_actionOpenFolder_triggered(); + void on_actionRenameFolder_triggered(); + void on_actionNewRepository_triggered(); + void on_actionOpenRepository_triggered(); + void on_actionCloseRepository_triggered(); + void on_actionCloneRepository_triggered(); + void on_actionCreateStash_triggered(); + void on_actionApplyStash_triggered(); + void on_actionDeleteStash_triggered(); + void on_actionDiffStash_triggered(); + void on_textBrowser_customContextMenuRequested(const QPoint &pos); + void on_fileTableView_customContextMenuRequested(const QPoint &pos); + void on_workspaceTreeView_customContextMenuRequested(const QPoint &pos); + void on_actionCreateTag_triggered(); + void on_actionDeleteTag_triggered(); + void on_actionCreateBranch_triggered(); + void on_actionMergeBranch_triggered(); + void on_actionEditRemote_triggered(); + void on_actionSetDefaultRemote_triggered(); + void on_actionAddRemote_triggered(); + void on_actionDeleteRemote_triggered(); + void on_actionAbortOperation_triggered(); private: - class MainWinUICallback : public UICallback - { - public: - MainWinUICallback() : mainWindow(0), aborted(false) - {} + class MainWinUICallback : public UICallback + { + public: + MainWinUICallback() : mainWindow(0), aborted(false) {} - void init(class MainWindow *mainWindow) - { - this->mainWindow = mainWindow; - } + void init(class MainWindow *mainWindow) { this->mainWindow = mainWindow; } - virtual void logText(const QString& text, bool isHTML); - virtual void beginProcess(const QString& text); - virtual void updateProcess(const QString& text); - virtual bool processAborted() const { return aborted; } - virtual void endProcess(); - virtual QMessageBox::StandardButton Query(const QString &title, const QString &query, QMessageBox::StandardButtons buttons); - void abortProcess() { aborted = true; } + virtual void logText(const QString &text, bool isHTML); + virtual void beginProcess(const QString &text); + virtual void updateProcess(const QString &text); + virtual bool processAborted() const { return aborted; } + virtual void endProcess(); + virtual QMessageBox::StandardButton Query(const QString &title, const QString &query, QMessageBox::StandardButtons buttons); + void abortProcess() { aborted = true; } - private: - class MainWindow *mainWindow; - bool aborted; - }; + private: + class MainWindow *mainWindow; + bool aborted; + }; - friend class MainWinUICallback; + friend class MainWinUICallback; - enum - { - MAX_RECENT=5 - }; + enum + { + MAX_RECENT = 5 + }; - typedef QMap icon_map_t; + typedef QMap icon_map_t; - Ui::MainWindow *ui; - QFileIconProvider iconProvider; - icon_map_t iconCache; - class QAction *recentWorkspaceActs[MAX_RECENT]; - class QAction *customActions[MAX_CUSTOM_ACTIONS]; - class QAction *fileActionSeparator; - class QAction *workspaceActionSeparator; - class QProgressBar *progressBar; - class QToolButton *abortButton; - class QLabel *lblTags; - class SearchBox *searchBox; - class QShortcut *searchShortcut; - QMenu *menuWorkspace; - QMenu *menuStashes; - QMenu *menuTags; - QMenu *menuBranches; - QMenu *menuRemotes; + Ui::MainWindow *ui; + QFileIconProvider iconProvider; + icon_map_t iconCache; + class QAction *recentWorkspaceActs[MAX_RECENT]; + class QAction *customActions[MAX_CUSTOM_ACTIONS]; + class QAction *fileActionSeparator; + class QAction *workspaceActionSeparator; + class QProgressBar *progressBar; + class QToolButton *abortButton; + class QLabel *lblTags; + class SearchBox *searchBox; + class QShortcut *searchShortcut; + QMenu *menuWorkspace; + QMenu *menuStashes; + QMenu *menuTags; + QMenu *menuBranches; + QMenu *menuRemotes; - bool operationAborted; - stringset_t selectedDirs; // The directory selected in the tree - QStringList selectedTags; - QStringList selectedBranches; - QStringList versionList; + bool operationAborted; + stringset_t selectedDirs; // The directory selected in the tree + QStringList selectedTags; + QStringList selectedBranches; + QStringList versionList; - Workspace workspace; - Workspace & getWorkspace() { return workspace; } - const Workspace & getWorkspace() const { return workspace; } + Workspace workspace; + Workspace &getWorkspace() { return workspace; } + const Workspace &getWorkspace() const { return workspace; } - Settings &settings; - QStringList workspaceHistory; + Settings &settings; + QStringList workspaceHistory; - MainWinUICallback uiCallback; + MainWinUICallback uiCallback; - ViewMode viewMode; + ViewMode viewMode; }; -#endif // MAINWINDOW_H - +#endif // MAINWINDOW_H diff --git a/src/RemoteDialog.cpp b/src/RemoteDialog.cpp index bf6ab7c..d922666 100644 --- a/src/RemoteDialog.cpp +++ b/src/RemoteDialog.cpp @@ -1,107 +1,98 @@ #include "RemoteDialog.h" -#include "ui_RemoteDialog.h" -#include -#include -#include -#include -#include #include "Utils.h" +#include "ui_RemoteDialog.h" +#include +#include +#include +#include +#include //----------------------------------------------------------------------------- -RemoteDialog::RemoteDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::RemoteDialog) +RemoteDialog::RemoteDialog(QWidget *parent) : QDialog(parent), ui(new Ui::RemoteDialog) { - ui->setupUi(this); + ui->setupUi(this); } //----------------------------------------------------------------------------- RemoteDialog::~RemoteDialog() { - delete ui; + delete ui; } //----------------------------------------------------------------------------- bool RemoteDialog::run(QWidget *parent, QUrl &url, QString &name) { - RemoteDialog dlg(parent); + RemoteDialog dlg(parent); - // Set URL components - if(!url.isEmpty()) - { - dlg.ui->lineName->setText(name); + // Set URL components + if (!url.isEmpty()) + { + dlg.ui->lineName->setText(name); - if(url.isLocalFile()) - dlg.ui->lineURL->setText(QDir::toNativeSeparators(url.toLocalFile())); - else - { - QString url_no_credentials = UrlToStringNoCredentials(url); - dlg.ui->lineURL->setText(url_no_credentials); - dlg.ui->lineUserName->setText(url.userName()); - dlg.ui->linePassword->setText(url.password()); - } - } + if (url.isLocalFile()) + dlg.ui->lineURL->setText(QDir::toNativeSeparators(url.toLocalFile())); + else + { + QString url_no_credentials = UrlToStringNoCredentials(url); + dlg.ui->lineURL->setText(url_no_credentials); + dlg.ui->lineUserName->setText(url.userName()); + dlg.ui->linePassword->setText(url.password()); + } + } - if(dlg.exec() != QDialog::Accepted) - return false; + if (dlg.exec() != QDialog::Accepted) + return false; - QString urltext = dlg.ui->lineURL->text(); + QString urltext = dlg.ui->lineURL->text(); - // Check if the url is a local file - if(QFileInfo(urltext).exists()) - url = QUrl::fromLocalFile(urltext); - else - { - url = QUrl::fromUserInput(urltext); - if(url.isEmpty() || !url.isValid()) - { - QMessageBox::critical(parent, tr("Error"), tr("Invalid URL."), QMessageBox::Ok ); - return false; - } - } + // Check if the url is a local file + if (QFileInfo(urltext).exists()) + url = QUrl::fromLocalFile(urltext); + else + { + url = QUrl::fromUserInput(urltext); + if (url.isEmpty() || !url.isValid()) + { + QMessageBox::critical(parent, tr("Error"), tr("Invalid URL."), QMessageBox::Ok); + return false; + } + } - if(!dlg.ui->lineUserName->text().trimmed().isEmpty()) - url.setUserName(dlg.ui->lineUserName->text()); + if (!dlg.ui->lineUserName->text().trimmed().isEmpty()) + url.setUserName(dlg.ui->lineUserName->text()); - if(!dlg.ui->linePassword->text().trimmed().isEmpty()) - url.setPassword(dlg.ui->linePassword->text()); + if (!dlg.ui->linePassword->text().trimmed().isEmpty()) + url.setPassword(dlg.ui->linePassword->text()); - name = dlg.ui->lineName->text().trimmed(); - if(name.isEmpty()) - name = UrlToStringNoCredentials(url); + name = dlg.ui->lineName->text().trimmed(); + if (name.isEmpty()) + name = UrlToStringNoCredentials(url); - return true; + return true; } //----------------------------------------------------------------------------- void RemoteDialog::GetRepositoryPath(QString &pathResult) { - QString filter(tr("Fossil Repository") + QString(" (*." FOSSIL_EXT ")")); + QString filter(tr("Fossil Repository") + QString(" (*." FOSSIL_EXT ")")); - pathResult = QFileDialog::getSaveFileName( - this, - tr("Select Fossil Repository"), - QDir::toNativeSeparators(pathResult), - filter, - &filter, - QFileDialog::DontConfirmOverwrite); + pathResult = QFileDialog::getSaveFileName(this, tr("Select Fossil Repository"), QDir::toNativeSeparators(pathResult), filter, &filter, QFileDialog::DontConfirmOverwrite); } //----------------------------------------------------------------------------- void RemoteDialog::on_btnSelectSourceRepo_clicked() { - QString path = ui->lineURL->text(); - GetRepositoryPath(path); + QString path = ui->lineURL->text(); + GetRepositoryPath(path); - if(path.trimmed().isEmpty()) - return; + if (path.trimmed().isEmpty()) + return; - if(!QFile::exists(path)) - { - QMessageBox::critical(this, tr("Error"), tr("Invalid Repository File."), QMessageBox::Ok); - return; - } + if (!QFile::exists(path)) + { + QMessageBox::critical(this, tr("Error"), tr("Invalid Repository File."), QMessageBox::Ok); + return; + } - ui->lineURL->setText(QDir::toNativeSeparators(path)); + ui->lineURL->setText(QDir::toNativeSeparators(path)); } - diff --git a/src/RemoteDialog.h b/src/RemoteDialog.h index afd30e9..7fc1319 100644 --- a/src/RemoteDialog.h +++ b/src/RemoteDialog.h @@ -3,27 +3,28 @@ #include -namespace Ui { +namespace Ui +{ class RemoteDialog; } class RemoteDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit RemoteDialog(QWidget *parent = 0); - ~RemoteDialog(); + explicit RemoteDialog(QWidget *parent = 0); + ~RemoteDialog(); - static bool run(QWidget *parent, class QUrl &url, QString &name); + static bool run(QWidget *parent, class QUrl &url, QString &name); private slots: - void on_btnSelectSourceRepo_clicked(); + void on_btnSelectSourceRepo_clicked(); private: - void GetRepositoryPath(QString &pathResult); + void GetRepositoryPath(QString &pathResult); - Ui::RemoteDialog *ui; + Ui::RemoteDialog *ui; }; -#endif // REMOTEDIALOG_H +#endif // REMOTEDIALOG_H diff --git a/src/RevisionDialog.cpp b/src/RevisionDialog.cpp index ed8b2a6..303ca93 100644 --- a/src/RevisionDialog.cpp +++ b/src/RevisionDialog.cpp @@ -1,100 +1,96 @@ #include "RevisionDialog.h" -#include "ui_RevisionDialog.h" #include "Utils.h" +#include "ui_RevisionDialog.h" //----------------------------------------------------------------------------- -RevisionDialog::RevisionDialog(QWidget *parent, const QStringList &completions, const QString &defaultValue) : - QDialog(parent), - ui(new Ui::RevisionDialog), - completer(completions, parent) +RevisionDialog::RevisionDialog(QWidget *parent, const QStringList &completions, const QString &defaultValue) : QDialog(parent), ui(new Ui::RevisionDialog), completer(completions, parent) { - ui->setupUi(this); - ui->cmbRevision->setCompleter(&completer); + ui->setupUi(this); + ui->cmbRevision->setCompleter(&completer); - ui->cmbRevision->addItems(completions); + ui->cmbRevision->addItems(completions); - if(!defaultValue.isEmpty()) - { + if (!defaultValue.isEmpty()) + { #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) - int index = ui->cmbRevision->findText(defaultValue); - if(index>=0) - ui->cmbRevision->setCurrentIndex(index); + int index = ui->cmbRevision->findText(defaultValue); + if (index >= 0) + ui->cmbRevision->setCurrentIndex(index); #else - ui->cmbRevision->setCurrentText(defaultValue); + ui->cmbRevision->setCurrentText(defaultValue); #endif - } + } } //----------------------------------------------------------------------------- RevisionDialog::~RevisionDialog() { - delete ui; + delete ui; } //----------------------------------------------------------------------------- QString RevisionDialog::runUpdate(QWidget *parent, const QString &title, const QStringList &completions, const QString &defaultValue) { - RevisionDialog dlg(parent, completions, defaultValue); - dlg.setWindowTitle(title); - dlg.ui->lblName->setVisible(false); - dlg.ui->lineName->setVisible(false); - dlg.ui->lblIntegrate->setVisible(false); - dlg.ui->chkIntegrate->setVisible(false); - dlg.ui->lblForce->setVisible(false); - dlg.ui->chkForce->setVisible(false); + RevisionDialog dlg(parent, completions, defaultValue); + dlg.setWindowTitle(title); + dlg.ui->lblName->setVisible(false); + dlg.ui->lineName->setVisible(false); + dlg.ui->lblIntegrate->setVisible(false); + dlg.ui->chkIntegrate->setVisible(false); + dlg.ui->lblForce->setVisible(false); + dlg.ui->chkForce->setVisible(false); - dlg.adjustSize(); + dlg.adjustSize(); - if(dlg.exec() != QDialog::Accepted) - return QString(""); - return dlg.ui->cmbRevision->currentText().trimmed(); + if (dlg.exec() != QDialog::Accepted) + return QString(""); + return dlg.ui->cmbRevision->currentText().trimmed(); } //----------------------------------------------------------------------------- QString RevisionDialog::runMerge(QWidget *parent, const QString &title, const QStringList &completions, const QString &defaultValue, bool &integrate, bool &force) { - RevisionDialog dlg(parent, completions, defaultValue); - dlg.setWindowTitle(title); - dlg.ui->lblName->setVisible(false); - dlg.ui->lineName->setVisible(false); - dlg.ui->lblIntegrate->setVisible(true); - dlg.ui->chkIntegrate->setVisible(true); - dlg.ui->chkIntegrate->setChecked(integrate); - dlg.ui->lblForce->setVisible(true); - dlg.ui->chkForce->setVisible(true); - dlg.ui->chkForce->setChecked(force); + RevisionDialog dlg(parent, completions, defaultValue); + dlg.setWindowTitle(title); + dlg.ui->lblName->setVisible(false); + dlg.ui->lineName->setVisible(false); + dlg.ui->lblIntegrate->setVisible(true); + dlg.ui->chkIntegrate->setVisible(true); + dlg.ui->chkIntegrate->setChecked(integrate); + dlg.ui->lblForce->setVisible(true); + dlg.ui->chkForce->setVisible(true); + dlg.ui->chkForce->setChecked(force); - dlg.adjustSize(); + dlg.adjustSize(); - if(dlg.exec() != QDialog::Accepted) - return QString(""); + if (dlg.exec() != QDialog::Accepted) + return QString(""); - integrate = dlg.ui->chkIntegrate->checkState() == Qt::Checked; - force = dlg.ui->chkForce->checkState() == Qt::Checked; + integrate = dlg.ui->chkIntegrate->checkState() == Qt::Checked; + force = dlg.ui->chkForce->checkState() == Qt::Checked; - return dlg.ui->cmbRevision->currentText().trimmed(); + return dlg.ui->cmbRevision->currentText().trimmed(); } - //----------------------------------------------------------------------------- bool RevisionDialog::runNewTag(QWidget *parent, const QString &title, const QStringList &completions, const QString &defaultValue, QString &revision, QString &name) { - RevisionDialog dlg(parent, completions, defaultValue); - dlg.setWindowTitle(title); + RevisionDialog dlg(parent, completions, defaultValue); + dlg.setWindowTitle(title); - dlg.ui->lblName->setVisible(true); - dlg.ui->lineName->setVisible(true); - dlg.ui->lblIntegrate->setVisible(false); - dlg.ui->chkIntegrate->setVisible(false); - dlg.ui->lblForce->setVisible(false); - dlg.ui->chkForce->setVisible(false); + dlg.ui->lblName->setVisible(true); + dlg.ui->lineName->setVisible(true); + dlg.ui->lblIntegrate->setVisible(false); + dlg.ui->chkIntegrate->setVisible(false); + dlg.ui->lblForce->setVisible(false); + dlg.ui->chkForce->setVisible(false); - dlg.adjustSize(); + dlg.adjustSize(); - if(dlg.exec() != QDialog::Accepted) - return false; + if (dlg.exec() != QDialog::Accepted) + return false; - revision = dlg.ui->cmbRevision->currentText().trimmed(); - name = dlg.ui->lineName->text().trimmed(); - return true; + revision = dlg.ui->cmbRevision->currentText().trimmed(); + name = dlg.ui->lineName->text().trimmed(); + return true; } diff --git a/src/RevisionDialog.h b/src/RevisionDialog.h index 42f678a..2fe9794 100644 --- a/src/RevisionDialog.h +++ b/src/RevisionDialog.h @@ -1,28 +1,29 @@ #ifndef REVISIONDIALOG_H #define REVISIONDIALOG_H -#include #include +#include -namespace Ui { - class RevisionDialog; +namespace Ui +{ +class RevisionDialog; } class RevisionDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit RevisionDialog(QWidget *parent, const QStringList &completions, const QString &defaultValue); - ~RevisionDialog(); + explicit RevisionDialog(QWidget *parent, const QStringList &completions, const QString &defaultValue); + ~RevisionDialog(); - static QString runUpdate(QWidget *parent, const QString &title, const QStringList &completions, const QString &defaultValue); - static QString runMerge(QWidget* parent, const QString& title, const QStringList& completions, const QString& defaultValue, bool& integrate, bool& force); - static bool runNewTag(QWidget *parent, const QString &title, const QStringList &completions, const QString &defaultValue, QString &revision, QString &name); + static QString runUpdate(QWidget *parent, const QString &title, const QStringList &completions, const QString &defaultValue); + static QString runMerge(QWidget *parent, const QString &title, const QStringList &completions, const QString &defaultValue, bool &integrate, bool &force); + static bool runNewTag(QWidget *parent, const QString &title, const QStringList &completions, const QString &defaultValue, QString &revision, QString &name); private: - Ui::RevisionDialog *ui; - QCompleter completer; + Ui::RevisionDialog *ui; + QCompleter completer; }; -#endif // REVISIONDIALOG_H +#endif // REVISIONDIALOG_H diff --git a/src/SearchBox.cpp b/src/SearchBox.cpp index 0cbf495..598c424 100644 --- a/src/SearchBox.cpp +++ b/src/SearchBox.cpp @@ -1,24 +1,18 @@ #include "SearchBox.h" #include -SearchBox::SearchBox(QWidget *parent) : QLineEdit(parent) -{ -} +SearchBox::SearchBox(QWidget *parent) : QLineEdit(parent) {} -SearchBox::~SearchBox() -{ - -} +SearchBox::~SearchBox() {} void SearchBox::keyPressEvent(QKeyEvent *event) { - // Clear text on escape - if(event->key() == Qt::Key_Escape) - { - setText(""); - clearFocus(); - } - else - QLineEdit::keyPressEvent(event); + // Clear text on escape + if (event->key() == Qt::Key_Escape) + { + setText(""); + clearFocus(); + } + else + QLineEdit::keyPressEvent(event); } - diff --git a/src/SearchBox.h b/src/SearchBox.h index 53b7487..178d610 100644 --- a/src/SearchBox.h +++ b/src/SearchBox.h @@ -5,19 +5,17 @@ class SearchBox : public QLineEdit { - Q_OBJECT + Q_OBJECT public: - explicit SearchBox(QWidget* parent=0); - ~SearchBox(); + explicit SearchBox(QWidget *parent = 0); + ~SearchBox(); signals: public slots: protected: - void keyPressEvent(QKeyEvent *event); - + void keyPressEvent(QKeyEvent *event); }; - -#endif // SEARCHBOX_H +#endif // SEARCHBOX_H diff --git a/src/SettingsDialog.cpp b/src/SettingsDialog.cpp index 7329971..35bc163 100644 --- a/src/SettingsDialog.cpp +++ b/src/SettingsDialog.cpp @@ -1,210 +1,204 @@ #include "SettingsDialog.h" -#include "ui_SettingsDialog.h" #include "Utils.h" +#include "ui_SettingsDialog.h" #include /////////////////////////////////////////////////////////////////////////////// -SettingsDialog::SettingsDialog(QWidget *parent, Settings &_settings) : - QDialog(parent, Qt::Sheet), - ui(new Ui::SettingsDialog), - settings(&_settings) +SettingsDialog::SettingsDialog(QWidget *parent, Settings &_settings) : QDialog(parent, Qt::Sheet), ui(new Ui::SettingsDialog), settings(&_settings) { - ui->setupUi(this); + ui->setupUi(this); - CreateLangMap(); + CreateLangMap(); - ui->cmbDoubleClickAction->addItem(tr("Diff File")); - ui->cmbDoubleClickAction->addItem(tr("Open File")); - ui->cmbDoubleClickAction->addItem(tr("Open Containing Folder")); - ui->cmbDoubleClickAction->addItem(tr("Custom Action %0").arg(1)); + ui->cmbDoubleClickAction->addItem(tr("Diff File")); + ui->cmbDoubleClickAction->addItem(tr("Open File")); + ui->cmbDoubleClickAction->addItem(tr("Open Containing Folder")); + ui->cmbDoubleClickAction->addItem(tr("Custom Action %0").arg(1)); - ui->cmbFossilBrowser->addItem(tr("System")); - ui->cmbFossilBrowser->addItem(tr("Internal")); + ui->cmbFossilBrowser->addItem(tr("System")); + ui->cmbFossilBrowser->addItem(tr("Internal")); - // App Settings - ui->lineFossilPath->setText(QDir::toNativeSeparators(settings->GetValue(FUEL_SETTING_FOSSIL_PATH).toString())); - ui->cmbDoubleClickAction->setCurrentIndex(settings->GetValue(FUEL_SETTING_FILE_DBLCLICK).toInt()); - ui->cmbFossilBrowser->setCurrentIndex(settings->GetValue(FUEL_SETTING_WEB_BROWSER).toInt()); + // App Settings + ui->lineFossilPath->setText(QDir::toNativeSeparators(settings->GetValue(FUEL_SETTING_FOSSIL_PATH).toString())); + ui->cmbDoubleClickAction->setCurrentIndex(settings->GetValue(FUEL_SETTING_FILE_DBLCLICK).toInt()); + ui->cmbFossilBrowser->setCurrentIndex(settings->GetValue(FUEL_SETTING_WEB_BROWSER).toInt()); - // Initialize language combo - foreach(const LangMap &m, langMap) - ui->cmbActiveLanguage->addItem(m.name); + // Initialize language combo + foreach (const LangMap &m, langMap) + ui->cmbActiveLanguage->addItem(m.name); - QString lang = settings->GetValue(FUEL_SETTING_LANGUAGE).toString(); - // Select current language - ui->cmbActiveLanguage->setCurrentIndex( - ui->cmbActiveLanguage->findText( - LangIdToName(lang))); + QString lang = settings->GetValue(FUEL_SETTING_LANGUAGE).toString(); + // Select current language + ui->cmbActiveLanguage->setCurrentIndex(ui->cmbActiveLanguage->findText(LangIdToName(lang))); + lastActionIndex = 0; + currentCustomActions = settings->GetCustomActions(); - lastActionIndex = 0; - currentCustomActions = settings->GetCustomActions(); + ui->cmbCustomActionContext->addItem(tr("Files")); + ui->cmbCustomActionContext->addItem(tr("Folders")); + ui->cmbCustomActionContext->setCurrentIndex(0); - ui->cmbCustomActionContext->addItem(tr("Files")); - ui->cmbCustomActionContext->addItem(tr("Folders")); - ui->cmbCustomActionContext->setCurrentIndex(0); + GetCustomAction(0); - GetCustomAction(0); - - for(int i=0; icmbCustomAction->addItem(a.Id); - } - ui->cmbCustomAction->setCurrentIndex(0); + for (int i = 0; i < currentCustomActions.size(); ++i) + { + CustomAction &a = currentCustomActions[i]; + ui->cmbCustomAction->addItem(a.Id); + } + ui->cmbCustomAction->setCurrentIndex(0); } //----------------------------------------------------------------------------- SettingsDialog::~SettingsDialog() { - delete ui; + delete ui; } //----------------------------------------------------------------------------- bool SettingsDialog::run(QWidget *parent, Settings &settings) { - SettingsDialog dlg(parent, settings); - return dlg.exec() == QDialog::Accepted; + SettingsDialog dlg(parent, settings); + return dlg.exec() == QDialog::Accepted; } //----------------------------------------------------------------------------- void SettingsDialog::on_buttonBox_accepted() { - settings->SetValue(FUEL_SETTING_FOSSIL_PATH, QDir::fromNativeSeparators(ui->lineFossilPath->text())); - Q_ASSERT(ui->cmbDoubleClickAction->currentIndex()>=FILE_DLBCLICK_ACTION_DIFF && ui->cmbDoubleClickAction->currentIndex()SetValue(FUEL_SETTING_FILE_DBLCLICK, ui->cmbDoubleClickAction->currentIndex()); - settings->SetValue(FUEL_SETTING_WEB_BROWSER, ui->cmbFossilBrowser->currentIndex()); + settings->SetValue(FUEL_SETTING_FOSSIL_PATH, QDir::fromNativeSeparators(ui->lineFossilPath->text())); + Q_ASSERT(ui->cmbDoubleClickAction->currentIndex() >= FILE_DLBCLICK_ACTION_DIFF && ui->cmbDoubleClickAction->currentIndex() < FILE_DLBCLICK_ACTION_MAX); + settings->SetValue(FUEL_SETTING_FILE_DBLCLICK, ui->cmbDoubleClickAction->currentIndex()); + settings->SetValue(FUEL_SETTING_WEB_BROWSER, ui->cmbFossilBrowser->currentIndex()); - Q_ASSERT(settings->HasValue(FUEL_SETTING_LANGUAGE)); - QString curr_langid = settings->GetValue(FUEL_SETTING_LANGUAGE).toString(); - QString new_langid = LangNameToId(ui->cmbActiveLanguage->currentText()); - Q_ASSERT(!new_langid.isEmpty()); - settings->SetValue(FUEL_SETTING_LANGUAGE, new_langid); + Q_ASSERT(settings->HasValue(FUEL_SETTING_LANGUAGE)); + QString curr_langid = settings->GetValue(FUEL_SETTING_LANGUAGE).toString(); + QString new_langid = LangNameToId(ui->cmbActiveLanguage->currentText()); + Q_ASSERT(!new_langid.isEmpty()); + settings->SetValue(FUEL_SETTING_LANGUAGE, new_langid); - if(curr_langid != new_langid) - QMessageBox::information(this, tr("Restart required"), tr("The language change will take effect after restarting the application"), QMessageBox::Ok); + if (curr_langid != new_langid) + QMessageBox::information(this, tr("Restart required"), tr("The language change will take effect after restarting the application"), QMessageBox::Ok); - for(int i=0; icmbCustomAction->currentIndex()); + PutCustomAction(ui->cmbCustomAction->currentIndex()); - settings->GetCustomActions() = currentCustomActions; + settings->GetCustomActions() = currentCustomActions; - settings->ApplyEnvironment(); + settings->ApplyEnvironment(); } //----------------------------------------------------------------------------- void SettingsDialog::on_btnSelectFossil_clicked() { - QString path = SelectExe(this, tr("Select Fossil executable")); - if(!path.isEmpty()) - ui->lineFossilPath->setText(QDir::toNativeSeparators(path)); + QString path = SelectExe(this, tr("Select Fossil executable")); + if (!path.isEmpty()) + ui->lineFossilPath->setText(QDir::toNativeSeparators(path)); } //----------------------------------------------------------------------------- void SettingsDialog::on_btnClearMessageHistory_clicked() { - if(DialogQuery(this, tr("Clear Commit Message History"), tr("Are you sure you want to clear the commit message history?"))==QMessageBox::Yes) - settings->SetValue(FUEL_SETTING_COMMIT_MSG, QStringList()); + if (DialogQuery(this, tr("Clear Commit Message History"), tr("Are you sure you want to clear the commit message history?")) == QMessageBox::Yes) + settings->SetValue(FUEL_SETTING_COMMIT_MSG, QStringList()); } //----------------------------------------------------------------------------- void SettingsDialog::CreateLangMap() { - langMap.append(LangMap("nl_NL", "Dutch (NL)")); - langMap.append(LangMap("en_US", "English (US)")); - langMap.append(LangMap("fr_FR", "French (FR)")); - langMap.append(LangMap("de_DE", "German (DE)")); - langMap.append(LangMap("el_GR", "Greek (GR)")); - langMap.append(LangMap("it_IT", "Italian (IT)")); - langMap.append(LangMap("ko_KR", "Korean (KO)")); - langMap.append(LangMap("pt_PT", "Portuguese (PT)")); - langMap.append(LangMap("ru_RU", "Russian (RU)")); - langMap.append(LangMap("es_ES", "Spanish (ES)")); + langMap.append(LangMap("nl_NL", "Dutch (NL)")); + langMap.append(LangMap("en_US", "English (US)")); + langMap.append(LangMap("fr_FR", "French (FR)")); + langMap.append(LangMap("de_DE", "German (DE)")); + langMap.append(LangMap("el_GR", "Greek (GR)")); + langMap.append(LangMap("it_IT", "Italian (IT)")); + langMap.append(LangMap("ko_KR", "Korean (KO)")); + langMap.append(LangMap("pt_PT", "Portuguese (PT)")); + langMap.append(LangMap("ru_RU", "Russian (RU)")); + langMap.append(LangMap("es_ES", "Spanish (ES)")); } //----------------------------------------------------------------------------- QString SettingsDialog::LangIdToName(const QString &id) { - foreach(const LangMap &m, langMap) - { - if(m.id == id) - return m.name; - } + foreach (const LangMap &m, langMap) + { + if (m.id == id) + return m.name; + } - return ""; + return ""; } //----------------------------------------------------------------------------- QString SettingsDialog::LangNameToId(const QString &name) { - foreach(const LangMap &m, langMap) - { - if(m.name == name) - return m.id; - } + foreach (const LangMap &m, langMap) + { + if (m.name == name) + return m.id; + } - return ""; + return ""; } //----------------------------------------------------------------------------- void SettingsDialog::on_btnSelectCustomFileActionCommand_clicked() { - QString path = SelectExe(this, tr("Select command")); - if(path.isEmpty()) - return; + QString path = SelectExe(this, tr("Select command")); + if (path.isEmpty()) + return; - // Quote path if it contains spaces - if(path.indexOf(' ')!=-1) - path = '"' + path + '"'; + // Quote path if it contains spaces + if (path.indexOf(' ') != -1) + path = '"' + path + '"'; - ui->lineCustomActionCommand->setText(QDir::toNativeSeparators(path)); + ui->lineCustomActionCommand->setText(QDir::toNativeSeparators(path)); } //----------------------------------------------------------------------------- void SettingsDialog::GetCustomAction(int index) { - Q_ASSERT(index>=0 && index < currentCustomActions.size()); - CustomAction &action = currentCustomActions[index]; - ui->lineCustomActionDescription->setText(action.Description); - ui->lineCustomActionCommand->setText(action.Command); - ui->cmbCustomActionContext->setCurrentIndex(action.Context-1); - ui->chkCustomActionMultipleSelection->setChecked(action.MultipleSelection); + Q_ASSERT(index >= 0 && index < currentCustomActions.size()); + CustomAction &action = currentCustomActions[index]; + ui->lineCustomActionDescription->setText(action.Description); + ui->lineCustomActionCommand->setText(action.Command); + ui->cmbCustomActionContext->setCurrentIndex(action.Context - 1); + ui->chkCustomActionMultipleSelection->setChecked(action.MultipleSelection); } //----------------------------------------------------------------------------- void SettingsDialog::PutCustomAction(int index) { - Q_ASSERT(index>=0 && index < currentCustomActions.size()); - CustomAction &action = currentCustomActions[index]; - action.Description = ui->lineCustomActionDescription->text().trimmed(); - action.Command = ui->lineCustomActionCommand->text().trimmed(); - action.Context = static_cast(ui->cmbCustomActionContext->currentIndex()+1); - action.MultipleSelection = ui->chkCustomActionMultipleSelection->isChecked(); + Q_ASSERT(index >= 0 && index < currentCustomActions.size()); + CustomAction &action = currentCustomActions[index]; + action.Description = ui->lineCustomActionDescription->text().trimmed(); + action.Command = ui->lineCustomActionCommand->text().trimmed(); + action.Context = static_cast(ui->cmbCustomActionContext->currentIndex() + 1); + action.MultipleSelection = ui->chkCustomActionMultipleSelection->isChecked(); } //----------------------------------------------------------------------------- void SettingsDialog::on_cmbCustomAction_currentIndexChanged(int index) { - if(index != lastActionIndex) - PutCustomAction(lastActionIndex); + if (index != lastActionIndex) + PutCustomAction(lastActionIndex); - GetCustomAction(index); - lastActionIndex = index; + GetCustomAction(index); + lastActionIndex = index; } //----------------------------------------------------------------------------- void SettingsDialog::on_cmbCustomActionContext_currentIndexChanged(int index) { - int action_index = ui->cmbCustomAction->currentIndex(); - if(action_index<0) - return; - Q_ASSERT(action_index>=0 && action_index < currentCustomActions.size()); - currentCustomActions[action_index].Context = static_cast(index+1); + int action_index = ui->cmbCustomAction->currentIndex(); + if (action_index < 0) + return; + Q_ASSERT(action_index >= 0 && action_index < currentCustomActions.size()); + currentCustomActions[action_index].Context = static_cast(index + 1); } diff --git a/src/SettingsDialog.h b/src/SettingsDialog.h index 53d0966..a146de3 100644 --- a/src/SettingsDialog.h +++ b/src/SettingsDialog.h @@ -1,55 +1,52 @@ #ifndef SETTINGSDIALOG_H #define SETTINGSDIALOG_H -#include #include "AppSettings.h" +#include -namespace Ui { - class SettingsDialog; +namespace Ui +{ +class SettingsDialog; } class SettingsDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit SettingsDialog(QWidget *parent, Settings &_settings); - ~SettingsDialog(); - - static bool run(QWidget *parent, Settings &_settings); + explicit SettingsDialog(QWidget *parent, Settings &_settings); + ~SettingsDialog(); + static bool run(QWidget *parent, Settings &_settings); private slots: - void on_btnSelectFossil_clicked(); - void on_buttonBox_accepted(); - void on_btnClearMessageHistory_clicked(); - void on_btnSelectCustomFileActionCommand_clicked(); - void on_cmbCustomAction_currentIndexChanged(int index); - void on_cmbCustomActionContext_currentIndexChanged(int index); + void on_btnSelectFossil_clicked(); + void on_buttonBox_accepted(); + void on_btnClearMessageHistory_clicked(); + void on_btnSelectCustomFileActionCommand_clicked(); + void on_cmbCustomAction_currentIndexChanged(int index); + void on_cmbCustomActionContext_currentIndexChanged(int index); private: - QString LangIdToName(const QString &id); - QString LangNameToId(const QString &name); - void CreateLangMap(); - void GetCustomAction(int index); - void PutCustomAction(int index); + QString LangIdToName(const QString &id); + QString LangNameToId(const QString &name); + void CreateLangMap(); + void GetCustomAction(int index); + void PutCustomAction(int index); - struct LangMap - { - LangMap(const QString &_id, const QString &_name) - : id(_id), name(_name) - { - } + struct LangMap + { + LangMap(const QString &_id, const QString &_name) : id(_id), name(_name) {} - QString id; - QString name; - }; + QString id; + QString name; + }; - QList langMap; - Ui::SettingsDialog *ui; - Settings *settings; - Settings::custom_actions_t currentCustomActions; - int lastActionIndex; + QList langMap; + Ui::SettingsDialog *ui; + Settings *settings; + Settings::custom_actions_t currentCustomActions; + int lastActionIndex; }; -#endif // SETTINGSDIALOG_H +#endif // SETTINGSDIALOG_H diff --git a/src/Utils.cpp b/src/Utils.cpp index 8dad8f4..953c3f5 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -1,76 +1,71 @@ #include "Utils.h" -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include #include /////////////////////////////////////////////////////////////////////////////// QMessageBox::StandardButton DialogQuery(QWidget *parent, const QString &title, const QString &query, QMessageBox::StandardButtons buttons) { - QMessageBox mb(QMessageBox::Question, title, query, buttons, parent, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::Sheet ); - mb.setDefaultButton(QMessageBox::No); - mb.setWindowModality(Qt::WindowModal); - mb.setModal(true); - mb.exec(); - QMessageBox::StandardButton res = mb.standardButton(mb.clickedButton()); - return res; + QMessageBox mb(QMessageBox::Question, title, query, buttons, parent, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::Sheet); + mb.setDefaultButton(QMessageBox::No); + mb.setWindowModality(Qt::WindowModal); + mb.setModal(true); + mb.exec(); + QMessageBox::StandardButton res = mb.standardButton(mb.clickedButton()); + return res; } //----------------------------------------------------------------------------- QString QuotePath(const QString &path) { - return path; + return path; } //----------------------------------------------------------------------------- QStringList QuotePaths(const QStringList &paths) { - QStringList res; - for(int i=0; i +#if 0 // Unused +# include static bool DialogQueryText(QWidget *parent, const QString &title, const QString &query, QString &text, bool isPassword=false) { @@ -92,10 +87,9 @@ static bool DialogQueryText(QWidget *parent, const QString &title, const QString } #endif - #ifdef Q_OS_WIN // Explorer File Context Menu support. Based on http://www.microsoft.com/msj/0497/wicked/wicked0497.aspx -#include +# include //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // @@ -120,227 +114,225 @@ static bool DialogQueryText(QWidget *parent, const QString &title, const QString //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ bool ShowExplorerMenu(HWND hwnd, const QString &path, const QPoint &qpoint) { - struct Util - { - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // FUNCTION: GetNextItem - // DESCRIPTION: Finds the next item in an item ID list. - // INPUT: pidl = Pointer to an item ID list. - // RETURNS: Pointer to the next item. - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - static LPITEMIDLIST GetNextItem (LPITEMIDLIST pidl) - { - USHORT nLen; + struct Util + { + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // FUNCTION: GetNextItem + // DESCRIPTION: Finds the next item in an item ID list. + // INPUT: pidl = Pointer to an item ID list. + // RETURNS: Pointer to the next item. + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + static LPITEMIDLIST GetNextItem(LPITEMIDLIST pidl) + { + USHORT nLen; - if ((nLen = pidl->mkid.cb) == 0) - return NULL; + if ((nLen = pidl->mkid.cb) == 0) + return NULL; - return (LPITEMIDLIST) (((LPBYTE) pidl) + nLen); - } + return (LPITEMIDLIST)(((LPBYTE)pidl) + nLen); + } - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // FUNCTION: GetItemCount - // DESCRIPTION: Computes the number of item IDs in an item ID list. - // INPUT: pidl = Pointer to an item ID list. - // RETURNS: Number of item IDs in the list. - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - static UINT GetItemCount (LPITEMIDLIST pidl) - { - USHORT nLen; - UINT nCount; + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // FUNCTION: GetItemCount + // DESCRIPTION: Computes the number of item IDs in an item ID list. + // INPUT: pidl = Pointer to an item ID list. + // RETURNS: Number of item IDs in the list. + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + static UINT GetItemCount(LPITEMIDLIST pidl) + { + USHORT nLen; + UINT nCount; - nCount = 0; - while ((nLen = pidl->mkid.cb) != 0) { - pidl = GetNextItem (pidl); - nCount++; - } - return nCount; - } + nCount = 0; + while ((nLen = pidl->mkid.cb) != 0) + { + pidl = GetNextItem(pidl); + nCount++; + } + return nCount; + } - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // FUNCTION: DuplicateItem - // DESCRIPTION: Makes a copy of the next item in an item ID list. - // INPUT: pMalloc = Pointer to an IMalloc interface. - // pidl = Pointer to an item ID list. - // RETURNS: Pointer to an ITEMIDLIST containing the copied item ID. - // NOTES: It is the caller's responsibility to free the memory - // allocated by this function when the item ID is no longer - // needed. Example: - // pidlItem = DuplicateItem (pMalloc, pidl); - // . - // . - // . - // pMalloc->lpVtbl->Free (pMalloc, pidlItem); - // Failure to free the ITEMIDLIST will result in memory - // leaks. - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - static LPITEMIDLIST DuplicateItem (LPMALLOC pMalloc, LPITEMIDLIST pidl) - { - USHORT nLen; - LPITEMIDLIST pidlNew; + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // FUNCTION: DuplicateItem + // DESCRIPTION: Makes a copy of the next item in an item ID list. + // INPUT: pMalloc = Pointer to an IMalloc interface. + // pidl = Pointer to an item ID list. + // RETURNS: Pointer to an ITEMIDLIST containing the copied item ID. + // NOTES: It is the caller's responsibility to free the memory + // allocated by this function when the item ID is no longer + // needed. Example: + // pidlItem = DuplicateItem (pMalloc, pidl); + // . + // . + // . + // pMalloc->lpVtbl->Free (pMalloc, pidlItem); + // Failure to free the ITEMIDLIST will result in memory + // leaks. + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + static LPITEMIDLIST DuplicateItem(LPMALLOC pMalloc, LPITEMIDLIST pidl) + { + USHORT nLen; + LPITEMIDLIST pidlNew; - nLen = pidl->mkid.cb; - if (nLen == 0) - return NULL; + nLen = pidl->mkid.cb; + if (nLen == 0) + return NULL; - pidlNew = (LPITEMIDLIST) pMalloc->Alloc ( - nLen + sizeof (USHORT)); - if (pidlNew == NULL) - return NULL; + pidlNew = (LPITEMIDLIST)pMalloc->Alloc(nLen + sizeof(USHORT)); + if (pidlNew == NULL) + return NULL; - CopyMemory (pidlNew, pidl, nLen); - *((USHORT*) (((LPBYTE) pidlNew) + nLen)) = 0; + CopyMemory(pidlNew, pidl, nLen); + *((USHORT *)(((LPBYTE)pidlNew) + nLen)) = 0; - return pidlNew; - } - }; + return pidlNew; + } + }; + LPITEMIDLIST pidlMain, pidlItem, pidlNextItem, *ppidl; + UINT nCount; + POINT point; + point.x = qpoint.x(); + point.y = qpoint.y(); - LPITEMIDLIST pidlMain, pidlItem, pidlNextItem, *ppidl; - UINT nCount; - POINT point; - point.x = qpoint.x(); - point.y = qpoint.y(); + WCHAR wchPath[MAX_PATH]; + memset(wchPath, 0, sizeof(wchPath)); + Q_ASSERT(path.length() < MAX_PATH); + path.toWCharArray(wchPath); - WCHAR wchPath[MAX_PATH]; - memset(wchPath, 0, sizeof(wchPath)); - Q_ASSERT(path.length()Release(); + return bResult; + } - LPSHELLFOLDER psfFolder; - if (!SUCCEEDED (SHGetDesktopFolder (&psfFolder))) { - pMalloc->Release(); - return bResult; - } + // + // Convert the path name into a pointer to an item ID list (pidl). + // + ULONG ulCount, ulAttr; + if (SUCCEEDED(psfFolder->ParseDisplayName(hwnd, NULL, wchPath, &ulCount, &pidlMain, &ulAttr)) && (pidlMain != NULL)) + { - // - // Convert the path name into a pointer to an item ID list (pidl). - // - ULONG ulCount, ulAttr; - if (SUCCEEDED (psfFolder->ParseDisplayName (hwnd, - NULL, wchPath, &ulCount, &pidlMain, &ulAttr)) && (pidlMain != NULL)) { + if ((nCount = Util::GetItemCount(pidlMain)) > 0) + { // nCount must be > 0 + // + // Initialize psfFolder with a pointer to the IShellFolder + // interface of the folder that contains the item whose context + // menu we're after, and initialize pidlItem with a pointer to + // the item's item ID. If nCount > 1, this requires us to walk + // the list of item IDs stored in pidlMain and bind to each + // subfolder referenced in the list. + // + pidlItem = pidlMain; - if ( (nCount = Util::GetItemCount (pidlMain))>0) { // nCount must be > 0 - // - // Initialize psfFolder with a pointer to the IShellFolder - // interface of the folder that contains the item whose context - // menu we're after, and initialize pidlItem with a pointer to - // the item's item ID. If nCount > 1, this requires us to walk - // the list of item IDs stored in pidlMain and bind to each - // subfolder referenced in the list. - // - pidlItem = pidlMain; + while (--nCount) + { + // + // Create a 1-item item ID list for the next item in pidlMain. + // + pidlNextItem = Util::DuplicateItem(pMalloc, pidlItem); + if (pidlNextItem == NULL) + { + pMalloc->Free(pidlMain); + psfFolder->Release(); + pMalloc->Release(); + return bResult; + } - while (--nCount) { - // - // Create a 1-item item ID list for the next item in pidlMain. - // - pidlNextItem = Util::DuplicateItem (pMalloc, pidlItem); - if (pidlNextItem == NULL) { - pMalloc->Free(pidlMain); - psfFolder->Release (); - pMalloc->Release (); - return bResult; - } + // + // Bind to the folder specified in the new item ID list. + // + LPSHELLFOLDER psfNextFolder; + if (!SUCCEEDED(psfFolder->BindToObject(pidlNextItem, NULL, IID_IShellFolder, (void **)&psfNextFolder))) + { + pMalloc->Free(pidlNextItem); + pMalloc->Free(pidlMain); + psfFolder->Release(); + pMalloc->Release(); + return bResult; + } - // - // Bind to the folder specified in the new item ID list. - // - LPSHELLFOLDER psfNextFolder; - if (!SUCCEEDED (psfFolder->BindToObject ( - pidlNextItem, NULL, IID_IShellFolder, (void**)&psfNextFolder))) { - pMalloc->Free (pidlNextItem); - pMalloc->Free (pidlMain); - psfFolder->Release (); - pMalloc->Release (); - return bResult; - } + // + // Release the IShellFolder pointer to the parent folder + // and set psfFolder equal to the IShellFolder pointer for + // the current folder. + // + psfFolder->Release(); + psfFolder = psfNextFolder; - // - // Release the IShellFolder pointer to the parent folder - // and set psfFolder equal to the IShellFolder pointer for - // the current folder. - // - psfFolder->Release (); - psfFolder = psfNextFolder; + // + // Release the storage for the 1-item item ID list we created + // just a moment ago and initialize pidlItem so that it points + // to the next item in pidlMain. + // + pMalloc->Free(pidlNextItem); + pidlItem = Util::GetNextItem(pidlItem); + } - // - // Release the storage for the 1-item item ID list we created - // just a moment ago and initialize pidlItem so that it points - // to the next item in pidlMain. - // - pMalloc->Free(pidlNextItem); - pidlItem = Util::GetNextItem (pidlItem); - } + // + // Get a pointer to the item's IContextMenu interface and call + // IContextMenu::QueryContextMenu to initialize a context menu. + // + ppidl = &pidlItem; + LPCONTEXTMENU pContextMenu; + if (SUCCEEDED(psfFolder->GetUIObjectOf(hwnd, 1, (const ITEMIDLIST **)ppidl, IID_IContextMenu, NULL, (void **)&pContextMenu))) + { - // - // Get a pointer to the item's IContextMenu interface and call - // IContextMenu::QueryContextMenu to initialize a context menu. - // - ppidl = &pidlItem; - LPCONTEXTMENU pContextMenu; - if (SUCCEEDED (psfFolder->GetUIObjectOf ( - hwnd, 1, (const ITEMIDLIST **)ppidl, IID_IContextMenu, NULL, (void**)&pContextMenu))) { + HMENU hMenu = CreatePopupMenu(); + if (SUCCEEDED(pContextMenu->QueryContextMenu(hMenu, 0, 1, 0x7FFF, CMF_EXPLORE))) + { - HMENU hMenu = CreatePopupMenu (); - if (SUCCEEDED (pContextMenu->QueryContextMenu ( - hMenu, 0, 1, 0x7FFF, CMF_EXPLORE))) { + // + // Display the context menu. + // + UINT nCmd = TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_RETURNCMD, point.x, point.y, 0, hwnd, NULL); + // + // If a command was selected from the menu, execute it. + // + if (nCmd) + { + CMINVOKECOMMANDINFO ici; + memset(&ici, 0, sizeof(ici)); + ici.cbSize = sizeof(CMINVOKECOMMANDINFO); + ici.fMask = 0; + ici.hwnd = hwnd; + ici.lpVerb = MAKEINTRESOURCEA(nCmd - 1); + ici.lpParameters = NULL; + ici.lpDirectory = NULL; + ici.nShow = SW_SHOWNORMAL; + ici.dwHotKey = 0; + ici.hIcon = NULL; - // - // Display the context menu. - // - UINT nCmd = TrackPopupMenu (hMenu, TPM_LEFTALIGN | - TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_RETURNCMD, - point.x, point.y, 0, hwnd, NULL); + if (SUCCEEDED(pContextMenu->InvokeCommand((CMINVOKECOMMANDINFO *)&ici))) + bResult = true; + } + } + DestroyMenu(hMenu); + pContextMenu->Release(); + } + } + pMalloc->Free(pidlMain); + } + // + // Clean up and return. + // + psfFolder->Release(); + pMalloc->Release(); - // - // If a command was selected from the menu, execute it. - // - if (nCmd) { - CMINVOKECOMMANDINFO ici; - memset(&ici, 0, sizeof(ici) ); - ici.cbSize = sizeof (CMINVOKECOMMANDINFO); - ici.fMask = 0; - ici.hwnd = hwnd; - ici.lpVerb = MAKEINTRESOURCEA (nCmd - 1); - ici.lpParameters = NULL; - ici.lpDirectory = NULL; - ici.nShow = SW_SHOWNORMAL; - ici.dwHotKey = 0; - ici.hIcon = NULL; - - if (SUCCEEDED ( - pContextMenu->InvokeCommand ( - (CMINVOKECOMMANDINFO*)&ici))) - bResult = true; - } - } - DestroyMenu (hMenu); - pContextMenu->Release (); - } - } - pMalloc->Free (pidlMain); - } - - // - // Clean up and return. - // - psfFolder->Release (); - pMalloc->Release (); - - return bResult; + return bResult; } #endif @@ -348,181 +340,180 @@ bool ShowExplorerMenu(HWND hwnd, const QString &path, const QPoint &qpoint) //----------------------------------------------------------------------------- void ParseProperties(QStringMap &properties, const QStringList &lines, QChar separator) { - properties.clear(); - foreach(QString l, lines) - { - l = l.trimmed(); - int index = l.indexOf(separator); + properties.clear(); + foreach (QString l, lines) + { + l = l.trimmed(); + int index = l.indexOf(separator); - QString key; - QString value; - if(index!=-1) - { - key = l.left(index).trimmed(); - value = l.mid(index+1).trimmed(); - } - else - key = l; + QString key; + QString value; + if (index != -1) + { + key = l.left(index).trimmed(); + value = l.mid(index + 1).trimmed(); + } + else + key = l; - properties.insert(key, value); - } + properties.insert(key, value); + } } - //------------------------------------------------------------------------------ void GetStandardItemTextRecursive(QString &name, const QStandardItem &item, const QChar &separator) { - if(item.parent()) - { - GetStandardItemTextRecursive(name, *item.parent()); - name.append(separator); - } + if (item.parent()) + { + GetStandardItemTextRecursive(name, *item.parent()); + name.append(separator); + } - name.append(item.data(Qt::DisplayRole).toString()); + name.append(item.data(Qt::DisplayRole).toString()); } //------------------------------------------------------------------------------ void BuildNameToModelIndex(name_modelindex_map_t &map, const QStandardItem &item) { - QString name; - GetStandardItemTextRecursive(name, item); - map.insert(name, item.index()); + QString name; + GetStandardItemTextRecursive(name, item); + map.insert(name, item.index()); - for(int i=0; i 0) - { - extraParams = command.mid(cmd_end+1); - command = command.mid(cmd_start, cmd_end-backtrack); - } + int cmd_end = command.indexOf(cmd_char_end, cmd_start); + if (cmd_end > 0) + { + extraParams = command.mid(cmd_end + 1); + command = command.mid(cmd_start, cmd_end - backtrack); + } - command = command.trimmed(); - extraParams = extraParams.trimmed(); + command = command.trimmed(); + extraParams = extraParams.trimmed(); } //------------------------------------------------------------------------------ -bool SpawnExternalProcess(QObject *processParent, const QString& command, const QStringList& fileList, const stringset_t& pathSet, const QString &workspaceDir, UICallback &uiCallback) +bool SpawnExternalProcess(QObject *processParent, const QString &command, const QStringList &fileList, const stringset_t &pathSet, const QString &workspaceDir, UICallback &uiCallback) { - static const char* MACRO_FILE = "%FILE"; - static const char* MACRO_FOLDER = "%FOLDER"; - static const char* MACRO_WORKSPACE = "%WORKSPACE"; + static const char *MACRO_FILE = "%FILE"; + static const char *MACRO_FOLDER = "%FOLDER"; + static const char *MACRO_WORKSPACE = "%WORKSPACE"; - QStringList params; + QStringList params; - QString cmd, extra_params; - SplitCommandLine(command, cmd, extra_params); + QString cmd, extra_params; + SplitCommandLine(command, cmd, extra_params); - // Push all additional params, except those containing macros - QString macro_file; - QString macro_folder; + // Push all additional params, except those containing macros + QString macro_file; + QString macro_folder; - if(!extra_params.isEmpty()) - { - QStringList extra_param_list = extra_params.split(' '); + if (!extra_params.isEmpty()) + { + QStringList extra_param_list = extra_params.split(' '); - foreach(const QString &p, extra_param_list) - { - if(p.indexOf(MACRO_FILE)!=-1) - { - macro_file = p; - continue; - } - else if(p.indexOf(MACRO_FOLDER)!=-1) - { - macro_folder = p; - continue; - } - else if(p.indexOf(MACRO_WORKSPACE)!=-1) - { - // Add in-place - QString n = p; - n.replace(MACRO_WORKSPACE, QDir::toNativeSeparators(workspaceDir), Qt::CaseInsensitive); - params.push_back(n); - continue; - } + foreach (const QString &p, extra_param_list) + { + if (p.indexOf(MACRO_FILE) != -1) + { + macro_file = p; + continue; + } + else if (p.indexOf(MACRO_FOLDER) != -1) + { + macro_folder = p; + continue; + } + else if (p.indexOf(MACRO_WORKSPACE) != -1) + { + // Add in-place + QString n = p; + n.replace(MACRO_WORKSPACE, QDir::toNativeSeparators(workspaceDir), Qt::CaseInsensitive); + params.push_back(n); + continue; + } - params.push_back(p); - } - } + params.push_back(p); + } + } - // Build file params - if(!macro_file.isEmpty()) - { - foreach(const QString &f, fileList) - { - QString path = QDir::toNativeSeparators(QFileInfo(workspaceDir + PATH_SEPARATOR + f).absoluteFilePath()); + // Build file params + if (!macro_file.isEmpty()) + { + foreach (const QString &f, fileList) + { + QString path = QDir::toNativeSeparators(QFileInfo(workspaceDir + PATH_SEPARATOR + f).absoluteFilePath()); - QString macro = macro_file; - path = macro.replace(MACRO_FILE, path, Qt::CaseInsensitive); - params.append(path); - } - } + QString macro = macro_file; + path = macro.replace(MACRO_FILE, path, Qt::CaseInsensitive); + params.append(path); + } + } - // Build folder params - if(!macro_folder.isEmpty()) - { - foreach(const QString &f, pathSet) - { - QString path = QDir::toNativeSeparators(QFileInfo(workspaceDir + PATH_SEPARATOR + f).absoluteFilePath()); + // Build folder params + if (!macro_folder.isEmpty()) + { + foreach (const QString &f, pathSet) + { + QString path = QDir::toNativeSeparators(QFileInfo(workspaceDir + PATH_SEPARATOR + f).absoluteFilePath()); - QString macro = macro_folder; - path = macro.replace(MACRO_FOLDER, path, Qt::CaseInsensitive); - params.append(path); - } - } + QString macro = macro_folder; + path = macro.replace(MACRO_FOLDER, path, Qt::CaseInsensitive); + params.append(path); + } + } - uiCallback.logText(""+cmd + " "+params.join(" ")+"
", true); + uiCallback.logText("" + cmd + " " + params.join(" ") + "
", true); - QProcess proc(processParent); - return proc.startDetached(cmd, params); + QProcess proc(processParent); + return proc.startDetached(cmd, params); } //------------------------------------------------------------------------------ -void TrimStringList(QStringList& list) +void TrimStringList(QStringList &list) { - for(int i=0; i -#include #include -#include +#include #include #include +#include +#include -#define COUNTOF(array) (sizeof(array)/sizeof(array[0])) -#define FOSSIL_CHECKOUT1 "_FOSSIL_" -#define FOSSIL_CHECKOUT2 ".fslckout" -#define FOSSIL_EXT "fossil" -#define PATH_SEPARATOR "/" +#define COUNTOF(array) (sizeof(array) / sizeof(array[0])) +#define FOSSIL_CHECKOUT1 "_FOSSIL_" +#define FOSSIL_CHECKOUT2 ".fslckout" +#define FOSSIL_EXT "fossil" +#define PATH_SEPARATOR "/" typedef QSet stringset_t; - class UICallback { public: - virtual void logText(const QString &text, bool isHTML)=0; - virtual void beginProcess(const QString &text)=0; - virtual void updateProcess(const QString &text)=0; - virtual bool processAborted() const=0; - virtual void endProcess()=0; - virtual QMessageBox::StandardButton Query(const QString &title, const QString &query, QMessageBox::StandardButtons buttons)=0; + virtual void logText(const QString &text, bool isHTML) = 0; + virtual void beginProcess(const QString &text) = 0; + virtual void updateProcess(const QString &text) = 0; + virtual bool processAborted() const = 0; + virtual void endProcess() = 0; + virtual QMessageBox::StandardButton Query(const QString &title, const QString &query, QMessageBox::StandardButtons buttons) = 0; }; - class ScopedStatus { public: - ScopedStatus(UICallback *callback, const QString &text) : uiCallback(callback) - { - uiCallback->beginProcess(text); - } + ScopedStatus(UICallback *callback, const QString &text) : uiCallback(callback) { uiCallback->beginProcess(text); } - ~ScopedStatus() - { - uiCallback->endProcess(); - } + ~ScopedStatus() { uiCallback->endProcess(); } private: - UICallback *uiCallback; + UICallback *uiCallback; }; - -QMessageBox::StandardButton DialogQuery(QWidget *parent, const QString &title, const QString &query, QMessageBox::StandardButtons buttons = QMessageBox::Yes|QMessageBox::No); -QString QuotePath(const QString &path); -QStringList QuotePaths(const QStringList &paths); -QString SelectExe(QWidget *parent, const QString &description); - +QMessageBox::StandardButton DialogQuery(QWidget *parent, const QString &title, const QString &query, QMessageBox::StandardButtons buttons = QMessageBox::Yes | QMessageBox::No); +QString QuotePath(const QString &path); +QStringList QuotePaths(const QStringList &paths); +QString SelectExe(QWidget *parent, const QString &description); typedef QMap name_modelindex_map_t; -void GetStandardItemTextRecursive(QString &name, const QStandardItem &item, const QChar &separator='/'); -void BuildNameToModelIndex(name_modelindex_map_t &map, const QStandardItem &item); -void BuildNameToModelIndex(name_modelindex_map_t &map, const QStandardItemModel &model); -bool KeychainSet(QObject* parent, const QUrl& url, QSettings &settings); -bool KeychainGet(QObject* parent, QUrl& url, QSettings &settings); -bool KeychainDelete(QObject* parent, const QUrl& url, QSettings &settings); -QString HashString(const QString &str); -QString UrlToStringDisplay(const QUrl &url); -QString UrlToStringNoCredentials(const QUrl& url); -QString UrlToString(const QUrl &url); -void SplitCommandLine(const QString &commandLine, QString &command, QString &extraParams); -bool SpawnExternalProcess(QObject *processParent, const QString& command, const QStringList& fileList, const stringset_t& pathSet, const QString &workspaceDir, UICallback &uiCallback); -void TrimStringList(QStringList &list); +void GetStandardItemTextRecursive(QString &name, const QStandardItem &item, const QChar &separator = '/'); +void BuildNameToModelIndex(name_modelindex_map_t &map, const QStandardItem &item); +void BuildNameToModelIndex(name_modelindex_map_t &map, const QStandardItemModel &model); +bool KeychainSet(QObject *parent, const QUrl &url, QSettings &settings); +bool KeychainGet(QObject *parent, QUrl &url, QSettings &settings); +bool KeychainDelete(QObject *parent, const QUrl &url, QSettings &settings); +QString HashString(const QString &str); +QString UrlToStringDisplay(const QUrl &url); +QString UrlToStringNoCredentials(const QUrl &url); +QString UrlToString(const QUrl &url); +void SplitCommandLine(const QString &commandLine, QString &command, QString &extraParams); +bool SpawnExternalProcess(QObject *processParent, const QString &command, const QStringList &fileList, const stringset_t &pathSet, const QString &workspaceDir, UICallback &uiCallback); +void TrimStringList(QStringList &list); typedef QMap QStringMap; -void ParseProperties(QStringMap &properties, const QStringList &lines, QChar separator=' '); +void ParseProperties(QStringMap &properties, const QStringList &lines, QChar separator = ' '); #ifdef Q_OS_WIN - bool ShowExplorerMenu(HWND hwnd, const QString &path, const QPoint &qpoint); +bool ShowExplorerMenu(HWND hwnd, const QString &path, const QPoint &qpoint); #endif -#endif // UTILS_H +#endif // UTILS_H diff --git a/src/Workspace.cpp b/src/Workspace.cpp index be51a6a..fdf3bd1 100644 --- a/src/Workspace.cpp +++ b/src/Workspace.cpp @@ -1,105 +1,102 @@ #include "Workspace.h" -#include #include "Utils.h" +#include //----------------------------------------------------------------------------- -Workspace::Workspace() -{ -} +Workspace::Workspace() {} //----------------------------------------------------------------------------- Workspace::~Workspace() { - clearState(); - remotes.clear(); + clearState(); + remotes.clear(); } //------------------------------------------------------------------------------ void Workspace::clearState() { - // Dispose RepoFiles - foreach(WorkspaceFile *r, getFiles()) - delete r; + // Dispose RepoFiles + foreach (WorkspaceFile *r, getFiles()) + delete r; - getFiles().clear(); - getPaths().clear(); - pathState.clear(); - stashMap.clear(); - branchNames.clear(); - tags.clear(); - isIntegrated = false; + getFiles().clear(); + getPaths().clear(); + pathState.clear(); + stashMap.clear(); + branchNames.clear(); + tags.clear(); + isIntegrated = false; } //------------------------------------------------------------------------------ void Workspace::storeWorkspace(QSettings &store) { - QString workspace = fossil().getWorkspacePath(); - if(workspace.isEmpty()) - return; + QString workspace = fossil().getWorkspacePath(); + if (workspace.isEmpty()) + return; - store.beginGroup("Remotes"); - QString workspace_hash = HashString(QDir::toNativeSeparators(workspace)); - - store.beginWriteArray(workspace_hash); - int index = 0; - for(remote_map_t::iterator it=remotes.begin(); it!=remotes.end(); ++it, ++index) - { - store.setArrayIndex(index); - store.setValue("Name", it->name); - QUrl url = it->url; - url.setPassword(""); - store.setValue("Url", url); - if(it->isDefault) - store.setValue("Default", it->isDefault); - else - store.remove("Default"); - } - store.endArray(); - store.endGroup(); + store.beginGroup("Remotes"); + QString workspace_hash = HashString(QDir::toNativeSeparators(workspace)); + store.beginWriteArray(workspace_hash); + int index = 0; + for (remote_map_t::iterator it = remotes.begin(); it != remotes.end(); ++it, ++index) + { + store.setArrayIndex(index); + store.setValue("Name", it->name); + QUrl url = it->url; + url.setPassword(""); + store.setValue("Url", url); + if (it->isDefault) + store.setValue("Default", it->isDefault); + else + store.remove("Default"); + } + store.endArray(); + store.endGroup(); } //------------------------------------------------------------------------------ -bool Workspace::switchWorkspace(const QString& workspace, QSettings &store) +bool Workspace::switchWorkspace(const QString &workspace, QSettings &store) { - // Save Remotes - storeWorkspace(store); - clearState(); - remotes.clear(); + // Save Remotes + storeWorkspace(store); + clearState(); + remotes.clear(); - fossil().setWorkspace(""); - if(workspace.isEmpty()) - return true; + fossil().setWorkspace(""); + if (workspace.isEmpty()) + return true; - QString new_workspace = QFileInfo(workspace).absoluteFilePath(); + QString new_workspace = QFileInfo(workspace).absoluteFilePath(); - if(!QDir::setCurrent(new_workspace)) - return false; + if (!QDir::setCurrent(new_workspace)) + return false; - fossil().setWorkspace(new_workspace); + fossil().setWorkspace(new_workspace); - // Load Remotes - QString workspace_hash = HashString(QDir::toNativeSeparators(new_workspace)); + // Load Remotes + QString workspace_hash = HashString(QDir::toNativeSeparators(new_workspace)); - QString gr = store.group(); + QString gr = store.group(); - store.beginGroup("Remotes"); - gr = store.group(); - int num_remotes = store.beginReadArray(workspace_hash); - for(int i=0; i r.length(); + return l.length() > r.length(); } //------------------------------------------------------------------------------ void Workspace::scanWorkspace(bool scanLocal, bool scanIgnored, bool scanModified, bool scanUnchanged, const QStringList &ignorePatterns, UICallback &uiCallback) { - // Scan all workspace files - QFileInfoList all_files; - QString wkdir = fossil().getWorkspacePath(); + // Scan all workspace files + QFileInfoList all_files; + QString wkdir = fossil().getWorkspacePath(); - if(wkdir.isEmpty()) - return; + if (wkdir.isEmpty()) + return; - // Retrieve the status of files tracked by fossil - QStringList res; - if(!fossil().listFiles(res)) - return; + // Retrieve the status of files tracked by fossil + QStringList res; + if (!fossil().listFiles(res)) + return; - bool scan_files = scanLocal; + bool scan_files = scanLocal; - clearState(); + clearState(); - QStringList paths; + QStringList paths; - uiCallback.beginProcess(""); - if(scan_files) - { - QCoreApplication::processEvents(); + uiCallback.beginProcess(""); + if (scan_files) + { + QCoreApplication::processEvents(); - QStringList ignore; - if(!scanIgnored) - ignore = ignorePatterns; + QStringList ignore; + if (!scanIgnored) + ignore = ignorePatterns; - if(!scanDirectory(all_files, wkdir, wkdir, ignore, uiCallback)) - goto _done; + if (!scanDirectory(all_files, wkdir, wkdir, ignore, uiCallback)) + goto _done; - for(QFileInfoList::iterator it=all_files.begin(); it!=all_files.end(); ++it) - { - QString filename = it->fileName(); - QString fullpath = it->absoluteFilePath(); + for (QFileInfoList::iterator it = all_files.begin(); it != all_files.end(); ++it) + { + QString filename = it->fileName(); + QString fullpath = it->absoluteFilePath(); - // Skip fossil files - if(filename == FOSSIL_CHECKOUT1 || filename == FOSSIL_CHECKOUT2 || (!fossil().getRepositoryFile().isEmpty() && QFileInfo(fullpath) == QFileInfo(fossil().getRepositoryFile()))) - continue; + // Skip fossil files + if (filename == FOSSIL_CHECKOUT1 || filename == FOSSIL_CHECKOUT2 || (!fossil().getRepositoryFile().isEmpty() && QFileInfo(fullpath) == QFileInfo(fossil().getRepositoryFile()))) + continue; - WorkspaceFile::Type type = WorkspaceFile::TYPE_UNKNOWN; + WorkspaceFile::Type type = WorkspaceFile::TYPE_UNKNOWN; - WorkspaceFile *rf = new WorkspaceFile(*it, type, wkdir); - const QString &path = rf->getPath(); - getFiles().insert(rf->getFilePath(), rf); - getPaths().insert(path); + WorkspaceFile *rf = new WorkspaceFile(*it, type, wkdir); + const QString &path = rf->getPath(); + getFiles().insert(rf->getFilePath(), rf); + getPaths().insert(path); - // Add or merge file state into directory state - pathstate_map_t::iterator state_it = pathState.find(path); - if(state_it != pathState.end()) - state_it.value() = static_cast(state_it.value() | type); - else - { - pathState.insert(path, type); - paths.append(path); // keep path in list for depth sort - } - } - } - uiCallback.endProcess(); + // Add or merge file state into directory state + pathstate_map_t::iterator state_it = pathState.find(path); + if (state_it != pathState.end()) + state_it.value() = static_cast(state_it.value() | type); + else + { + pathState.insert(path, type); + paths.append(path); // keep path in list for depth sort + } + } + } + uiCallback.endProcess(); - uiCallback.beginProcess(QObject::tr("Updating...")); + uiCallback.beginProcess(QObject::tr("Updating...")); - // Update Files and Directories - for(QStringList::iterator line_it=res.begin(); line_it!=res.end(); ++line_it) - { - QString line = (*line_it).trimmed(); - if(line.length()==0) - continue; + // Update Files and Directories + for (QStringList::iterator line_it = res.begin(); line_it != res.end(); ++line_it) + { + QString line = (*line_it).trimmed(); + if (line.length() == 0) + continue; - int space_index = line.indexOf(' '); - if(space_index==-1) - continue; + int space_index = line.indexOf(' '); + if (space_index == -1) + continue; - QString status_text = line.left(space_index); - QString fname = line.right(line.length() - space_index).trimmed(); - WorkspaceFile::Type type = WorkspaceFile::TYPE_UNKNOWN; + QString status_text = line.left(space_index); + QString fname = line.right(line.length() - space_index).trimmed(); + WorkspaceFile::Type type = WorkspaceFile::TYPE_UNKNOWN; - // Generate a RepoFile for all non-existant fossil files - // or for all files if we skipped scanning the workspace - bool add_missing = !scan_files; + // Generate a RepoFile for all non-existant fossil files + // or for all files if we skipped scanning the workspace + bool add_missing = !scan_files; - if(status_text=="EDITED") - type = WorkspaceFile::TYPE_EDITTED; - else if(status_text=="ADDED") - type = WorkspaceFile::TYPE_ADDED; - else if(status_text=="DELETED") - { - type = WorkspaceFile::TYPE_DELETED; - add_missing = true; - } - else if(status_text=="MISSING") - { - type = WorkspaceFile::TYPE_MISSING; - add_missing = true; - } - else if(status_text=="RENAMED") - type = WorkspaceFile::TYPE_RENAMED; - else if(status_text=="UNCHANGED") - type = WorkspaceFile::TYPE_UNCHANGED; - else if(status_text=="CONFLICT") - type = WorkspaceFile::TYPE_CONFLICTED; - else if(status_text=="UPDATED_BY_MERGE" || status_text=="ADDED_BY_MERGE" || status_text=="ADDED_BY_INTEGRATE" || status_text=="UPDATED_BY_INTEGRATE") - type = WorkspaceFile::TYPE_MERGED; + if (status_text == "EDITED") + type = WorkspaceFile::TYPE_EDITTED; + else if (status_text == "ADDED") + type = WorkspaceFile::TYPE_ADDED; + else if (status_text == "DELETED") + { + type = WorkspaceFile::TYPE_DELETED; + add_missing = true; + } + else if (status_text == "MISSING") + { + type = WorkspaceFile::TYPE_MISSING; + add_missing = true; + } + else if (status_text == "RENAMED") + type = WorkspaceFile::TYPE_RENAMED; + else if (status_text == "UNCHANGED") + type = WorkspaceFile::TYPE_UNCHANGED; + else if (status_text == "CONFLICT") + type = WorkspaceFile::TYPE_CONFLICTED; + else if (status_text == "UPDATED_BY_MERGE" || status_text == "ADDED_BY_MERGE" || status_text == "ADDED_BY_INTEGRATE" || status_text == "UPDATED_BY_INTEGRATE") + type = WorkspaceFile::TYPE_MERGED; - // Filter unwanted file types - if( ((type & WorkspaceFile::TYPE_MODIFIED) && !scanModified) || - ((type & WorkspaceFile::TYPE_UNCHANGED) && !scanUnchanged)) - { - getFiles().remove(fname); - continue; - } - else - add_missing = true; + // Filter unwanted file types + if (((type & WorkspaceFile::TYPE_MODIFIED) && !scanModified) || ((type & WorkspaceFile::TYPE_UNCHANGED) && !scanUnchanged)) + { + getFiles().remove(fname); + continue; + } + else + add_missing = true; - filemap_t::iterator it = getFiles().find(fname); + filemap_t::iterator it = getFiles().find(fname); - WorkspaceFile *rf = 0; - if(add_missing && it==getFiles().end()) - { - QFileInfo info(wkdir+QDir::separator()+fname); - rf = new WorkspaceFile(info, type, wkdir); - getFiles().insert(rf->getFilePath(), rf); - } + WorkspaceFile *rf = 0; + if (add_missing && it == getFiles().end()) + { + QFileInfo info(wkdir + QDir::separator() + fname); + rf = new WorkspaceFile(info, type, wkdir); + getFiles().insert(rf->getFilePath(), rf); + } - if(!rf) - { - it = getFiles().find(fname); - Q_ASSERT(it!=getFiles().end()); - rf = *it; - } + if (!rf) + { + it = getFiles().find(fname); + Q_ASSERT(it != getFiles().end()); + rf = *it; + } - rf->setType(type); + rf->setType(type); - QString path = rf->getPath(); - getPaths().insert(path); + QString path = rf->getPath(); + getPaths().insert(path); - // Add or merge file state into directory state - pathstate_map_t::iterator state_it = pathState.find(path); - if(state_it != pathState.end()) - state_it.value() = static_cast(state_it.value() | type); - else - { - pathState.insert(path, type); - paths.append(path); // keep path in list for depth sort - } - } + // Add or merge file state into directory state + pathstate_map_t::iterator state_it = pathState.find(path); + if (state_it != pathState.end()) + state_it.value() = static_cast(state_it.value() | type); + else + { + pathState.insert(path, type); + paths.append(path); // keep path in list for depth sort + } + } - // Sort paths, so that children (longer path) are before parents (shorter path) - std::sort(paths.begin(), paths.end(), StringLengthDescending); - foreach(const QString &p, paths) - { - pathstate_map_t::iterator state_it = pathState.find(p); - Q_ASSERT(state_it != pathState.end()); - WorkspaceFile::Type state = state_it.value(); + // Sort paths, so that children (longer path) are before parents (shorter path) + std::sort(paths.begin(), paths.end(), StringLengthDescending); + foreach (const QString &p, paths) + { + pathstate_map_t::iterator state_it = pathState.find(p); + Q_ASSERT(state_it != pathState.end()); + WorkspaceFile::Type state = state_it.value(); - // Propagate child dir state to parents - QString parent_path = p; - while(!parent_path.isEmpty()) - { - // Extract parent path - int sep_index = parent_path.lastIndexOf(PATH_SEPARATOR); - if(sep_index>=0) - parent_path = parent_path.left(sep_index); - else - parent_path = ""; + // Propagate child dir state to parents + QString parent_path = p; + while (!parent_path.isEmpty()) + { + // Extract parent path + int sep_index = parent_path.lastIndexOf(PATH_SEPARATOR); + if (sep_index >= 0) + parent_path = parent_path.left(sep_index); + else + parent_path = ""; - // Merge path of child to parent - pathstate_map_t::iterator state_it = pathState.find(parent_path); - if(state_it != pathState.end()) - state_it.value() = static_cast(state_it.value() | state); - else - pathState.insert(parent_path, state); - } - } + // Merge path of child to parent + pathstate_map_t::iterator state_it = pathState.find(parent_path); + if (state_it != pathState.end()) + state_it.value() = static_cast(state_it.value() | state); + else + pathState.insert(parent_path, state); + } + } - // Check if the repository needs integration - res.clear(); - fossil().statusWorkspace(res); - isIntegrated = false; - foreach(const QString &l, res) - { - if(l.trimmed().indexOf("INTEGRATE")==0) - { - isIntegrated = true; - break; - } - } + // Check if the repository needs integration + res.clear(); + fossil().statusWorkspace(res); + isIntegrated = false; + foreach (const QString &l, res) + { + if (l.trimmed().indexOf("INTEGRATE") == 0) + { + isIntegrated = true; + break; + } + } - // Load the stashes, branches and tags - fossil().stashList(getStashes()); + // Load the stashes, branches and tags + fossil().stashList(getStashes()); - fossil().branchList(branchNames, branchNames); + fossil().branchList(branchNames, branchNames); - fossil().tagList(tags); - // Fossil includes the branches in the tag list - // So remove them - foreach(const QString &name, branchNames) - tags.remove(name); + fossil().tagList(tags); + // Fossil includes the branches in the tag list + // So remove them + foreach (const QString &name, branchNames) + tags.remove(name); _done: - uiCallback.endProcess(); + uiCallback.endProcess(); } //------------------------------------------------------------------------------ -bool Workspace::addRemote(const QUrl& url, const QString& name) +bool Workspace::addRemote(const QUrl &url, const QString &name) { - if(remotes.contains(url)) - return false; + if (remotes.contains(url)) + return false; - Q_ASSERT(url.password().isEmpty()); + Q_ASSERT(url.password().isEmpty()); - Remote r(name, url); - remotes.insert(url, r); - return true; + Remote r(name, url); + remotes.insert(url, r); + return true; } //------------------------------------------------------------------------------ -bool Workspace::removeRemote(const QUrl& url) +bool Workspace::removeRemote(const QUrl &url) { - return remotes.remove(url) > 0; + return remotes.remove(url) > 0; } //------------------------------------------------------------------------------ -bool Workspace::setRemoteDefault(const QUrl& url) +bool Workspace::setRemoteDefault(const QUrl &url) { - Q_ASSERT(url.password().isEmpty()); + Q_ASSERT(url.password().isEmpty()); - const QString &url_str = url.toString(); + const QString &url_str = url.toString(); - bool found = false; - for(remote_map_t::iterator it=remotes.begin(); it!=remotes.end(); ++it) - { - if(it->url.toString() == url_str) // FIXME: Use strings as QUrl to QUrl comparisons sometime fail!? - { - it->isDefault = true; - found = true; - } - else - it->isDefault = false; - } - return found; + bool found = false; + for (remote_map_t::iterator it = remotes.begin(); it != remotes.end(); ++it) + { + if (it->url.toString() == url_str) // FIXME: Use strings as QUrl to QUrl comparisons sometime fail!? + { + it->isDefault = true; + found = true; + } + else + it->isDefault = false; + } + return found; } //------------------------------------------------------------------------------ QUrl Workspace::getRemoteDefault() const { - for(remote_map_t::const_iterator it=remotes.begin(); it!=remotes.end(); ++it) - { - if(it->isDefault) - return it->url; - } + for (remote_map_t::const_iterator it = remotes.begin(); it != remotes.end(); ++it) + { + if (it->isDefault) + return it->url; + } - return QUrl(); + return QUrl(); } //------------------------------------------------------------------------------ -Remote * Workspace::findRemote(const QUrl& url) +Remote *Workspace::findRemote(const QUrl &url) { - remote_map_t::iterator it = remotes.find(url); - if(it!=remotes.end()) - return &(*it); - return NULL; + remote_map_t::iterator it = remotes.find(url); + if (it != remotes.end()) + return &(*it); + return NULL; } - diff --git a/src/Workspace.h b/src/Workspace.h index 0c726f9..6983f3c 100644 --- a/src/Workspace.h +++ b/src/Workspace.h @@ -1,15 +1,15 @@ #ifndef WORKSPACE_H #define WORKSPACE_H -#include -#include -#include -#include -#include -#include +#include "Fossil.h" #include "Utils.h" #include "WorkspaceCommon.h" -#include "Fossil.h" +#include +#include +#include +#include +#include +#include ////////////////////////////////////////////////////////////////////////// // Workspace @@ -17,202 +17,121 @@ class Workspace { public: - Workspace(); - ~Workspace(); + Workspace(); + ~Workspace(); - void clearState(); + void clearState(); - Fossil & fossil() { return bridge; } - const Fossil & fossil() const { return bridge; } + Fossil &fossil() { return bridge; } + const Fossil &fossil() const { return bridge; } - const QString & getPath() const { return fossil().getWorkspacePath(); } - bool switchWorkspace(const QString &workspace, QSettings &store); - void scanWorkspace(bool scanLocal, bool scanIgnored, bool scanModified, bool scanUnchanged, const QStringList& ignorePatterns, UICallback &uiCallback); + const QString &getPath() const { return fossil().getWorkspacePath(); } + bool switchWorkspace(const QString &workspace, QSettings &store); + void scanWorkspace(bool scanLocal, bool scanIgnored, bool scanModified, bool scanUnchanged, const QStringList &ignorePatterns, UICallback &uiCallback); - QStandardItemModel &getFileModel() { return repoFileModel; } - QStandardItemModel &getTreeModel() { return repoTreeModel; } + QStandardItemModel &getFileModel() { return repoFileModel; } + QStandardItemModel &getTreeModel() { return repoTreeModel; } - filemap_t &getFiles() { return workspaceFiles; } - stringset_t &getPaths() { return pathSet; } - pathstate_map_t &getPathState() { return pathState; } - stashmap_t &getStashes() { return stashMap; } - QStringMap &getTags() { return tags; } - QStringList &getBranches() { return branchNames; } - bool otherChanges() const { return isIntegrated; } - const QString &getCurrentRevision() const { return fossil().getCurrentRevision(); } - const QStringList &getActiveTags() const { return fossil().getActiveTags(); } - const QString &getProjectName() const { return fossil().getProjectName(); } + filemap_t &getFiles() { return workspaceFiles; } + stringset_t &getPaths() { return pathSet; } + pathstate_map_t &getPathState() { return pathState; } + stashmap_t &getStashes() { return stashMap; } + QStringMap &getTags() { return tags; } + QStringList &getBranches() { return branchNames; } + bool otherChanges() const { return isIntegrated; } + const QString &getCurrentRevision() const { return fossil().getCurrentRevision(); } + const QStringList &getActiveTags() const { return fossil().getActiveTags(); } + const QString &getProjectName() const { return fossil().getProjectName(); } - // Remotes - const remote_map_t &getRemotes() const { return remotes; } - bool addRemote(const QUrl &url, const QString &name); - bool removeRemote(const QUrl &url); - bool setRemoteDefault(const QUrl& url); - QUrl getRemoteDefault() const; - Remote * findRemote(const QUrl& url); + // Remotes + const remote_map_t &getRemotes() const { return remotes; } + bool addRemote(const QUrl &url, const QString &name); + bool removeRemote(const QUrl &url); + bool setRemoteDefault(const QUrl &url); + QUrl getRemoteDefault() const; + Remote *findRemote(const QUrl &url); - void storeWorkspace(QSettings &store); + void storeWorkspace(QSettings &store); - // Fossil Wrappers - void Init(UICallback *callback, const QString &exePath) - { - fossil().Init(callback, exePath); - } + // Fossil Wrappers + void Init(UICallback *callback, const QString &exePath) { fossil().Init(callback, exePath); } - bool create(const QString &repositoryPath, const QString& workspacePath) - { - return fossil().createWorkspace(repositoryPath, workspacePath); - } + bool create(const QString &repositoryPath, const QString &workspacePath) { return fossil().createWorkspace(repositoryPath, workspacePath); } - bool createRepository(const QString &repositoryPath) - { - return fossil().createRepository(repositoryPath); - } + bool createRepository(const QString &repositoryPath) { return fossil().createRepository(repositoryPath); } - WorkspaceState getState() - { - return fossil().getWorkspaceState(); - } + WorkspaceState getState() { return fossil().getWorkspaceState(); } - bool close(bool force=false) - { - return fossil().closeWorkspace(force); - } + bool close(bool force = false) { return fossil().closeWorkspace(force); } - bool cloneRepository(const QString &repository, const QUrl &url, const QUrl &proxyUrl) - { - return fossil().cloneRepository(repository, url, proxyUrl); - } + bool cloneRepository(const QString &repository, const QUrl &url, const QUrl &proxyUrl) { return fossil().cloneRepository(repository, url, proxyUrl); } - bool push(const QUrl& url) - { - return fossil().pushWorkspace(url); - } + bool push(const QUrl &url) { return fossil().pushWorkspace(url); } - bool pull(const QUrl& url) - { - return fossil().pullWorkspace(url); - } + bool pull(const QUrl &url) { return fossil().pullWorkspace(url); } - bool update(QStringList& result, const QString& revision, bool explainOnly) - { - return fossil().updateWorkspace(result, revision, explainOnly); - } + bool update(QStringList &result, const QString &revision, bool explainOnly) { return fossil().updateWorkspace(result, revision, explainOnly); } - bool undo(QStringList& result, bool explainOnly) - { - return fossil().undoWorkspace(result, explainOnly); - } + bool undo(QStringList &result, bool explainOnly) { return fossil().undoWorkspace(result, explainOnly); } - bool diffFile(const QString &repoFile, bool graphical) - { - return fossil().diffFile(repoFile, graphical); - } + bool diffFile(const QString &repoFile, bool graphical) { return fossil().diffFile(repoFile, graphical); } - bool commitFiles(const QStringList &fileList, const QString &comment, const QString& newBranchName, bool isPrivateBranch) - { - return fossil().commitFiles(fileList, comment, newBranchName, isPrivateBranch); - } + bool commitFiles(const QStringList &fileList, const QString &comment, const QString &newBranchName, bool isPrivateBranch) + { + return fossil().commitFiles(fileList, comment, newBranchName, isPrivateBranch); + } - bool addFiles(const QStringList& fileList) - { - return fossil().addFiles(fileList); - } + bool addFiles(const QStringList &fileList) { return fossil().addFiles(fileList); } - bool removeFiles(const QStringList& fileList, bool deleteLocal) - { - return fossil().removeFiles(fileList, deleteLocal); - } + bool removeFiles(const QStringList &fileList, bool deleteLocal) { return fossil().removeFiles(fileList, deleteLocal); } - bool revertFiles(const QStringList& fileList) - { - return fossil().revertFiles(fileList); - } + bool revertFiles(const QStringList &fileList) { return fossil().revertFiles(fileList); } - bool renameFile(const QString& beforePath, const QString& afterPath, bool renameLocal) - { - return fossil().renameFile(beforePath, afterPath, renameLocal); - } + bool renameFile(const QString &beforePath, const QString &afterPath, bool renameLocal) { return fossil().renameFile(beforePath, afterPath, renameLocal); } - // Stashes - bool stashNew(const QStringList& fileList, const QString& name, bool revert) - { - return fossil().stashNew(fileList, name, revert); - } + // Stashes + bool stashNew(const QStringList &fileList, const QString &name, bool revert) { return fossil().stashNew(fileList, name, revert); } - bool stashList(stashmap_t &stashes) - { - return fossil().stashList(stashes); - } + bool stashList(stashmap_t &stashes) { return fossil().stashList(stashes); } - bool stashApply(const QString& name) - { - return fossil().stashApply(name); - } + bool stashApply(const QString &name) { return fossil().stashApply(name); } - bool stashDrop(const QString& name) - { - return fossil().stashDrop(name); - } + bool stashDrop(const QString &name) { return fossil().stashDrop(name); } - bool stashDiff(const QString& name) - { - return fossil().stashDiff(name); - } + bool stashDiff(const QString &name) { return fossil().stashDiff(name); } - // Tags - bool tagList(QStringMap& tags) - { - return fossil().tagList(tags); - } + // Tags + bool tagList(QStringMap &tags) { return fossil().tagList(tags); } - bool tagNew(const QString& name, const QString& revision) - { - return fossil().tagNew(name, revision); - } + bool tagNew(const QString &name, const QString &revision) { return fossil().tagNew(name, revision); } - bool tagDelete(const QString& name, const QString& revision) - { - return fossil().tagDelete(name, revision); - } + bool tagDelete(const QString &name, const QString &revision) { return fossil().tagDelete(name, revision); } - // Branches - bool branchList(QStringList& branches, QStringList& activeBranches) - { - return fossil().branchList(branches, activeBranches); - } + // Branches + bool branchList(QStringList &branches, QStringList &activeBranches) { return fossil().branchList(branches, activeBranches); } - bool branchNew(const QString& name, const QString& revisionBasis, bool isPrivate=false) - { - return fossil().branchNew(name, revisionBasis, isPrivate); - } + bool branchNew(const QString &name, const QString &revisionBasis, bool isPrivate = false) { return fossil().branchNew(name, revisionBasis, isPrivate); } - bool branchMerge(QStringList& res, const QString& revision, bool integrate, bool force, bool testOnly) - { - return fossil().branchMerge(res, revision, integrate, force, testOnly); - } + bool branchMerge(QStringList &res, const QString &revision, bool integrate, bool force, bool testOnly) { return fossil().branchMerge(res, revision, integrate, force, testOnly); } - bool getInterfaceVersion(QString &version) - { - return fossil().getExeVersion(version); - } + bool getInterfaceVersion(QString &version) { return fossil().getExeVersion(version); } private: - static bool scanDirectory(QFileInfoList &entries, const QString& dirPath, const QString &baseDir, const QStringList& ignorePatterns, UICallback &uiCallback); + static bool scanDirectory(QFileInfoList &entries, const QString &dirPath, const QString &baseDir, const QStringList &ignorePatterns, UICallback &uiCallback); private: - Fossil bridge; - filemap_t workspaceFiles; - stringset_t pathSet; - pathstate_map_t pathState; - stashmap_t stashMap; - QStringList branchNames; - QStringMap tags; - remote_map_t remotes; - bool isIntegrated; + Fossil bridge; + filemap_t workspaceFiles; + stringset_t pathSet; + pathstate_map_t pathState; + stashmap_t stashMap; + QStringList branchNames; + QStringMap tags; + remote_map_t remotes; + bool isIntegrated; - QStandardItemModel repoFileModel; - QStandardItemModel repoTreeModel; + QStandardItemModel repoFileModel; + QStandardItemModel repoTreeModel; }; -#endif // WORKSPACE_H +#endif // WORKSPACE_H diff --git a/src/WorkspaceCommon.h b/src/WorkspaceCommon.h index 31c3e8d..2c871eb 100644 --- a/src/WorkspaceCommon.h +++ b/src/WorkspaceCommon.h @@ -1,21 +1,21 @@ #ifndef WORKSPACECOMMON_H #define WORKSPACECOMMON_H -#include -#include -#include -#include -#include #include "Utils.h" +#include +#include +#include +#include +#include ////////////////////////////////////////////////////////////////////////// // WorkspaceState ////////////////////////////////////////////////////////////////////////// enum WorkspaceState { - WORKSPACE_STATE_OK, - WORKSPACE_STATE_NOTFOUND, - WORKSPACE_STATE_OLDSCHEMA + WORKSPACE_STATE_OK, + WORKSPACE_STATE_NOTFOUND, + WORKSPACE_STATE_OLDSCHEMA }; ////////////////////////////////////////////////////////////////////////// @@ -23,107 +23,81 @@ enum WorkspaceState ////////////////////////////////////////////////////////////////////////// struct WorkspaceFile { - enum Type - { - TYPE_UNKNOWN = 1<<0, - TYPE_UNCHANGED = 1<<1, - TYPE_EDITTED = 1<<2, - TYPE_ADDED = 1<<3, - TYPE_DELETED = 1<<4, - TYPE_MISSING = 1<<5, - TYPE_RENAMED = 1<<6, - TYPE_CONFLICTED = 1<<7, - TYPE_MERGED = 1<<8, - TYPE_MODIFIED = TYPE_EDITTED|TYPE_ADDED|TYPE_DELETED|TYPE_MISSING|TYPE_RENAMED|TYPE_CONFLICTED|TYPE_MERGED, - TYPE_REPO = TYPE_UNCHANGED|TYPE_MODIFIED, - TYPE_ALL = TYPE_UNKNOWN|TYPE_REPO - }; + enum Type + { + TYPE_UNKNOWN = 1 << 0, + TYPE_UNCHANGED = 1 << 1, + TYPE_EDITTED = 1 << 2, + TYPE_ADDED = 1 << 3, + TYPE_DELETED = 1 << 4, + TYPE_MISSING = 1 << 5, + TYPE_RENAMED = 1 << 6, + TYPE_CONFLICTED = 1 << 7, + TYPE_MERGED = 1 << 8, + TYPE_MODIFIED = TYPE_EDITTED | TYPE_ADDED | TYPE_DELETED | TYPE_MISSING | TYPE_RENAMED | TYPE_CONFLICTED | TYPE_MERGED, + TYPE_REPO = TYPE_UNCHANGED | TYPE_MODIFIED, + TYPE_ALL = TYPE_UNKNOWN | TYPE_REPO + }; - WorkspaceFile(const QFileInfo &info, Type type, const QString &repoPath) - { - FileInfo = info; - FileType = type; - FilePath = getRelativeFilename(repoPath); - Path = FileInfo.absolutePath(); + WorkspaceFile(const QFileInfo &info, Type type, const QString &repoPath) + { + FileInfo = info; + FileType = type; + FilePath = getRelativeFilename(repoPath); + Path = FileInfo.absolutePath(); - // Strip the workspace path from the path - Q_ASSERT(Path.indexOf(repoPath)==0); - Path = Path.mid(repoPath.length()+1); - } + // Strip the workspace path from the path + Q_ASSERT(Path.indexOf(repoPath) == 0); + Path = Path.mid(repoPath.length() + 1); + } - bool isType(Type t) const - { - return FileType == t; - } + bool isType(Type t) const { return FileType == t; } - void setType(Type t) - { - FileType = t; - } + void setType(Type t) { FileType = t; } - Type getType() const - { - return FileType; - } + Type getType() const { return FileType; } - QFileInfo getFileInfo() const - { - return FileInfo; - } + QFileInfo getFileInfo() const { return FileInfo; } - const QString &getFilePath() const - { - return FilePath; - } + const QString &getFilePath() const { return FilePath; } - QString getFilename() const - { - return FileInfo.fileName(); - } + QString getFilename() const { return FileInfo.fileName(); } - const QString &getPath() const - { - return Path; - } + const QString &getPath() const { return Path; } - QString getRelativeFilename(const QString &path) - { - QString abs_base_dir = QDir(path).absolutePath(); + QString getRelativeFilename(const QString &path) + { + QString abs_base_dir = QDir(path).absolutePath(); - QString relative = FileInfo.absoluteFilePath(); - int index = relative.indexOf(abs_base_dir); - if(index<0) - return QString(""); + QString relative = FileInfo.absoluteFilePath(); + int index = relative.indexOf(abs_base_dir); + if (index < 0) + return QString(""); - return relative.right(relative.length() - abs_base_dir.length()-1); - } + return relative.right(relative.length() - abs_base_dir.length() - 1); + } private: - QFileInfo FileInfo; - Type FileType; - QString FilePath; - QString Path; + QFileInfo FileInfo; + Type FileType; + QString FilePath; + QString Path; }; class Remote { public: - Remote(const QString &_name, const QUrl &_url, bool _isDefault=false) - : name(_name), url(_url), isDefault(_isDefault) - { - } - - QString name; - QUrl url; - bool isDefault; + Remote(const QString &_name, const QUrl &_url, bool _isDefault = false) : name(_name), url(_url), isDefault(_isDefault) {} + QString name; + QUrl url; + bool isDefault; }; typedef QMap remote_map_t; typedef QMap pathstate_map_t; -typedef QList filelist_t; -typedef QMap filemap_t; +typedef QList filelist_t; +typedef QMap filemap_t; typedef QMap stashmap_t; - -#endif // WORKSPACECOMMON_H +#endif // WORKSPACECOMMON_H diff --git a/src/main.cpp b/src/main.cpp index 17e5350..8a40e27 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,46 +1,42 @@ -#include #include "MainWindow.h" +#include int main(int argc, char *argv[]) { - QApplication app(argc, argv); - app.setApplicationName("Fuel"); - app.setApplicationVersion(FUEL_VERSION); - app.setOrganizationDomain("fuel-scm.org"); - app.setOrganizationName("Fuel-SCM"); + QApplication app(argc, argv); + app.setApplicationName("Fuel"); + app.setApplicationVersion(FUEL_VERSION); + app.setOrganizationDomain("fuel-scm.org"); + app.setOrganizationName("Fuel-SCM"); +#ifdef Q_OS_MACX + // Native OSX applications don't have menu icons + app.setAttribute(Qt::AA_DontShowIconsInMenus); +#endif + { + bool portable = false; + QString workspace; - #ifdef Q_OS_MACX - // Native OSX applications don't have menu icons - app.setAttribute(Qt::AA_DontShowIconsInMenus); - #endif - { - bool portable = false; - QString workspace; + Q_ASSERT(app.arguments().size() > 0); + for (int i = 1; i < app.arguments().size(); ++i) + { + QString arg = app.arguments()[i]; + // Parse options + if (arg.indexOf("--") != -1) + { + if (arg.indexOf("portable") != -1) + portable = true; + continue; + } + else + workspace = arg; + } - Q_ASSERT(app.arguments().size()>0); - for(int i=1; i