Page Menu
Home
GnuPG
Search
Configure Global Search
Log In
Files
F25703412
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Size
123 KB
Subscribers
None
View Options
diff --git a/configdialog.cpp b/configdialog.cpp
index dcef8dc..923e682 100644
--- a/configdialog.cpp
+++ b/configdialog.cpp
@@ -1,873 +1,876 @@
#include "configdialog.h"
-#include "ui_configdialog.h"
-#include "mainwindow.h"
#include "keygendialog.h"
+#include "mainwindow.h"
+#include "ui_configdialog.h"
#include <QDebug>
-#include <QMessageBox>
#include <QDir>
+#include <QMessageBox>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
/**
* @brief ConfigDialog::ConfigDialog
* @param parent
*/
ConfigDialog::ConfigDialog(MainWindow *parent)
: QDialog(parent), ui(new Ui::ConfigDialog) {
mainWindow = parent;
ui->setupUi(this);
ui->profileTable->verticalHeader()->hide();
ui->profileTable->horizontalHeader()->setStretchLastSection(true);
ui->label->setText(ui->label->text() + VERSION);
ui->comboBoxClipboard->clear();
ui->comboBoxClipboard->addItem(tr("No Clipboard"));
ui->comboBoxClipboard->addItem(tr("Always copy to clipboard"));
ui->comboBoxClipboard->addItem(tr("On-demand copy to clipboard"));
ui->comboBoxClipboard->setCurrentIndex(0);
}
/**
* @brief ConfigDialog::~ConfigDialog
*/
ConfigDialog::~ConfigDialog() {
mainWindow->setGitExecutable(ui->gitPath->text());
mainWindow->setGpgExecutable(ui->gpgPath->text());
mainWindow->setPassExecutable(ui->passPath->text());
}
/**
* @brief ConfigDialog::setPassPath
* @param path
*/
void ConfigDialog::setPassPath(QString path) { ui->passPath->setText(path); }
/**
* @brief ConfigDialog::setGitPath
* @param path
*/
void ConfigDialog::setGitPath(QString path) {
ui->gitPath->setText(path);
if (path.isEmpty()) {
useGit(false);
ui->checkBoxUseGit->setEnabled(false);
} else {
ui->checkBoxUseGit->setEnabled(true);
}
}
/**
* @brief ConfigDialog::setGpgPath
* @param path
*/
void ConfigDialog::setGpgPath(QString path) { ui->gpgPath->setText(path); }
/**
* @brief ConfigDialog::setStorePath
* @param path
*/
void ConfigDialog::setStorePath(QString path) { ui->storePath->setText(path); }
/**
* @brief ConfigDialog::getPassPath
* @return
*/
QString ConfigDialog::getPassPath() { return ui->passPath->text(); }
/**
* @brief ConfigDialog::getGitPath
* @return
*/
QString ConfigDialog::getGitPath() { return ui->gitPath->text(); }
/**
* @brief ConfigDialog::getGpgPath
* @return
*/
QString ConfigDialog::getGpgPath() { return ui->gpgPath->text(); }
/**
* @brief ConfigDialog::getStorePath
* @return
*/
QString ConfigDialog::getStorePath() { return ui->storePath->text(); }
/**
* @brief ConfigDialog::usePass
* @return
*/
bool ConfigDialog::usePass() { return ui->radioButtonPass->isChecked(); }
/**
* @brief ConfigDialog::usePass
* @param pass
*/
void ConfigDialog::usePass(bool usePass) {
if (usePass) {
ui->radioButtonNative->setChecked(false);
ui->radioButtonPass->setChecked(true);
} else {
ui->radioButtonNative->setChecked(true);
ui->radioButtonPass->setChecked(false);
}
setGroupBoxState();
}
/**
* @brief ConfigDialog::on_radioButtonNative_clicked
*/
void ConfigDialog::on_radioButtonNative_clicked() { setGroupBoxState(); }
/**
* @brief ConfigDialog::on_radioButtonPass_clicked
*/
void ConfigDialog::on_radioButtonPass_clicked() { setGroupBoxState(); }
/**
* @brief ConfigDialog::setGroupBoxState
*/
void ConfigDialog::setGroupBoxState() {
if (ui->radioButtonPass->isChecked()) {
ui->groupBoxNative->setEnabled(false);
ui->groupBoxPass->setEnabled(true);
} else {
ui->groupBoxNative->setEnabled(true);
ui->groupBoxPass->setEnabled(false);
}
}
/**
* @brief ConfigDialog::selectExecutable
* @return
*/
QString ConfigDialog::selectExecutable() {
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.setOption(QFileDialog::ReadOnly);
if (dialog.exec())
return dialog.selectedFiles().first();
else
return "";
}
/**
* @brief ConfigDialog::selectFolder
* @return
*/
QString ConfigDialog::selectFolder() {
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::Directory);
dialog.setFilter(QDir::NoFilter);
dialog.setOption(QFileDialog::ShowDirsOnly);
if (dialog.exec())
return dialog.selectedFiles().first();
else
return "";
}
/**
* @brief ConfigDialog::on_toolButtonGit_clicked
*/
void ConfigDialog::on_toolButtonGit_clicked() {
QString git = selectExecutable();
if (!git.isEmpty()) {
ui->gitPath->setText(git);
ui->checkBoxUseGit->setEnabled(true);
} else {
useGit(false);
ui->checkBoxUseGit->setEnabled(false);
}
}
/**
* @brief ConfigDialog::on_toolButtonGpg_clicked
*/
void ConfigDialog::on_toolButtonGpg_clicked() {
QString gpg = selectExecutable();
if (!gpg.isEmpty())
ui->gpgPath->setText(gpg);
}
/**
* @brief ConfigDialog::on_toolButtonPass_clicked
*/
void ConfigDialog::on_toolButtonPass_clicked() {
QString pass = selectExecutable();
if (!pass.isEmpty())
ui->passPath->setText(pass);
}
/**
* @brief ConfigDialog::on_toolButtonStore_clicked
*/
void ConfigDialog::on_toolButtonStore_clicked() {
QString store = selectFolder();
- if (!store.isEmpty()) // TODO(annejan) call check
+ if (!store.isEmpty()) // TODO(annejan) call check
ui->storePath->setText(store);
}
/**
* @brief ConfigDialog::on_comboBoxClipboard_activated
*/
void ConfigDialog::on_comboBoxClipboard_activated() {
if (ui->comboBoxClipboard->currentIndex() > 0) {
ui->checkBoxAutoclear->setEnabled(true);
ui->checkBoxHidePassword->setEnabled(true);
ui->checkBoxHideContent->setEnabled(true);
if (ui->checkBoxAutoclear->isChecked()) {
ui->spinBoxAutoclearSeconds->setEnabled(true);
ui->labelSeconds->setEnabled(true);
} else {
ui->spinBoxAutoclearSeconds->setEnabled(false);
ui->labelSeconds->setEnabled(false);
}
} else {
ui->checkBoxAutoclear->setEnabled(false);
ui->spinBoxAutoclearSeconds->setEnabled(false);
ui->labelSeconds->setEnabled(false);
ui->checkBoxHidePassword->setEnabled(false);
ui->checkBoxHideContent->setEnabled(false);
}
}
/**
* @brief ConfigDialog::on_checkBoxAutoclearPanel_clicked
*/
void ConfigDialog::on_checkBoxAutoclearPanel_clicked() {
if (ui->checkBoxAutoclearPanel->isChecked()) {
ui->spinBoxAutoclearPanelSeconds->setEnabled(true);
ui->labelPanelSeconds->setEnabled(true);
} else {
ui->spinBoxAutoclearPanelSeconds->setEnabled(false);
ui->labelPanelSeconds->setEnabled(false);
}
}
/**
* @brief ConfigDialog::useClipboard
*/
void ConfigDialog::useClipboard(MainWindow::clipBoardType useClipboard) {
ui->comboBoxClipboard->setCurrentIndex(static_cast<int>(useClipboard));
on_comboBoxClipboard_activated();
}
/**
* @brief ConfigDialog::useAutoclear
* @param useAutoclear
*/
void ConfigDialog::useAutoclear(bool useAutoclear) {
ui->checkBoxAutoclear->setChecked(useAutoclear);
on_checkBoxAutoclear_clicked();
}
/**
* @brief ConfigDialog::setAutoclear
* @param seconds
*/
void ConfigDialog::setAutoclear(int seconds) {
ui->spinBoxAutoclearSeconds->setValue(seconds);
}
/**
* @brief ConfigDialog::useAutoclearPanel
* @param useAutoclearPanel
*/
void ConfigDialog::useAutoclearPanel(bool useAutoclearPanel) {
ui->checkBoxAutoclearPanel->setChecked(useAutoclearPanel);
on_checkBoxAutoclearPanel_clicked();
}
/**
* @brief ConfigDialog::setAutoclearPanel
* @param seconds
*/
void ConfigDialog::setAutoclearPanel(int seconds) {
ui->spinBoxAutoclearPanelSeconds->setValue(seconds);
}
/**
* @brief ConfigDialog::useClipboard
* @return
*/
MainWindow::clipBoardType ConfigDialog::useClipboard() {
return static_cast<MainWindow::clipBoardType>(
ui->comboBoxClipboard->currentIndex());
}
/**
* @brief ConfigDialog::useAutoclear
* @return
*/
bool ConfigDialog::useAutoclear() { return ui->checkBoxAutoclear->isChecked(); }
/**
* @brief ConfigDialog::getAutoclear
* @return
*/
int ConfigDialog::getAutoclear() {
return ui->spinBoxAutoclearSeconds->value();
}
/**
* @brief ConfigDialog::on_checkBoxAutoclear_clicked
*/
void ConfigDialog::on_checkBoxAutoclear_clicked() {
on_comboBoxClipboard_activated();
}
/**
* @brief ConfigDialog::useAutoclearPanel
* @return
*/
bool ConfigDialog::useAutoclearPanel() {
return ui->checkBoxAutoclearPanel->isChecked();
}
/**
* @brief ConfigDialog::getAutoclearPanel
* @return
*/
int ConfigDialog::getAutoclearPanel() {
return ui->spinBoxAutoclearPanelSeconds->value();
}
/**
* @brief ConfigDialog::hidePassword
* @return
*/
bool ConfigDialog::hidePassword() {
return ui->checkBoxHidePassword->isChecked();
}
/**
* @brief ConfigDialog::hideContent
* @return
*/
bool ConfigDialog::hideContent() {
return ui->checkBoxHideContent->isChecked();
}
/**
* @brief ConfigDialog::hidePassword
* @param hidePassword
*/
void ConfigDialog::hidePassword(bool hidePassword) {
ui->checkBoxHidePassword->setChecked(hidePassword);
}
/**
* @brief ConfigDialog::hideContent
* @param hideContent
*/
void ConfigDialog::hideContent(bool hideContent) {
ui->checkBoxHideContent->setChecked(hideContent);
}
/**
* @brief ConfigDialog::addGPGId
* @return
*/
bool ConfigDialog::addGPGId() { return ui->checkBoxAddGPGId->isChecked(); }
/**
* @brief ConfigDialog::addGPGId
* @param addGPGId
*/
void ConfigDialog::addGPGId(bool addGPGId) {
ui->checkBoxAddGPGId->setChecked(addGPGId);
}
/**
* @brief ConfigDialog::genKey
* @param QString batch
*/
void ConfigDialog::genKey(QString batch, QDialog *dialog) {
mainWindow->generateKeyPair(batch, dialog);
}
/**
* @brief ConfigDialog::setProfiles
* @param profiles
* @param profile
*/
void ConfigDialog::setProfiles(QHash<QString, QString> profiles,
QString profile) {
// qDebug() << profiles;
if (profiles.contains("")) {
profiles.remove("");
// remove weird "" key value pairs
}
ui->profileTable->setRowCount(profiles.count());
QHashIterator<QString, QString> i(profiles);
int n = 0;
while (i.hasNext()) {
i.next();
if (!i.value().isEmpty() && !i.key().isEmpty()) {
ui->profileTable->setItem(n, 0, new QTableWidgetItem(i.key()));
ui->profileTable->setItem(n, 1, new QTableWidgetItem(i.value()));
// qDebug() << "naam:" + i.key();
if (i.key() == profile)
ui->profileTable->selectRow(n);
}
++n;
}
}
/**
* @brief ConfigDialog::getProfiles
* @return
*/
QHash<QString, QString> ConfigDialog::getProfiles() {
QHash<QString, QString> profiles;
// Check?
for (int i = 0; i < ui->profileTable->rowCount(); ++i) {
QTableWidgetItem *pathItem = ui->profileTable->item(i, 1);
if (0 != pathItem) {
QTableWidgetItem *item = ui->profileTable->item(i, 0);
if (item == 0) {
qDebug() << "empty name, shoud fix in frontend";
continue;
}
profiles.insert(item->text(), pathItem->text());
}
}
return profiles;
}
/**
* @brief ConfigDialog::on_addButton_clicked
*/
void ConfigDialog::on_addButton_clicked() {
int n = ui->profileTable->rowCount();
ui->profileTable->insertRow(n);
ui->profileTable->setItem(n, 1, new QTableWidgetItem(ui->storePath->text()));
ui->profileTable->selectRow(n);
ui->deleteButton->setEnabled(true);
}
/**
* @brief ConfigDialog::on_deleteButton_clicked
*/
void ConfigDialog::on_deleteButton_clicked() {
- QSet<int> selectedRows; // we use a set to prevent doubles
+ QSet<int> selectedRows; // we use a set to prevent doubles
QList<QTableWidgetItem *> itemList = ui->profileTable->selectedItems();
if (itemList.count() == 0) {
QMessageBox::warning(this, tr("No profile selected"),
tr("No profile selected to delete"));
return;
}
QTableWidgetItem *item;
- foreach(item, itemList)
+ foreach (item, itemList)
selectedRows.insert(item->row());
// get a list, and sort it big to small
QList<int> rows = selectedRows.toList();
qSort(rows.begin(), rows.end());
// now actually do the removing:
- foreach(int row, rows)
+ foreach (int row, rows)
ui->profileTable->removeRow(row);
if (ui->profileTable->rowCount() < 1)
ui->deleteButton->setEnabled(false);
}
void ConfigDialog::criticalMessage(const QString &title, const QString &text) {
QMessageBox::critical(this, title, text, QMessageBox::Ok, QMessageBox::Ok);
}
/**
* @brief ConfigDialog::wizard
*/
void ConfigDialog::wizard() {
// mainWindow->checkConfig();
bool clean = false;
QString gpg = ui->gpgPath->text();
// QString gpg = mainWindow->getGpgExecutable();
if (!QFile(gpg).exists()) {
criticalMessage(
tr("GnuPG not found"),
tr("Please install GnuPG on your system.<br>Install "
"<strong>gpg</strong> using your favorite package manager<br>or <a "
"href=\"https://www.gnupg.org/download/#sec-1-2\">download</a> it "
"from GnuPG.org"));
clean = true;
}
QStringList names = mainWindow->getSecretKeys();
qDebug() << names;
if (QFile(gpg).exists() && names.empty()) {
KeygenDialog d(this);
if (!d.exec())
return;
}
QString passStore = ui->storePath->text();
if (!QFile(passStore).exists()) {
// TODO(annejan) pass version?
if (QMessageBox::question(
this, tr("Create password-store?"),
tr("Would you like to create a password-store at %1?")
.arg(passStore),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
QDir().mkdir(passStore);
#ifdef Q_OS_WIN
SetFileAttributes(passStore.toStdWString().c_str(),
FILE_ATTRIBUTE_HIDDEN);
#endif
if (useGit())
mainWindow->executePassGitInit();
mainWindow->userDialog(passStore);
}
}
if (!QFile(passStore + ".gpg-id").exists()) {
qDebug() << ".gpg-id file does not exist";
if (!clean) {
criticalMessage(tr("Password store not initialised"),
tr("The folder %1 doesn't seem to be a password store or "
"is not yet initialised.")
.arg(passStore));
}
while (!QFile(passStore).exists()) {
on_toolButtonStore_clicked();
// allow user to cancel
if (passStore == ui->storePath->text())
return;
passStore = ui->storePath->text();
}
if (!QFile(passStore + ".gpg-id").exists()) {
qDebug() << ".gpg-id file still does not exist :/";
// appears not to be store
// init yes / no ?
mainWindow->userDialog(passStore);
}
}
}
/**
* @brief ConfigDialog::useTrayIcon
* @return
*/
bool ConfigDialog::useTrayIcon() {
return ui->checkBoxUseTrayIcon->isChecked();
}
/**
* @brief ConfigDialog::hideOnClose
* @return
*/
bool ConfigDialog::hideOnClose() {
return ui->checkBoxHideOnClose->isEnabled() &&
ui->checkBoxHideOnClose->isChecked();
}
/**
* @brief ConfigDialog::useTrayIcon
* @param useSystray
*/
void ConfigDialog::useTrayIcon(bool useSystray) {
ui->checkBoxUseTrayIcon->setChecked(useSystray);
ui->checkBoxHideOnClose->setEnabled(useSystray);
ui->checkBoxStartMinimized->setEnabled(useSystray);
if (!useSystray) {
ui->checkBoxHideOnClose->setChecked(false);
ui->checkBoxStartMinimized->setChecked(false);
}
}
/**
* @brief ConfigDialog::hideOnClose
* @param hideOnClose
*/
void ConfigDialog::hideOnClose(bool hideOnClose) {
ui->checkBoxHideOnClose->setChecked(hideOnClose);
}
/**
* @brief ConfigDialog::on_checkBoxUseTrayIcon_clicked
*/
void ConfigDialog::on_checkBoxUseTrayIcon_clicked() {
if (ui->checkBoxUseTrayIcon->isChecked()) {
ui->checkBoxHideOnClose->setEnabled(true);
ui->checkBoxStartMinimized->setEnabled(true);
} else {
ui->checkBoxStartMinimized->setEnabled(false);
ui->checkBoxHideOnClose->setEnabled(false);
}
}
/**
* @brief ConfigDialog::closeEvent
* @param event
*/
void ConfigDialog::closeEvent(QCloseEvent *event) {
// TODO(annejan) save window size or something?
event->accept();
}
/**
* @brief ConfigDialog::useGit
* @param useGit
*/
void ConfigDialog::useGit(bool useGit) {
ui->checkBoxUseGit->setChecked(useGit);
on_checkBoxUseGit_clicked();
}
/**
* @brief ConfigDialog::useGit
* @return
*/
bool ConfigDialog::useGit() { return ui->checkBoxUseGit->isChecked(); }
/**
* @brief ConfigDialog::on_checkBoxUseGit_clicked
*/
void ConfigDialog::on_checkBoxUseGit_clicked() {
ui->checkBoxAddGPGId->setEnabled(ui->checkBoxUseGit->isChecked());
ui->checkBoxAutoPull->setEnabled(ui->checkBoxUseGit->isChecked());
ui->checkBoxAutoPush->setEnabled(ui->checkBoxUseGit->isChecked());
}
/**
* @brief ConfigDialog::on_toolButtonPwgen_clicked
*/
void ConfigDialog::on_toolButtonPwgen_clicked() {
QString pwgen = selectExecutable();
if (!pwgen.isEmpty()) {
ui->pwgenPath->setText(pwgen);
ui->checkBoxUsePwgen->setEnabled(true);
} else {
ui->checkBoxUsePwgen->setEnabled(false);
ui->checkBoxUsePwgen->setChecked(false);
}
}
/**
* @brief ConfigDialog::getPwgenPath
* @return
*/
QString ConfigDialog::getPwgenPath() { return ui->pwgenPath->text(); }
/**
* @brief ConfigDialog::setPwgenPath
* @param pwgen
*/
void ConfigDialog::setPwgenPath(QString pwgen) {
ui->pwgenPath->setText(pwgen);
if (pwgen.isEmpty()) {
ui->checkBoxUsePwgen->setChecked(false);
ui->checkBoxUsePwgen->setEnabled(false);
}
on_checkBoxUsePwgen_clicked();
}
/**
* @brief ConfigDialog::on_checkBoxUsPwgen_clicked
*/
void ConfigDialog::on_checkBoxUsePwgen_clicked() {
bool usePwgen = ui->checkBoxUsePwgen->isChecked();
ui->checkBoxAvoidCapitals->setEnabled(usePwgen);
ui->checkBoxAvoidNumbers->setEnabled(usePwgen);
ui->checkBoxLessRandom->setEnabled(usePwgen);
ui->checkBoxUseSymbols->setEnabled(usePwgen);
ui->lineEditPasswordChars->setEnabled(!usePwgen);
ui->labelPasswordChars->setEnabled(!usePwgen);
}
/**
* @brief ConfigDialog::usePwgen
* @param usePwgen
*/
void ConfigDialog::usePwgen(bool usePwgen) {
if (ui->pwgenPath->text().isEmpty())
usePwgen = false;
ui->checkBoxUsePwgen->setChecked(usePwgen);
on_checkBoxUsePwgen_clicked();
}
void ConfigDialog::avoidCapitals(bool avoidCapitals) {
ui->checkBoxAvoidCapitals->setChecked(avoidCapitals);
}
void ConfigDialog::avoidNumbers(bool avoidNumbers) {
ui->checkBoxAvoidNumbers->setChecked(avoidNumbers);
}
void ConfigDialog::lessRandom(bool lessRandom) {
ui->checkBoxLessRandom->setChecked(lessRandom);
}
/**
* @brief ConfigDialog::useSymbols
* @param useSymbols
*/
void ConfigDialog::useSymbols(bool useSymbols) {
ui->checkBoxUseSymbols->setChecked(useSymbols);
}
/**
* @brief ConfigDialog::setPasswordLength
* @param pwLen
*/
void ConfigDialog::setPasswordLength(int pwLen) {
ui->spinBoxPasswordLength->setValue(pwLen);
}
void ConfigDialog::setPasswordChars(QString pwChars) {
ui->lineEditPasswordChars->setText(pwChars);
}
/**
* @brief ConfigDialog::usePwgen
* @return
*/
bool ConfigDialog::usePwgen() { return ui->checkBoxUsePwgen->isChecked(); }
-bool ConfigDialog::avoidCapitals() { return ui->checkBoxAvoidCapitals->isChecked(); }
-bool ConfigDialog::avoidNumbers() { return ui->checkBoxAvoidNumbers->isChecked(); }
+bool ConfigDialog::avoidCapitals() {
+ return ui->checkBoxAvoidCapitals->isChecked();
+}
+bool ConfigDialog::avoidNumbers() {
+ return ui->checkBoxAvoidNumbers->isChecked();
+}
bool ConfigDialog::lessRandom() { return ui->checkBoxLessRandom->isChecked(); }
-
/**
* @brief ConfigDialog::useSymbols
* @return
*/
bool ConfigDialog::useSymbols() { return ui->checkBoxUseSymbols->isChecked(); }
/**
* @brief ConfigDialog::getPasswordLength
* @return
*/
int ConfigDialog::getPasswordLength() {
return ui->spinBoxPasswordLength->value();
}
/**
* @brief ConfigDialog::getPasswordChars
* @return
*/
QString ConfigDialog::getPasswordChars() {
return ui->lineEditPasswordChars->text();
}
/**
* @brief ConfigDialog::startMinimized
* @return
*/
bool ConfigDialog::startMinimized() {
return ui->checkBoxStartMinimized->isChecked();
}
/**
* @brief ConfigDialog::startMinimized
* @param startMinimized
*/
void ConfigDialog::startMinimized(bool startMinimized) {
ui->checkBoxStartMinimized->setChecked(startMinimized);
}
/**
* @brief ConfigDialog::on_checkBoxUseTemplate_clicked
*/
void ConfigDialog::on_checkBoxUseTemplate_clicked() {
ui->plainTextEditTemplate->setEnabled(ui->checkBoxUseTemplate->isChecked());
ui->checkBoxTemplateAllFields->setEnabled(
ui->checkBoxUseTemplate->isChecked());
}
/**
* @brief ConfigDialog::useTemplate
* @param useTemplate
*/
void ConfigDialog::useTemplate(bool useTemplate) {
ui->checkBoxUseTemplate->setChecked(useTemplate);
on_checkBoxUseTemplate_clicked();
}
/**
* @brief ConfigDialog::useTemplate
* @return
*/
bool ConfigDialog::useTemplate() {
return ui->checkBoxUseTemplate->isChecked();
}
/**
* @brief ConfigDialog::setTemplate
* @param passTemplate
*/
void ConfigDialog::setTemplate(QString passTemplate) {
ui->plainTextEditTemplate->setPlainText(passTemplate);
}
/**
* @brief ConfigDialog::getTemplate
* @return
*/
QString ConfigDialog::getTemplate() {
return ui->plainTextEditTemplate->toPlainText();
}
/**
* @brief ConfigDialog::autoPull
* @param autoPull
*/
void ConfigDialog::autoPull(bool autoPull) {
ui->checkBoxAutoPull->setChecked(autoPull);
}
/**
* @brief ConfigDialog::autoPush
* @param autoPush
*/
void ConfigDialog::autoPush(bool autoPush) {
ui->checkBoxAutoPush->setChecked(autoPush);
}
/**
* @brief ConfigDialog::autoPull
* @return
*/
bool ConfigDialog::autoPull() { return ui->checkBoxAutoPull->isChecked(); }
/**
* @brief ConfigDialog::autoPush
* @return
*/
bool ConfigDialog::autoPush() { return ui->checkBoxAutoPush->isChecked(); }
/**
* @brief ConfigDialog::templateAllFields
* @return
*/
bool ConfigDialog::templateAllFields() {
return ui->checkBoxTemplateAllFields->isChecked();
}
/**
* @brief ConfigDialog::templateAllFields
* @param templateAll
*/
void ConfigDialog::templateAllFields(bool templateAll) {
ui->checkBoxTemplateAllFields->setChecked(templateAll);
}
/**
* @brief ConfigDialog::alwaysOnTop
* @param alwaysOnTop
*/
void ConfigDialog::alwaysOnTop(bool alwaysOnTop) {
- ui->checkBoxAlwaysOnTop->setChecked(alwaysOnTop);
+ ui->checkBoxAlwaysOnTop->setChecked(alwaysOnTop);
}
/**
* @brief ConfigDialog::alwaysOnTop
* @return
*/
bool ConfigDialog::alwaysOnTop() {
- return ui->checkBoxAlwaysOnTop->isChecked();
+ return ui->checkBoxAlwaysOnTop->isChecked();
}
diff --git a/configdialog.h b/configdialog.h
index cd15d08..b48386c 100644
--- a/configdialog.h
+++ b/configdialog.h
@@ -1,121 +1,121 @@
#ifndef CONFIGDIALOG_H_
#define CONFIGDIALOG_H_
+#include "mainwindow.h"
+#include <QCloseEvent>
#include <QDialog>
#include <QFileDialog>
#include <QTableWidgetItem>
-#include <QCloseEvent>
-#include "mainwindow.h"
namespace Ui {
struct UserInfo;
class ConfigDialog;
}
class ConfigDialog : public QDialog {
Q_OBJECT
- public:
+public:
explicit ConfigDialog(MainWindow *parent);
~ConfigDialog();
void setPassPath(QString);
void setGitPath(QString);
void setGpgPath(QString);
void setStorePath(QString);
void setProfiles(QHash<QString, QString>, QString);
void usePass(bool usePass);
void useClipboard(MainWindow::clipBoardType);
void useAutoclear(bool useAutoclear);
void setAutoclear(int seconds);
void useAutoclearPanel(bool useAutoclearPanel);
void setAutoclearPanel(int seconds);
void hidePassword(bool hidePassword);
void hideContent(bool hideContent);
void addGPGId(bool addGPGId);
QString getPassPath();
QString getGitPath();
QString getGpgPath();
QString getStorePath();
QHash<QString, QString> getProfiles();
bool usePass();
MainWindow::clipBoardType useClipboard();
bool useAutoclear();
int getAutoclear();
bool useAutoclearPanel();
int getAutoclearPanel();
bool hidePassword();
bool hideContent();
bool addGPGId();
void wizard();
void genKey(QString, QDialog *);
bool useTrayIcon();
bool hideOnClose();
bool startMinimized();
void useTrayIcon(bool useTrayIdon);
void hideOnClose(bool hideOnClose);
void startMinimized(bool startMinimized);
void useGit(bool useGit);
bool useGit();
QString getPwgenPath();
void setPwgenPath(QString);
void usePwgen(bool usePwgen);
void avoidCapitals(bool avoidCapitals);
void avoidNumbers(bool avoidNumbers);
void lessRandom(bool lessRandom);
void useSymbols(bool useSymbols);
void setPasswordLength(int pwLen);
void setPasswordChars(QString);
bool usePwgen();
bool avoidCapitals();
bool avoidNumbers();
bool lessRandom();
bool useSymbols();
int getPasswordLength();
QString getPasswordChars();
bool useTemplate();
void useTemplate(bool useTemplate);
QString getTemplate();
void setTemplate(QString);
void templateAllFields(bool templateAllFields);
bool templateAllFields();
bool autoPull();
void autoPull(bool autoPull);
bool autoPush();
void autoPush(bool autoPush);
bool alwaysOnTop();
void alwaysOnTop(bool alwaysOnTop);
- protected:
+protected:
void closeEvent(QCloseEvent *event);
- private slots:
+private slots:
void on_radioButtonNative_clicked();
void on_radioButtonPass_clicked();
void on_toolButtonGit_clicked();
void on_toolButtonGpg_clicked();
void on_toolButtonPwgen_clicked();
void on_toolButtonPass_clicked();
void on_toolButtonStore_clicked();
void on_comboBoxClipboard_activated();
void on_checkBoxAutoclear_clicked();
void on_checkBoxAutoclearPanel_clicked();
void on_addButton_clicked();
void on_deleteButton_clicked();
void on_checkBoxUseTrayIcon_clicked();
void on_checkBoxUseGit_clicked();
void on_checkBoxUsePwgen_clicked();
void on_checkBoxUseTemplate_clicked();
- private:
+private:
QScopedPointer<Ui::ConfigDialog> ui;
void setGroupBoxState();
QString selectExecutable();
QString selectFolder();
// QMessageBox::critical with hack to avoid crashes with
// Qt 5.4.1 when QApplication::exec was not yet called
void criticalMessage(const QString &title, const QString &text);
MainWindow *mainWindow;
};
-#endif // CONFIGDIALOG_H_
+#endif // CONFIGDIALOG_H_
diff --git a/keygendialog.cpp b/keygendialog.cpp
index 4fe2ad3..0fcb302 100644
--- a/keygendialog.cpp
+++ b/keygendialog.cpp
@@ -1,128 +1,128 @@
#include "keygendialog.h"
+#include "qprogressindicator.h"
+#include "ui_keygendialog.h"
#include <QDebug>
#include <QMessageBox>
-#include "ui_keygendialog.h"
-#include "qprogressindicator.h"
KeygenDialog::KeygenDialog(ConfigDialog *parent)
: QDialog(parent), ui(new Ui::KeygenDialog) {
ui->setupUi(this);
dialog = parent;
}
KeygenDialog::~KeygenDialog() { delete ui; }
void KeygenDialog::on_passphrase1_textChanged(const QString &arg1) {
if (ui->passphrase1->text() == ui->passphrase2->text()) {
ui->buttonBox->setEnabled(true);
replace("Passphrase", arg1);
if (arg1 == "")
no_protection(true);
else
no_protection(false);
} else {
ui->buttonBox->setEnabled(false);
}
}
void KeygenDialog::on_passphrase2_textChanged(const QString &arg1) {
on_passphrase1_textChanged(arg1);
}
void KeygenDialog::on_checkBox_stateChanged(int arg1) {
if (arg1) {
ui->plainTextEdit->setReadOnly(false);
ui->plainTextEdit->setEnabled(true);
} else {
ui->plainTextEdit->setReadOnly(true);
ui->plainTextEdit->setEnabled(false);
}
}
void KeygenDialog::on_email_textChanged(const QString &arg1) {
replace("Name-Email", arg1);
}
void KeygenDialog::on_name_textChanged(const QString &arg1) {
replace("Name-Real", arg1);
}
/**
* @brief KeygenDialog::replace
* @param key
* @param value
*/
void KeygenDialog::replace(QString key, QString value) {
QStringList clear;
QString expert = ui->plainTextEdit->toPlainText();
QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
- foreach(QString line, lines) {
+ foreach (QString line, lines) {
line.replace(QRegExp(key + ":.*"), key + ": " + value);
if (key == "Passphrase")
line.replace("%no-protection", "Passphrase: " + value);
clear.append(line);
}
ui->plainTextEdit->setPlainText(clear.join("\n"));
}
/**
* @brief KeygenDialog::no_protection
* @param enable
*/
void KeygenDialog::no_protection(bool enable) {
QStringList clear;
QString expert = ui->plainTextEdit->toPlainText();
QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
- foreach(QString line, lines) {
+ foreach (QString line, lines) {
bool remove = false;
if (!enable) {
if (line.indexOf("%no-protection") == 0)
remove = true;
} else {
if (line.indexOf("Passphrase") == 0)
line = "%no-protection";
}
if (!remove)
clear.append(line);
}
ui->plainTextEdit->setPlainText(clear.join("\n"));
}
/**
* @brief KeygenDialog::done
* @param r
*/
void KeygenDialog::done(int r) {
- if (QDialog::Accepted == r) { // ok was pressed
+ if (QDialog::Accepted == r) { // ok was pressed
ui->widget->setEnabled(false);
ui->buttonBox->setEnabled(false);
ui->checkBox->setEnabled(false);
ui->plainTextEdit->setEnabled(false);
QProgressIndicator *pi = new QProgressIndicator();
pi->startAnimation();
pi->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->frame->hide();
ui->label->setText(
QString("This operation can take some minutes.<br />") +
"We need to generate a lot of random bytes. It is a good idea to "
"perform "
"some other action (type on the keyboard, move the mouse, utilize the "
"disks) during the prime generation; this gives the random number "
"generator a better chance to gain enough entropy.");
this->layout()->addWidget(pi);
this->show();
dialog->genKey(ui->plainTextEdit->toPlainText(), this);
- } else { // cancel, close or exc was pressed
+ } else { // cancel, close or exc was pressed
QDialog::done(r);
return;
}
}
void KeygenDialog::closeEvent(QCloseEvent *event) {
// TODO(annejan) save window size or somethign
event->accept();
}
diff --git a/keygendialog.h b/keygendialog.h
index 19d996c..406cd6d 100644
--- a/keygendialog.h
+++ b/keygendialog.h
@@ -1,37 +1,37 @@
#ifndef KEYGENDIALOG_H_
#define KEYGENDIALOG_H_
-#include <QDialog>
-#include <QCloseEvent>
#include "configdialog.h"
+#include <QCloseEvent>
+#include <QDialog>
namespace Ui {
class KeygenDialog;
}
class KeygenDialog : public QDialog {
Q_OBJECT
- public:
+public:
explicit KeygenDialog(ConfigDialog *parent = 0);
~KeygenDialog();
- protected:
+protected:
void closeEvent(QCloseEvent *event);
- private slots:
+private slots:
void on_passphrase1_textChanged(const QString &arg1);
void on_passphrase2_textChanged(const QString &arg1);
void on_checkBox_stateChanged(int arg1);
void on_email_textChanged(const QString &arg1);
void on_name_textChanged(const QString &arg1);
- private:
+private:
Ui::KeygenDialog *ui;
void replace(QString, QString);
void done(int r);
void no_protection(bool enable);
ConfigDialog *dialog;
};
-#endif // KEYGENDIALOG_H_
+#endif // KEYGENDIALOG_H_
diff --git a/main.cpp b/main.cpp
index d65a9e3..9c9c065 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,52 +1,52 @@
+#include "mainwindow.h"
#include <QApplication>
#include <QTranslator>
-#include "mainwindow.h"
int main(int argc, char *argv[]) {
// check for stupid apple psid or whatever flag
QString text = "";
for (int i = 1; i < argc; ++i) {
if (i > 1)
text += " ";
text += argv[i];
}
#if SINGLE_APP
QString name = qgetenv("USER");
if (name.isEmpty())
name = qgetenv("USERNAME");
SingleApplication app(argc, argv, name + "QtPass");
if (app.isRunning()) {
if (text.length() > 0)
app.sendMessage(text);
return 0;
}
#else
QApplication app(argc, argv);
#endif
QCoreApplication::setOrganizationName("IJHack");
QCoreApplication::setOrganizationDomain("ijhack.org");
QCoreApplication::setApplicationName("QtPass");
QCoreApplication::setApplicationVersion(VERSION);
// Setup and load translator for localization
QTranslator translator;
QString locale = QLocale::system().name();
// locale = "nl_NL";
// locale = "he_IL";
// locale = "ar_MA";
translator.load(QString(":localization/localization_") + locale +
QString(".qm"));
app.installTranslator(&translator);
app.setLayoutDirection(QObject::tr("LTR") == "RTL" ? Qt::RightToLeft
: Qt::LeftToRight);
MainWindow w;
app.setActiveWindow(&w);
app.setWindowIcon(QIcon(":artwork/icon.png"));
w.setApp(&app);
w.setText(text);
w.show();
return app.exec();
}
diff --git a/mainwindow.cpp b/mainwindow.cpp
index 18de5fe..9319696 100644
--- a/mainwindow.cpp
+++ b/mainwindow.cpp
@@ -1,1872 +1,1868 @@
#include "mainwindow.h"
#include <QClipboard>
+#include <QCloseEvent>
#include <QDebug>
+#include <QFileInfo>
#include <QInputDialog>
+#include <QLabel>
#include <QMessageBox>
-#include <QTimer>
-#include <QFileInfo>
#include <QQueue>
-#include <QCloseEvent>
-#include <QLabel>
+#include <QTimer>
#ifdef Q_OS_WIN
#define WIN32_LEAN_AND_MEAN /*_KILLING_MACHINE*/
#define WIN32_EXTRA_LEAN
#include <windows.h>
#include <winnetwk.h>
#undef DELETE
#endif
-#include "ui_mainwindow.h"
#include "configdialog.h"
-#include "usersdialog.h"
#include "keygendialog.h"
#include "passworddialog.h"
+#include "ui_mainwindow.h"
+#include "usersdialog.h"
#include "util.h"
/**
* @brief MainWindow::MainWindow
* @param parent
*/
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow), process(new QProcess(this)),
fusedav(this), keygen(NULL), tray(NULL) {
// connect(process.data(), SIGNAL(readyReadStandardOutput()), this,
// SLOT(readyRead()));
connect(process.data(), SIGNAL(error(QProcess::ProcessError)), this,
SLOT(processError(QProcess::ProcessError)));
connect(process.data(), SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(processFinished(int, QProcess::ExitStatus)));
ui->setupUi(this);
enableUiElements(true);
wrapperRunning = false;
execQueue = new QQueue<execQueueItem>;
ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
freshStart = true;
startupPhase = true;
autoclearTimer = NULL;
if (!checkConfig()) {
// no working config
QApplication::quit();
}
ui->copyPasswordButton->setEnabled(false);
setClippedPassword("");
QtPass = NULL;
QTimer::singleShot(10, this, SLOT(focusInput()));
// Add a Actions to the Add-Button
QIcon addFileIcon = QIcon::fromTheme("file_new");
QIcon addFolderIcon = QIcon::fromTheme("folder_new");
actionAddPassword = new QAction(addFileIcon, tr("Add Password"), this);
actionAddFolder = new QAction(addFolderIcon, tr("Add Folder"), this);
ui->addButton->addAction(actionAddPassword);
ui->addButton->addAction(actionAddFolder);
- connect(actionAddPassword, SIGNAL(triggered()), this, SLOT(on_addButton_clicked()));
+ connect(actionAddPassword, SIGNAL(triggered()), this,
+ SLOT(on_addButton_clicked()));
connect(actionAddFolder, SIGNAL(triggered()), this, SLOT(addFolder()));
qsrand(QDateTime::currentDateTime().toTime_t());
#if QT_VERSION >= 0x050200
ui->lineEdit->setClearButtonEnabled(true);
#endif
}
void MainWindow::focusInput() {
ui->lineEdit->selectAll();
ui->lineEdit->setFocus();
}
/**
* @brief MainWindow::~MainWindow
*/
MainWindow::~MainWindow() {
#ifdef Q_OS_WIN
if (useWebDav)
WNetCancelConnection2A(passStore.toUtf8().constData(), 0, 1);
#else
if (fusedav.state() == QProcess::Running) {
fusedav.terminate();
fusedav.waitForFinished(2000);
}
#endif
}
QSettings &MainWindow::getSettings() {
if (!settings) {
QString portable_ini = QCoreApplication::applicationDirPath() +
QDir::separator() + "qtpass.ini";
// qDebug() << "Settings file: " + portable_ini;
if (QFile(portable_ini).exists()) {
// qDebug() << "Settings file exists, loading it in";
settings.reset(new QSettings(portable_ini, QSettings::IniFormat));
} else {
// qDebug() << "Settings file does not exist, use defaults";
settings.reset(new QSettings("IJHack", "QtPass"));
}
}
return *settings;
}
-void MainWindow::changeEvent(QEvent *event)
-{
- QWidget::changeEvent(event);
- if (event->type() == QEvent::ActivationChange)
- {
- if(this->isActiveWindow())
- {
- ui->lineEdit->selectAll();
- ui->lineEdit->setFocus();
- }
+void MainWindow::changeEvent(QEvent *event) {
+ QWidget::changeEvent(event);
+ if (event->type() == QEvent::ActivationChange) {
+ if (this->isActiveWindow()) {
+ ui->lineEdit->selectAll();
+ ui->lineEdit->setFocus();
}
+ }
}
-
void MainWindow::mountWebDav() {
#ifdef Q_OS_WIN
char dst[20] = {0};
NETRESOURCEA netres;
memset(&netres, 0, sizeof(netres));
netres.dwType = RESOURCETYPE_DISK;
netres.lpLocalName = 0;
netres.lpRemoteName = webDavUrl.toUtf8().data();
DWORD size = sizeof(dst);
DWORD r = WNetUseConnectionA(
reinterpret_cast<HWND>(effectiveWinId()), &netres,
webDavPassword.toUtf8().constData(), webDavUser.toUtf8().constData(),
CONNECT_TEMPORARY | CONNECT_INTERACTIVE | CONNECT_REDIRECT, dst, &size,
0);
if (r == NO_ERROR) {
passStore = dst;
} else {
char message[256] = {0};
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, r, 0, message,
sizeof(message), 0);
ui->textBrowser->setTextColor(Qt::red);
ui->textBrowser->setText(tr("Failed to connect WebDAV:\n") + message +
" (0x" + QString::number(r, 16) + ")");
}
#else
fusedav.start("fusedav -o nonempty -u \"" + webDavUser + "\" " + webDavUrl +
" \"" + passStore + '"');
fusedav.waitForStarted();
if (fusedav.state() == QProcess::Running) {
QString pwd = webDavPassword;
bool ok = true;
if (pwd.isEmpty()) {
pwd = QInputDialog::getText(this, tr("QtPass WebDAV password"),
tr("Enter password to connect to WebDAV:"),
QLineEdit::Password, "", &ok);
}
if (ok && !pwd.isEmpty()) {
fusedav.write(pwd.toUtf8() + '\n');
fusedav.closeWriteChannel();
fusedav.waitForFinished(2000);
} else {
fusedav.terminate();
}
}
QString error = fusedav.readAllStandardError();
int prompt = error.indexOf("Password:");
if (prompt >= 0)
error.remove(0, prompt + 10);
if (fusedav.state() != QProcess::Running)
error = tr("fusedav exited unexpectedly\n") + error;
if (error.size() > 0) {
ui->textBrowser->setTextColor(Qt::red);
ui->textBrowser->setText(
tr("Failed to start fusedav to connect WebDAV:\n") + error);
}
#endif
}
/**
* @brief MainWindow::checkConfig
*/
bool MainWindow::checkConfig() {
QSettings &settings(getSettings());
QString version = settings.value("version").toString();
if (freshStart) {
settings.beginGroup("mainwindow");
restoreGeometry(settings.value("geometry", saveGeometry()).toByteArray());
restoreState(settings.value("savestate", saveState()).toByteArray());
move(settings.value("pos", pos()).toPoint());
resize(settings.value("size", size()).toSize());
QList<int> splitter = ui->splitter->sizes();
int left = settings.value("splitterLeft", splitter[0]).toInt();
int right = settings.value("splitterRight", splitter[1]).toInt();
if (left > 0 || right > 0) {
splitter[0] = left;
splitter[1] = right;
ui->splitter->setSizes(splitter);
}
if (settings.value("maximized", isMaximized()).toBool())
showMaximized();
settings.endGroup();
}
usePass = (settings.value("usePass") == "true");
useClipboard = CLIPBOARD_NEVER;
if (settings.value("useClipboard") == "true" ||
settings.value("useClipboard") == "1")
useClipboard = CLIPBOARD_ALWAYS;
else if (settings.value("useClipboard") == "2")
useClipboard = CLIPBOARD_ON_DEMAND;
useAutoclear = (settings.value("useAutoclear") == "true");
autoclearSeconds = settings.value("autoclearSeconds").toInt();
useAutoclearPanel = (settings.value("useAutoclearPanel") == "true");
autoclearPanelSeconds = settings.value("autoclearPanelSeconds").toInt();
hidePassword = (settings.value("hidePassword") == "true");
hideContent = (settings.value("hideContent") == "true");
addGPGId = (settings.value("addGPGId") != "false");
passStore = settings.value("passStore").toString();
if (passStore.isEmpty()) {
passStore = Util::findPasswordStore();
settings.setValue("passStore", passStore);
}
passStore = Util::normalizeFolderPath(passStore);
passExecutable = settings.value("passExecutable").toString();
if (passExecutable.isEmpty())
passExecutable = Util::findBinaryInPath("pass");
gitExecutable = settings.value("gitExecutable").toString();
if (gitExecutable.isEmpty())
gitExecutable = Util::findBinaryInPath("git");
gpgExecutable = settings.value("gpgExecutable").toString();
if (gpgExecutable.isEmpty())
gpgExecutable = Util::findBinaryInPath("gpg2");
pwgenExecutable = settings.value("pwgenExecutable").toString();
if (pwgenExecutable.isEmpty())
pwgenExecutable = Util::findBinaryInPath("pwgen");
gpgHome = settings.value("gpgHome").toString();
useWebDav = (settings.value("useWebDav") == "true");
webDavUrl = settings.value("webDavUrl").toString();
webDavUser = settings.value("webDavUser").toString();
webDavPassword = settings.value("webDavPassword").toString();
profile = settings.value("profile").toString();
settings.beginGroup("profiles");
QStringList keys = settings.childKeys();
- foreach(QString key, keys)
+ foreach (QString key, keys)
profiles[key] = settings.value(key).toString();
settings.endGroup();
useGit = (settings.value("useGit") == "true");
usePwgen = (settings.value("usePwgen") == "true");
avoidCapitals = settings.value("avoidCapitals").toBool();
avoidNumbers = settings.value("avoidNumbers").toBool();
lessRandom = settings.value("lessRandom").toBool();
useSymbols = (settings.value("useSymbols") == "true");
passwordLength = settings.value("passwordLength").toInt();
passwordChars = settings.value("passwordChars").toString();
useTrayIcon = settings.value("useTrayIcon").toBool();
hideOnClose = settings.value("hideOnClose").toBool();
startMinimized = settings.value("startMinimized").toBool();
alwaysOnTop = settings.value("alwaysOnTop").toBool();
if (alwaysOnTop) {
- Qt::WindowFlags flags = windowFlags();
- this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
- this->show();
+ Qt::WindowFlags flags = windowFlags();
+ this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
+ this->show();
}
autoPull = settings.value("autoPull").toBool();
autoPush = settings.value("autoPush").toBool();
if (useTrayIcon && tray == NULL) {
initTrayIcon();
if (freshStart && startMinimized) {
// since we are still in constructor, can't directly hide
QTimer::singleShot(10, this, SLOT(hide()));
}
} else if (!useTrayIcon && tray != NULL) {
destroyTrayIcon();
}
passTemplate = settings.value("passTemplate").toString();
useTemplate = settings.value("useTemplate").toBool();
templateAllFields = settings.value("templateAllFields").toBool();
// qDebug() << version;
// Config updates
if (version.isEmpty()) {
qDebug() << "assuming fresh install";
if (autoclearSeconds < 5)
autoclearSeconds = 10;
if (autoclearPanelSeconds < 5)
autoclearPanelSeconds = 10;
passwordLength = 16;
passwordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456"
"7890~!@#$%^&*()_-+={}[]|:;<>,.?";
if (!pwgenExecutable.isEmpty())
usePwgen = true;
else
usePwgen = false;
passTemplate = "login\nurl";
} else {
// QStringList ver = version.split(".");
// qDebug() << ver;
// if (ver[0] == "0" && ver[1] == "8") {
//// upgrade to 0.9
// }
if (passwordChars.isEmpty())
passwordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234"
"567890~!@#$%^&*()_-+={}[]|:;<>,.?";
if (passTemplate.isEmpty())
passTemplate = "login\nurl";
}
settings.setValue("version", VERSION);
if (Util::checkConfig(passStore, passExecutable, gpgExecutable)) {
config();
if (freshStart &&
Util::checkConfig(passStore, passExecutable, gpgExecutable))
return false;
}
freshStart = false;
// TODO(annejan): this needs to be before we try to access the store,
// but it would be better to do it after the Window is shown,
// as the long delay it can cause is irritating otherwise.
if (useWebDav)
mountWebDav();
model.setNameFilters(QStringList() << "*.gpg");
model.setNameFilterDisables(false);
proxyModel.setSourceModel(&model);
proxyModel.setModelAndStore(&model, passStore);
selectionModel.reset(new QItemSelectionModel(&proxyModel));
model.fetchMore(model.setRootPath(passStore));
model.sort(0, Qt::AscendingOrder);
ui->treeView->setModel(&proxyModel);
ui->treeView->setRootIndex(
proxyModel.mapFromSource(model.setRootPath(passStore)));
ui->treeView->setColumnHidden(1, true);
ui->treeView->setColumnHidden(2, true);
ui->treeView->setColumnHidden(3, true);
ui->treeView->setHeaderHidden(true);
ui->treeView->setIndentation(15);
ui->treeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->treeView, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showContextMenu(const QPoint &)));
ui->textBrowser->setOpenExternalLinks(true);
ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->textBrowser, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showBrowserContextMenu(const QPoint &)));
updateProfileBox();
env = QProcess::systemEnvironment();
if (!gpgHome.isEmpty()) {
QDir absHome(gpgHome);
absHome.makeAbsolute();
env << "GNUPGHOME=" + absHome.path();
}
#ifdef __APPLE__
// If it exists, add the gpgtools to PATH
if (QFile("/usr/local/MacGPG2/bin").exists())
env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:");
// Add missing /usr/local/bin
if (env.filter("/usr/local/bin").isEmpty())
env.replaceInStrings("PATH=", "PATH=/usr/local/bin:");
#endif
// QMessageBox::information(this, "env", env.join("\n"));
updateEnv();
if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) {
ui->pushButton->hide();
ui->updateButton->hide();
- ui->horizontalSpacer->changeSize(0, 20, QSizePolicy::Maximum, QSizePolicy::Minimum);
+ ui->horizontalSpacer->changeSize(0, 20, QSizePolicy::Maximum,
+ QSizePolicy::Minimum);
} else {
ui->pushButton->show();
ui->updateButton->show();
- ui->horizontalSpacer->changeSize(24, 24, QSizePolicy::Minimum, QSizePolicy::Minimum);
+ ui->horizontalSpacer->changeSize(24, 24, QSizePolicy::Minimum,
+ QSizePolicy::Minimum);
}
startupPhase = false;
return true;
}
/**
* @brief MainWindow::config
*/
void MainWindow::config() {
QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
d->setModal(true);
// Automatically default to pass if it's available
usePass = freshStart ? QFile(passExecutable).exists() : usePass;
d->setPassPath(passExecutable);
d->setGitPath(gitExecutable);
d->setGpgPath(gpgExecutable);
d->setStorePath(passStore);
d->usePass(usePass);
d->useClipboard(useClipboard);
d->useAutoclear(useAutoclear);
d->setAutoclear(autoclearSeconds);
d->useAutoclearPanel(useAutoclearPanel);
d->setAutoclearPanel(autoclearPanelSeconds);
d->hidePassword(hidePassword);
d->hideContent(hideContent);
d->addGPGId(addGPGId);
d->useTrayIcon(useTrayIcon);
d->hideOnClose(hideOnClose);
d->startMinimized(startMinimized);
d->setProfiles(profiles, profile);
d->useGit(useGit);
d->setPwgenPath(pwgenExecutable);
d->usePwgen(usePwgen);
d->avoidCapitals(avoidCapitals);
d->avoidNumbers(avoidNumbers);
d->lessRandom(lessRandom);
d->useSymbols(useSymbols);
d->setPasswordLength(passwordLength);
d->setPasswordChars(passwordChars);
d->useTemplate(useTemplate);
d->setTemplate(passTemplate);
d->templateAllFields(templateAllFields);
d->autoPull(autoPull);
d->autoPush(autoPush);
d->alwaysOnTop(alwaysOnTop);
if (startupPhase)
- d->wizard(); // does shit
+ d->wizard(); // does shit
if (d->exec()) {
if (d->result() == QDialog::Accepted) {
passExecutable = d->getPassPath();
gitExecutable = d->getGitPath();
gpgExecutable = d->getGpgPath();
passStore = Util::normalizeFolderPath(d->getStorePath());
usePass = d->usePass();
useClipboard = d->useClipboard();
useAutoclear = d->useAutoclear();
autoclearSeconds = d->getAutoclear();
useAutoclearPanel = d->useAutoclearPanel();
autoclearPanelSeconds = d->getAutoclearPanel();
hidePassword = d->hidePassword();
hideContent = d->hideContent();
addGPGId = d->addGPGId();
useTrayIcon = d->useTrayIcon();
hideOnClose = d->hideOnClose();
startMinimized = d->startMinimized();
profiles = d->getProfiles();
useGit = d->useGit();
pwgenExecutable = d->getPwgenPath();
usePwgen = d->usePwgen();
avoidCapitals = d->avoidCapitals();
avoidNumbers = d->avoidNumbers();
lessRandom = d->lessRandom();
useSymbols = d->useSymbols();
passwordLength = d->getPasswordLength();
passwordChars = d->getPasswordChars();
useTemplate = d->useTemplate();
passTemplate = d->getTemplate();
templateAllFields = d->templateAllFields();
autoPush = d->autoPush();
autoPull = d->autoPull();
alwaysOnTop = d->alwaysOnTop();
QSettings &settings(getSettings());
settings.setValue("version", VERSION);
settings.setValue("passExecutable", passExecutable);
settings.setValue("gitExecutable", gitExecutable);
settings.setValue("gpgExecutable", gpgExecutable);
settings.setValue("passStore", passStore);
settings.setValue("usePass", usePass ? "true" : "false");
switch (useClipboard) {
case CLIPBOARD_ALWAYS:
settings.setValue("useClipboard", "true");
break;
case CLIPBOARD_ON_DEMAND:
settings.setValue("useClipboard", "2");
break;
default:
settings.setValue("useClipboard", "false");
break;
}
settings.setValue("useAutoclear", useAutoclear ? "true" : "false");
settings.setValue("autoclearSeconds", autoclearSeconds);
settings.setValue("useAutoclearPanel",
useAutoclearPanel ? "true" : "false");
settings.setValue("autoclearPanelSeconds", autoclearPanelSeconds);
settings.setValue("hidePassword", hidePassword ? "true" : "false");
settings.setValue("hideContent", hideContent ? "true" : "false");
settings.setValue("addGPGId", addGPGId ? "true" : "false");
settings.setValue("useTrayIcon", useTrayIcon ? "true" : "false");
settings.setValue("hideOnClose", hideOnClose ? "true" : "false");
settings.setValue("startMinimized", startMinimized ? "true" : "false");
settings.setValue("useGit", useGit ? "true" : "false");
settings.setValue("pwgenExecutable", pwgenExecutable);
settings.setValue("usePwgen", usePwgen ? "true" : "false");
settings.setValue("avoidCapitals", avoidCapitals ? "true" : "false");
settings.setValue("avoidNumbers", avoidNumbers ? "true" : "false");
settings.setValue("lessRandom", lessRandom ? "true" : "false");
settings.setValue("useSymbols", useSymbols ? "true" : "false");
settings.setValue("passwordLength", passwordLength);
settings.setValue("passwordChars", passwordChars);
settings.setValue("useTemplate", useTemplate);
settings.setValue("passTemplate", passTemplate);
settings.setValue("templateAllFields", templateAllFields);
settings.setValue("autoPull", autoPull ? "true" : "false");
settings.setValue("autoPush", autoPush ? "true" : "false");
settings.setValue("alwaysOnTop", alwaysOnTop ? "true" : "false");
if (alwaysOnTop) {
- Qt::WindowFlags flags = windowFlags();
- this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
- this->show();
+ Qt::WindowFlags flags = windowFlags();
+ this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
+ this->show();
} else {
- this->setWindowFlags(Qt::Window);
- this->show();
+ this->setWindowFlags(Qt::Window);
+ this->show();
}
if (!profiles.isEmpty()) {
settings.beginGroup("profiles");
settings.remove("");
bool profileExists = false;
QHashIterator<QString, QString> i(profiles);
while (i.hasNext()) {
i.next();
// qDebug() << i.key() + "|" + i.value();
if (i.key() == profile)
profileExists = true;
settings.setValue(i.key(), i.value());
}
if (!profileExists) {
// just take the last one
profile = i.key();
}
settings.endGroup();
} else {
settings.remove("profiles");
}
updateProfileBox();
ui->treeView->setRootIndex(
proxyModel.mapFromSource(model.setRootPath(passStore)));
if (freshStart &&
Util::checkConfig(passStore, passExecutable, gpgExecutable))
config();
updateEnv();
if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) {
- ui->pushButton->hide();
- ui->updateButton->hide();
- ui->horizontalSpacer->changeSize(0, 20, QSizePolicy::Maximum, QSizePolicy::Minimum);
+ ui->pushButton->hide();
+ ui->updateButton->hide();
+ ui->horizontalSpacer->changeSize(0, 20, QSizePolicy::Maximum,
+ QSizePolicy::Minimum);
} else {
- ui->pushButton->show();
- ui->updateButton->show();
- ui->horizontalSpacer->changeSize(24, 24, QSizePolicy::Minimum, QSizePolicy::Minimum);
+ ui->pushButton->show();
+ ui->updateButton->show();
+ ui->horizontalSpacer->changeSize(24, 24, QSizePolicy::Minimum,
+ QSizePolicy::Minimum);
}
if (useTrayIcon && tray == NULL)
initTrayIcon();
else if (!useTrayIcon && tray != NULL)
destroyTrayIcon();
}
freshStart = false;
}
}
/**
* @brief MainWindow::on_updateButton_clicked
*/
void MainWindow::on_updateButton_clicked() {
ui->statusBar->showMessage(tr("Updating password-store"), 2000);
currentAction = GIT;
if (usePass)
executePass("git pull");
else
executeWrapper(gitExecutable, "pull");
}
/**
* @brief MainWindow::on_pushButton_clicked
*/
void MainWindow::on_pushButton_clicked() {
ui->statusBar->showMessage(tr("Updating password-store"), 2000);
currentAction = GIT;
if (usePass)
executePass("git push");
else
executeWrapper(gitExecutable, "push");
}
QString MainWindow::getDir(const QModelIndex &index, bool forPass) {
QString abspath = QDir(passStore).absolutePath() + '/';
if (!index.isValid())
return forPass ? "" : abspath;
QFileInfo info = model.fileInfo(proxyModel.mapToSource(index));
QString filePath =
(info.isFile() ? info.absolutePath() : info.absoluteFilePath());
if (forPass) {
filePath = QDir(abspath).relativeFilePath(filePath);
}
filePath += '/';
return filePath;
}
QString MainWindow::getFile(const QModelIndex &index, bool forPass) {
if (!index.isValid() ||
!model.fileInfo(proxyModel.mapToSource(index)).isFile())
return QString();
QString filePath = model.filePath(proxyModel.mapToSource(index));
if (forPass) {
filePath = QDir(passStore).relativeFilePath(filePath);
filePath.replace(QRegExp("\\.gpg$"), "");
}
return filePath;
}
/**
* @brief MainWindow::on_treeView_clicked
* @param index
*/
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
currentDir = getDir(ui->treeView->currentIndex(), false);
lastDecrypt = "Could not decrypt";
setClippedPassword("");
QString file = getFile(index, usePass);
if (!file.isEmpty()) {
currentAction = GPG;
if (usePass)
executePass("show \"" + file + '"');
else
executeWrapper(gpgExecutable,
"-d --quiet --yes --no-encrypt-to --batch --use-agent \"" +
file + '"');
} else {
ui->editButton->setEnabled(false);
ui->deleteButton->setEnabled(true);
}
}
/**
* @brief When doubleclicked on TreeViewItem, open the edit Window
* @param index
*/
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
- // TODO: do nothing when clicked on folder
+ // TODO: do nothing when clicked on folder
QFileInfo fileOrFolder =
model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
QString file = "";
if (fileOrFolder.isFile()) {
QString file = getFile(index, usePass);
if (file.isEmpty()) {
QMessageBox::critical(
this, tr("Can not edit"),
tr("Selected password file does not exist, not able to edit"));
return;
}
setPassword(file, true, false);
}
}
-
-
/**
* @brief MainWindow::executePass
* @param args
*/
void MainWindow::executePass(QString args, QString input) {
executeWrapper(passExecutable, args, input);
}
/**
* @brief MainWindow::executePassGitInit
*/
void MainWindow::executePassGitInit() {
qDebug() << "Pass git init called";
if (usePass)
executePass("git init");
else
executeWrapper("git", "init \"" + passStore + '"');
}
/**
* @brief MainWindow::executeWrapper
* @param app
* @param args
*/
void MainWindow::executeWrapper(QString app, QString args, QString input) {
// qDebug() << app + " " + args;
// Happens a lot if e.g. git binary is not set.
// This will result in bogus "QProcess::FailedToStart" messages,
// also hiding legitimate errors from the gpg commands.
if (app.isEmpty()) {
qDebug() << "Trying to execute nothing..";
return;
}
// Convert to absolute path, just in case
app = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(app);
if (wrapperRunning) {
execQueueItem item;
item.app = app;
item.args = args;
item.input = input;
execQueue->enqueue(item);
qDebug() << item.app + "," + item.args + "," + item.input;
return;
}
wrapperRunning = true;
process->setWorkingDirectory(passStore);
process->setEnvironment(env);
clearTemplateWidgets();
ui->textBrowser->clear();
ui->textBrowser->setTextColor(Qt::black);
enableUiElements(false);
if (autoclearTimer != NULL) {
autoclearTimer->stop();
delete autoclearTimer;
autoclearTimer = NULL;
}
process->start('"' + app + "\" " + args);
if (!input.isEmpty())
process->write(input.toUtf8());
process->closeWriteChannel();
}
/**
* @brief MainWindow::readyRead
*/
void MainWindow::readyRead(bool finished = false) {
if (currentAction == PWGEN)
return;
QString output = "";
QString error = process->readAllStandardError();
if (currentAction != GPG_INTERNAL) {
output = process->readAllStandardOutput();
if (finished && currentAction == GPG) {
lastDecrypt = output;
QStringList tokens = output.split("\n");
if (useClipboard != CLIPBOARD_NEVER && !output.isEmpty()) {
setClippedPassword(tokens[0]);
if (useClipboard == CLIPBOARD_ALWAYS)
copyPasswordToClipboard();
if (useAutoclearPanel) {
QTimer::singleShot(1000 * autoclearPanelSeconds, this,
SLOT(clearPanel()));
}
if (hidePassword && !useTemplate) {
tokens[0] = "***" + tr("Password hidden") + "***";
output = tokens.join("\n");
}
if (hideContent)
output = "***" + tr("Content hidden") + "***";
}
if (useTemplate) {
while (ui->formLayout->count() > 0) {
QLayoutItem *item = ui->formLayout->takeAt(0);
delete item->widget();
delete item;
}
QLineEdit *pass = new QLineEdit();
pass->setText(tokens[0]);
tokens.pop_front();
if (hidePassword)
pass->setEchoMode(QLineEdit::Password);
pass->setReadOnly(true);
ui->formLayout->addRow(pass);
for (int j = 0; j < tokens.length(); ++j) {
QString token = tokens.at(j);
if (token.contains(':')) {
int colon = token.indexOf(':');
QString field = token.left(colon);
if (templateAllFields || passTemplate.contains(field)) {
QString value = token.right(token.length() - colon - 1);
if (!passTemplate.contains(field) && value.startsWith("//"))
- continue; // colon is probably from a url
+ continue; // colon is probably from a url
QLineEdit *line = new QLineEdit();
line->setObjectName(field);
line->setText(value);
line->setReadOnly(true);
ui->formLayout->addRow(new QLabel(field), line);
tokens.removeAt(j);
- --j; // tokens.length() also got shortened by the remove..
+ --j; // tokens.length() also got shortened by the remove..
}
}
}
if (ui->formLayout->count() == 0)
ui->verticalLayoutPassword->setSpacing(0);
else
ui->verticalLayoutPassword->setSpacing(6);
output = tokens.join("\n");
} else {
clearTemplateWidgets();
}
if (useAutoclearPanel) {
autoclearPass = output;
autoclearTimer = new QTimer(this);
autoclearTimer->setSingleShot(true);
autoclearTimer->setInterval(1000 * autoclearPanelSeconds);
connect(autoclearTimer, SIGNAL(timeout()), this, SLOT(clearPanel()));
autoclearTimer->start();
}
}
output.replace(QRegExp("<"), "<");
output.replace(QRegExp(">"), ">");
} else {
// qDebug() << process->readAllStandardOutput();
// qDebug() << process->readAllStandardError();
if (finished && 0 != keygen) {
qDebug() << "Keygen Done";
keygen->close();
keygen = 0;
// TODO(annejan) some sanity checking ?
}
}
if (!error.isEmpty()) {
if (currentAction == GIT) {
// https://github.com/IJHack/qtpass/issues/111
output = "<span style=\"color: darkgray;\">" + error + "</span><br />" +
output;
} else {
output =
"<span style=\"color: red;\">" + error + "</span><br />" + output;
}
}
output.replace(QRegExp("((?:https?|ftp)://\\S+)"), "<a href=\"\\1\">\\1</a>");
output.replace(QRegExp("\n"), "<br />");
if (!ui->textBrowser->toPlainText().isEmpty())
output = ui->textBrowser->toHtml() + output;
ui->textBrowser->setHtml(output);
}
/**
* @brief MainWindow::clearClipboard
*/
void MainWindow::clearClipboard() {
QClipboard *clipboard = QApplication::clipboard();
if (clipboard->text() == getClippedPassword()) {
clipboard->clear();
ui->statusBar->showMessage(tr("Clipboard cleared"), 3000);
} else {
ui->statusBar->showMessage(tr("Clipboard not cleared"), 3000);
}
}
/**
* @brief MainWindow::clearPanel
*/
void MainWindow::clearPanel() {
while (ui->formLayout->count() > 0) {
QLayoutItem *item = ui->formLayout->takeAt(0);
delete item->widget();
delete item;
}
QString output = "***" + tr("Password and Content hidden") + "***";
ui->textBrowser->setHtml(output);
}
/**
* @brief MainWindow::processFinished
* @param exitCode
* @param exitStatus
*/
void MainWindow::processFinished(int exitCode,
QProcess::ExitStatus exitStatus) {
wrapperRunning = false;
bool error = exitStatus != QProcess::NormalExit || exitCode > 0;
readyRead(true);
enableUiElements(true);
if (!error && currentAction == EDIT)
on_treeView_clicked(ui->treeView->currentIndex());
if (!execQueue->isEmpty()) {
execQueueItem item = execQueue->dequeue();
executeWrapper(item.app, item.args, item.input);
}
}
/** QStringList tokens = output.split("\n");
* @brief MainWindow::enableUiElements
* @param state
*/
void MainWindow::enableUiElements(bool state) {
ui->updateButton->setEnabled(state);
ui->treeView->setEnabled(state);
ui->lineEdit->setEnabled(state);
ui->lineEdit->installEventFilter(this);
ui->addButton->setEnabled(state);
ui->usersButton->setEnabled(state);
ui->configButton->setEnabled(state);
// is a file selected?
state &= ui->treeView->currentIndex().isValid();
ui->deleteButton->setEnabled(state);
ui->editButton->setEnabled(state);
ui->pushButton->setEnabled(state);
}
/**
* @brief MainWindow::processError
* @param error
*/
void MainWindow::processError(QProcess::ProcessError error) {
QString errorString;
switch (error) {
case QProcess::FailedToStart:
errorString = tr("QProcess::FailedToStart");
break;
case QProcess::Crashed:
errorString = tr("QProcess::Crashed");
break;
case QProcess::Timedout:
errorString = tr("QProcess::Timedout");
break;
case QProcess::ReadError:
errorString = tr("QProcess::ReadError");
break;
case QProcess::WriteError:
errorString = tr("QProcess::WriteError");
break;
case QProcess::UnknownError:
errorString = tr("QProcess::UnknownError");
break;
}
ui->textBrowser->setTextColor(Qt::red);
ui->textBrowser->setText(errorString);
if (process->state() == QProcess::NotRunning)
enableUiElements(true);
}
/**
* @brief MainWindow::setPassExecutable
* @param path
*/
void MainWindow::setPassExecutable(QString path) { passExecutable = path; }
/**
* @brief MainWindow::setGitExecutable
* @param path
*/
void MainWindow::setGitExecutable(QString path) { gitExecutable = path; }
/**
* @brief MainWindow::setGpgExecutable
* @param path
*/
void MainWindow::setGpgExecutable(QString path) { gpgExecutable = path; }
/**
* @brief MainWindow::getGpgExecutable
* @return
*/
QString MainWindow::getGpgExecutable() { return gpgExecutable; }
/**
* @brief MainWindow::on_configButton_clicked
*/
void MainWindow::on_configButton_clicked() { config(); }
/**
- * @brief Executes when the string in the search box changes, collapses the TreeView
+ * @brief Executes when the string in the search box changes, collapses the
+ * TreeView
* @param arg1
*/
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
ui->treeView->expandAll();
ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
QString query = arg1;
query.replace(QRegExp(" "), ".*");
QRegExp regExp(query, Qt::CaseInsensitive);
proxyModel.setFilterRegExp(regExp);
ui->treeView->setRootIndex(
proxyModel.mapFromSource(model.setRootPath(passStore)));
selectFirstFile();
}
-
/**
* @brief MainWindow::on_lineEdit_returnPressed
*/
void MainWindow::on_lineEdit_returnPressed() {
- qDebug() << "on_lineEdit_returnPressed";
+ qDebug() << "on_lineEdit_returnPressed";
selectFirstFile();
on_treeView_clicked(ui->treeView->currentIndex());
}
/**
* @brief MainWindow::selectFirstFile
*/
void MainWindow::selectFirstFile() {
QModelIndex index = proxyModel.mapFromSource(model.setRootPath(passStore));
index = firstFile(index);
ui->treeView->setCurrentIndex(index);
}
/**
* @brief MainWindow::firstFile
* @param parentIndex
* @return QModelIndex
*/
QModelIndex MainWindow::firstFile(QModelIndex parentIndex) {
QModelIndex index = parentIndex;
int numRows = proxyModel.rowCount(parentIndex);
for (int row = 0; row < numRows; ++row) {
index = proxyModel.index(row, 0, parentIndex);
if (model.fileInfo(proxyModel.mapToSource(index)).isFile())
return index;
if (proxyModel.hasChildren(index))
return firstFile(index);
}
return index;
}
/**
* @brief MainWindow::getRecipientList
* @param for_file
* @return
*/
QStringList MainWindow::getRecipientList(QString for_file) {
QDir gpgIdPath(QFileInfo(for_file.startsWith(passStore)
? for_file
: passStore + for_file)
.absoluteDir());
bool found = false;
while (gpgIdPath.exists() && gpgIdPath.absolutePath().startsWith(passStore)) {
if (QFile(gpgIdPath.absoluteFilePath(".gpg-id")).exists()) {
found = true;
break;
}
if (!gpgIdPath.cdUp())
break;
}
QFile gpgId(found ? gpgIdPath.absoluteFilePath(".gpg-id")
: passStore + ".gpg-id");
if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text))
return QStringList();
QStringList recipients;
while (!gpgId.atEnd()) {
QString recipient(gpgId.readLine());
recipient = recipient.trimmed();
if (!recipient.isEmpty())
recipients += recipient;
}
return recipients;
}
/**
* @brief MainWindow::getRecipientString
* @param for_file
* @param separator
* @param count
* @return
*/
QString MainWindow::getRecipientString(QString for_file, QString separator,
int *count) {
QString recipients_str;
QStringList recipients_list = getRecipientList(for_file);
if (count)
*count = recipients_list.size();
- foreach(const QString recipient, recipients_list)
+ foreach (const QString recipient, recipients_list)
recipients_str += separator + '"' + recipient + '"';
return recipients_str;
}
/**
* @brief MainWindow::setPassword
* @param file
* @param overwrite
*/
void MainWindow::setPassword(QString file, bool overwrite, bool isNew = false) {
if (!isNew && lastDecrypt.isEmpty()) {
// warn?
return;
}
PasswordDialog d(this);
d.setFile(file);
d.setTemplate(passTemplate);
d.useTemplate(useTemplate);
d.templateAll(templateAllFields);
d.setPassword(lastDecrypt);
if (!d.exec()) {
d.setPassword(NULL);
return;
}
QString newValue = d.getPassword();
if (newValue.isEmpty())
return;
if (newValue.right(1) != "\n")
newValue += "\n";
currentAction = EDIT;
if (usePass) {
QString force(overwrite ? " -f " : " ");
executePass("insert" + force + "-m \"" + file + '"', newValue);
} else {
QString recipients = getRecipientString(file, " -r ");
if (recipients.isEmpty()) {
QMessageBox::critical(this, tr("Can not edit"),
tr("Could not read encryption key to use, .gpg-id "
"file missing or invalid."));
return;
}
QString force(overwrite ? " --yes " : " ");
executeWrapper(gpgExecutable, force + "--batch -eq --output \"" + file +
"\" " + recipients + " -",
newValue);
if (!useWebDav && useGit) {
if (!overwrite)
executeWrapper(gitExecutable, "add \"" + file + '"');
QString path = QDir(passStore).relativeFilePath(file);
path.replace(QRegExp("\\.gpg$"), "");
executeWrapper(gitExecutable, "commit \"" + file + "\" -m \"" +
(overwrite ? "Edit" : "Add") + " for " +
path + " using QtPass.\"");
if (autoPush)
on_pushButton_clicked();
}
}
}
/**
* @brief MainWindow::on_addButton_clicked
*/
void MainWindow::on_addButton_clicked() {
// Check for active and selected encryption key
-// QList<UserInfo> users=listKeys();
-// UserInfo testuser;
-// bool noUserEnabled = false;
-// // Check if at least one active user is selected
-// for (int i = 0; i< users.length();i++) {
-// testuser = users[i];
-// noUserEnabled = users[i].enabled | noUserEnabled;
-// }
-// // Error if no user is enabled, so a password doesn't get saved
-// if (noUserEnabled==false) {
-// QMessageBox::critical(this, tr("Can not get key list"),
-// tr("No Key for encryption selected! \nPlease select a valid key pair in the users dialouge"));
-// return;
-// }
+ // QList<UserInfo> users=listKeys();
+ // UserInfo testuser;
+ // bool noUserEnabled = false;
+ // // Check if at least one active user is selected
+ // for (int i = 0; i< users.length();i++) {
+ // testuser = users[i];
+ // noUserEnabled = users[i].enabled | noUserEnabled;
+ // }
+ // // Error if no user is enabled, so a password doesn't get saved
+ // if (noUserEnabled==false) {
+ // QMessageBox::critical(this, tr("Can not get key list"),
+ // tr("No Key for encryption selected! \nPlease
+ // select a valid key pair in the users dialouge"));
+ // return;
+ // }
bool ok;
QString dir = getDir(ui->treeView->currentIndex(), usePass);
QString file = QInputDialog::getText(
this, tr("New file"),
tr("New password file: \n(Will be placed in %1 )")
.arg(passStore + getDir(ui->treeView->currentIndex(), true)),
QLineEdit::Normal, "", &ok);
if (!ok || file.isEmpty())
return;
file = dir + file;
if (!usePass)
file += ".gpg";
lastDecrypt = "";
setPassword(file, false, true);
}
/**
* @brief MainWindow::on_deleteButton_clicked
*/
void MainWindow::on_deleteButton_clicked() {
QFileInfo fileOrFolder =
model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
QString file = "";
if (fileOrFolder.isFile()) {
file = getFile(ui->treeView->currentIndex(), usePass);
if (QMessageBox::question(
this, tr("Delete password?"),
tr("Are you sure you want to delete %1?")
.arg(QDir::separator() +
getFile(ui->treeView->currentIndex(), true)),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
if (usePass) {
currentAction = DELETE;
executePass("rm -f \"" + file + '"');
if (useGit && autoPush)
on_pushButton_clicked();
} else {
if (useGit) {
executeWrapper(gitExecutable, "rm -f \"" + file + '"');
executeWrapper(gitExecutable,
"commit \"" + file + "\" -m \"Remove for " +
getFile(ui->treeView->currentIndex(), true) +
" using QtPass.\"");
if (autoPush)
on_pushButton_clicked();
} else {
QFile(file).remove();
}
}
} else {
file = getDir(ui->treeView->currentIndex(), usePass);
// TODO: message box should accept enter key
if (QMessageBox::question(
this, tr("Delete folder?"),
tr("Are you sure you want to delete %1?")
.arg(QDir::separator() +
getDir(ui->treeView->currentIndex(), true)),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
return;
} else {
if (usePass) {
currentAction = DELETE;
executePass("rm -rf \"" + file + '"');
if (useGit && autoPush) {
on_pushButton_clicked();
}
} else {
if (useGit) {
executeWrapper(gitExecutable, "rm -rf \"" + file + '"');
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QDir dir(file);
dir.removeRecursively();
#else
removeDir(passStore + file);
#endif
executeWrapper(gitExecutable,
"commit \"" + file + "\" -m \"Remove for " +
getFile(ui->treeView->currentIndex(), true) +
" using QtPass.\"");
if (autoPush) {
on_pushButton_clicked();
}
} else {
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QDir dir(file);
dir.removeRecursively();
#else
removeDir(passStore + file);
#endif
}
}
}
}
lastDecrypt = "";
}
/**
* @brief MainWindow::removeDir
* @param dirName
* @return
*/
bool MainWindow::removeDir(const QString &dirName) {
bool result = true;
QDir dir(dirName);
if (dir.exists(dirName)) {
- Q_FOREACH(QFileInfo info,
+ Q_FOREACH (QFileInfo info,
dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System |
QDir::Hidden | QDir::AllDirs | QDir::Files,
QDir::DirsFirst)) {
if (info.isDir())
result = removeDir(info.absoluteFilePath());
else
result = QFile::remove(info.absoluteFilePath());
if (!result)
return result;
}
result = dir.rmdir(dirName);
}
return result;
}
/**
* @brief MainWindow::on_editButton_clicked
*/
void MainWindow::on_editButton_clicked() {
QString file = getFile(ui->treeView->currentIndex(), usePass);
if (file.isEmpty()) {
QMessageBox::critical(
this, tr("Can not edit"),
tr("Selected password file does not exist, not able to edit"));
return;
}
setPassword(file, true);
}
/**
* @brief MainWindow::listKeys
* @param keystring
* @param secret
* @return
*/
QList<UserInfo> MainWindow::listKeys(QString keystring, bool secret) {
waitFor(5);
QList<UserInfo> users;
currentAction = GPG_INTERNAL;
QString listopt = secret ? "--list-secret-keys " : "--list-keys ";
executeWrapper(gpgExecutable,
"--no-tty --with-colons " + listopt + keystring);
process->waitForFinished(2000);
if (process->exitStatus() != QProcess::NormalExit)
return users;
QStringList keys = QString(process->readAllStandardOutput())
.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
UserInfo current_user;
- foreach(QString key, keys) {
+ foreach (QString key, keys) {
QStringList props = key.split(':');
if (props.size() < 10)
continue;
if (props[0] == (secret ? "sec" : "pub")) {
if (!current_user.key_id.isEmpty())
users.append(current_user);
current_user = UserInfo();
current_user.key_id = props[4];
current_user.name = props[9].toUtf8();
current_user.validity = props[8][0].toLatin1();
current_user.created.setTime_t(props[5].toInt());
current_user.expiry.setTime_t(props[6].toInt());
} else if (current_user.name.isEmpty() && props[0] == "uid") {
current_user.name = props[9];
}
}
if (!current_user.key_id.isEmpty())
users.append(current_user);
return users;
}
void MainWindow::userDialog(QString dir) {
if (!dir.isEmpty())
currentDir = dir;
on_usersButton_clicked();
}
void MainWindow::on_usersButton_clicked() {
QList<UserInfo> users = listKeys();
if (users.size() == 0) {
QMessageBox::critical(this, tr("Can not get key list"),
tr("Unable to get list of available gpg keys"));
return;
}
QList<UserInfo> secret_keys = listKeys("", true);
- foreach(const UserInfo &sec, secret_keys) {
+ foreach (const UserInfo &sec, secret_keys) {
for (QList<UserInfo>::iterator it = users.begin(); it != users.end(); ++it)
if (sec.key_id == it->key_id)
it->have_secret = true;
}
QList<UserInfo> selected_users;
QString dir = currentDir.isEmpty()
? getDir(ui->treeView->currentIndex(), false)
: currentDir;
int count = 0;
QString recipients =
getRecipientString(dir.isEmpty() ? "" : dir, " ", &count);
if (!recipients.isEmpty())
selected_users = listKeys(recipients);
- foreach(const UserInfo &sel, selected_users) {
+ foreach (const UserInfo &sel, selected_users) {
for (QList<UserInfo>::iterator it = users.begin(); it != users.end(); ++it)
if (sel.key_id == it->key_id)
it->enabled = true;
}
if (count > selected_users.size()) {
// Some keys seem missing from keyring, add them separately
QStringList recipients = getRecipientList(dir.isEmpty() ? "" : dir);
- foreach(const QString recipient, recipients) {
+ foreach (const QString recipient, recipients) {
if (listKeys(recipient).size() < 1) {
UserInfo i;
i.enabled = true;
i.key_id = recipient;
i.name = " ?? " + tr("Key not found in keyring");
users.append(i);
}
}
}
UsersDialog d(this);
d.setUsers(&users);
if (!d.exec()) {
d.setUsers(NULL);
return;
}
d.setUsers(NULL);
QString gpgIdFile = dir + ".gpg-id";
QFile gpgId(gpgIdFile);
bool addFile = false;
if (addGPGId) {
QFileInfo checkFile(gpgIdFile);
if (!checkFile.exists() || !checkFile.isFile())
addFile = true;
}
if (!gpgId.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::critical(this, tr("Cannot update"),
tr("Failed to open .gpg-id for writing."));
return;
}
bool secret_selected = false;
- foreach(const UserInfo &user, users) {
+ foreach (const UserInfo &user, users) {
if (user.enabled) {
gpgId.write((user.key_id + "\n").toUtf8());
secret_selected |= user.have_secret;
}
}
gpgId.close();
if (!secret_selected) {
QMessageBox::critical(
this, tr("Check selected users!"),
tr("None of the selected keys have a secret key available.\n"
"You will not be able to decrypt any newly added passwords!"));
}
if (!useWebDav && useGit && !gitExecutable.isEmpty()) {
if (addFile)
executeWrapper(gitExecutable, "add \"" + gpgIdFile + '"');
QString path = gpgIdFile;
path.replace(QRegExp("\\.gpg$"), "");
executeWrapper(gitExecutable, "commit \"" + gpgIdFile + "\" -m \"Added " +
path + " using QtPass.\"");
if (autoPush)
on_pushButton_clicked();
}
}
/**
* @brief MainWindow::setApp
* @param app
*/
void MainWindow::setApp(SingleApplication *app) {
#if SINGLE_APP
connect(app, SIGNAL(messageAvailable(QString)), this,
SLOT(messageAvailable(QString)));
#endif
}
/**
* @brief MainWindow::messageAvailable
* @param message
*/
void MainWindow::messageAvailable(QString message) {
if (message.isEmpty()) {
focusInput();
} else {
ui->treeView->expandAll();
ui->lineEdit->setText(message);
on_lineEdit_returnPressed();
}
show();
raise();
}
/**
* @brief MainWindow::setText
* @param message
*/
void MainWindow::setText(QString text) { ui->lineEdit->setText(text); }
/**
* @brief MainWindow::updateEnv
*/
void MainWindow::updateEnv() {
QStringList store = env.filter("PASSWORD_STORE_DIR");
// put PASSWORD_STORE_DIR in env
if (store.isEmpty()) {
// qDebug() << "Added PASSWORD_STORE_DIR";
env.append("PASSWORD_STORE_DIR=" + passStore);
} else {
// qDebug() << "Update PASSWORD_STORE_DIR with " + passStore;
env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" + passStore);
}
}
/**
* @brief MainWindow::getSecretKeys
* @return QStringList keys
*/
QStringList MainWindow::getSecretKeys() {
QList<UserInfo> keys = listKeys("", true);
QStringList names;
if (keys.size() == 0)
return names;
- foreach(const UserInfo &sec, keys)
+ foreach (const UserInfo &sec, keys)
names << sec.name;
return names;
}
/**
* @brief Dialog::genKey
* @param QString batch
*/
void MainWindow::generateKeyPair(QString batch, QDialog *keygenWindow) {
keygen = keygenWindow;
ui->statusBar->showMessage(tr("Generating GPG key pair"), 60000);
currentAction = GPG_INTERNAL;
executeWrapper(gpgExecutable, "--gen-key --no-tty --batch", batch);
}
/**
* @brief MainWindow::updateProfileBox
*/
void MainWindow::updateProfileBox() {
// qDebug() << profiles.size();
if (profiles.isEmpty()) {
ui->profileBox->hide();
} else {
ui->profileBox->show();
if (profiles.size() < 2)
ui->profileBox->setEnabled(false);
else
ui->profileBox->setEnabled(true);
ui->profileBox->clear();
QHashIterator<QString, QString> i(profiles);
while (i.hasNext()) {
i.next();
if (!i.key().isEmpty())
ui->profileBox->addItem(i.key());
}
}
int index = ui->profileBox->findText(profile);
- if (index != -1) // -1 for not found
+ if (index != -1) // -1 for not found
ui->profileBox->setCurrentIndex(index);
}
/**
* @brief MainWindow::on_profileBox_currentIndexChanged
* @param name
*/
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
if (startupPhase || name == profile)
return;
profile = name;
passStore = profiles[name];
ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
QSettings &settings(getSettings());
settings.setValue("profile", profile);
settings.setValue("passStore", passStore);
// qDebug() << env;
QStringList store = env.filter("PASSWORD_STORE_DIR");
// put PASSWORD_STORE_DIR in env
if (store.isEmpty()) {
// qDebug() << "Added PASSWORD_STORE_DIR";
env.append("PASSWORD_STORE_DIR=" + passStore);
} else {
// qDebug() << "Update PASSWORD_STORE_DIR";
env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" + passStore);
}
ui->treeView->setRootIndex(
proxyModel.mapFromSource(model.setRootPath(passStore)));
}
/**
* @brief MainWindow::initTrayIcon
*/
void MainWindow::initTrayIcon() {
if (tray != NULL) {
qDebug() << "Creating tray icon again?";
return;
}
if (QSystemTrayIcon::isSystemTrayAvailable() == true) {
// Setup tray icon
this->tray = new TrayIcon(this);
if (tray == NULL)
qDebug() << "Allocating tray icon failed.";
} else {
qDebug() << "No tray icon for this OS possibly also not show options?";
}
}
/**
* @brief MainWindow::destroyTrayIcon
*/
void MainWindow::destroyTrayIcon() {
if (tray == NULL) {
qDebug() << "Destroy non existing tray icon?";
return;
}
delete this->tray;
tray = NULL;
}
/**
* @brief MainWindow::closeEvent
* @param event
*/
void MainWindow::closeEvent(QCloseEvent *event) {
if (hideOnClose) {
this->hide();
event->ignore();
} else {
settings->beginGroup("mainwindow");
settings->setValue("geometry", saveGeometry());
settings->setValue("savestate", saveState());
settings->setValue("maximized", isMaximized());
if (!isMaximized()) {
settings->setValue("pos", pos());
settings->setValue("size", size());
}
settings->setValue("splitterLeft", ui->splitter->sizes()[0]);
settings->setValue("splitterRight", ui->splitter->sizes()[1]);
settings->endGroup();
event->accept();
}
}
-bool MainWindow::eventFilter(QObject *obj, QEvent *event)
-{
- if (obj == ui->lineEdit && event->type() == QEvent::KeyPress)
- {
- QKeyEvent *key = static_cast<QKeyEvent *>(event);
- if(key->key() == Qt::Key_Down) {
- ui->treeView->setFocus();
- }
+bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
+ if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
+ QKeyEvent *key = static_cast<QKeyEvent *>(event);
+ if (key->key() == Qt::Key_Down) {
+ ui->treeView->setFocus();
}
- return QObject::eventFilter(obj, event);
+ }
+ return QObject::eventFilter(obj, event);
}
-void MainWindow::keyPressEvent(QKeyEvent * event) {
- switch (event->key()) {
- case Qt::Key_Delete:
- on_deleteButton_clicked();
- break;
- case Qt::Key_Return:
- case Qt::Key_Enter:
- on_treeView_clicked(ui->treeView->currentIndex());
- break;
- case Qt::Key_Escape:
- ui->lineEdit->clear();
- break;
- default:
- break;
- }
+void MainWindow::keyPressEvent(QKeyEvent *event) {
+ switch (event->key()) {
+ case Qt::Key_Delete:
+ on_deleteButton_clicked();
+ break;
+ case Qt::Key_Return:
+ case Qt::Key_Enter:
+ on_treeView_clicked(ui->treeView->currentIndex());
+ break;
+ case Qt::Key_Escape:
+ ui->lineEdit->clear();
+ break;
+ default:
+ break;
+ }
}
-
void MainWindow::on_copyPasswordButton_clicked() { copyPasswordToClipboard(); }
/**
* @brief MainWindow::showContextMenu
* @param pos
*/
void MainWindow::showContextMenu(const QPoint &pos) {
QModelIndex index = ui->treeView->indexAt(pos);
bool selected = true;
if (!index.isValid()) {
ui->treeView->clearSelection();
ui->deleteButton->setEnabled(false);
ui->editButton->setEnabled(false);
currentDir = "";
selected = false;
}
ui->treeView->setCurrentIndex(index);
QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
QFileInfo fileOrFolder =
model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
QMenu contextMenu;
if (!selected || fileOrFolder.isDir()) {
QAction *addFolder = contextMenu.addAction(tr("Add folder"));
QAction *addPassword = contextMenu.addAction(tr("Add password"));
QAction *users = contextMenu.addAction(tr("Users"));
connect(addFolder, SIGNAL(triggered()), this, SLOT(addFolder()));
connect(addPassword, SIGNAL(triggered()), this,
SLOT(on_addButton_clicked()));
connect(users, SIGNAL(triggered()), this, SLOT(on_usersButton_clicked()));
} else if (fileOrFolder.isFile()) {
QAction *edit = contextMenu.addAction(tr("Edit"));
connect(edit, SIGNAL(triggered()), this, SLOT(editPassword()));
}
if (selected) {
// if (useClipboard != CLIPBOARD_NEVER) {
// contextMenu.addSeparator();
// QAction* copyItem = contextMenu.addAction(tr("Copy Password"));
// if (getClippedPassword().length() == 0) copyItem->setEnabled(false);
// connect(copyItem, SIGNAL(triggered()), this,
// SLOT(copyPasswordToClipboard()));
// }
contextMenu.addSeparator();
QAction *deleteItem = contextMenu.addAction(tr("Delete"));
connect(deleteItem, SIGNAL(triggered()), this,
SLOT(on_deleteButton_clicked()));
}
contextMenu.exec(globalPos);
}
/**
* @brief MainWindow::showContextMenu
* @param pos
*/
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
if (useClipboard != CLIPBOARD_NEVER) {
contextMenu->addSeparator();
QAction *copyItem = contextMenu->addAction(tr("Copy Password"));
if (getClippedPassword().length() == 0)
copyItem->setEnabled(false);
connect(copyItem, SIGNAL(triggered()), this,
SLOT(copyPasswordToClipboard()));
}
QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
contextMenu->exec(globalPos);
}
/**
* @brief MainWindow::addFolder
*/
void MainWindow::addFolder() {
bool ok;
QString dir = getDir(ui->treeView->currentIndex(), false);
QString newdir = QInputDialog::getText(
this, tr("New file"),
tr("New Folder: \n(Will be placed in %1 )")
- .arg(passStore + getDir(ui->treeView->currentIndex(), true)),
+ .arg(passStore + getDir(ui->treeView->currentIndex(), true)),
QLineEdit::Normal, "", &ok);
if (!ok || newdir.isEmpty())
return;
newdir.prepend(dir);
// qDebug() << newdir;
QDir().mkdir(newdir);
// TODO(annejan) add to git?
}
/**
* @brief MainWindow::editPassword
*/
void MainWindow::editPassword() {
if (useGit && autoPull)
on_updateButton_clicked();
waitFor(30);
// TODO(annejan) move to editbutton stuff possibly?
currentDir = getDir(ui->treeView->currentIndex(), false);
lastDecrypt = "Could not decrypt";
QString file = getFile(ui->treeView->currentIndex(), usePass);
if (!file.isEmpty()) {
currentAction = GPG;
if (usePass)
executePass('"' + file + '"');
else
executeWrapper(gpgExecutable,
"-d --quiet --yes --no-encrypt-to --batch --use-agent \"" +
file + '"');
- process->waitForFinished(30000); // long wait (passphrase stuff)
+ process->waitForFinished(30000); // long wait (passphrase stuff)
if (process->exitStatus() == QProcess::NormalExit)
on_editButton_clicked();
}
}
/**
* @brief MainWindow::generatePassword
* @return
*/
QString MainWindow::generatePassword() {
QString passwd;
if (usePwgen) {
waitFor(2);
// --secure goes first as it overrides --no-* otherwise
- QString args = QString("-1 ") +
- (lessRandom ? "" : "--secure ") +
+ QString args = QString("-1 ") + (lessRandom ? "" : "--secure ") +
(avoidCapitals ? "--no-capitalize " : "--capitalize ") +
- (avoidNumbers ? "--no-numerals " : "--numerals ") +
- (useSymbols ? "--symbols " : "") +
+ (avoidNumbers ? "--no-numerals " : "--numerals ") +
+ (useSymbols ? "--symbols " : "") +
QString::number(passwordLength);
currentAction = PWGEN;
executeWrapper(pwgenExecutable, args);
process->waitForFinished(1000);
if (process->exitStatus() == QProcess::NormalExit)
passwd =
QString(process->readAllStandardOutput()).remove(QRegExp("[\\n\\r]"));
else
qDebug() << "pwgen fail";
} else {
int length = passwordChars.length();
if (length > 0) {
for (int i = 0; i < passwordLength; ++i) {
int index = qrand() % length;
QChar nextChar = passwordChars.at(index);
passwd.append(nextChar);
}
} else {
QMessageBox::critical(
this, tr("No characters chosen"),
tr("Can't generate password, there are no characters to choose from "
"set in the configuration!"));
}
}
return passwd;
}
/**
* @brief MainWindow::waitFor
* @param seconds
*/
void MainWindow::waitFor(int seconds) {
QDateTime current = QDateTime::currentDateTime();
uint stop = current.toTime_t() + seconds;
while (!process->atEnd() || !execQueue->isEmpty()) {
current = QDateTime::currentDateTime();
if (stop < current.toTime_t()) {
QMessageBox::critical(
this, tr("Timed out"),
tr("Can't start process, previous one is still running!"));
return;
}
Util::qSleep(100);
}
}
/**
* @brief MainWindow::clearTemplateWidgets
*/
void MainWindow::clearTemplateWidgets() {
while (ui->formLayout->count() > 0) {
QLayoutItem *item = ui->formLayout->takeAt(0);
delete item->widget();
delete item;
}
ui->verticalLayoutPassword->setSpacing(0);
}
/*
* @brief Mainwindow::copyPasswordToClipboard - copy the clipped password (if
* not "") to the clipboard
* @return
*/
void MainWindow::copyPasswordToClipboard() {
if (clippedPass.length() > 0) {
QClipboard *clip = QApplication::clipboard();
clip->setText(clippedPass);
ui->statusBar->showMessage(tr("Password copied to clipboard"), 3000);
if (useAutoclear) {
QTimer::singleShot(1000 * autoclearSeconds, this, SLOT(clearClipboard()));
}
}
}
/**
* @brief Mainwindow::setClippedPassword - set the stored clipped password
* @return none
*/
void MainWindow::setClippedPassword(const QString &pass) {
clippedPass = pass;
if (clippedPass.length() == 0)
ui->copyPasswordButton->setEnabled(false);
else
ui->copyPasswordButton->setEnabled(true);
}
const QString &MainWindow::getClippedPassword() { return clippedPass; }
diff --git a/mainwindow.h b/mainwindow.h
index 3f642e8..8867900 100644
--- a/mainwindow.h
+++ b/mainwindow.h
@@ -1,182 +1,181 @@
#ifndef MAINWINDOW_H_
#define MAINWINDOW_H_
-#include <QMainWindow>
-#include <QTreeView>
+#include "storemodel.h"
+#include "trayicon.h"
#include <QFileSystemModel>
+#include <QMainWindow>
#include <QProcess>
#include <QQueue>
#include <QSettings>
#include <QTimer>
-#include "storemodel.h"
-#include "trayicon.h"
+#include <QTreeView>
#if SINGLE_APP
#include "singleapplication.h"
#else
#define SingleApplication QApplication
#endif
namespace Ui {
class MainWindow;
}
struct execQueueItem {
QString app;
QString args;
QString input;
};
struct UserInfo;
class MainWindow : public QMainWindow {
Q_OBJECT
enum actionType { GPG, GIT, EDIT, DELETE, GPG_INTERNAL, PWGEN };
- public:
+public:
enum clipBoardType {
CLIPBOARD_NEVER = 0,
CLIPBOARD_ALWAYS = 1,
CLIPBOARD_ON_DEMAND = 2
};
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void setPassExecutable(QString);
void setGitExecutable(QString);
void setGpgExecutable(QString);
QString getGpgExecutable();
bool checkConfig();
void setApp(SingleApplication *app);
void setText(QString);
QStringList getSecretKeys();
void generateKeyPair(QString, QDialog *);
void userDialog(QString = "");
QString generatePassword();
void config();
void executePassGitInit();
- protected:
+protected:
void closeEvent(QCloseEvent *event);
- void keyPressEvent(QKeyEvent * event);
+ void keyPressEvent(QKeyEvent *event);
void changeEvent(QEvent *event);
bool eventFilter(QObject *obj, QEvent *event);
-
- private slots:
+private slots:
void on_updateButton_clicked();
void on_pushButton_clicked();
void on_treeView_clicked(const QModelIndex &index);
void on_treeView_doubleClicked(const QModelIndex &index);
void on_configButton_clicked();
void readyRead(bool finished);
void processFinished(int, QProcess::ExitStatus);
void processError(QProcess::ProcessError);
void clearClipboard();
void clearPanel();
void on_lineEdit_textChanged(const QString &arg1);
void on_lineEdit_returnPressed();
void on_addButton_clicked();
void on_deleteButton_clicked();
void on_editButton_clicked();
void on_usersButton_clicked();
void messageAvailable(QString message);
void on_profileBox_currentIndexChanged(QString);
void on_copyPasswordButton_clicked();
void showContextMenu(const QPoint &pos);
void showBrowserContextMenu(const QPoint &pos);
void addFolder();
void editPassword();
void focusInput();
void copyPasswordToClipboard();
- private:
+private:
QAction *actionAddPassword;
QAction *actionAddFolder;
QApplication *QtPass;
QScopedPointer<QSettings> settings;
QScopedPointer<Ui::MainWindow> ui;
QFileSystemModel model;
StoreModel proxyModel;
QScopedPointer<QItemSelectionModel> selectionModel;
QScopedPointer<QProcess> process;
bool usePass;
clipBoardType useClipboard;
bool useAutoclear;
bool useAutoclearPanel;
bool hidePassword;
bool hideContent;
bool addGPGId;
int autoclearSeconds;
int autoclearPanelSeconds;
QString passStore;
QString passExecutable;
QString gitExecutable;
QString gpgExecutable;
QString pwgenExecutable;
QString gpgHome;
bool useWebDav;
QString webDavUrl;
QString webDavUser;
QString webDavPassword;
QProcess fusedav;
QString clippedPass;
QString autoclearPass;
QTimer *autoclearTimer;
actionType currentAction;
QString lastDecrypt;
bool wrapperRunning;
QStringList env;
QQueue<execQueueItem> *execQueue;
bool freshStart;
QDialog *keygen;
QString currentDir;
QHash<QString, QString> profiles;
QString profile;
bool startupPhase;
TrayIcon *tray;
bool useTrayIcon;
bool hideOnClose;
bool startMinimized;
bool useGit;
bool usePwgen;
bool avoidCapitals;
bool avoidNumbers;
bool lessRandom;
bool useSymbols;
int passwordLength;
QString passwordChars;
bool useTemplate;
QString passTemplate;
bool templateAllFields;
bool autoPull;
bool autoPush;
bool alwaysOnTop;
void updateText();
void executePass(QString, QString = QString());
void executeWrapper(QString, QString, QString = QString());
void enableUiElements(bool state);
void selectFirstFile();
QModelIndex firstFile(QModelIndex parentIndex);
QString getDir(const QModelIndex &, bool);
QString getFile(const QModelIndex &, bool);
void setPassword(QString, bool, bool);
QSettings &getSettings();
QList<UserInfo> listKeys(QString keystring = "", bool secret = false);
QStringList getRecipientList(QString for_file);
QString getRecipientString(QString for_file, QString separator = " ",
int *count = NULL);
void mountWebDav();
void updateEnv();
void updateProfileBox();
void initTrayIcon();
void destroyTrayIcon();
bool removeDir(const QString &dirName);
void waitFor(int seconds);
void clearTemplateWidgets();
void setClippedPassword(const QString &pass);
const QString &getClippedPassword();
};
-#endif // MAINWINDOW_H_
+#endif // MAINWINDOW_H_
diff --git a/passworddialog.cpp b/passworddialog.cpp
index 688bcef..ac5230d 100644
--- a/passworddialog.cpp
+++ b/passworddialog.cpp
@@ -1,111 +1,111 @@
#include "passworddialog.h"
+#include "ui_passworddialog.h"
+#include <QDebug>
#include <QLabel>
#include <QLineEdit>
-#include <QDebug>
-#include "ui_passworddialog.h"
PasswordDialog::PasswordDialog(MainWindow *parent)
: QDialog(parent), ui(new Ui::PasswordDialog) {
mainWindow = parent;
templating = false;
allFields = false;
ui->setupUi(this);
}
PasswordDialog::~PasswordDialog() { delete ui; }
void PasswordDialog::on_checkBoxShow_stateChanged(int arg1) {
if (arg1)
ui->lineEditPassword->setEchoMode(QLineEdit::Normal);
else
ui->lineEditPassword->setEchoMode(QLineEdit::Password);
}
void PasswordDialog::on_createPasswordButton_clicked() {
ui->widget->setEnabled(false);
ui->lineEditPassword->setText(mainWindow->generatePassword());
ui->widget->setEnabled(true);
}
void PasswordDialog::setPassword(QString password) {
QStringList tokens = password.split("\n");
ui->lineEditPassword->setText(tokens[0]);
tokens.pop_front();
if (templating) {
QWidget *previous = ui->checkBoxShow;
for (int i = 0; i < ui->formLayout->rowCount(); ++i) {
QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole);
if (item == NULL)
continue;
QWidget *widget = item->widget();
for (int j = 0; j < tokens.length(); ++j) {
QString token = tokens.at(j);
if (token.startsWith(widget->objectName() + ':')) {
tokens.removeAt(j);
QString value = token.remove(0, widget->objectName().length() + 1);
- reinterpret_cast<QLineEdit*>(widget)->setText(value);
+ reinterpret_cast<QLineEdit *>(widget)->setText(value);
}
}
previous = widget;
}
if (allFields) {
for (int j = 0; j < tokens.length(); ++j) {
QString token = tokens.at(j);
if (token.contains(':')) {
int colon = token.indexOf(':');
QString field = token.left(colon);
QString value = token.right(token.length() - colon - 1);
if (!passTemplate.contains(field) && value.startsWith("//"))
- continue; // colon is probably from a url
+ continue; // colon is probably from a url
QLineEdit *line = new QLineEdit();
line->setObjectName(field);
line->setText(value);
ui->formLayout->addRow(new QLabel(field), line);
setTabOrder(previous, line);
previous = line;
tokens.removeAt(j);
- --j; // tokens.length() also got shortened by the remove..
+ --j; // tokens.length() also got shortened by the remove..
}
}
}
}
ui->plainTextEdit->insertPlainText(tokens.join("\n"));
}
QString PasswordDialog::getPassword() {
QString passFile = ui->lineEditPassword->text() + "\n";
for (int i = 0; i < ui->formLayout->rowCount(); ++i) {
QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole);
if (item == NULL)
continue;
QWidget *widget = item->widget();
- QString text = reinterpret_cast<QLineEdit*>(widget)->text();
+ QString text = reinterpret_cast<QLineEdit *>(widget)->text();
if (text.isEmpty())
continue;
passFile += widget->objectName() + ":" + text + "\n";
}
passFile += ui->plainTextEdit->toPlainText();
return passFile;
}
void PasswordDialog::setTemplate(QString rawFields) {
fields = rawFields.split('\n');
QWidget *previous = ui->checkBoxShow;
- foreach(QString field, fields) {
+ foreach (QString field, fields) {
if (field.isEmpty())
continue;
QLineEdit *line = new QLineEdit();
line->setObjectName(field);
ui->formLayout->addRow(new QLabel(field), line);
setTabOrder(previous, line);
previous = line;
}
}
void PasswordDialog::setFile(QString file) {
this->setWindowTitle(this->windowTitle() + " " + file);
}
void PasswordDialog::templateAll(bool templateAll) { allFields = templateAll; }
void PasswordDialog::useTemplate(bool useTemplate) { templating = useTemplate; }
diff --git a/passworddialog.h b/passworddialog.h
index 3267cf4..3aedf1e 100644
--- a/passworddialog.h
+++ b/passworddialog.h
@@ -1,37 +1,37 @@
#ifndef PASSWORDDIALOG_H_
#define PASSWORDDIALOG_H_
-#include <QDialog>
#include "mainwindow.h"
+#include <QDialog>
namespace Ui {
class PasswordDialog;
}
class PasswordDialog : public QDialog {
Q_OBJECT
- public:
+public:
explicit PasswordDialog(MainWindow *parent = 0);
~PasswordDialog();
void setPassword(QString);
QString getPassword();
void setTemplate(QString);
void setFile(QString);
void useTemplate(bool useTemplate);
void templateAll(bool templateAll);
- private slots:
+private slots:
void on_checkBoxShow_stateChanged(int arg1);
void on_createPasswordButton_clicked();
- private:
+private:
Ui::PasswordDialog *ui;
MainWindow *mainWindow;
QString passTemplate;
QStringList fields;
bool templating;
bool allFields;
};
-#endif // PASSWORDDIALOG_H_
+#endif // PASSWORDDIALOG_H_
diff --git a/qprogressindicator.h b/qprogressindicator.h
index 980ebd7..b4a8b1b 100644
--- a/qprogressindicator.h
+++ b/qprogressindicator.h
@@ -1,99 +1,99 @@
#ifndef QPROGRESSINDICATOR_H_
#define QPROGRESSINDICATOR_H_
-#include <QWidget>
#include <QColor>
+#include <QWidget>
/*!
\class QProgressIndicator
\brief The QProgressIndicator class lets an application display a progress
indicator to show that a lengthy task is under way.
Progress indicators are indeterminate and do nothing more than spin to show
that the application is busy.
\sa QProgressBar
*/
class QProgressIndicator : public QWidget {
Q_OBJECT
Q_PROPERTY(int delay READ animationDelay WRITE setAnimationDelay)
Q_PROPERTY(bool displayedWhenStopped READ isDisplayedWhenStopped WRITE
setDisplayedWhenStopped)
Q_PROPERTY(QColor color READ color WRITE setColor)
- public:
+public:
explicit QProgressIndicator(QWidget *parent = 0);
/*! Returns the delay between animation steps.
\return The number of milliseconds between animation steps. By default,
the animation delay is set to 40 milliseconds.
\sa setAnimationDelay
*/
int animationDelay() const { return m_delay; }
/*! Returns a Boolean value indicating whether the component is currently
animated.
\return Animation state.
\sa startAnimation stopAnimation
*/
bool isAnimated() const;
/*! Returns a Boolean value indicating whether the receiver shows itself even
when it is not animating.
\return Return true if the progress indicator shows itself even when it is
not animating. By default, it returns false.
\sa setDisplayedWhenStopped
*/
bool isDisplayedWhenStopped() const;
/*! Returns the color of the component.
\sa setColor
*/
const QColor &color() const { return m_color; }
virtual QSize sizeHint() const;
int heightForWidth(int w) const;
- public slots:
+public slots:
/*! Starts the spin animation.
\sa stopAnimation isAnimated
*/
void startAnimation();
/*! Stops the spin animation.
\sa startAnimation isAnimated
*/
void stopAnimation();
/*! Sets the delay between animation steps.
Setting the \a delay to a value larger than 40 slows the animation, while
setting the \a delay to a smaller value speeds it up.
\param delay The delay, in milliseconds.
\sa animationDelay
*/
void setAnimationDelay(int delay);
/*! Sets whether the component hides itself when it is not animating.
\param state The animation state. Set false to hide the progress indicator
when it is not animating; otherwise true.
\sa isDisplayedWhenStopped
*/
void setDisplayedWhenStopped(bool state);
/*! Sets the color of the components to the given color.
\sa color
*/
void setColor(const QColor &color);
- protected:
+protected:
virtual void timerEvent(QTimerEvent *event);
virtual void paintEvent(QPaintEvent *event);
- private:
+private:
int m_angle;
int m_timerId;
int m_delay;
bool m_displayedWhenStopped;
QColor m_color;
};
-#endif // QPROGRESSINDICATOR_H_
+#endif // QPROGRESSINDICATOR_H_
diff --git a/singleapplication.h b/singleapplication.h
index ad64244..bfe212c 100644
--- a/singleapplication.h
+++ b/singleapplication.h
@@ -1,30 +1,30 @@
#ifndef SINGLEAPPLICATION_H_
#define SINGLEAPPLICATION_H_
#include <QApplication>
-#include <QSharedMemory>
#include <QLocalServer>
+#include <QSharedMemory>
class SingleApplication : public QApplication {
Q_OBJECT
- public:
+public:
SingleApplication(int &argc, char *argv[], const QString uniqueKey);
bool isRunning();
bool sendMessage(const QString &message);
- public slots:
+public slots:
void receiveMessage();
- signals:
+signals:
void messageAvailable(QString message);
- private:
+private:
bool _isRunning;
QString _uniqueKey;
QSharedMemory sharedMemory;
QScopedPointer<QLocalServer> localServer;
static const int timeout = 1000;
};
-#endif // SINGLEAPPLICATION_H_
+#endif // SINGLEAPPLICATION_H_
diff --git a/storemodel.h b/storemodel.h
index c489c0e..11304db 100644
--- a/storemodel.h
+++ b/storemodel.h
@@ -1,23 +1,23 @@
#ifndef STOREMODEL_H_
#define STOREMODEL_H_
-#include <QSortFilterProxyModel>
#include <QFileSystemModel>
#include <QRegExp>
+#include <QSortFilterProxyModel>
class StoreModel : public QSortFilterProxyModel {
Q_OBJECT
- private:
+private:
QFileSystemModel *fs;
QString store;
- public:
+public:
StoreModel();
bool filterAcceptsRow(int, const QModelIndex &) const;
bool ShowThis(const QModelIndex) const;
void setModelAndStore(QFileSystemModel *sourceModel, QString passStore);
QVariant data(const QModelIndex &index, int role) const;
};
-#endif // STOREMODEL_H_
+#endif // STOREMODEL_H_
diff --git a/trayicon.cpp b/trayicon.cpp
index f7cf765..8022d60 100644
--- a/trayicon.cpp
+++ b/trayicon.cpp
@@ -1,73 +1,73 @@
#include "trayicon.h"
TrayIcon::TrayIcon(QMainWindow *parent) {
parentwin = parent;
createActions();
createTrayIcon();
sysTrayIcon->setIcon(QIcon(":/artwork/icon.png"));
sysTrayIcon->show();
QObject::connect(sysTrayIcon,
SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}
void TrayIcon::setVisible(bool visible) {
if (visible == true)
parentwin->show();
else
parentwin->hide();
}
void TrayIcon::createActions() {
// minimizeAction = new QAction(tr("Mi&nimize"), this);
// connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
// maximizeAction = new QAction(tr("Ma&ximize"), this);
// connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
// restoreAction = new QAction(tr("&Restore"), this);
// connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}
void TrayIcon::createTrayIcon() {
trayIconMenu = new QMenu(this);
// trayIconMenu->addAction(minimizeAction);
// trayIconMenu->addAction(maximizeAction);
// trayIconMenu->addAction(restoreAction);
// trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
sysTrayIcon = new QSystemTrayIcon(this);
sysTrayIcon->setContextMenu(trayIconMenu);
}
void TrayIcon::showHideParent() {
if (parentwin->isVisible() == true)
parentwin->hide();
else
parentwin->show();
}
void TrayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) {
switch (reason) {
case QSystemTrayIcon::Trigger:
case QSystemTrayIcon::DoubleClick:
showHideParent();
break;
case QSystemTrayIcon::MiddleClick:
showMessage("test", "test msg", 1000);
break;
- default:{};
+ default: {};
}
}
void TrayIcon::showMessage(QString title, QString msg, int time) {
sysTrayIcon->showMessage(title, msg, QSystemTrayIcon::Information, time);
}
diff --git a/trayicon.h b/trayicon.h
index 4eaacf0..ae2286d 100644
--- a/trayicon.h
+++ b/trayicon.h
@@ -1,39 +1,39 @@
#ifndef TRAYICON_H_
#define TRAYICON_H_
-#include <QApplication>
-#include <QMenu>
#include <QAction>
+#include <QApplication>
#include <QMainWindow>
+#include <QMenu>
#include <QSystemTrayIcon>
#include <QWidget>
class TrayIcon : public QWidget {
Q_OBJECT
- public:
+public:
explicit TrayIcon(QMainWindow *parent);
void showMessage(QString title, QString msg, int time);
void setVisible(bool visible);
- signals:
+signals:
- public slots:
+public slots:
void showHideParent();
void iconActivated(QSystemTrayIcon::ActivationReason reason);
- private:
+private:
void createActions();
void createTrayIcon();
// QAction *minimizeAction;
// QAction *maximizeAction;
QAction *settingsAction;
QAction *quitAction;
QSystemTrayIcon *sysTrayIcon;
QMenu *trayIconMenu;
QMainWindow *parentwin;
};
-#endif // TRAYICON_H_
+#endif // TRAYICON_H_
diff --git a/usersdialog.cpp b/usersdialog.cpp
index 3dc395e..fcd5296 100644
--- a/usersdialog.cpp
+++ b/usersdialog.cpp
@@ -1,110 +1,110 @@
#include "usersdialog.h"
-#include <QRegExp>
-#include <QDebug>
#include "ui_usersdialog.h"
+#include <QDebug>
+#include <QRegExp>
UsersDialog::UsersDialog(QWidget *parent)
: QDialog(parent), ui(new Ui::UsersDialog) {
ui->setupUi(this);
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
connect(ui->listWidget, SIGNAL(itemChanged(QListWidgetItem *)), this,
SLOT(itemChange(QListWidgetItem *)));
userList = NULL;
#if QT_VERSION >= 0x050200
ui->lineEdit->setClearButtonEnabled(true);
#endif
}
UsersDialog::~UsersDialog() { delete ui; }
Q_DECLARE_METATYPE(UserInfo *)
void UsersDialog::itemChange(QListWidgetItem *item) {
if (!item)
return;
UserInfo *info = item->data(Qt::UserRole).value<UserInfo *>();
if (!info)
return;
info->enabled = item->checkState() == Qt::Checked;
}
void UsersDialog::setUsers(QList<UserInfo> *users) {
userList = users;
populateList("");
}
void UsersDialog::populateList(const QString &filter) {
QRegExp nameFilter("*" + filter + "*");
nameFilter.setPatternSyntax(QRegExp::Wildcard);
nameFilter.setCaseSensitivity(Qt::CaseInsensitive);
ui->listWidget->clear();
if (userList) {
for (QList<UserInfo>::iterator it = userList->begin();
it != userList->end(); ++it) {
UserInfo &user(*it);
if (filter.isEmpty() || nameFilter.exactMatch(user.name)) {
if (user.validity == '-' && !ui->checkBox->isChecked())
continue;
if (user.expiry.toTime_t() > 0 &&
user.expiry.daysTo(QDateTime::currentDateTime()) > 0 &&
!ui->checkBox->isChecked())
continue;
QString userText = user.name + "\n" + user.key_id;
if (user.created.toTime_t() > 0) {
userText += " " + tr("created") + " " +
user.created.toString(Qt::SystemLocaleShortDate);
}
if (user.expiry.toTime_t() > 0)
userText += " " + tr("expires") + " " +
user.expiry.toString(Qt::SystemLocaleShortDate);
QListWidgetItem *item = new QListWidgetItem(userText, ui->listWidget);
item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
item->setData(Qt::UserRole, QVariant::fromValue(&user));
if (user.have_secret) {
// item->setForeground(QColor(32, 74, 135));
item->setForeground(Qt::blue);
QFont font;
font.setFamily(font.defaultFamily());
font.setBold(true);
item->setFont(font);
} else if (user.validity == '-') {
item->setBackground(QColor(164, 0, 0));
item->setForeground(Qt::white);
} else if (user.expiry.toTime_t() > 0 &&
user.expiry.daysTo(QDateTime::currentDateTime()) > 0) {
item->setForeground(QColor(164, 0, 0));
}
ui->listWidget->addItem(item);
}
}
}
}
void UsersDialog::on_clearButton_clicked() {
ui->lineEdit->clear();
populateList("");
}
void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
populateList(filter);
}
void UsersDialog::closeEvent(QCloseEvent *event) {
// TODO(annejan) save window size or somethign
event->accept();
}
void UsersDialog::on_checkBox_clicked() { populateList(ui->lineEdit->text()); }
-void UsersDialog::keyPressEvent(QKeyEvent * event) {
- switch (event->key()) {
- case Qt::Key_Escape:
- ui->lineEdit->clear();
- break;
- default:
- break;
- }
+void UsersDialog::keyPressEvent(QKeyEvent *event) {
+ switch (event->key()) {
+ case Qt::Key_Escape:
+ ui->lineEdit->clear();
+ break;
+ default:
+ break;
+ }
}
diff --git a/usersdialog.h b/usersdialog.h
index d51981a..adb2385 100644
--- a/usersdialog.h
+++ b/usersdialog.h
@@ -1,52 +1,52 @@
#ifndef USERSDIALOG_H_
#define USERSDIALOG_H_
+#include <QCloseEvent>
+#include <QDateTime>
#include <QDialog>
#include <QList>
#include <QStandardItemModel>
-#include <QCloseEvent>
-#include <QDateTime>
namespace Ui {
class UsersDialog;
}
class QListWidgetItem;
struct UserInfo {
UserInfo() : validity('-'), have_secret(false), enabled(false) {}
QString name;
QString key_id;
char validity;
bool have_secret;
bool enabled;
QDateTime expiry;
QDateTime created;
};
class UsersDialog : public QDialog {
Q_OBJECT
- public:
+public:
explicit UsersDialog(QWidget *parent = 0);
~UsersDialog();
void setUsers(QList<UserInfo> *);
- protected:
+protected:
void closeEvent(QCloseEvent *event);
- void keyPressEvent(QKeyEvent * event);
+ void keyPressEvent(QKeyEvent *event);
- private slots:
+private slots:
void itemChange(QListWidgetItem *item);
void on_clearButton_clicked();
void on_lineEdit_textChanged(const QString &filter);
void on_checkBox_clicked();
- private:
+private:
Ui::UsersDialog *ui;
QList<UserInfo> *userList;
void populateList(const QString &filter);
};
-#endif // USERSDIALOG_H_
+#endif // USERSDIALOG_H_
diff --git a/util.cpp b/util.cpp
index 053aa01..216ed6e 100644
--- a/util.cpp
+++ b/util.cpp
@@ -1,131 +1,131 @@
#include "util.h"
#include <QDebug>
+#include <QDir>
#include <QFileInfo>
#include <QProcessEnvironment>
#include <QString>
-#include <QDir>
#ifdef Q_OS_WIN
#include <windows.h>
#else
#include <sys/time.h>
#endif
QProcessEnvironment Util::_env;
bool Util::_envInitialised;
/**
* @brief Util::initialiseEnvironment
*/
void Util::initialiseEnvironment() {
if (!_envInitialised) {
_env = QProcessEnvironment::systemEnvironment();
#ifdef __APPLE__
// TODO(annejan) checks here
QString path = _env.value("PATH");
if (!path.contains("/usr/local/MacGPG2/bin") &&
QFile("/usr/local/MacGPG2/bin").exists())
path += ":/usr/local/MacGPG2/bin";
if (!path.contains("/usr/local/bin"))
path += ":/usr/local/bin";
_env.insert("PATH", path);
#endif
_envInitialised = true;
}
}
/**
* @brief Util::findPasswordStore
* @return
*/
QString Util::findPasswordStore() {
QString path;
initialiseEnvironment();
if (_env.contains("PASSWORD_STORE_DIR")) {
path = _env.value("PASSWORD_STORE_DIR");
} else {
#ifdef Q_OS_WIN
path = QDir::homePath() + QDir::separator() + "password-store" +
QDir::separator();
#else
path = QDir::homePath() + QDir::separator() + ".password-store" +
QDir::separator();
#endif
}
return Util::normalizeFolderPath(path);
}
/**
* @brief Util::normalizeFolderPath
* @param path
* @return
*/
QString Util::normalizeFolderPath(QString path) {
if (!path.endsWith("/") && !path.endsWith(QDir::separator()))
path += QDir::separator();
return path;
}
QString Util::findBinaryInPath(QString binary) {
initialiseEnvironment();
QString ret = "";
binary.prepend(QDir::separator());
if (_env.contains("PATH")) {
QString path = _env.value("PATH");
QStringList entries;
#ifndef Q_OS_WIN
entries = path.split(':');
if (entries.length() < 2) {
#endif
entries = path.split(';');
#ifndef Q_OS_WIN
}
#endif
- foreach(QString entry, entries) {
+ foreach (QString entry, entries) {
QScopedPointer<QFileInfo> qfi(new QFileInfo(entry.append(binary)));
#ifdef Q_OS_WIN
if (!qfi->exists())
qfi.reset(new QFileInfo(entry.append(".exe")));
#endif
qDebug() << entry;
if (!qfi->isExecutable())
continue;
ret = qfi->absoluteFilePath();
break;
}
}
return ret;
}
/**
* @brief Util::checkConfig
* @param passStore
* @param passExecutable
* @param gpgExecutable
* @return
*/
bool Util::checkConfig(QString passStore, QString passExecutable,
QString gpgExecutable) {
return !QFile(passStore + ".gpg-id").exists() ||
(!QFile(passExecutable).exists() && !QFile(gpgExecutable).exists());
}
/**
* @brief Util::qSleep
* @param ms
*/
void Util::qSleep(int ms) {
#ifdef Q_OS_WIN
Sleep(uint(ms));
#else
struct timespec ts = {ms / 1000, (ms % 1000) * 1000 * 1000};
nanosleep(&ts, NULL);
#endif
}
diff --git a/util.h b/util.h
index e3ec61b..60d0385 100644
--- a/util.h
+++ b/util.h
@@ -1,22 +1,22 @@
#ifndef UTIL_H_
#define UTIL_H_
-#include <QString>
#include <QProcessEnvironment>
+#include <QString>
class Util {
- public:
+public:
static QString findBinaryInPath(QString binary);
static QString findPasswordStore();
static QString normalizeFolderPath(QString path);
static bool checkConfig(QString passStore, QString passExecutable,
QString gpgExecutable);
static void qSleep(int ms);
- private:
+private:
static void initialiseEnvironment();
static QProcessEnvironment _env;
static bool _envInitialised;
};
-#endif // UTIL_H_
+#endif // UTIL_H_
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Tue, Jul 8, 12:16 PM (8 h, 9 m)
Storage Engine
local-disk
Storage Format
Raw Data
Storage Handle
8d/26/573bda07cc6763424a15fcc822d1
Attached To
rGPGPASS GnuPG Password Manager
Event Timeline
Log In to Comment