diff options
Diffstat (limited to '')
45 files changed, 1816 insertions, 1976 deletions
diff --git a/include/GPG4USB.h b/include/GPG4USB.h index 95a6476c..05c979e6 100644 --- a/include/GPG4USB.h +++ b/include/GPG4USB.h @@ -11,6 +11,8 @@ #include <clocale> #include <cerrno> +#include <qglobal.h> + #include <QtCore> #include <QtWidgets> #include <QtNetwork/QtNetwork> diff --git a/include/attachments.h b/include/attachments.h index 2d614463..b5bbc7ca 100644 --- a/include/attachments.h +++ b/include/attachments.h @@ -43,8 +43,8 @@ private: void saveByteArrayToFile(QByteArray outBuffer, QString filename); - QAction *saveFileAct; - QAction *openFileAct; + QAction *saveFileAct{}; + QAction *openFileAct{}; AttachmentTableModel *table; QTableView *tableView; QSettings settings; diff --git a/include/attachmenttablemodel.h b/include/attachmenttablemodel.h index 987f75f6..9e9d937a 100644 --- a/include/attachmenttablemodel.h +++ b/include/attachmenttablemodel.h @@ -40,7 +40,7 @@ public: QVariant headerData(int section, Qt::Orientation orientation, int role) const override; - void add(MimePart mp); + void add(const MimePart& mp); MimePart getSelectedMimePart(QModelIndex index); diff --git a/include/editorpage.h b/include/editorpage.h index 0268c3e2..bf32ec0f 100644 --- a/include/editorpage.h +++ b/include/editorpage.h @@ -52,7 +52,7 @@ public: * @param filePath Path of the file handled in this tab * @param parent Pointer to the parent widget */ - explicit EditorPage(const QString &filePath = "", QWidget *parent = nullptr); + explicit EditorPage(QString filePath = "", QWidget *parent = nullptr); /** * @details Get the filepath of the currently activated tab. diff --git a/include/gpgcontext.h b/include/gpgcontext.h index a1680e6b..9e807992 100644 --- a/include/gpgcontext.h +++ b/include/gpgcontext.h @@ -111,9 +111,9 @@ namespace GpgME { void clearPasswordCache(); - void exportSecretKey(QString uid, QByteArray *outBuffer); + void exportSecretKey(const QString& uid, QByteArray *outBuffer); - gpgme_key_t getKeyDetails(QString uid); + gpgme_key_t getKeyDetails(const QString& uid); gpgme_signature_t verify(QByteArray *inBuffer, QByteArray *sigBuffer = nullptr); @@ -126,11 +126,11 @@ namespace GpgME { * * @param in Pointer to the QBytearray to check. */ - void preventNoDataErr(QByteArray *in); + static void preventNoDataErr(QByteArray *in); - GpgKey getKeyByFpr(QString fpr); + GpgKey getKeyByFpr(const QString& fpr); - GpgKey getKeyById(QString id); + GpgKey getKeyById(const QString& id); static QString gpgErrString(gpgme_error_t err); @@ -144,9 +144,9 @@ namespace GpgME { * \li 1, if the text is partially signed, * \li 0, if the text is not signed at all. */ - int textIsSigned(const QByteArray &text); + static int textIsSigned(const QByteArray &text); - QString beautifyFingerprint(QString fingerprint); + static QString beautifyFingerprint(QString fingerprint); signals: @@ -157,21 +157,21 @@ namespace GpgME { void slotRefreshKeyList(); private: - gpgme_ctx_t mCtx; - gpgme_data_t in; - [[maybe_unused]] gpgme_data_t out; + gpgme_ctx_t mCtx{}; + gpgme_data_t in{}; + [[maybe_unused]] gpgme_data_t out{}; gpgme_error_t err; - gpgme_error_t readToBuffer(gpgme_data_t in, QByteArray *outBuffer); + static gpgme_error_t readToBuffer(gpgme_data_t dataIn, QByteArray *outBuffer); QByteArray mPasswordCache; QSettings settings; [[maybe_unused]] bool debug; GpgKeyList mKeyList; - [[nodiscard]] int checkErr(gpgme_error_t err) const; + [[nodiscard]] static void checkErr(gpgme_error_t gpgmeError) ; - [[nodiscard]] int checkErr(gpgme_error_t err, QString comment) const; + [[nodiscard]] static void checkErr(gpgme_error_t gpgmeError, const QString& comment) ; static gpgme_error_t passphraseCb(void *hook, const char *uid_hint, const char *passphrase_info, @@ -181,7 +181,7 @@ namespace GpgME { const char *passphrase_info, int last_was_bad, int fd); - void executeGpgCommand(QStringList arguments, + void executeGpgCommand(const QStringList& arguments, QByteArray *stdOut, QByteArray *stdErr); diff --git a/include/helppage.h b/include/helppage.h index d911e391..981f3c10 100644 --- a/include/helppage.h +++ b/include/helppage.h @@ -27,7 +27,7 @@ class HelpPage : public QWidget { Q_OBJECT public: - explicit HelpPage(QString path, QWidget *parent = nullptr); + explicit HelpPage(const QString& path, QWidget *parent = nullptr); QTextBrowser *getBrowser(); @@ -35,11 +35,11 @@ signals: public slots: - void slotOpenUrl(QUrl url); + void slotOpenUrl(const QUrl& url); private: QTextBrowser *browser; /** The textbrowser of the tab */ - QUrl localizedHelp(QUrl path); + QUrl localizedHelp(const QUrl& path); }; diff --git a/include/keygendialog.h b/include/keygendialog.h index b52a8d86..9a6b219c 100644 --- a/include/keygendialog.h +++ b/include/keygendialog.h @@ -52,20 +52,20 @@ private: int checkPassWordStrength(); GpgME::GpgContext *mCtx; /** The current gpg context */ - __attribute__((unused)) KeyGenThread *keyGenThread; /** Thread for key generation */ + __attribute__((unused)) KeyGenThread *keyGenThread{}; /** Thread for key generation */ __attribute__((unused)) QStringList errorMessages; /** List of errors occuring when checking entries of lineedits */ QDialogButtonBox *buttonBox; /** Box for standardbuttons */ - QLabel *errorLabel; /** Label containing error message */ - QLineEdit *nameEdit; /** Lineedit for the keys name */ - QLineEdit *emailEdit; /** Lineedit for the keys email */ - QLineEdit *commentEdit; /** Lineedit for the keys comment */ - QLineEdit *passwordEdit; /** Lineedit for the keys password */ - QLineEdit *repeatpwEdit; /** Lineedit for the repetition of the keys password */ - QSpinBox *keySizeSpinBox; /** Spinbox for the keys size (in bit) */ - QComboBox *keyTypeComboBox; /** Combobox for Keytpe */ - QDateTimeEdit *dateEdit; /** Dateedit for expiration date */ - QCheckBox *expireCheckBox; /** Checkbox, if key should expire */ - QSlider *pwStrengthSlider; /** Slider showing the password strength */ + QLabel *errorLabel{}; /** Label containing error message */ + QLineEdit *nameEdit{}; /** Lineedit for the keys name */ + QLineEdit *emailEdit{}; /** Lineedit for the keys email */ + QLineEdit *commentEdit{}; /** Lineedit for the keys comment */ + QLineEdit *passwordEdit{}; /** Lineedit for the keys password */ + QLineEdit *repeatpwEdit{}; /** Lineedit for the repetition of the keys password */ + QSpinBox *keySizeSpinBox{}; /** Spinbox for the keys size (in bit) */ + QComboBox *keyTypeComboBox{}; /** Combobox for Keytpe */ + QDateTimeEdit *dateEdit{}; /** Dateedit for expiration date */ + QCheckBox *expireCheckBox{}; /** Checkbox, if key should expire */ + QSlider *pwStrengthSlider{}; /** Slider showing the password strength */ private slots: diff --git a/include/keyimportdetaildialog.h b/include/keyimportdetaildialog.h index cace45dd..966f8828 100644 --- a/include/keyimportdetaildialog.h +++ b/include/keyimportdetaildialog.h @@ -36,13 +36,13 @@ private: void createGeneralInfoBox(); void createKeysTable(); void createButtonBox(); - QString getStatusString(int keyStatus); + static QString getStatusString(int keyStatus); - QTableWidget *keysTable; + QTableWidget *keysTable{}; GpgME::GpgContext *mCtx; - QGroupBox *generalInfoBox; - QGroupBox *keyInfoBox; - QDialogButtonBox *buttonBox; + QGroupBox *generalInfoBox{}; + QGroupBox *keyInfoBox{}; + QDialogButtonBox *buttonBox{}; GpgImportInformation mResult; }; diff --git a/include/keylist.h b/include/keylist.h index 428486fb..1b8bb7ff 100644 --- a/include/keylist.h +++ b/include/keylist.h @@ -47,9 +47,9 @@ public: //QStringList *getPrivateChecked(); QStringList *getSelected(); - void markKeys(QStringList *keyIds); + [[maybe_unused]] static void markKeys(QStringList *keyIds); - bool containsPrivateKeys(); + [[maybe_unused]] bool containsPrivateKeys(); public slots: @@ -63,7 +63,7 @@ private: GpgME::GpgContext *mCtx; QTableWidget *mKeyList; QMenu *popupMenu; - QNetworkAccessManager *qnam; + QNetworkAccessManager *qnam{}; private slots: diff --git a/include/keymgmt.h b/include/keymgmt.h index b0b09bd6..0a6057d2 100755 --- a/include/keymgmt.h +++ b/include/keymgmt.h @@ -36,9 +36,9 @@ Q_OBJECT public: explicit KeyMgmt(GpgME::GpgContext *ctx, QWidget *parent = nullptr); - QAction *importKeyFromClipboardAct; - QAction *importKeyFromFileAct; - QAction *importKeyFromKeyServerAct; + QAction *importKeyFromClipboardAct{}; + QAction *importKeyFromFileAct{}; + QAction *importKeyFromKeyServerAct{}; public slots: @@ -77,18 +77,18 @@ private: KeyList *mKeyList; GpgME::GpgContext *mCtx; - QMenu *fileMenu; - QMenu *keyMenu; - QMenu *importKeyMenu; - QAction *exportKeyToFileAct; - QAction *exportKeyToClipboardAct; - QAction *deleteCheckedKeysAct; - QAction *deleteSelectedKeysAct; - QAction *generateKeyDialogAct; - QAction *closeAct; - QAction *showKeyDetailsAct; + QMenu *fileMenu{}; + QMenu *keyMenu{}; + QMenu *importKeyMenu{}; + QAction *exportKeyToFileAct{}; + QAction *exportKeyToClipboardAct{}; + QAction *deleteCheckedKeysAct{}; + QAction *deleteSelectedKeysAct{}; + QAction *generateKeyDialogAct{}; + QAction *closeAct{}; + QAction *showKeyDetailsAct{}; [[maybe_unused]] QMessageBox msgbox; - KeyServerImportDialog *importDialog; + KeyServerImportDialog *importDialog{}; protected: void closeEvent(QCloseEvent *event) override; diff --git a/include/keyserverimportdialog.h b/include/keyserverimportdialog.h index 7c79764b..289aa231 100644 --- a/include/keyserverimportdialog.h +++ b/include/keyserverimportdialog.h @@ -36,7 +36,7 @@ public: void slotImport(QStringList keyIds); - void slotImport(QStringList keyIds, QUrl keyserverUrl); + void slotImport(QStringList keyIds, const QUrl& keyserverUrl); private slots: @@ -57,7 +57,7 @@ private: QPushButton *createButton(const QString &text, const char *member); - QComboBox *createComboBox(); + static QComboBox *createComboBox(); GpgME::GpgContext *mCtx; KeyList *mKeyList; @@ -70,9 +70,9 @@ private: QPushButton *closeButton; QPushButton *importButton; QPushButton *searchButton; - QTableWidget *keysTable; + QTableWidget *keysTable{}; [[maybe_unused]] QUrl url; - QNetworkAccessManager *qnam; + QNetworkAccessManager *qnam{}; }; diff --git a/include/mainwindow.h b/include/mainwindow.h index 3969b842..a72696bf 100644 --- a/include/mainwindow.h +++ b/include/mainwindow.h @@ -50,7 +50,7 @@ public: public slots: - void slotSetStatusBarText(QString text); + void slotSetStatusBarText(const QString& text); protected: /** @@ -163,7 +163,7 @@ private slots: /** * @details Open online-tutorial in default browser. */ - void slotOpenTutorial(); + static void slotOpenTutorial(); /** * @details Open integrated help in new tab. @@ -173,7 +173,7 @@ private slots: /** * @details Open integrated help in new tab with the specified page. */ - void slotOpenHelp(QString page); + void slotOpenHelp(const QString& page); /** * @details Show a warn message in status bar, if there are files in attachment folder. @@ -183,7 +183,7 @@ private slots: /** * @details Open online translation tutorial in default browser. */ - void slotOpenTranslate(); + static void slotOpenTranslate(); /** * @details Replace double linebreaks by single linebreaks in currently active tab. @@ -270,7 +270,7 @@ private: /** * @brief return true, if restart is needed */ - bool getRestartNeeded(); + bool getRestartNeeded() const; TextEdit *edit; /** Tabwidget holding the edit-windows */ QMenu *fileMenu; /** Submenu for file-operations*/ diff --git a/include/quitdialog.h b/include/quitdialog.h index b0558d27..0927ebef 100755 --- a/include/quitdialog.h +++ b/include/quitdialog.h @@ -28,9 +28,9 @@ class QuitDialog : public QDialog { Q_OBJECT public: - QuitDialog(QWidget *parent, QHash<int, QString> unsavedDocs); + QuitDialog(QWidget *parent, const QHash<int, QString>& unsavedDocs); - bool isDiscarded(); + bool isDiscarded() const; QList<int> getTabIdsToSave(); @@ -39,8 +39,8 @@ private slots: void slotMyDiscard(); private: - [[maybe_unused]] QAction *closeAct; - [[maybe_unused]] QLabel *nameLabel; + [[maybe_unused]] QAction *closeAct{}; + [[maybe_unused]] QLabel *nameLabel{}; bool discarded; QTableWidget *mFileList; }; diff --git a/include/settingsdialog.h b/include/settingsdialog.h index 572a7aad..c0395598 100755 --- a/include/settingsdialog.h +++ b/include/settingsdialog.h @@ -36,7 +36,7 @@ public: private: QCheckBox *rememberPasswordCheckBox; - [[maybe_unused]] QCheckBox *importConfirmationcheckBox; + [[maybe_unused]] QCheckBox *importConfirmationcheckBox{}; QCheckBox *saveCheckedKeysCheckBox; QCheckBox *importConfirmationCheckBox; QComboBox *langSelectBox; @@ -159,7 +159,7 @@ public: void applySettings(); private: - QString getRelativePath(QString dir1, QString dir2); + static QString getRelativePath(const QString& dir1, const QString& dir2); QString defKeydbPath; /** The default keydb path used by gpg4usb */ QString accKeydbPath; /** The currently used keydb path */ @@ -202,9 +202,9 @@ private: QTabWidget *tabWidget; QDialogButtonBox *buttonBox; GpgME::GpgContext *mCtx; /** The current gpg context */ - bool restartNeeded; + bool restartNeeded{}; - bool getRestartNeeded(); + bool getRestartNeeded() const; private slots: diff --git a/include/textedit.h b/include/textedit.h index 92a453c3..9a7a0cae 100644 --- a/include/textedit.h +++ b/include/textedit.h @@ -56,22 +56,22 @@ public: */ bool maybeSaveAnyTab(); - int tabCount(); + int tabCount() const; /** * @details textpage of the currently activated tab * @return \li reference to QTextEdit if tab has one * \li 0 otherwise (e.g. if helppage) */ - QTextEdit *curTextPage(); + QTextEdit *curTextPage() const; - QTextBrowser *curHelpPage(); + QTextBrowser *curHelpPage() const; /** * @details List of currently unsaved tabs. * @returns QHash<int, QString> Hash of tabindexes and title of unsaved tabs. */ - QHash<int, QString> unsavedDocuments(); + QHash<int, QString> unsavedDocuments() const; QTabWidget *tabWidget; /** Widget containing the tabs of the editor */ @@ -81,18 +81,18 @@ public slots: * @details Return pointer to the currently activated tabpage. * */ - EditorPage *slotCurPage(); + EditorPage *slotCurPage() const; /** * @details Insert a ">" at the begining of every line of current textedit. */ - void slotQuote(); + void slotQuote() const; /** * @details replace the text of currently active textedit with given text. * @param text to fill on. */ - void slotFillTextEditWithText(QString text); + void slotFillTextEditWithText(const QString& text) const; /** * @details Saves the content of the current tab, if it has a filepath @@ -131,12 +131,12 @@ public slots: * @param title title for the tab * @param path path for html file to show */ - void slotNewHelpTab(QString title, QString path); + void slotNewHelpTab(const QString& title, const QString& path) const; /** * @details put a * in front of current tabs title, if current textedit is modified */ - void slotShowModified(); + void slotShowModified() const; /** * @details close the current tab and decrease TabWidget->count by \a 1 @@ -148,13 +148,13 @@ public slots: * @details Switch to the next tab. * */ - void slotSwitchTabUp(); + void slotSwitchTabUp() const; /** * @details Switch to the previous tab. * */ - void slotSwitchTabDown(); + void slotSwitchTabDown() const; private: /** @@ -163,7 +163,7 @@ private: * @param a filename path * @return QString containing the filename */ - QString strippedName(const QString &fullFileName); + static QString strippedName(const QString &fullFileName); /** * @brief @@ -190,23 +190,23 @@ private slots: /** * @details Cut selected text in current textpage. */ - void slotCut(); + void slotCut() const; /** * @details Copy selected text of current textpage to clipboard. */ - void slotCopy(); + void slotCopy() const; /** * @details Paste text from clipboard to current textpage. */ - void slotPaste(); + void slotPaste() const; /** * @details Undo last change in current textpage. * */ - void slotUndo(); + void slotUndo() const; /**************************************************************************************** * Name: redo * Description: redo last change in current textpage @@ -218,11 +218,11 @@ private slots: * @brief * */ - void slotRedo(); + void slotRedo() const; - void slotZoomIn(); + void slotZoomIn() const; - void slotZoomOut(); + void slotZoomOut() const; /**************************************************************************************** * Name: selectAll * Description: select all in current textpage @@ -234,7 +234,7 @@ private slots: * @brief * */ - void slotSelectAll(); + void slotSelectAll() const; protected: // void dragEnterEvent(QDragEnterEvent *event); diff --git a/include/verifydetailsdialog.h b/include/verifydetailsdialog.h index 439e8596..cb9d1bfa 100644 --- a/include/verifydetailsdialog.h +++ b/include/verifydetailsdialog.h @@ -42,7 +42,7 @@ private: QWidget *mVbox; QByteArray *mInputData; /** Data to be verified */ QByteArray *mInputSignature; /** Data to be verified */ - QDialogButtonBox *buttonBox; + QDialogButtonBox *buttonBox{}; }; #endif // __VERIFYDETAILSDIALOG_H__ diff --git a/include/verifykeydetailbox.h b/include/verifykeydetailbox.h index 7563b92c..4f93ab67 100644 --- a/include/verifykeydetailbox.h +++ b/include/verifykeydetailbox.h @@ -39,7 +39,7 @@ private: GpgME::GpgContext *mCtx; KeyList *mKeyList; - QString beautifyFingerprint(QString fingerprint); + static QString beautifyFingerprint(QString fingerprint); QString fpr; }; diff --git a/include/verifynotification.h b/include/verifynotification.h index dd7f2600..309814ed 100644 --- a/include/verifynotification.h +++ b/include/verifynotification.h @@ -66,7 +66,7 @@ public: * @param text The text to be set. * @param verifyLabelStatus The status of label to set the specified color. */ - void setVerifyLabel(QString text, verify_label_status verifyLabelStatus); + void setVerifyLabel(const QString& text, verify_label_status verifyLabelStatus); /** * @details Show the import from keyserver-action in detailsmenu. diff --git a/include/wizard.h b/include/wizard.h index 41736e56..7008c77c 100644 --- a/include/wizard.h +++ b/include/wizard.h @@ -48,7 +48,7 @@ public: Wizard(GpgME::GpgContext *ctx, KeyMgmt *keyMgmt, QWidget *parent = nullptr); - static bool importPubAndSecKeysFromDir(QString dir, KeyMgmt *keyMgmt); + static bool importPubAndSecKeysFromDir(const QString& dir, KeyMgmt *keyMgmt); private: GpgME::GpgContext *mCtx; @@ -75,7 +75,7 @@ public: private slots: - void slotLangChange(QString lang); + void slotLangChange(const QString& lang); }; class ChoosePage : public QWizardPage { @@ -107,7 +107,7 @@ private slots: */ void slotImportFromOlderGpg4usb(); - bool slotImportConfFromGpg4usb(QString dir); + bool slotImportConfFromGpg4usb(const QString& dir); private: [[nodiscard]] int nextId() const override; @@ -141,7 +141,7 @@ private: * @returns String containg the gnupg-homedir, but NULL, if the in windows registry entry * doesn't exist or in linux ~/.gnupg doesn't exist */ - QString getGnuPGHome(); + static QString getGnuPGHome(); GpgME::GpgContext *mCtx; QPushButton *importFromGnupgButton; diff --git a/src/aboutdialog.cpp b/src/aboutdialog.cpp index 3362342a..d119c6af 100644 --- a/src/aboutdialog.cpp +++ b/src/aboutdialog.cpp @@ -22,21 +22,20 @@ #include "aboutdialog.h" AboutDialog::AboutDialog(QWidget *parent) - : QDialog(parent) -{ - this->setWindowTitle(tr("About ")+ qApp->applicationName()); + : QDialog(parent) { + this->setWindowTitle(tr("About ") + qApp->applicationName()); - QTabWidget *tabWidget = new QTabWidget; - InfoTab *infoTab = new InfoTab; - TranslatorsTab *translatorsTab = new TranslatorsTab; + auto *tabWidget = new QTabWidget; + auto *infoTab = new InfoTab; + auto *translatorsTab = new TranslatorsTab; tabWidget->addTab(infoTab, tr("General")); tabWidget->addTab(translatorsTab, tr("Translators")); - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); + auto *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); connect(buttonBox, SIGNAL(accepted()), this, SLOT(close())); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(tabWidget); mainLayout->addWidget(buttonBox); setLayout(mainLayout); @@ -45,27 +44,27 @@ AboutDialog::AboutDialog(QWidget *parent) } InfoTab::InfoTab(QWidget *parent) - : QWidget(parent) -{ - QPixmap *pixmap = new QPixmap(":gpg4usb-logo.png"); - QString *text = new QString("<center><h2>" + qApp->applicationName() + " " - + qApp->applicationVersion() + "</h2></center>" - + tr("<center>This application allows simple encryption <br>" - "and decryption of text messages or files.<br>" - "It's licensed under the GPL v3<br><br>" - "<b>Developer:</b><br>" - "Bene, Heimer, Juergen, Nils, Ubbo<br><br>" - "If you have any questions or suggestions have a look<br/>" - "at our <a href=\"http://gpg4usb.cpunk.de/contact.php\">" - "contact page</a> or send a mail to our<br/> mailing list at" - " <a href=\"mailto:[email protected]\">[email protected]</a>.") + tr("<br><br> Built with Qt ") + qVersion() - + tr(" and GPGME ") + GpgME::GpgContext::getGpgmeVersion() +"</center>"); + : QWidget(parent) { + auto *pixmap = new QPixmap(":gpg4usb-logo.png"); + auto *text = new QString("<center><h2>" + qApp->applicationName() + " " + + qApp->applicationVersion() + "</h2></center>" + + tr("<center>This application allows simple encryption <br>" + "and decryption of text messages or files.<br>" + "It's licensed under the GPL v3<br><br>" + "<b>Developer:</b><br>" + "Bene, Heimer, Juergen, Nils, Ubbo<br><br>" + "If you have any questions or suggestions have a look<br/>" + "at our <a href=\"http://gpg4usb.cpunk.de/contact.php\">" + "contact page</a> or send a mail to our<br/> mailing list at" + " <a href=\"mailto:[email protected]\">[email protected]</a>.") + + tr("<br><br> Built with Qt ") + qVersion() + + tr(" and GPGME ") + GpgME::GpgContext::getGpgmeVersion() + "</center>"); - QGridLayout *layout = new QGridLayout(); - QLabel *pixmapLabel = new QLabel(); + auto *layout = new QGridLayout(); + auto *pixmapLabel = new QLabel(); pixmapLabel->setPixmap(*pixmap); layout->addWidget(pixmapLabel, 0, 0, 1, -1, Qt::AlignCenter); - QLabel *aboutLabel = new QLabel(); + auto *aboutLabel = new QLabel(); aboutLabel->setText(*text); aboutLabel->setOpenExternalLinks(true); layout->addWidget(aboutLabel, 1, 0, 1, -1); @@ -76,15 +75,14 @@ InfoTab::InfoTab(QWidget *parent) } TranslatorsTab::TranslatorsTab(QWidget *parent) - : QWidget(parent) -{ + : QWidget(parent) { QFile translatorsFile; - translatorsFile.setFileName(qApp->applicationDirPath()+"/TRANSLATORS"); + translatorsFile.setFileName(qApp->applicationDirPath() + "/TRANSLATORS"); translatorsFile.open(QIODevice::ReadOnly); QByteArray inBuffer = translatorsFile.readAll(); - QLabel *label = new QLabel(inBuffer); - QVBoxLayout *mainLayout = new QVBoxLayout(this); + auto *label = new QLabel(inBuffer); + auto *mainLayout = new QVBoxLayout(this); mainLayout->addWidget(label); setLayout(mainLayout); diff --git a/src/attachments.cpp b/src/attachments.cpp index 1110464a..be6ed663 100644 --- a/src/attachments.cpp +++ b/src/attachments.cpp @@ -36,9 +36,10 @@ #include "attachments.h" +#include <utility> + Attachments::Attachments(QWidget *parent) - : QWidget(parent) -{ + : QWidget(parent) { table = new AttachmentTableModel(this); tableView = new QTableView; @@ -54,27 +55,25 @@ Attachments::Attachments(QWidget *parent) tableView->setColumnWidth(0, 300); tableView->horizontalHeader()->setStretchLastSection(true); - QVBoxLayout *layout = new QVBoxLayout; + auto *layout = new QVBoxLayout; layout->addWidget(tableView); - layout->setContentsMargins(0,0,0,0); + layout->setContentsMargins(0, 0, 0, 0); setLayout(layout); createActions(); } -void Attachments::contextMenuEvent(QContextMenuEvent *event) -{ +void Attachments::contextMenuEvent(QContextMenuEvent *event) { QMenu menu(this); menu.addAction(saveFileAct); // enable open with only if allowed by user - if(settings.value("mime/openAttachment").toBool()) + if (settings.value("mime/openAttachment").toBool()) menu.addAction(openFileAct); menu.exec(event->globalPos()); } -void Attachments::createActions() -{ +void Attachments::createActions() { saveFileAct = new QAction(tr("Save File"), this); saveFileAct->setToolTip(tr("Save this file")); saveFileAct->setIcon(QIcon(":filesave.png")); @@ -87,12 +86,11 @@ void Attachments::createActions() } -void Attachments::slotSaveFile() -{ +void Attachments::slotSaveFile() { QModelIndexList indexes = tableView->selectionModel()->selection().indexes(); - if (indexes.size() < 1) { + if (indexes.empty()) { return; } @@ -107,11 +105,10 @@ void Attachments::slotSaveFile() } -void Attachments::saveByteArrayToFile(QByteArray outBuffer, QString filename) -{ +void Attachments::saveByteArrayToFile(QByteArray outBuffer, QString filename) { //QString path=""; - QString path = filename; + QString path = std::move(filename); QString outfileName = QFileDialog::getSaveFileName(this, tr("Save File"), path); if (outfileName.isEmpty()) return; @@ -120,8 +117,8 @@ void Attachments::saveByteArrayToFile(QByteArray outBuffer, QString filename) if (!outfile.open(QFile::WriteOnly)) { QMessageBox::warning(this, tr("File"), tr("Cannot write file %1:\n%2.") - .arg(outfileName) - .arg(outfile.errorString())); + .arg(outfileName) + .arg(outfile.errorString())); return; } @@ -141,7 +138,7 @@ void Attachments::slotOpenFile() { // TODO: make attachmentdir constant or configurable QString attachmentDir = qApp->applicationDirPath() + "/attachments/"; //QDir p = QDir(qApp->applicationDirPath() + "/attachments/"); - if(!QDir(attachmentDir).exists()) { + if (!QDir(attachmentDir).exists()) { QDir().mkpath(attachmentDir); } @@ -157,7 +154,7 @@ void Attachments::slotOpenFile() { filename.remove(0, 1); filename.prepend(attachmentDir); - // qDebug() << "file: " << filename; + // qDebug() << "file: " << filename; QByteArray outBuffer = QByteArray::fromBase64(mp.body); @@ -165,19 +162,18 @@ void Attachments::slotOpenFile() { if (!outfile.open(QFile::WriteOnly)) { QMessageBox::warning(this, tr("File"), tr("Cannot write file %1:\n%2.") - .arg(filename) - .arg(outfile.errorString())); + .arg(filename) + .arg(outfile.errorString())); return; } QDataStream out(&outfile); out.writeRawData(outBuffer.data(), outBuffer.length()); outfile.close(); - QDesktopServices::openUrl(QUrl("file://"+filename, QUrl::TolerantMode)); + QDesktopServices::openUrl(QUrl("file://" + filename, QUrl::TolerantMode)); } -void Attachments::addMimePart(MimePart *mp) -{ +void Attachments::addMimePart(MimePart *mp) { table->add(*mp); } diff --git a/src/attachmenttablemodel.cpp b/src/attachmenttablemodel.cpp index 6b698b61..07d380f4 100644 --- a/src/attachmenttablemodel.cpp +++ b/src/attachmenttablemodel.cpp @@ -21,39 +21,36 @@ #include "attachmenttablemodel.h" +#include <utility> + /** compare with http://doc.qt.nokia.com/4.6/itemviews-addressbook.html */ AttachmentTableModel::AttachmentTableModel(QObject *parent) : - QAbstractTableModel(parent) -{ + QAbstractTableModel(parent) { } AttachmentTableModel::AttachmentTableModel(QList<MimePart> mimeparts, QObject *parent) : - QAbstractTableModel(parent) -{ - listOfMimeparts = mimeparts; + QAbstractTableModel(parent) { + listOfMimeparts = std::move(mimeparts); } -void AttachmentTableModel::add(MimePart mp) -{ +void AttachmentTableModel::add(const MimePart &mp) { listOfMimeparts.append(mp); //QModelIndex changedIndex0 = createIndex(listOfMimeparts.size(), 0); //QModelIndex changedIndex1 = createIndex(listOfMimeparts.size(), 1); //emit(dataChanged(changedIndex0, changedIndex1)); // TODO: check the data-changed signal - // reset(); + // reset(); } -MimePart AttachmentTableModel::getSelectedMimePart(QModelIndex index) -{ +MimePart AttachmentTableModel::getSelectedMimePart(QModelIndex index) { return listOfMimeparts.at(index.row()); } -MimePart AttachmentTableModel::getMimePart(int index) -{ +MimePart AttachmentTableModel::getMimePart(int index) { return listOfMimeparts.at(index); } @@ -65,20 +62,17 @@ MimePart AttachmentTableModel::getMimePart(int index) }*/ -int AttachmentTableModel::rowCount(const QModelIndex &parent) const -{ +int AttachmentTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return listOfMimeparts.size(); } -int AttachmentTableModel::columnCount(const QModelIndex &parent) const -{ +int AttachmentTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return 2; } -QVariant AttachmentTableModel::data(const QModelIndex &index, int role) const -{ +QVariant AttachmentTableModel::data(const QModelIndex &index, int role) const { //qDebug() << "called, index: " << index.column(); @@ -116,22 +110,21 @@ QVariant AttachmentTableModel::data(const QModelIndex &index, int role) const return QVariant(); } -QVariant AttachmentTableModel::headerData(int section, Qt::Orientation orientation, int role) const -{ +QVariant AttachmentTableModel::headerData(int section, Qt::Orientation orientation, int role) const { //qDebug() << "called, section: " << section; if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { - case 0: - return tr("Filename"); + case 0: + return tr("Filename"); - case 1: - return tr("Contenttype"); + case 1: + return tr("Contenttype"); - default: - return QVariant(); + default: + return QVariant(); } } return QVariant(); diff --git a/src/editorpage.cpp b/src/editorpage.cpp index 28926a99..0e8b596b 100644 --- a/src/editorpage.cpp +++ b/src/editorpage.cpp @@ -21,18 +21,19 @@ #include "editorpage.h" -EditorPage::EditorPage(const QString &filePath, QWidget *parent) : QWidget(parent), - fullFilePath(filePath) -{ +#include <utility> + +EditorPage::EditorPage(QString filePath, QWidget *parent) : QWidget(parent), + fullFilePath(std::move(filePath)) { // Set the Textedit properties - textPage = new QTextEdit(); + textPage = new QTextEdit(); textPage->setAcceptRichText(false); // Set the layout style mainLayout = new QVBoxLayout(); mainLayout->setSpacing(0); mainLayout->addWidget(textPage); - mainLayout->setContentsMargins(0,0,0,0); + mainLayout->setContentsMargins(0, 0, 0, 0); setLayout(mainLayout); setAttribute(Qt::WA_DeleteOnClose); @@ -41,36 +42,30 @@ EditorPage::EditorPage(const QString &filePath, QWidget *parent) : QWidget(paren //connect(textPage, SIGNAL(textChanged()), this, SLOT(formatGpgHeader())); } -const QString& EditorPage::getFilePath() const -{ +const QString &EditorPage::getFilePath() const { return fullFilePath; } -QTextEdit* EditorPage::getTextPage() -{ +QTextEdit *EditorPage::getTextPage() { return textPage; } -void EditorPage::setFilePath(const QString &filePath) -{ +void EditorPage::setFilePath(const QString &filePath) { fullFilePath = filePath; } -void EditorPage::showNotificationWidget(QWidget *widget, const char *className) -{ - widget->setProperty(className,true); +void EditorPage::showNotificationWidget(QWidget *widget, const char *className) { + widget->setProperty(className, true); mainLayout->addWidget(widget); } -void EditorPage::closeNoteByClass(const char *className) -{ +void EditorPage::closeNoteByClass(const char *className) { QList<QWidget *> widgets = findChildren<QWidget *>(); - foreach(QWidget * widget, widgets) - { - if (widget->property(className) == true) { + foreach(QWidget *widget, widgets) { + if (widget->property(className) == true) { widget->close(); + } } - } } void EditorPage::slotFormatGpgHeader() { @@ -82,7 +77,7 @@ void EditorPage::slotFormatGpgHeader() { int startSig = content.indexOf(GpgConstants::PGP_SIGNATURE_BEGIN); int endSig = content.indexOf(GpgConstants::PGP_SIGNATURE_END); - if(start < 0 || startSig < 0 || endSig < 0 || signMarked) { + if (start < 0 || startSig < 0 || endSig < 0 || signMarked) { return; } @@ -90,7 +85,7 @@ void EditorPage::slotFormatGpgHeader() { // Set the fontstyle for the header QTextCharFormat signFormat; - signFormat.setForeground(QBrush(QColor::fromRgb(80,80,80))); + signFormat.setForeground(QBrush(QColor::fromRgb(80, 80, 80))); signFormat.setFontPointSize(9); // set font style for the signature diff --git a/src/fileencryptiondialog.cpp b/src/fileencryptiondialog.cpp index 38b7de56..9b433ce8 100755 --- a/src/fileencryptiondialog.cpp +++ b/src/fileencryptiondialog.cpp @@ -21,10 +21,9 @@ #include "fileencryptiondialog.h" -FileEncryptionDialog::FileEncryptionDialog(GpgME::GpgContext *ctx, QStringList keyList, DialogAction action, QWidget *parent) - : QDialog(parent) - -{ +FileEncryptionDialog::FileEncryptionDialog(GpgME::GpgContext *ctx, QStringList keyList, DialogAction action, + QWidget *parent) + : QDialog(parent) { mAction = action; mCtx = ctx; if (mAction == Decrypt) { @@ -43,39 +42,39 @@ FileEncryptionDialog::FileEncryptionDialog(GpgME::GpgContext *ctx, QStringList k setModal(true); - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + auto *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(slotExecuteAction())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - QGroupBox *groupBox1 = new QGroupBox(tr("File")); + auto *groupBox1 = new QGroupBox(tr("File")); /* Setup input & Outputfileselection*/ inputFileEdit = new QLineEdit(); - QPushButton *fb1 = new QPushButton("..."); + auto *fb1 = new QPushButton("..."); connect(fb1, SIGNAL(clicked()), this, SLOT(slotSelectInputFile())); - QLabel *fl1 = new QLabel(tr("Input")); + auto *fl1 = new QLabel(tr("Input")); fl1->setBuddy(inputFileEdit); outputFileEdit = new QLineEdit(); - QPushButton *fb2 = new QPushButton("..."); + auto *fb2 = new QPushButton("..."); connect(fb2, SIGNAL(clicked()), this, SLOT(slotSelectOutputFile())); - QLabel *fl2 = new QLabel(tr("Output")); + auto *fl2 = new QLabel(tr("Output")); fl2->setBuddy(outputFileEdit); - QGridLayout *gLayout = new QGridLayout(); + auto *gLayout = new QGridLayout(); gLayout->addWidget(fl1, 0, 0); gLayout->addWidget(inputFileEdit, 0, 1); gLayout->addWidget(fb1, 0, 2); signFileEdit = new QLineEdit(); // verify does not need outfile, but signature file - if(mAction != Verify) { + if (mAction != Verify) { gLayout->addWidget(fl2, 1, 0); gLayout->addWidget(outputFileEdit, 1, 1); gLayout->addWidget(fb2, 1, 2); } else { - QPushButton *sfb1 = new QPushButton("..."); + auto *sfb1 = new QPushButton("..."); connect(sfb1, SIGNAL(clicked()), this, SLOT(slotSelectSignFile())); - QLabel *sfl1 = new QLabel(tr("Signature")); + auto *sfl1 = new QLabel(tr("Signature")); sfl1->setBuddy(signFileEdit); gLayout->addWidget(sfl1, 1, 0); @@ -94,7 +93,7 @@ FileEncryptionDialog::FileEncryptionDialog(GpgME::GpgContext *ctx, QStringList k statusLabel = new QLabel(); statusLabel->setStyleSheet("QLabel {color: red;}"); - QVBoxLayout *vbox2 = new QVBoxLayout(); + auto *vbox2 = new QVBoxLayout(); vbox2->addWidget(groupBox1); vbox2->addWidget(mKeyList); vbox2->addWidget(statusLabel); @@ -102,15 +101,14 @@ FileEncryptionDialog::FileEncryptionDialog(GpgME::GpgContext *ctx, QStringList k vbox2->addStretch(0); setLayout(vbox2); - if(action == Encrypt || action == Sign) { + if (action == Encrypt || action == Sign) { slotShowKeyList(); } exec(); } -void FileEncryptionDialog::slotSelectInputFile() -{ +void FileEncryptionDialog::slotSelectInputFile() { QString path = ""; if (inputFileEdit->text().size() > 0) { path = QFileInfo(inputFileEdit->text()).absolutePath(); @@ -121,9 +119,9 @@ void FileEncryptionDialog::slotSelectInputFile() inputFileEdit->setText(infileName); // try to find a matching output-filename, if not yet done - if (infileName > 0 - && outputFileEdit->text().size() == 0 - && signFileEdit->text().size() == 0) { + if (!infileName.isEmpty() + && outputFileEdit->text().size() == 0 + && signFileEdit->text().size() == 0) { if (mAction == Encrypt) { outputFileEdit->setText(infileName + ".asc"); } else if (mAction == Sign) { @@ -142,26 +140,26 @@ void FileEncryptionDialog::slotSelectInputFile() } } -void FileEncryptionDialog::slotSelectOutputFile() -{ +void FileEncryptionDialog::slotSelectOutputFile() { QString path = ""; if (outputFileEdit->text().size() > 0) { path = QFileInfo(outputFileEdit->text()).absolutePath(); } - QString outfileName = QFileDialog::getSaveFileName(this, tr("Save File"),path, NULL ,NULL ,QFileDialog::DontConfirmOverwrite); + QString outfileName = QFileDialog::getSaveFileName(this, tr("Save File"), path, nullptr, nullptr, + QFileDialog::DontConfirmOverwrite); outputFileEdit->setText(outfileName); } -void FileEncryptionDialog::slotSelectSignFile() -{ +void FileEncryptionDialog::slotSelectSignFile() { QString path = ""; if (signFileEdit->text().size() > 0) { path = QFileInfo(signFileEdit->text()).absolutePath(); } - QString signfileName = QFileDialog::getSaveFileName(this, tr("Open File"),path, NULL ,NULL ,QFileDialog::DontConfirmOverwrite); + QString signfileName = QFileDialog::getSaveFileName(this, tr("Open File"), path, nullptr, nullptr, + QFileDialog::DontConfirmOverwrite); signFileEdit->setText(signfileName); if (inputFileEdit->text().size() == 0 && signfileName.endsWith(".sig", Qt::CaseInsensitive)) { @@ -172,37 +170,36 @@ void FileEncryptionDialog::slotSelectSignFile() } -void FileEncryptionDialog::slotExecuteAction() -{ +void FileEncryptionDialog::slotExecuteAction() { QFile infile; infile.setFileName(inputFileEdit->text()); if (!infile.open(QIODevice::ReadOnly)) { - statusLabel->setText( tr("Couldn't open file")); + statusLabel->setText(tr("Couldn't open file")); inputFileEdit->setStyleSheet("QLineEdit { background: yellow }"); return; } QByteArray inBuffer = infile.readAll(); - QByteArray *outBuffer = new QByteArray(); + auto *outBuffer = new QByteArray(); infile.close(); - if ( mAction == Encrypt ) { - if (! mCtx->encrypt(mKeyList->getChecked(), inBuffer, outBuffer)) return; + if (mAction == Encrypt) { + if (!mCtx->encrypt(mKeyList->getChecked(), inBuffer, outBuffer)) return; } - if ( mAction == Decrypt ) { - if (! mCtx->decrypt(inBuffer, outBuffer)) return; + if (mAction == Decrypt) { + if (!mCtx->decrypt(inBuffer, outBuffer)) return; } - if( mAction == Sign ) { - if(! mCtx->sign(mKeyList->getChecked(), inBuffer, outBuffer, true)) return; + if (mAction == Sign) { + if (!mCtx->sign(mKeyList->getChecked(), inBuffer, outBuffer, true)) return; } - if( mAction == Verify ) { + if (mAction == Verify) { QFile signfile; signfile.setFileName(signFileEdit->text()); if (!signfile.open(QIODevice::ReadOnly)) { - statusLabel->setText( tr("Couldn't open file")); + statusLabel->setText(tr("Couldn't open file")); signFileEdit->setStyleSheet("QLineEdit { background: yellow }"); return; } @@ -212,12 +209,12 @@ void FileEncryptionDialog::slotExecuteAction() } QFile outfile(outputFileEdit->text()); - if (outfile.exists()){ + if (outfile.exists()) { QMessageBox::StandardButton ret; ret = QMessageBox::warning(this, tr("File"), - tr("File exists! Do you want to overwrite it?"), - QMessageBox::Ok|QMessageBox::Cancel); - if (ret == QMessageBox::Cancel){ + tr("File exists! Do you want to overwrite it?"), + QMessageBox::Ok | QMessageBox::Cancel); + if (ret == QMessageBox::Cancel) { return; } } @@ -225,25 +222,23 @@ void FileEncryptionDialog::slotExecuteAction() if (!outfile.open(QFile::WriteOnly)) { QMessageBox::warning(this, tr("File"), tr("Cannot write file %1:\n%2.") - .arg(outputFileEdit->text()) - .arg(outfile.errorString())); + .arg(outputFileEdit->text()) + .arg(outfile.errorString())); return; } QDataStream out(&outfile); out.writeRawData(outBuffer->data(), outBuffer->length()); outfile.close(); - QMessageBox::information(0, "Done", "Output saved to " + outputFileEdit->text()); + QMessageBox::information(nullptr, "Done", "Output saved to " + outputFileEdit->text()); accept(); } -void FileEncryptionDialog::slotShowKeyList() -{ +void FileEncryptionDialog::slotShowKeyList() { mKeyList->show(); } -void FileEncryptionDialog::slotHideKeyList() -{ +void FileEncryptionDialog::slotHideKeyList() { mKeyList->hide(); } diff --git a/src/findwidget.cpp b/src/findwidget.cpp index ff8de5a5..7bbbe0df 100644 --- a/src/findwidget.cpp +++ b/src/findwidget.cpp @@ -6,11 +6,11 @@ FindWidget::FindWidget(QWidget *parent, QTextEdit *edit) : { mTextpage = edit; findEdit = new QLineEdit(this); - QPushButton *closeButton= new QPushButton(this->style()->standardIcon(QStyle::SP_TitleBarCloseButton),"",this); - QPushButton *nextButton= new QPushButton(QIcon(":button_next.png"), ""); - QPushButton *previousButton= new QPushButton(QIcon(":button_previous.png"), ""); + auto *closeButton= new QPushButton(this->style()->standardIcon(QStyle::SP_TitleBarCloseButton),"",this); + auto *nextButton= new QPushButton(QIcon(":button_next.png"), ""); + auto *previousButton= new QPushButton(QIcon(":button_previous.png"), ""); - QHBoxLayout *notificationWidgetLayout = new QHBoxLayout(this); + auto *notificationWidgetLayout = new QHBoxLayout(this); notificationWidgetLayout->setContentsMargins(10,0,0,0); notificationWidgetLayout->addWidget(new QLabel(tr("Find:"))); notificationWidgetLayout->addWidget(findEdit,2); diff --git a/src/gpgconstants.cpp b/src/gpgconstants.cpp index 0d3306ab..9e919386 100644 --- a/src/gpgconstants.cpp +++ b/src/gpgconstants.cpp @@ -22,10 +22,10 @@ #include "gpgconstants.h" #include <QString> -const char* GpgConstants::PGP_CRYPT_BEGIN = "-----BEGIN PGP MESSAGE-----"; -const char* GpgConstants::PGP_CRYPT_END = "-----END PGP MESSAGE-----"; -const char* GpgConstants::PGP_SIGNED_BEGIN = "-----BEGIN PGP SIGNED MESSAGE-----"; -const char* GpgConstants::PGP_SIGNED_END = "-----END PGP SIGNATURE-----"; -const char* GpgConstants::PGP_SIGNATURE_BEGIN = "-----BEGIN PGP SIGNATURE-----"; -const char* GpgConstants::PGP_SIGNATURE_END = "-----END PGP SIGNATURE-----"; +const char *GpgConstants::PGP_CRYPT_BEGIN = "-----BEGIN PGP MESSAGE-----"; +const char *GpgConstants::PGP_CRYPT_END = "-----END PGP MESSAGE-----"; +const char *GpgConstants::PGP_SIGNED_BEGIN = "-----BEGIN PGP SIGNED MESSAGE-----"; +const char *GpgConstants::PGP_SIGNED_END = "-----END PGP SIGNATURE-----"; +const char *GpgConstants::PGP_SIGNATURE_BEGIN = "-----BEGIN PGP SIGNATURE-----"; +const char *GpgConstants::PGP_SIGNATURE_END = "-----END PGP SIGNATURE-----"; diff --git a/src/gpgcontext.cpp b/src/gpgcontext.cpp index af42eb55..08315083 100644 --- a/src/gpgcontext.cpp +++ b/src/gpgcontext.cpp @@ -21,593 +21,574 @@ #include "gpgcontext.h" #include <unistd.h> /* contains read/write */ + #ifdef _WIN32 #include <windows.h> #endif -namespace GpgME -{ +namespace GpgME { /** Constructor * Set up gpgme-context, set paths to app-run path */ -GpgContext::GpgContext() -{ - /** get application path */ - QString appPath = qApp->applicationDirPath(); - - /** The function `gpgme_check_version' must be called before any other - * function in the library, because it initializes the thread support - * subsystem in GPGME. (from the info page) */ - gpgme_check_version(NULL); - - // TODO: Set gpgme_language to config - /*QSettings settings; - qDebug() << " - " << settings.value("int/lang").toLocale().name(); - qDebug() << " - " << QLocale(settings.value("int/lang").toString()).name();*/ - - // the locale set here is used for the other setlocale calls which have NULL - // -> NULL means use default, which is configured here - setlocale(LC_ALL, ""); - - /** set locale, because tests do also */ - gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL)); - //qDebug() << "Locale set to" << LC_CTYPE << " - " << setlocale(LC_CTYPE, NULL); + GpgContext::GpgContext() { + /** get application path */ + QString appPath = qApp->applicationDirPath(); + + /** The function `gpgme_check_version' must be called before any other + * function in the library, because it initializes the thread support + * subsystem in GPGME. (from the info page) */ + gpgme_check_version(nullptr); + + // TODO: Set gpgme_language to config + /*QSettings qSettings; + qDebug() << " - " << qSettings.value("int/lang").toLocale().name(); + qDebug() << " - " << QLocale(qSettings.value("int/lang").toString()).name();*/ + + // the locale set here is used for the other setlocale calls which have nullptr + // -> nullptr means use default, which is configured here + setlocale(LC_ALL, ""); + + /** set locale, because tests do also */ + gpgme_set_locale(nullptr, LC_CTYPE, setlocale(LC_CTYPE, nullptr)); + //qDebug() << "Locale set to" << LC_CTYPE << " - " << setlocale(LC_CTYPE, nullptr); #ifndef _WIN32 - gpgme_set_locale(NULL, LC_MESSAGES, setlocale(LC_MESSAGES, NULL)); + gpgme_set_locale(nullptr, LC_MESSAGES, setlocale(LC_MESSAGES, nullptr)); #endif - err = gpgme_new(&mCtx); + err = gpgme_new(&mCtx); - checkErr(err); - /** here come the settings, instead of /usr/bin/gpg - * a executable in the same path as app is used. - * also lin/win must be checked, for calling gpg.exe if needed - */ + checkErr(err); + /** here come the qSettings, instead of /usr/bin/gpg + * a executable in the same path as app is used. + * also lin/win must be checked, for calling gpg.exe if needed + */ #ifdef _WIN32 - gpgBin = appPath + "/bin/gpg.exe"; + gpgBin = appPath + "/bin/gpg.exe"; #else - gpgBin = appPath + "/bin/gpg"; + gpgBin = appPath + "/bin/gpg"; #endif - QSettings settings; - QString accKeydbPath = settings.value("gpgpaths/keydbpath").toString(); - QString gpgKeys = appPath + "/keydb/"+accKeydbPath; + QSettings qSettings; + QString accKeydbPath = qSettings.value("gpgpaths/keydbpath").toString(); + QString qGpgKeys = appPath + "/keydb/" + accKeydbPath; - if (accKeydbPath != "") { - if (!QDir(gpgKeys).exists()) { - QMessageBox::critical(0,tr("keydb path"),tr("Didn't find keydb directory. Switching to gpg4usb's default keydb directory for this session.")); - gpgKeys = appPath + "/keydb"; + if (accKeydbPath != "") { + if (!QDir(qGpgKeys).exists()) { + QMessageBox::critical(0, tr("keydb path"), + tr("Didn't find keydb directory. Switching to gpg4usb's default keydb directory for this session.")); + qGpgKeys = appPath + "/keydb"; + } } - } - /* err = gpgme_ctx_set_engine_info(mCtx, GPGME_PROTOCOL_OpenPGP, - gpgBin.toUtf8().constData(), - gpgKeys.toUtf8().constData());*/ + /* err = gpgme_ctx_set_engine_info(mCtx, GPGME_PROTOCOL_OpenPGP, + gpgBin.toUtf8().constData(), + qGpgKeys.toUtf8().constData());*/ #ifndef GPG4USB_NON_PORTABLE - err = gpgme_ctx_set_engine_info(mCtx, GPGME_PROTOCOL_OpenPGP, - gpgBin.toLocal8Bit().constData(), - gpgKeys.toLocal8Bit().constData()); - checkErr(err); + err = gpgme_ctx_set_engine_info(mCtx, GPGME_PROTOCOL_OpenPGP, + gpgBin.toLocal8Bit().constData(), + qGpgKeys.toLocal8Bit().constData()); + checkErr(err); #endif - gpgme_engine_info_t engineInfo; - engineInfo = gpgme_ctx_get_engine_info(mCtx); + gpgme_engine_info_t engineInfo; + engineInfo = gpgme_ctx_get_engine_info(mCtx); - while (engineInfo !=NULL ) { - qDebug() << gpgme_get_protocol_name(engineInfo->protocol); - engineInfo=engineInfo->next; - } + while (engineInfo != nullptr) { + qDebug() << gpgme_get_protocol_name(engineInfo->protocol); + engineInfo = engineInfo->next; + } - /** Setting the output type must be done at the beginning */ - /** think this means ascii-armor --> ? */ - gpgme_set_armor(mCtx, 1); - /** passphrase-callback */ - gpgme_set_passphrase_cb(mCtx, passphraseCb, this); - - /** check if app is called with -d from command line */ - if (qApp->arguments().contains("-d")) { - qDebug() << "gpgme_data_t debug on"; - debug = true; - } else { - debug = false; - } + /** Setting the output type must be done at the beginning */ + /** think this means ascii-armor --> ? */ + gpgme_set_armor(mCtx, 1); + /** passphrase-callback */ + gpgme_set_passphrase_cb(mCtx, passphraseCb, this); + + /** check if app is called with -d from command line */ + if (qApp->arguments().contains("-d")) { + qDebug() << "gpgme_data_t debug on"; + debug = true; + } else { + debug = false; + } - connect(this,SIGNAL(signalKeyDBChanged()),this,SLOT(slotRefreshKeyList())); - slotRefreshKeyList(); -} + connect(this, SIGNAL(signalKeyDBChanged()), this, SLOT(slotRefreshKeyList())); + slotRefreshKeyList(); + } /** Destructor * Release gpgme-context */ -GpgContext::~GpgContext() -{ - if (mCtx) gpgme_release(mCtx); - mCtx = 0; -} + GpgContext::~GpgContext() { + if (mCtx) gpgme_release(mCtx); + mCtx = 0; + } /** Import Key from QByteArray * */ -GpgImportInformation GpgContext::importKey(QByteArray inBuffer) -{ - GpgImportInformation *importInformation = new GpgImportInformation(); - err = gpgme_data_new_from_mem(&in, inBuffer.data(), inBuffer.size(), 1); - checkErr(err); - err = gpgme_op_import(mCtx, in); - gpgme_import_result_t result; - - result = gpgme_op_import_result(mCtx); - if (result->unchanged){ - importInformation->unchanged = result->unchanged; - } - if (result->considered){ - importInformation->considered = result->considered; - } - if (result->no_user_id){ - importInformation->no_user_id = result->no_user_id; - } - if (result->imported){ - importInformation->imported = result->imported; - } - if (result->imported_rsa){ - importInformation->imported_rsa = result->imported_rsa; - } - if (result->unchanged){ - importInformation->unchanged = result->unchanged; - } - if (result->new_user_ids){ - importInformation->new_user_ids = result->new_user_ids; - } - if (result->new_sub_keys){ - importInformation->new_sub_keys = result->new_sub_keys; - } - if (result->new_signatures){ - importInformation->new_signatures = result->new_signatures; - } - if (result->new_revocations){ - importInformation->new_revocations =result->new_revocations; - } - if (result->secret_read){ - importInformation->secret_read = result->secret_read; - } - if (result->secret_imported){ - importInformation->secret_imported = result->secret_imported; - } - if (result->secret_unchanged){ - importInformation->secret_unchanged = result->secret_unchanged; - } - if (result->not_imported){ - importInformation->not_imported = result->not_imported; - } - gpgme_import_status_t status = result->imports; - while (status != NULL) { - GpgImportedKey key; - key.importStatus = status->status; - key.fpr = status->fpr; - importInformation->importedKeys.append(key); - status=status->next; + GpgImportInformation GpgContext::importKey(QByteArray inBuffer) { + auto *importInformation = new GpgImportInformation(); + err = gpgme_data_new_from_mem(&in, inBuffer.data(), inBuffer.size(), 1); + checkErr(err); + err = gpgme_op_import(mCtx, in); + gpgme_import_result_t result; + + result = gpgme_op_import_result(mCtx); + if (result->unchanged) { + importInformation->unchanged = result->unchanged; + } + if (result->considered) { + importInformation->considered = result->considered; + } + if (result->no_user_id) { + importInformation->no_user_id = result->no_user_id; + } + if (result->imported) { + importInformation->imported = result->imported; + } + if (result->imported_rsa) { + importInformation->imported_rsa = result->imported_rsa; + } + if (result->unchanged) { + importInformation->unchanged = result->unchanged; + } + if (result->new_user_ids) { + importInformation->new_user_ids = result->new_user_ids; + } + if (result->new_sub_keys) { + importInformation->new_sub_keys = result->new_sub_keys; + } + if (result->new_signatures) { + importInformation->new_signatures = result->new_signatures; + } + if (result->new_revocations) { + importInformation->new_revocations = result->new_revocations; + } + if (result->secret_read) { + importInformation->secret_read = result->secret_read; + } + if (result->secret_imported) { + importInformation->secret_imported = result->secret_imported; + } + if (result->secret_unchanged) { + importInformation->secret_unchanged = result->secret_unchanged; + } + if (result->not_imported) { + importInformation->not_imported = result->not_imported; + } + gpgme_import_status_t status = result->imports; + while (status != nullptr) { + GpgImportedKey key; + key.importStatus = static_cast<int>(status->status); + key.fpr = status->fpr; + importInformation->importedKeys.append(key); + status = status->next; + } + checkErr(err); + emit signalKeyDBChanged(); + gpgme_data_release(in); + return *importInformation; } - checkErr(err); - emit signalKeyDBChanged(); - gpgme_data_release(in); - return *importInformation; -} /** Generate New Key with values params * */ -void GpgContext::generateKey(QString *params) -{ - err = gpgme_op_genkey(mCtx, params->toUtf8().data(), NULL, NULL); - checkErr(err); - emit signalKeyDBChanged(); -} + void GpgContext::generateKey(QString *params) { + err = gpgme_op_genkey(mCtx, params->toUtf8().data(), nullptr, nullptr); + checkErr(err); + emit signalKeyDBChanged(); + } /** Export Key to QByteArray * */ -bool GpgContext::exportKeys(QStringList *uidList, QByteArray *outBuffer) -{ - size_t read_bytes; - gpgme_data_t out = 0; - outBuffer->resize(0); - - if (uidList->count() == 0) { - QMessageBox::critical(0, "Export Keys Error", "No Keys Selected"); - return false; - } + bool GpgContext::exportKeys(QStringList *uidList, QByteArray *outBuffer) { + size_t read_bytes; + gpgme_data_t dataOut = nullptr; + outBuffer->resize(0); + + if (uidList->count() == 0) { + QMessageBox::critical(nullptr, "Export Keys Error", "No Keys Selected"); + return false; + } - for (int i = 0; i < uidList->count(); i++) { - err = gpgme_data_new(&out); - checkErr(err); + for (int i = 0; i < uidList->count(); i++) { + err = gpgme_data_new(&dataOut); + checkErr(err); - err = gpgme_op_export(mCtx, uidList->at(i).toUtf8().constData(), 0, out); - checkErr(err); + err = gpgme_op_export(mCtx, uidList->at(i).toUtf8().constData(), 0, dataOut); + checkErr(err); - read_bytes = gpgme_data_seek(out, 0, SEEK_END); + read_bytes = gpgme_data_seek(dataOut, 0, SEEK_END); - err = readToBuffer(out, outBuffer); - checkErr(err); - gpgme_data_release(out); + err = readToBuffer(dataOut, outBuffer); + checkErr(err); + gpgme_data_release(dataOut); + } + return true; } - return true; -} -gpgme_key_t GpgContext::getKeyDetails(QString uid) -{ - gpgme_key_t key; + gpgme_key_t GpgContext::getKeyDetails(const QString& uid) { + gpgme_key_t key; - // try secret - gpgme_get_key(mCtx, uid.toUtf8().constData(), &key, 1); - // ok, its a public key - if (!key) { - gpgme_get_key(mCtx, uid.toUtf8().constData(), &key, 0); + // try secret + gpgme_get_key(mCtx, uid.toUtf8().constData(), &key, 1); + // ok, its a public key + if (!key) { + gpgme_get_key(mCtx, uid.toUtf8().constData(), &key, 0); + } + return key; } - return key; -} /** List all availabe Keys (VERY much like kgpgme) */ -GpgKeyList GpgContext::listKeys() -{ - gpgme_error_t err; - gpgme_key_t key; - - GpgKeyList keys; - //TODO dont run the loop more often than necessary - // list all keys ( the 0 is for all ) - err = gpgme_op_keylist_start(mCtx, NULL, 0); - checkErr(err); - while (!(err = gpgme_op_keylist_next(mCtx, &key))) { - GpgKey gpgkey; - - if (!key->subkeys) - continue; - - gpgkey.id = key->subkeys->keyid; - gpgkey.fpr = key->subkeys->fpr; - gpgkey.expired = (key->expired != 0); - gpgkey.revoked = (key->revoked != 0); - - if (key->uids) { - gpgkey.name = QString::fromUtf8(key->uids->name); - gpgkey.email = QString::fromUtf8(key->uids->email); - } - keys.append(gpgkey); - gpgme_key_unref(key); - } - gpgme_op_keylist_end(mCtx); - - // list only private keys ( the 1 does ) - gpgme_op_keylist_start(mCtx, NULL, 1); - while (!(err = gpgme_op_keylist_next(mCtx, &key))) { - if (!key->subkeys) - continue; - // iterate keys, mark privates - GpgKeyList::iterator it = keys.begin(); - while (it != keys.end()) { - if (key->subkeys->keyid == it->id.toStdString()) - it->privkey = true; - it++; - } - - gpgme_key_unref(key); - } - gpgme_op_keylist_end(mCtx); + GpgKeyList GpgContext::listKeys() { + gpgme_error_t gpgmeError; + gpgme_key_t key; + + GpgKeyList keys; + //TODO dont run the loop more often than necessary + // list all keys ( the 0 is for all ) + gpgmeError = gpgme_op_keylist_start(mCtx, nullptr, 0); + checkErr(gpgmeError); + while (!(gpgmeError = gpgme_op_keylist_next(mCtx, &key))) { + GpgKey gpgkey; + + if (!key->subkeys) + continue; + + gpgkey.id = key->subkeys->keyid; + gpgkey.fpr = key->subkeys->fpr; + gpgkey.expired = (key->expired != 0u); + gpgkey.revoked = (key->revoked != 0u); + + if (key->uids) { + gpgkey.name = QString::fromUtf8(key->uids->name); + gpgkey.email = QString::fromUtf8(key->uids->email); + } + keys.append(gpgkey); + gpgme_key_unref(key); + } + gpgme_op_keylist_end(mCtx); - return keys; -} + // list only private keys ( the 1 does ) + gpgme_op_keylist_start(mCtx, nullptr, 1); + while (!(gpgmeError = gpgme_op_keylist_next(mCtx, &key))) { + if (!key->subkeys) + continue; + // iterate keys, mark privates + GpgKeyList::iterator it = keys.begin(); + while (it != keys.end()) { + if (key->subkeys->keyid == it->id.toStdString()) + it->privkey = true; + it++; + } + + gpgme_key_unref(key); + } + gpgme_op_keylist_end(mCtx); + + return keys; + } /** Delete keys */ -void GpgContext::deleteKeys(QStringList *uidList) -{ - QString tmp; - gpgme_key_t key; + void GpgContext::deleteKeys(QStringList *uidList) { + QString tmp; + gpgme_key_t key; - foreach(tmp, *uidList) { - gpgme_op_keylist_start(mCtx, tmp.toUtf8().constData(), 0); - gpgme_op_keylist_next(mCtx, &key); - gpgme_op_keylist_end(mCtx); - gpgme_op_delete(mCtx, key, 1); + foreach(tmp, *uidList) { + gpgme_op_keylist_start(mCtx, tmp.toUtf8().constData(), 0); + gpgme_op_keylist_next(mCtx, &key); + gpgme_op_keylist_end(mCtx); + gpgme_op_delete(mCtx, key, 1); + } + emit signalKeyDBChanged(); } - emit signalKeyDBChanged(); -} /** Encrypt inBuffer for reciepients-uids, write * result to outBuffer */ -bool GpgContext::encrypt(QStringList *uidList, const QByteArray &inBuffer, QByteArray *outBuffer) -{ + bool GpgContext::encrypt(QStringList *uidList, const QByteArray &inBuffer, QByteArray *outBuffer) { - gpgme_data_t in = 0, out = 0; - outBuffer->resize(0); + gpgme_data_t dataIn = nullptr, dataOut = nullptr; + outBuffer->resize(0); - if (uidList->count() == 0) { - QMessageBox::critical(0, tr("No Key Selected"), tr("No Key Selected")); - return false; - } + if (uidList->count() == 0) { + QMessageBox::critical(nullptr, tr("No Key Selected"), tr("No Key Selected")); + return false; + } - //gpgme_encrypt_result_t e_result; - gpgme_key_t recipients[uidList->count()+1]; + //gpgme_encrypt_result_t e_result; + gpgme_key_t recipients[uidList->count() + 1]; - /* get key for user */ - for (int i = 0; i < uidList->count(); i++) { - // the last 0 is for public keys, 1 would return private keys - gpgme_op_keylist_start(mCtx, uidList->at(i).toUtf8().constData(), 0); - gpgme_op_keylist_next(mCtx, &recipients[i]); - gpgme_op_keylist_end(mCtx); - } - //Last entry in array has to be NULL - recipients[uidList->count()] = NULL; - - //If the last parameter isnt 0, a private copy of data is made - if (mCtx) { - err = gpgme_data_new_from_mem(&in, inBuffer.data(), inBuffer.size(), 1); - checkErr(err); - if (!err) { - err = gpgme_data_new(&out); - checkErr(err); - if (!err) { - err = gpgme_op_encrypt(mCtx, recipients, GPGME_ENCRYPT_ALWAYS_TRUST, in, out); - checkErr(err); - if (!err) { - err = readToBuffer(out, outBuffer); - checkErr(err); - } - } - } - } - /* unref all keys */ - for (int i = 0; i <= uidList->count(); i++) { - gpgme_key_unref(recipients[i]); - } - if (in) { - gpgme_data_release(in); - } - if (out) { - gpgme_data_release(out); + /* get key for user */ + for (int i = 0; i < uidList->count(); i++) { + // the last 0 is for public keys, 1 would return private keys + gpgme_op_keylist_start(mCtx, uidList->at(i).toUtf8().constData(), 0); + gpgme_op_keylist_next(mCtx, &recipients[i]); + gpgme_op_keylist_end(mCtx); + } + //Last entry dataIn array has to be nullptr + recipients[uidList->count()] = nullptr; + + //If the last parameter isnt 0, a private copy of data is made + if (mCtx) { + err = gpgme_data_new_from_mem(&dataIn, inBuffer.data(), inBuffer.size(), 1); + checkErr(err); + if (!err) { + err = gpgme_data_new(&dataOut); + checkErr(err); + if (!err) { + err = gpgme_op_encrypt(mCtx, recipients, GPGME_ENCRYPT_ALWAYS_TRUST, dataIn, dataOut); + checkErr(err); + if (!err) { + err = readToBuffer(dataOut, outBuffer); + checkErr(err); + } + } + } + } + /* unref all keys */ + for (int i = 0; i <= uidList->count(); i++) { + gpgme_key_unref(recipients[i]); + } + if (dataIn) { + gpgme_data_release(dataIn); + } + if (dataOut) { + gpgme_data_release(dataOut); + } + return (err == GPG_ERR_NO_ERROR); } - return (err == GPG_ERR_NO_ERROR); -} /** Decrypt QByteAarray, return QByteArray * mainly from http://basket.kde.org/ (kgpgme.cpp) */ -bool GpgContext::decrypt(const QByteArray &inBuffer, QByteArray *outBuffer) -{ - gpgme_data_t in = 0, out = 0; - gpgme_decrypt_result_t result = 0; - QString errorString; - - outBuffer->resize(0); - if (mCtx) { - err = gpgme_data_new_from_mem(&in, inBuffer.data(), inBuffer.size(), 1); - checkErr(err); - if (!err) { - err = gpgme_data_new(&out); + bool GpgContext::decrypt(const QByteArray &inBuffer, QByteArray *outBuffer) { + gpgme_data_t dataIn = nullptr, dataOut = nullptr; + gpgme_decrypt_result_t result = nullptr; + QString errorString; + + outBuffer->resize(0); + if (mCtx) { + err = gpgme_data_new_from_mem(&dataIn, inBuffer.data(), inBuffer.size(), 1); checkErr(err); if (!err) { - err = gpgme_op_decrypt(mCtx, in, out); + err = gpgme_data_new(&dataOut); checkErr(err); - - if(gpg_err_code(err) == GPG_ERR_DECRYPT_FAILED) { - errorString.append(gpgErrString(err)).append("<br>"); - result = gpgme_op_decrypt_result(mCtx); - checkErr(result->recipients->status); - errorString.append(gpgErrString(result->recipients->status)).append("<br>"); - errorString.append(tr("<br>No private key with id %1 present in keyring").arg(result->recipients->keyid)); - } else { - errorString.append(gpgErrString(err)).append("<br>"); - } - if (!err) { - result = gpgme_op_decrypt_result(mCtx); - if (result->unsupported_algorithm) { - QMessageBox::critical(0, tr("Unsupported algorithm"), result->unsupported_algorithm); + err = gpgme_op_decrypt(mCtx, dataIn, dataOut); + checkErr(err); + + if (gpg_err_code(err) == GPG_ERR_DECRYPT_FAILED) { + errorString.append(gpgErrString(err)).append("<br>"); + result = gpgme_op_decrypt_result(mCtx); + checkErr(result->recipients->status); + errorString.append(gpgErrString(result->recipients->status)).append("<br>"); + errorString.append( + tr("<br>No private key with id %1 present dataIn keyring").arg(result->recipients->keyid)); } else { - err = readToBuffer(out, outBuffer); - checkErr(err); + errorString.append(gpgErrString(err)).append("<br>"); + } + + if (!err) { + result = gpgme_op_decrypt_result(mCtx); + if (result->unsupported_algorithm) { + QMessageBox::critical(0, tr("Unsupported algorithm"), result->unsupported_algorithm); + } else { + err = readToBuffer(dataOut, outBuffer); + checkErr(err); + } } } } } - } - if (gpg_err_code(err) != GPG_ERR_NO_ERROR && gpg_err_code(err) != GPG_ERR_CANCELED) { - QMessageBox::critical(0, tr("Error decrypting:"), errorString); - return false; - } + if (gpg_err_code(err) != GPG_ERR_NO_ERROR && gpg_err_code(err) != GPG_ERR_CANCELED) { + QMessageBox::critical(nullptr, tr("Error decrypting:"), errorString); + return false; + } - if (! settings.value("general/rememberPassword").toBool()) { - clearPasswordCache(); - } + if (!settings.value("general/rememberPassword").toBool()) { + clearPasswordCache(); + } - if (in) { - gpgme_data_release(in); - } - if (out) { - gpgme_data_release(out); + if (dataIn) { + gpgme_data_release(dataIn); + } + if (dataOut) { + gpgme_data_release(dataOut); + } + return (err == GPG_ERR_NO_ERROR); } - return (err == GPG_ERR_NO_ERROR); -} /** Read gpgme-Data to QByteArray * mainly from http://basket.kde.org/ (kgpgme.cpp) */ #define BUF_SIZE (32 * 1024) -gpgme_error_t GpgContext::readToBuffer(gpgme_data_t in, QByteArray *outBuffer) -{ - int ret; - gpgme_error_t err = GPG_ERR_NO_ERROR; - - ret = gpgme_data_seek(in, 0, SEEK_SET); - if (ret) { - err = gpgme_err_code_from_errno(errno); - checkErr(err, "failed dataseek in readToBuffer"); - } else { - char *buf = new char[BUF_SIZE + 2]; - - if (buf) { - while ((ret = gpgme_data_read(in, buf, BUF_SIZE)) > 0) { - uint size = outBuffer->size(); - outBuffer->resize(size + ret); + + gpgme_error_t GpgContext::readToBuffer(gpgme_data_t dataIn, QByteArray *outBuffer) { + off_t ret; + gpgme_error_t gpgErrNoError = GPG_ERR_NO_ERROR; + + ret = gpgme_data_seek(dataIn, 0, SEEK_SET); + if (ret) { + gpgErrNoError = gpgme_err_code_from_errno(errno); + checkErr(gpgErrNoError, "failed dataseek dataIn readToBuffer"); + } else { + char buf[BUF_SIZE + 2]; + + while ((ret = gpgme_data_read(dataIn, buf, BUF_SIZE)) > 0) { + const size_t size = outBuffer->size(); + outBuffer->resize(static_cast<int>(size + ret)); memcpy(outBuffer->data() + size, buf, ret); } if (ret < 0) { - err = gpgme_err_code_from_errno(errno); - checkErr(err, "failed data_read in readToBuffer"); + gpgErrNoError = gpgme_err_code_from_errno(errno); + checkErr(gpgErrNoError, "failed data_read dataIn readToBuffer"); } - delete[] buf; } + return gpgErrNoError; } - return err; -} /** The Passphrase window, if not provided by env-Var GPG_AGENT_INFO * originally copied from http://basket.kde.org/ (kgpgme.cpp), but modified */ -gpgme_error_t GpgContext::passphraseCb(void *hook, const char *uid_hint, - const char *passphrase_info, - int last_was_bad, int fd) -{ - GpgContext *gpg = static_cast<GpgContext*>(hook); - return gpg->passphrase(uid_hint, passphrase_info, last_was_bad, fd); -} - -gpgme_error_t GpgContext::passphrase(const char *uid_hint, - const char * /*passphrase_info*/, - int last_was_bad, int fd) -{ - gpgme_error_t returnValue = GPG_ERR_CANCELED; - QString passwordDialogMessage; - QString gpgHint = QString::fromUtf8(uid_hint); - bool result; + gpgme_error_t GpgContext::passphraseCb(void *hook, const char *uid_hint, + const char *passphrase_info, + int last_was_bad, int fd) { + auto *gpg = static_cast<GpgContext *>(hook); + return gpg->passphrase(uid_hint, passphrase_info, last_was_bad, fd); + } + + gpgme_error_t GpgContext::passphrase(const char *uid_hint, + const char * /*passphrase_info*/, + int last_was_bad, int fd) { + gpgme_error_t returnValue = GPG_ERR_CANCELED; + QString passwordDialogMessage; + QString gpgHint = QString::fromUtf8(uid_hint); + bool result; #ifdef _WIN32 - DWORD written; - HANDLE hd = (HANDLE)fd; + DWORD written; + HANDLE hd = (HANDLE)fd; #endif - if (last_was_bad) { - passwordDialogMessage += "<i>"+tr("Wrong password")+".</i><br><br>\n\n"; - clearPasswordCache(); - } + if (last_was_bad) { + passwordDialogMessage += "<i>" + tr("Wrong password") + ".</i><br><br>\n\n"; + clearPasswordCache(); + } - /** if uid provided */ - if (!gpgHint.isEmpty()) { - // remove UID, leave only username & email - gpgHint.remove(0, gpgHint.indexOf(" ")); - passwordDialogMessage += "<b>"+tr("Enter Password for")+"</b><br>" + gpgHint + "<br>"; - } + /** if uid provided */ + if (!gpgHint.isEmpty()) { + // remove UID, leave only username & email + gpgHint.remove(0, gpgHint.indexOf(" ")); + passwordDialogMessage += "<b>" + tr("Enter Password for") + "</b><br>" + gpgHint + "<br>"; + } - if (mPasswordCache.isEmpty()) { - QString password = QInputDialog::getText(QApplication::activeWindow(), tr("Enter Password"), - passwordDialogMessage, QLineEdit::Password, - "", &result); + if (mPasswordCache.isEmpty()) { + QString password = QInputDialog::getText(QApplication::activeWindow(), tr("Enter Password"), + passwordDialogMessage, QLineEdit::Password, + "", &result); - if (result) mPasswordCache = password.toUtf8(); - } else { - result = true; - } + if (result) mPasswordCache = password.toUtf8(); + } else { + result = true; + } - if (result) { + if (result) { #ifndef _WIN32 - if (write(fd, mPasswordCache.data(), mPasswordCache.length()) == -1) { - qDebug() << "something is terribly broken"; - } + if (write(fd, mPasswordCache.data(), mPasswordCache.length()) == -1) { + qDebug() << "something is terribly broken"; + } #else - WriteFile(hd, mPasswordCache.data(), mPasswordCache.length(), &written, 0); + WriteFile(hd, mPasswordCache.data(), mPasswordCache.length(), &written, 0); #endif - returnValue = GPG_ERR_NO_ERROR; - } + returnValue = GPG_ERR_NO_ERROR; + } #ifndef _WIN32 - if (write(fd, "\n", 1) == -1) { - qDebug() << "something is terribly broken"; - } + if (write(fd, "\n", 1) == -1) { + qDebug() << "something is terribly broken"; + } #else - WriteFile(hd, "\n", 1, &written, 0); - - /* program will hang on cancel if hd not closed */ - if(!result) { - CloseHandle(hd); - } + WriteFile(hd, "\n", 1, &written, 0); + + /* program will hang on cancel if hd not closed */ + if(!result) { + CloseHandle(hd); + } #endif - return returnValue; -} + return returnValue; + } /** also from kgpgme.cpp, seems to clear password from mem */ -void GpgContext::clearPasswordCache() -{ - if (mPasswordCache.size() > 0) { - mPasswordCache.fill('\0'); - mPasswordCache.truncate(0); + void GpgContext::clearPasswordCache() { + if (mPasswordCache.size() > 0) { + mPasswordCache.fill('\0'); + mPasswordCache.truncate(0); + } } -} // error-handling -int GpgContext::checkErr(gpgme_error_t err, QString comment) const -{ - //if (err != GPG_ERR_NO_ERROR && err != GPG_ERR_CANCELED) { - if (err != GPG_ERR_NO_ERROR) { - qDebug() << "[Error " << comment << "] Source: " << gpgme_strsource(err) << " String: " << gpgErrString(err); + void GpgContext::checkErr(gpgme_error_t gpgmeError, const QString& comment) { + //if (gpgmeError != GPG_ERR_NO_ERROR && gpgmeError != GPG_ERR_CANCELED) { + if (gpgmeError != GPG_ERR_NO_ERROR) { + qDebug() << "[Error " << comment << "] Source: " << gpgme_strsource(gpgmeError) << " String: " + << gpgErrString(gpgmeError); + } } - return err; -} -int GpgContext::checkErr(gpgme_error_t err) const -{ - //if (err != GPG_ERR_NO_ERROR && err != GPG_ERR_CANCELED) { - if (err != GPG_ERR_NO_ERROR) { - qDebug() << "[Error] Source: " << gpgme_strsource(err) << " String: " << gpgErrString(err); + void GpgContext::checkErr(gpgme_error_t gpgmeError) { + //if (gpgmeError != GPG_ERR_NO_ERROR && gpgmeError != GPG_ERR_CANCELED) { + if (gpgmeError != GPG_ERR_NO_ERROR) { + qDebug() << "[Error] Source: " << gpgme_strsource(gpgmeError) << " String: " << gpgErrString(gpgmeError); + } } - return err; -} -QString GpgContext::gpgErrString(gpgme_error_t err) { - return QString::fromUtf8(gpgme_strerror(err)); -} + QString GpgContext::gpgErrString(gpgme_error_t err) { + return QString::fromUtf8(gpgme_strerror(err)); + } /** export private key, TODO errohandling, e.g. like in seahorse (seahorse-gpg-op.c) **/ -void GpgContext::exportSecretKey(QString uid, QByteArray *outBuffer) -{ - qDebug() << *outBuffer; - // export private key to outBuffer - QStringList arguments; - arguments << "--armor" << "--export-secret-key" << uid; - QByteArray *err = new QByteArray(); - executeGpgCommand(arguments, outBuffer, err); - - // append public key to outBuffer - QByteArray *pubKey = new QByteArray(); - QStringList keyList; - keyList.append(uid); - exportKeys(&keyList,pubKey); - outBuffer->append(*pubKey); -} + void GpgContext::exportSecretKey(const QString& uid, QByteArray *outBuffer) { + qDebug() << *outBuffer; + // export private key to outBuffer + QStringList arguments; + arguments << "--armor" << "--export-secret-key" << uid; + auto *p_errArray = new QByteArray(); + executeGpgCommand(arguments, outBuffer, p_errArray); + + // append public key to outBuffer + auto *pubKey = new QByteArray(); + QStringList keyList; + keyList.append(uid); + exportKeys(&keyList, pubKey); + outBuffer->append(*pubKey); + } /** return type should be gpgme_error_t*/ -void GpgContext::executeGpgCommand(QStringList arguments, QByteArray *stdOut, QByteArray *stdErr) -{ - QStringList args; - args << "--homedir" << gpgKeys << "--batch" << arguments; + void GpgContext::executeGpgCommand(const QStringList& arguments, QByteArray *stdOut, QByteArray *stdErr) { + QStringList args; + args << "--homedir" << gpgKeys << "--batch" << arguments; - qDebug() << args; - QProcess gpg; - // qDebug() << "engine->file_name" << engine->file_name; + qDebug() << args; + QProcess gpg; + // qDebug() << "engine->file_name" << engine->file_name; - gpg.start(gpgBin, args); - gpg.waitForFinished(); + gpg.start(gpgBin, args); + gpg.waitForFinished(); - *stdOut = gpg.readAllStandardOutput(); - *stdErr = gpg.readAllStandardError(); - qDebug() << *stdOut; -} + *stdOut = gpg.readAllStandardOutput(); + *stdErr = gpg.readAllStandardError(); + qDebug() << *stdOut; + } /*** * if sigbuffer not set, the inbuffer should contain signed text @@ -617,152 +598,154 @@ void GpgContext::executeGpgCommand(QStringList arguments, QByteArray *stdOut, QB * -> valid * -> errors */ -gpgme_signature_t GpgContext::verify(QByteArray *inBuffer, QByteArray *sigBuffer) { - - int error=0; - gpgme_data_t in; - gpgme_error_t err; - gpgme_signature_t sign; - gpgme_verify_result_t result; - - err = gpgme_data_new_from_mem(&in, inBuffer->data(), inBuffer->size(), 1); - checkErr(err); - - if (sigBuffer != NULL ) { - gpgme_data_t sigdata; - err = gpgme_data_new_from_mem(&sigdata, sigBuffer->data(), sigBuffer->size(), 1); - err = gpgme_op_verify (mCtx, sigdata, in, NULL); - } else { - err = gpgme_op_verify (mCtx, in, NULL, in); - } - error = checkErr(err); + gpgme_signature_t GpgContext::verify(QByteArray *inBuffer, QByteArray *sigBuffer) { + + gpgme_data_t dataIn; + gpgme_error_t gpgmeError; + gpgme_signature_t sign; + gpgme_verify_result_t result; + + gpgmeError = gpgme_data_new_from_mem(&dataIn, inBuffer->data(), inBuffer->size(), 1); + checkErr(gpgmeError); + + if (sigBuffer != nullptr) { + gpgme_data_t sigdata; + gpgmeError = gpgme_data_new_from_mem(&sigdata, sigBuffer->data(), sigBuffer->size(), 1); + checkErr(gpgmeError); + gpgmeError = gpgme_op_verify(mCtx, sigdata, dataIn, nullptr); + } else { + gpgmeError = gpgme_op_verify(mCtx, dataIn, nullptr, dataIn); + } - if (error != 0) { - return NULL; + checkErr(gpgmeError); + + if (gpgmeError != 0) { + return nullptr; + } + + result = gpgme_op_verify_result(mCtx); + sign = result->signatures; + return sign; } - result = gpgme_op_verify_result (mCtx); - sign = result->signatures; - return sign; -} + /*** + * return type should contain: + * -> list of sigs + * -> valid + * -> decrypted message + */ + //void GpgContext::decryptVerify(QByteArray in) { -/*** - * return type should contain: - * -> list of sigs - * -> valid - * -> decrypted message - */ -//void GpgContext::decryptVerify(QByteArray in) { + /* gpgme_error_t err; + gpgme_data_t in, out; -/* gpgme_error_t err; - gpgme_data_t in, out; + gpgme_decrypt_result_t decrypt_result; + gpgme_verify_result_t verify_result; - gpgme_decrypt_result_t decrypt_result; - gpgme_verify_result_t verify_result; + err = gpgme_op_decrypt_verify (mCtx, in, out); + decrypt_result = gpgme_op_decrypt_result (mCtx); - err = gpgme_op_decrypt_verify (mCtx, in, out); - decrypt_result = gpgme_op_decrypt_result (mCtx); + verify_result = gpgme_op_verify_result (mCtx); + */ + //} + bool GpgContext::sign(QStringList *uidList, const QByteArray &inBuffer, QByteArray *outBuffer, bool detached) { - verify_result = gpgme_op_verify_result (mCtx); - */ -//} + gpgme_error_t gpgmeError; + gpgme_data_t dataIn, dataOut; + gpgme_sign_result_t result; + gpgme_sig_mode_t mode; -bool GpgContext::sign(QStringList *uidList, const QByteArray &inBuffer, QByteArray *outBuffer, bool detached) { + if (uidList->count() == 0) { + QMessageBox::critical(nullptr, tr("Key Selection"), tr("No Private Key Selected")); + return false; + } - gpgme_error_t err; - gpgme_data_t in, out; - gpgme_sign_result_t result; - gpgme_sig_mode_t mode; + // at start or end? + gpgme_signers_clear(mCtx); - if (uidList->count() == 0) { - QMessageBox::critical(0, tr("Key Selection"), tr("No Private Key Selected")); - return false; - } + //gpgme_encrypt_result_t e_result; + gpgme_key_t signers[uidList->count() + 1]; - // at start or end? - gpgme_signers_clear(mCtx); - //gpgme_encrypt_result_t e_result; - gpgme_key_t signers[uidList->count()+1]; + // TODO: do we really need array? adding one key dataIn loop should be ok + for (int i = 0; i < uidList->count(); i++) { + // the last 0 is for public keys, 1 would return private keys + gpgme_op_keylist_start(mCtx, uidList->at(i).toUtf8().constData(), 0); + gpgme_op_keylist_next(mCtx, &signers[i]); + gpgme_op_keylist_end(mCtx); + gpgmeError = gpgme_signers_add(mCtx, signers[i]); + checkErr(gpgmeError); + } - // TODO: do we really need array? adding one key in loop should be ok - for (int i = 0; i < uidList->count(); i++) { - // the last 0 is for public keys, 1 would return private keys - gpgme_op_keylist_start(mCtx, uidList->at(i).toUtf8().constData(), 0); - gpgme_op_keylist_next(mCtx, &signers[i]); - gpgme_op_keylist_end(mCtx); + gpgmeError = gpgme_data_new_from_mem(&dataIn, inBuffer.data(), inBuffer.size(), 1); + checkErr(gpgmeError); + gpgmeError = gpgme_data_new(&dataOut); + checkErr(gpgmeError); - err = gpgme_signers_add (mCtx, signers[i]); - checkErr(err); - } + /* + `GPGME_SIG_MODE_NORMAL' + A normal signature is made, the output includes the plaintext + and the signature. - err = gpgme_data_new_from_mem(&in, inBuffer.data(), inBuffer.size(), 1); - checkErr(err); - err = gpgme_data_new (&out); - checkErr(err); + `GPGME_SIG_MODE_DETACH' + A detached signature is made. - /* - `GPGME_SIG_MODE_NORMAL' - A normal signature is made, the output includes the plaintext - and the signature. + `GPGME_SIG_MODE_CLEAR' + A clear text signature is made. The ASCII armor and text + mode settings of the context are ignored. + */ - `GPGME_SIG_MODE_DETACH' - A detached signature is made. + if (detached) { + mode = GPGME_SIG_MODE_DETACH; + } else { + mode = GPGME_SIG_MODE_CLEAR; + } - `GPGME_SIG_MODE_CLEAR' - A clear text signature is made. The ASCII armor and text - mode settings of the context are ignored. - */ + gpgmeError = gpgme_op_sign(mCtx, dataIn, dataOut, mode); + checkErr(gpgmeError); - if(detached) { - mode = GPGME_SIG_MODE_DETACH; - } else { - mode = GPGME_SIG_MODE_CLEAR; - } + if (gpgmeError == GPG_ERR_CANCELED) { + return false; + } - err = gpgme_op_sign (mCtx, in, out, mode); - checkErr (err); + if (gpgmeError != GPG_ERR_NO_ERROR) { + QMessageBox::critical(nullptr, tr("Error in signing:"), QString::fromUtf8(gpgme_strerror(gpgmeError))); + return false; + } - if (err == GPG_ERR_CANCELED) { - return false; - } + result = gpgme_op_sign_result(mCtx); - if (err != GPG_ERR_NO_ERROR) { - QMessageBox::critical(0, tr("Error signing:"), QString::fromUtf8(gpgme_strerror(err))); - return false; - } + // TODO Handle the result - result = gpgme_op_sign_result (mCtx); - err = readToBuffer(out, outBuffer); - checkErr (err); + gpgmeError = readToBuffer(dataOut, outBuffer); + checkErr(gpgmeError); - gpgme_data_release(in); - gpgme_data_release(out); + gpgme_data_release(dataIn); + gpgme_data_release(dataOut); - if (! settings.value("general/rememberPassword").toBool()) { - clearPasswordCache(); - } + if (!settings.value("general/rememberPassword").toBool()) { + clearPasswordCache(); + } - return (err == GPG_ERR_NO_ERROR); -} + return (gpgmeError == GPG_ERR_NO_ERROR); + } /* * if there is no '\n' before the PGP-Begin-Block, but for example a whitespace, * GPGME doesn't recognise the Message as encrypted. This function adds '\n' * before the PGP-Begin-Block, if missing. */ -void GpgContext::preventNoDataErr(QByteArray *in) -{ - int block_start = in->indexOf(GpgConstants::PGP_CRYPT_BEGIN); - if (block_start > 0 && in->at(block_start - 1) != '\n') { - in->insert(block_start, '\n'); - } - block_start = in->indexOf(GpgConstants::PGP_SIGNED_BEGIN); - if (block_start > 0 && in->at(block_start - 1) != '\n') { - in->insert(block_start, '\n'); + void GpgContext::preventNoDataErr(QByteArray *in) { + int block_start = in->indexOf(GpgConstants::PGP_CRYPT_BEGIN); + if (block_start > 0 && in->at(block_start - 1) != '\n') { + in->insert(block_start, '\n'); + } + block_start = in->indexOf(GpgConstants::PGP_SIGNED_BEGIN); + if (block_start > 0 && in->at(block_start - 1) != '\n') { + in->insert(block_start, '\n'); + } } -} /* * isSigned returns: @@ -770,62 +753,62 @@ void GpgContext::preventNoDataErr(QByteArray *in) * - 1, if text is partially signed * - 2, if text is completly signed */ -int GpgContext::textIsSigned(const QByteArray &text) { - if (text.trimmed().startsWith(GpgConstants::PGP_SIGNED_BEGIN) && text.trimmed().endsWith(GpgConstants::PGP_SIGNED_END)) { - return 2; - } - if (text.contains(GpgConstants::PGP_SIGNED_BEGIN) && text.contains(GpgConstants::PGP_SIGNED_END)) { - return 1; + int GpgContext::textIsSigned(const QByteArray &text) { + if (text.trimmed().startsWith(GpgConstants::PGP_SIGNED_BEGIN) && + text.trimmed().endsWith(GpgConstants::PGP_SIGNED_END)) { + return 2; + } + if (text.contains(GpgConstants::PGP_SIGNED_BEGIN) && text.contains(GpgConstants::PGP_SIGNED_END)) { + return 1; + } + return 0; } - return 0; -} -QString GpgContext::beautifyFingerprint(QString fingerprint) -{ - uint len = fingerprint.length(); - if ((len > 0) && (len % 4 == 0)) - for (uint n = 0; 4 *(n + 1) < len; ++n) - fingerprint.insert(5 * n + 4, ' '); - return fingerprint; -} + QString GpgContext::beautifyFingerprint(QString fingerprint) { + uint len = fingerprint.length(); + if ((len > 0) && (len % 4 == 0)) + for (uint n = 0; 4 * (n + 1) < len; ++n) + fingerprint.insert(static_cast<int>(5u * n + 4u), ' '); + return fingerprint; + } -void GpgContext::slotRefreshKeyList() { - mKeyList = this->listKeys(); -} + void GpgContext::slotRefreshKeyList() { + mKeyList = this->listKeys(); + } /** * note: privkey status is not returned */ -GpgKey GpgContext::getKeyByFpr(QString fpr) { + GpgKey GpgContext::getKeyByFpr(const QString& fpr) { - //GpgKeyList list = this->listKeys(); - foreach (GpgKey key, mKeyList) { - if(key.fpr == fpr) { - return key; - } - } + //GpgKeyList list = this->listKeys(); + foreach (GpgKey key, mKeyList) { + if (key.fpr == fpr) { + return key; + } + } - return GpgKey(); -} + return GpgKey(); + } /** * note: privkey status is not returned */ -GpgKey GpgContext::getKeyById(QString id) { + GpgKey GpgContext::getKeyById(const QString& id) { - //GpgKeyList list = this->listKeys(); - foreach (GpgKey key, mKeyList) { - if(key.id == id) { - return key; - } - } + //GpgKeyList list = this->listKeys(); + foreach (GpgKey key, mKeyList) { + if (key.id == id) { + return key; + } + } - return GpgKey(); -} + return GpgKey(); + } -QString GpgContext::getGpgmeVersion() { - return QString(gpgme_check_version(NULL)); -} + QString GpgContext::getGpgmeVersion() { + return QString(gpgme_check_version(nullptr)); + } } diff --git a/src/helppage.cpp b/src/helppage.cpp index ace8c92c..c054dd36 100644 --- a/src/helppage.cpp +++ b/src/helppage.cpp @@ -21,15 +21,16 @@ #include "helppage.h" -HelpPage::HelpPage(const QString path, QWidget *parent) : - QWidget(parent) -{ +#include <utility> + +HelpPage::HelpPage(const QString &path, QWidget *parent) : + QWidget(parent) { browser = new QTextBrowser(); - QVBoxLayout* mainLayout = new QVBoxLayout(); + auto *mainLayout = new QVBoxLayout(); mainLayout->setSpacing(0); mainLayout->addWidget(browser); - mainLayout->setContentsMargins(0,0,0,0); + mainLayout->setContentsMargins(0, 0, 0, 0); setLayout(mainLayout); //setAttribute(Qt::WA_DeleteOnClose); //browser->setSource(QUrl::fromLocalFile(path)); @@ -41,8 +42,8 @@ HelpPage::HelpPage(const QString path, QWidget *parent) : } -void HelpPage::slotOpenUrl(QUrl url) { - browser->setSource(localizedHelp(url)); +void HelpPage::slotOpenUrl(const QUrl &url) { + browser->setSource(localizedHelp(url)); }; /** @@ -53,10 +54,10 @@ void HelpPage::slotOpenUrl(QUrl url) { * @param url * @return */ -QUrl HelpPage::localizedHelp(QUrl url) { +QUrl HelpPage::localizedHelp(const QUrl &url) { QString path = url.toLocalFile(); - QString filename = path.mid(path.lastIndexOf("/") + 1 ); - QString filepath = path.left(path.lastIndexOf("/") + 1 ); + QString filename = path.mid(path.lastIndexOf("/") + 1); + QString filepath = path.left(path.lastIndexOf("/") + 1); QStringList fileparts = filename.split("."); //QSettings settings; @@ -65,10 +66,10 @@ QUrl HelpPage::localizedHelp(QUrl url) { lang = QLocale::system().name(); } - fileparts.insert(1,lang); + fileparts.insert(1, lang); QString langfile = filepath + fileparts.join("."); - if(QFile(QUrl(langfile).toLocalFile()).exists()) { + if (QFile(QUrl(langfile).toLocalFile()).exists()) { return langfile; } else { return path; @@ -76,6 +77,6 @@ QUrl HelpPage::localizedHelp(QUrl url) { } -QTextBrowser* HelpPage::getBrowser() { +QTextBrowser *HelpPage::getBrowser() { return browser; } diff --git a/src/keydetailsdialog.cpp b/src/keydetailsdialog.cpp index 36f2e4aa..53ba26e4 100644 --- a/src/keydetailsdialog.cpp +++ b/src/keydetailsdialog.cpp @@ -21,9 +21,8 @@ #include "keydetailsdialog.h" -KeyDetailsDialog::KeyDetailsDialog(GpgME::GpgContext* ctx, gpgme_key_t key, QWidget *parent) - : QDialog(parent) -{ +KeyDetailsDialog::KeyDetailsDialog(GpgME::GpgContext *ctx, gpgme_key_t key, QWidget *parent) + : QDialog(parent) { mCtx = ctx; keyid = new QString(key->subkeys->keyid); @@ -57,7 +56,7 @@ KeyDetailsDialog::KeyDetailsDialog(GpgME::GpgContext* ctx, gpgme_key_t key, QWid // have el-gamal key? if (key->subkeys->next) { - keySizeVal.sprintf("%d / %d", int(key->subkeys->length), int(key->subkeys->next->length)); + keySizeVal.sprintf("%d / %d", int(key->subkeys->length), int(key->subkeys->next->length)); if (key->subkeys->next->expires == 0) { keyExpireVal += tr(" / Never"); } else { @@ -74,9 +73,9 @@ KeyDetailsDialog::KeyDetailsDialog(GpgME::GpgContext* ctx, gpgme_key_t key, QWid createdVarLabel = new QLabel(keyCreatedVal); algorithmVarLabel = new QLabel(keyAlgoVal); - QVBoxLayout *mvbox = new QVBoxLayout(); - QGridLayout *vboxKD = new QGridLayout(); - QGridLayout *vboxOD = new QGridLayout(); + auto *mvbox = new QVBoxLayout(); + auto *vboxKD = new QGridLayout(); + auto *vboxOD = new QGridLayout(); vboxOD->addWidget(new QLabel(tr("Name:")), 0, 0); vboxOD->addWidget(new QLabel(tr("E-Mailaddress:")), 1, 0); @@ -105,7 +104,7 @@ KeyDetailsDialog::KeyDetailsDialog(GpgME::GpgContext* ctx, gpgme_key_t key, QWid fingerPrintVarLabel = new QLabel(beautifyFingerprint(key->subkeys->fpr)); fingerPrintVarLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); fingerPrintVarLabel->setStyleSheet("margin-left: 20; margin-right: 20;"); - QHBoxLayout *hboxFP = new QHBoxLayout(); + auto *hboxFP = new QHBoxLayout(); hboxFP->addWidget(fingerPrintVarLabel); QIcon ico(":button_copy.png"); @@ -123,23 +122,24 @@ KeyDetailsDialog::KeyDetailsDialog(GpgME::GpgContext* ctx, gpgme_key_t key, QWid // If key has more than primary uid, also show the other uids gpgme_user_id_t addUserIds = key->uids->next; - if (addUserIds !=NULL) { - QVBoxLayout *vboxUID = new QVBoxLayout(); - while (addUserIds != NULL){ - addUserIdsVarLabel = new QLabel(QString::fromUtf8(addUserIds->name)+ QString(" <")+addUserIds->email+">"); + if (addUserIds != nullptr) { + auto *vboxUID = new QVBoxLayout(); + while (addUserIds != nullptr) { + addUserIdsVarLabel = new QLabel( + QString::fromUtf8(addUserIds->name) + QString(" <") + addUserIds->email + ">"); addUserIdsVarLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); vboxUID->addWidget(addUserIdsVarLabel); - addUserIds=addUserIds->next; + addUserIds = addUserIds->next; } additionalUidBox->setLayout(vboxUID); mvbox->addWidget(additionalUidBox); } if (key->secret) { - QGroupBox *privKeyBox = new QGroupBox(tr("Private Key")); - QVBoxLayout *vboxPK = new QVBoxLayout(); + auto *privKeyBox = new QGroupBox(tr("Private Key")); + auto *vboxPK = new QVBoxLayout(); - QPushButton *exportButton = new QPushButton(tr("Export Private Key")); + auto *exportButton = new QPushButton(tr("Export Private Key")); vboxPK->addWidget(exportButton); connect(exportButton, SIGNAL(clicked()), this, SLOT(slotExportPrivateKey())); @@ -147,13 +147,13 @@ KeyDetailsDialog::KeyDetailsDialog(GpgME::GpgContext* ctx, gpgme_key_t key, QWid mvbox->addWidget(privKeyBox); } - if((key->expired) || (key->revoked)) { - QHBoxLayout *expBox = new QHBoxLayout(); + if ((key->expired) || (key->revoked)) { + auto *expBox = new QHBoxLayout(); QIcon icon = QIcon::fromTheme("dialog-warning"); - QPixmap pixmap = icon.pixmap(QSize(32,32),QIcon::Normal,QIcon::On); + QPixmap pixmap = icon.pixmap(QSize(32, 32), QIcon::Normal, QIcon::On); - QLabel *expLabel = new QLabel(); - QLabel *iconLabel = new QLabel(); + auto *expLabel = new QLabel(); + auto *iconLabel = new QLabel(); if (key->expired) { expLabel->setText(tr("Warning: Key expired")); } @@ -180,8 +180,7 @@ KeyDetailsDialog::KeyDetailsDialog(GpgME::GpgContext* ctx, gpgme_key_t key, QWid exec(); } -void KeyDetailsDialog::slotExportPrivateKey() -{ +void KeyDetailsDialog::slotExportPrivateKey() { // Show a information box with explanation about private key int ret = QMessageBox::information(this, tr("Exporting private Key"), tr("You are about to export your private key.\n" @@ -192,14 +191,16 @@ void KeyDetailsDialog::slotExportPrivateKey() // export key, if ok was clicked if (ret == QMessageBox::Ok) { - QByteArray *keyArray = new QByteArray(); + auto *keyArray = new QByteArray(); mCtx->exportSecretKey(*keyid, keyArray); gpgme_key_t key = mCtx->getKeyDetails(*keyid); - QString fileString = QString::fromUtf8(key->uids->name) + " " + QString::fromUtf8(key->uids->email) + "(" + QString(key->subkeys->keyid)+ ")_pub_sec.asc"; - QString fileName = QFileDialog::getSaveFileName(this, tr("Export Key To File"), fileString, tr("Key Files") + " (*.asc *.txt);;All Files (*)"); + QString fileString = QString::fromUtf8(key->uids->name) + " " + QString::fromUtf8(key->uids->email) + "(" + + QString(key->subkeys->keyid) + ")_pub_sec.asc"; + QString fileName = QFileDialog::getSaveFileName(this, tr("Export Key To File"), fileString, + tr("Key Files") + " (*.asc *.txt);;All Files (*)"); QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - QMessageBox::critical(0,tr("Export error"),tr("Couldn't open %1 for writing").arg(fileName)); + QMessageBox::critical(nullptr, tr("Export error"), tr("Couldn't open %1 for writing").arg(fileName)); return; } QTextStream stream(&file); @@ -209,12 +210,11 @@ void KeyDetailsDialog::slotExportPrivateKey() } } -QString KeyDetailsDialog::beautifyFingerprint(QString fingerprint) -{ +QString KeyDetailsDialog::beautifyFingerprint(QString fingerprint) { uint len = fingerprint.length(); if ((len > 0) && (len % 4 == 0)) - for (uint n = 0; 4 *(n + 1) < len; ++n) - fingerprint.insert(5 * n + 4, ' '); + for (uint n = 0; 4 * (n + 1) < len; ++n) + fingerprint.insert(static_cast<int>(5u * n + 4u), ' '); return fingerprint; } diff --git a/src/keygendialog.cpp b/src/keygendialog.cpp index 2aa5f81f..16d8f9b5 100644 --- a/src/keygendialog.cpp +++ b/src/keygendialog.cpp @@ -23,8 +23,7 @@ #include "keygendialog.h" KeyGenDialog::KeyGenDialog(GpgME::GpgContext *ctx, QWidget *parent) - : QDialog(parent) -{ + : QDialog(parent) { mCtx = ctx; buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); @@ -33,8 +32,7 @@ KeyGenDialog::KeyGenDialog(GpgME::GpgContext *ctx, QWidget *parent) generateKeyDialog(); } -void KeyGenDialog::generateKeyDialog() -{ +void KeyGenDialog::generateKeyDialog() { errorLabel = new QLabel(tr("")); nameEdit = new QLineEdit(this); emailEdit = new QLineEdit(this); @@ -72,7 +70,7 @@ void KeyGenDialog::generateKeyDialog() pwStrengthSlider->setToolTip(tr("Password Strength")); pwStrengthSlider->setTickPosition(QSlider::TicksBelow); - QGridLayout *vbox1 = new QGridLayout; + auto *vbox1 = new QGridLayout; vbox1->addWidget(new QLabel(tr("Name:")), 0, 0); vbox1->addWidget(new QLabel(tr("E-Mailaddress:")), 1, 0); @@ -91,15 +89,15 @@ void KeyGenDialog::generateKeyDialog() vbox1->addWidget(dateEdit, 3, 1); vbox1->addWidget(expireCheckBox, 3, 2); vbox1->addWidget(keySizeSpinBox, 4, 1); - vbox1->addWidget(keyTypeComboBox,5, 1); + vbox1->addWidget(keyTypeComboBox, 5, 1); vbox1->addWidget(passwordEdit, 6, 1); vbox1->addWidget(repeatpwEdit, 7, 1); vbox1->addWidget(pwStrengthSlider, 7, 3); - QWidget *nameList = new QWidget(this); + auto *nameList = new QWidget(this); nameList->setLayout(vbox1); - QVBoxLayout *vbox2 = new QVBoxLayout(); + auto *vbox2 = new QVBoxLayout(); vbox2->addWidget(nameList); vbox2->addWidget(errorLabel); vbox2->addWidget(buttonBox); @@ -114,10 +112,9 @@ void KeyGenDialog::generateKeyDialog() this->setLayout(vbox2); } -void KeyGenDialog::slotKeyGenAccept() -{ +void KeyGenDialog::slotKeyGenAccept() { QString errorString = ""; - QString keyGenParams = ""; + QString keyGenParams; /** * check for errors in keygen dialog input */ @@ -133,20 +130,22 @@ void KeyGenDialog::slotKeyGenAccept() * create the string for key generation */ - if(keyTypeComboBox->currentText() == "RSA") { + if (keyTypeComboBox->currentText() == "RSA") { keyGenParams = "<GnupgKeyParms format=\"internal\">\n" - "Key-Type: RSA\n" - "Key-Usage: sign\n" - "Key-Length: " + keySizeSpinBox->cleanText() + "\n" - "Subkey-Type: RSA\n" - "Subkey-Length: " + keySizeSpinBox->cleanText() + "\n" - "Subkey-Usage: encrypt\n"; + "Key-Type: RSA\n" + "Key-Usage: sign\n" + "Key-Length: " + keySizeSpinBox->cleanText() + "\n" + "Subkey-Type: RSA\n" + "Subkey-Length: " + + keySizeSpinBox->cleanText() + "\n" + "Subkey-Usage: encrypt\n"; } else { keyGenParams = "<GnupgKeyParms format=\"internal\">\n" - "Key-Type: DSA\n" - "Key-Length: " + keySizeSpinBox->cleanText() + "\n" - "Subkey-Type: ELG-E\n" - "Subkey-Length: " + keySizeSpinBox->cleanText() + "\n"; + "Key-Type: DSA\n" + "Key-Length: " + keySizeSpinBox->cleanText() + "\n" + "Subkey-Type: ELG-E\n" + "Subkey-Length: " + + keySizeSpinBox->cleanText() + "\n"; } keyGenParams += "Name-Real: " + nameEdit->text().toUtf8() + "\n"; @@ -159,27 +158,30 @@ void KeyGenDialog::slotKeyGenAccept() if (expireCheckBox->checkState()) { keyGenParams += "Expire-Date: 0\n"; } else { - keyGenParams += "Expire-Date: " + dateEdit->sectionText(QDateTimeEdit::YearSection) + "-" + dateEdit->sectionText(QDateTimeEdit::MonthSection) + "-" + dateEdit->sectionText(QDateTimeEdit::DaySection) + "\n"; + keyGenParams += "Expire-Date: " + dateEdit->sectionText(QDateTimeEdit::YearSection) + "-" + + dateEdit->sectionText(QDateTimeEdit::MonthSection) + "-" + + dateEdit->sectionText(QDateTimeEdit::DaySection) + "\n"; } if (!(passwordEdit->text().isEmpty())) { keyGenParams += "Passphrase: " + passwordEdit->text() + "\n"; } keyGenParams += "</GnupgKeyParms>"; - KeyGenThread *kg = new KeyGenThread(keyGenParams, mCtx); + auto *kg = new KeyGenThread(keyGenParams, mCtx); kg->start(); this->accept(); - QDialog *dialog = new QDialog(this, Qt::CustomizeWindowHint | Qt::WindowTitleHint); + auto *dialog = new QDialog(this, Qt::CustomizeWindowHint | Qt::WindowTitleHint); dialog->setModal(true); dialog->setWindowTitle(tr("Generating Key...")); - QLabel *waitMessage = new QLabel(tr("Collecting random data for key generation.\n This may take a while.\n To speed up the process use your computer\n (e.g. browse the net, listen to music,...)")); - QProgressBar *pb = new QProgressBar(); + auto *waitMessage = new QLabel( + tr("Collecting random data for key generation.\n This may take a while.\n To speed up the process use your computer\n (e.g. browse the net, listen to music,...)")); + auto *pb = new QProgressBar(); pb->setRange(0, 0); - QVBoxLayout *layout = new QVBoxLayout(dialog); + auto *layout = new QVBoxLayout(dialog); layout->addWidget(waitMessage); layout->addWidget(pb); dialog->setLayout(layout); @@ -191,7 +193,7 @@ void KeyGenDialog::slotKeyGenAccept() } dialog->close(); - QMessageBox::information(0,tr("Success"),tr("New key created")); + QMessageBox::information(nullptr, tr("Success"), tr("New key created")); } else { /** * create error message @@ -206,8 +208,7 @@ void KeyGenDialog::slotKeyGenAccept() } } -void KeyGenDialog::slotExpireBoxChanged() -{ +void KeyGenDialog::slotExpireBoxChanged() { if (expireCheckBox->checkState()) { dateEdit->setEnabled(false); } else { @@ -215,14 +216,12 @@ void KeyGenDialog::slotExpireBoxChanged() } } -void KeyGenDialog::slotPasswordEditChanged() -{ +void KeyGenDialog::slotPasswordEditChanged() { pwStrengthSlider->setValue(checkPassWordStrength()); update(); } -int KeyGenDialog::checkPassWordStrength() -{ +int KeyGenDialog::checkPassWordStrength() { int strength = 0; // increase strength by two, if password has more than 7 characters diff --git a/src/keygenthread.cpp b/src/keygenthread.cpp index c5588773..3b004799 100644 --- a/src/keygenthread.cpp +++ b/src/keygenthread.cpp @@ -21,14 +21,14 @@ #include "keygenthread.h" -KeyGenThread::KeyGenThread(QString keyGenParams, GpgME::GpgContext *ctx) -{ - this->keyGenParams = keyGenParams; +#include <utility> + +KeyGenThread::KeyGenThread(QString keyGenParams, GpgME::GpgContext *ctx) { + this->keyGenParams = std::move(keyGenParams); this->mCtx = ctx; abort = false; } -void KeyGenThread::run() -{ +void KeyGenThread::run() { mCtx->generateKey(&keyGenParams); } diff --git a/src/keyimportdetaildialog.cpp b/src/keyimportdetaildialog.cpp index e606ca8b..c4b10675 100644 --- a/src/keyimportdetaildialog.cpp +++ b/src/keyimportdetaildialog.cpp @@ -21,18 +21,19 @@ #include "keyimportdetaildialog.h" -KeyImportDetailDialog::KeyImportDetailDialog(GpgME::GpgContext* ctx, GpgImportInformation result, QWidget *parent) - : QDialog(parent) -{ +#include <utility> + +KeyImportDetailDialog::KeyImportDetailDialog(GpgME::GpgContext *ctx, GpgImportInformation result, QWidget *parent) + : QDialog(parent) { mCtx = ctx; - mResult = result; + mResult = std::move(result); // If no key for import found, just show a message if (mResult.considered == 0) { - QMessageBox::information(0, tr("Key import details"), tr("No keys found to import")); + QMessageBox::information(nullptr, tr("Key import details"), tr("No keys found to import")); return; } - QVBoxLayout *mvbox = new QVBoxLayout(); + auto *mvbox = new QVBoxLayout(); this->createGeneralInfoBox(); mvbox->addWidget(generalInfoBox); @@ -45,54 +46,52 @@ KeyImportDetailDialog::KeyImportDetailDialog(GpgME::GpgContext* ctx, GpgImportIn this->setLayout(mvbox); this->setWindowTitle(tr("Key import details")); - this->resize(QSize(600,300)); + this->resize(QSize(600, 300)); this->setModal(true); this->exec(); } -void KeyImportDetailDialog::createGeneralInfoBox() -{ +void KeyImportDetailDialog::createGeneralInfoBox() { // GridBox for general import information generalInfoBox = new QGroupBox(tr("Genral key import info")); - QGridLayout *generalInfoBoxLayout = new QGridLayout(generalInfoBox); + auto *generalInfoBoxLayout = new QGridLayout(generalInfoBox); - generalInfoBoxLayout->addWidget(new QLabel(tr("Considered:")),1,0); - generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.considered)),1,1); - int row=2; - if (mResult.unchanged != 0){ - generalInfoBoxLayout->addWidget(new QLabel(tr("Public unchanged:")),row,0); - generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.unchanged)),row,1); + generalInfoBoxLayout->addWidget(new QLabel(tr("Considered:")), 1, 0); + generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.considered)), 1, 1); + int row = 2; + if (mResult.unchanged != 0) { + generalInfoBoxLayout->addWidget(new QLabel(tr("Public unchanged:")), row, 0); + generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.unchanged)), row, 1); row++; } - if (mResult.imported != 0){ - generalInfoBoxLayout->addWidget(new QLabel(tr("Imported:")),row,0); - generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.imported)),row,1); + if (mResult.imported != 0) { + generalInfoBoxLayout->addWidget(new QLabel(tr("Imported:")), row, 0); + generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.imported)), row, 1); row++; } - if (mResult.not_imported != 0){ - generalInfoBoxLayout->addWidget(new QLabel(tr("Not imported:")),row,0); - generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.not_imported)),row,1); + if (mResult.not_imported != 0) { + generalInfoBoxLayout->addWidget(new QLabel(tr("Not imported:")), row, 0); + generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.not_imported)), row, 1); row++; } - if (mResult.secret_read != 0){ - generalInfoBoxLayout->addWidget(new QLabel(tr("Private read:")),row,0); - generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.secret_read)),row,1); + if (mResult.secret_read != 0) { + generalInfoBoxLayout->addWidget(new QLabel(tr("Private read:")), row, 0); + generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.secret_read)), row, 1); row++; } - if (mResult.secret_imported != 0){ - generalInfoBoxLayout->addWidget(new QLabel(tr("Private imported:")),row,0); - generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.secret_imported)),row,1); + if (mResult.secret_imported != 0) { + generalInfoBoxLayout->addWidget(new QLabel(tr("Private imported:")), row, 0); + generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.secret_imported)), row, 1); row++; } - if (mResult.secret_unchanged != 0){ - generalInfoBoxLayout->addWidget(new QLabel(tr("Private unchanged:")),row,0); - generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.secret_unchanged)),row,1); + if (mResult.secret_unchanged != 0) { + generalInfoBoxLayout->addWidget(new QLabel(tr("Private unchanged:")), row, 0); + generalInfoBoxLayout->addWidget(new QLabel(QString::number(mResult.secret_unchanged)), row, 1); row++; } } -void KeyImportDetailDialog::createKeysTable() -{ +void KeyImportDetailDialog::createKeysTable() { keysTable = new QTableWidget(this); keysTable->setRowCount(0); keysTable->setColumnCount(4); @@ -101,60 +100,58 @@ void KeyImportDetailDialog::createKeysTable() keysTable->setSelectionMode(QAbstractItemView::NoSelection); QStringList headerLabels; - headerLabels << tr("Name") << tr("Email") << tr("Status") << tr("Fingerprint"); + headerLabels << tr("Name") << tr("Email") << tr("Status") << tr("Fingerprint"); keysTable->verticalHeader()->hide(); keysTable->setHorizontalHeaderLabels(headerLabels); int row = 0; - foreach (GpgImportedKey impKey, mResult.importedKeys) { - keysTable->setRowCount(row+1); - GpgKey key = mCtx->getKeyByFpr(impKey.fpr); - keysTable->setItem(row, 0, new QTableWidgetItem(key.name)); - keysTable->setItem(row, 1, new QTableWidgetItem(key.email)); - keysTable->setItem(row, 2 ,new QTableWidgetItem(getStatusString(impKey.importStatus))); - keysTable->setItem(row, 3, new QTableWidgetItem(impKey.fpr)); - row++; - } + foreach (GpgImportedKey impKey, mResult.importedKeys) { + keysTable->setRowCount(row + 1); + GpgKey key = mCtx->getKeyByFpr(impKey.fpr); + keysTable->setItem(row, 0, new QTableWidgetItem(key.name)); + keysTable->setItem(row, 1, new QTableWidgetItem(key.email)); + keysTable->setItem(row, 2, new QTableWidgetItem(getStatusString(impKey.importStatus))); + keysTable->setItem(row, 3, new QTableWidgetItem(impKey.fpr)); + row++; + } keysTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); keysTable->horizontalHeader()->setStretchLastSection(true); keysTable->resizeColumnsToContents(); } -QString KeyImportDetailDialog::getStatusString(int keyStatus) -{ +QString KeyImportDetailDialog::getStatusString(int keyStatus) { QString statusString; // keystatus is greater than 15, if key is private if (keyStatus > 15) { statusString.append(tr("private")); - keyStatus=keyStatus-16; + keyStatus = keyStatus - 16; } else { statusString.append(tr("public")); } if (keyStatus == 0) { - statusString.append(", "+tr("unchanged")); + statusString.append(", " + tr("unchanged")); } else { if (keyStatus == 1) { - statusString.append(", "+tr("new key")); + statusString.append(", " + tr("new key")); } else { if (keyStatus > 7) { - statusString.append(", "+tr("new subkey")); - keyStatus=keyStatus-8; + statusString.append(", " + tr("new subkey")); + keyStatus = keyStatus - 8; } if (keyStatus > 3) { - statusString.append(", "+tr("new signature")); - keyStatus=keyStatus-4; + statusString.append(", " + tr("new signature")); + keyStatus = keyStatus - 4; } if (keyStatus > 1) { - statusString.append(", "+tr("new uid")); - keyStatus=keyStatus-2; + statusString.append(", " + tr("new uid")); + keyStatus = keyStatus - 2; } } } return statusString; } -void KeyImportDetailDialog::createButtonBox() -{ +void KeyImportDetailDialog::createButtonBox() { buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); connect(buttonBox, SIGNAL(accepted()), this, SLOT(close())); } diff --git a/src/keylist.cpp b/src/keylist.cpp index e0178481..fbf5bb13 100644 --- a/src/keylist.cpp +++ b/src/keylist.cpp @@ -21,6 +21,8 @@ #include "keylist.h" +#include <utility> + KeyList::KeyList(GpgME::GpgContext *ctx, QWidget *parent) : QWidget(parent) { @@ -51,7 +53,7 @@ KeyList::KeyList(GpgME::GpgContext *ctx, QWidget *parent) mKeyList->setHorizontalHeaderLabels(labels); mKeyList->horizontalHeader()->setStretchLastSection(true); - QVBoxLayout *layout = new QVBoxLayout; + auto *layout = new QVBoxLayout; layout->addWidget(mKeyList); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(3); @@ -78,19 +80,19 @@ void KeyList::slotRefresh() GpgKeyList::iterator it = keys.begin(); while (it != keys.end()) { - QTableWidgetItem *tmp0 = new QTableWidgetItem(); + auto *tmp0 = new QTableWidgetItem(); tmp0->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable); tmp0->setCheckState(Qt::Unchecked); mKeyList->setItem(row, 0, tmp0); if (it->privkey) { - QTableWidgetItem *tmp1 = new QTableWidgetItem(QIcon(":kgpg_key2.png"), ""); + auto *tmp1 = new QTableWidgetItem(QIcon(":kgpg_key2.png"), ""); mKeyList->setItem(row, 1, tmp1); } - QTableWidgetItem *tmp2 = new QTableWidgetItem(it->name); + auto *tmp2 = new QTableWidgetItem(it->name); tmp2->setToolTip(it->name); mKeyList->setItem(row, 2, tmp2); - QTableWidgetItem *tmp3 = new QTableWidgetItem(it->email); + auto *tmp3 = new QTableWidgetItem(it->email); tmp3->setToolTip(it->email); // strike out expired keys if(it->expired || it->revoked) { @@ -100,9 +102,9 @@ void KeyList::slotRefresh() tmp3->setFont(strike); } mKeyList->setItem(row, 3, tmp3); - QTableWidgetItem *tmp4 = new QTableWidgetItem(it->id); + auto *tmp4 = new QTableWidgetItem(it->id); mKeyList->setItem(row, 4, tmp4); - QTableWidgetItem *tmp5 = new QTableWidgetItem(it->fpr); + auto *tmp5 = new QTableWidgetItem(it->fpr); mKeyList->setItem(row, 5, tmp5); @@ -115,7 +117,7 @@ void KeyList::slotRefresh() QStringList *KeyList::getChecked() { - QStringList *ret = new QStringList(); + auto *ret = new QStringList(); for (int i = 0; i < mKeyList->rowCount(); i++) { if (mKeyList->item(i, 0)->checkState() == Qt::Checked) { *ret << mKeyList->item(i, 4)->text(); @@ -126,7 +128,7 @@ QStringList *KeyList::getChecked() QStringList *KeyList::getAllPrivateKeys() { - QStringList *ret = new QStringList(); + auto *ret = new QStringList(); for (int i = 0; i < mKeyList->rowCount(); i++) { if (mKeyList->item(i, 1)) { *ret << mKeyList->item(i, 4)->text(); @@ -137,7 +139,7 @@ QStringList *KeyList::getAllPrivateKeys() QStringList *KeyList::getPrivateChecked() { - QStringList *ret = new QStringList(); + auto *ret = new QStringList(); for (int i = 0; i < mKeyList->rowCount(); i++) { if ((mKeyList->item(i, 0)->checkState() == Qt::Checked) && (mKeyList->item(i, 1))) { *ret << mKeyList->item(i, 4)->text(); @@ -159,7 +161,7 @@ void KeyList::setChecked(QStringList *keyIds) QStringList *KeyList::getSelected() { - QStringList *ret = new QStringList(); + auto *ret = new QStringList(); for (int i = 0; i < mKeyList->rowCount(); i++) { if (mKeyList->item(i, 0)->isSelected() == 1) { @@ -169,7 +171,7 @@ QStringList *KeyList::getSelected() return ret; } -bool KeyList::containsPrivateKeys() +[[maybe_unused]] bool KeyList::containsPrivateKeys() { for (int i = 0; i < mKeyList->rowCount(); i++) { if (mKeyList->item(i, 1)) { @@ -199,22 +201,22 @@ void KeyList::dropEvent(QDropEvent* event) // importKeyDialog(); QSettings settings; - QDialog *dialog = new QDialog(); + auto *dialog = new QDialog(); dialog->setWindowTitle(tr("Import Keys")); QLabel *label; label = new QLabel(tr("You've dropped something on the keylist.\n gpg4usb will now try to import key(s).")+"\n"); // "always import keys"-CheckBox - QCheckBox *checkBox = new QCheckBox(tr("Always import without bothering.")); + auto *checkBox = new QCheckBox(tr("Always import without bothering.")); if (settings.value("general/confirmImportKeys").toBool()) checkBox->setCheckState(Qt::Unchecked); // Buttons for ok and cancel - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + auto *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), dialog, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), dialog, SLOT(reject())); - QVBoxLayout *vbox = new QVBoxLayout(); + auto *vbox = new QVBoxLayout(); vbox->addWidget(label); vbox->addWidget(checkBox); vbox->addWidget(buttonBox); @@ -262,7 +264,7 @@ void KeyList::dragEnterEvent(QDragEnterEvent *event) /** set background color for Keys and put them to top * */ -void KeyList::markKeys(QStringList *keyIds) +[[maybe_unused]] void KeyList::markKeys(QStringList *keyIds) { foreach(QString id, *keyIds) { qDebug() << "marked: " << id; @@ -271,7 +273,7 @@ void KeyList::markKeys(QStringList *keyIds) void KeyList::importKeys(QByteArray inBuffer) { - GpgImportInformation result = mCtx->importKey(inBuffer); + GpgImportInformation result = mCtx->importKey(std::move(inBuffer)); new KeyImportDetailDialog(mCtx, result, this); } @@ -308,7 +310,7 @@ void KeyList::uploadKeyToServer(QByteArray *keys) void KeyList::uploadFinished() { - QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); + auto *reply = qobject_cast<QNetworkReply *>(sender()); QByteArray response = reply->readAll(); qDebug() << "RESPNOSE: " << response.data(); @@ -322,5 +324,4 @@ void KeyList::uploadFinished() } reply->deleteLater(); - reply = 0; } diff --git a/src/keymgmt.cpp b/src/keymgmt.cpp index 70e8d30e..9d75a3fd 100755 --- a/src/keymgmt.cpp +++ b/src/keymgmt.cpp @@ -22,6 +22,8 @@ #include "keymgmt.h" +#include <utility> + KeyMgmt::KeyMgmt(GpgME::GpgContext *ctx, QWidget *parent ) : QMainWindow(parent) { mCtx = ctx; @@ -138,7 +140,7 @@ void KeyMgmt::createToolBars() keyToolBar->setObjectName("keytoolbar"); // add button with popup menu for import - QToolButton* toolButton = new QToolButton(this); + auto* toolButton = new QToolButton(this); toolButton->setMenu(importKeyMenu); toolButton->setPopupMode(QToolButton::InstantPopup); toolButton->setIcon(QIcon(":key_import.png")); @@ -157,7 +159,7 @@ void KeyMgmt::createToolBars() void KeyMgmt::slotImportKeys(QByteArray inBuffer) { - GpgImportInformation result = mCtx->importKey(inBuffer); + GpgImportInformation result = mCtx->importKey(std::move(inBuffer)); new KeyImportDetailDialog(mCtx, result, this); } @@ -242,7 +244,7 @@ void KeyMgmt::slotShowKeyDetails() void KeyMgmt::slotExportKeyToFile() { - QByteArray *keyArray = new QByteArray(); + auto *keyArray = new QByteArray(); if (!mCtx->exportKeys(mKeyList->getChecked(), keyArray)) { return; } @@ -262,7 +264,7 @@ void KeyMgmt::slotExportKeyToFile() void KeyMgmt::slotExportKeyToClipboard() { - QByteArray *keyArray = new QByteArray(); + auto *keyArray = new QByteArray(); QClipboard *cb = QApplication::clipboard(); if (!mCtx->exportKeys(mKeyList->getChecked(), keyArray)) { return; @@ -273,7 +275,7 @@ void KeyMgmt::slotExportKeyToClipboard() void KeyMgmt::slotGenerateKeyDialog() { - KeyGenDialog *keyGenDialog = new KeyGenDialog(mCtx,this); + auto *keyGenDialog = new KeyGenDialog(mCtx,this); keyGenDialog->show(); } diff --git a/src/keyserverimportdialog.cpp b/src/keyserverimportdialog.cpp index e581234a..c68851b4 100644 --- a/src/keyserverimportdialog.cpp +++ b/src/keyserverimportdialog.cpp @@ -22,9 +22,10 @@ #include "keyserverimportdialog.h" +#include <utility> + KeyServerImportDialog::KeyServerImportDialog(GpgME::GpgContext *ctx, KeyList *keyList, QWidget *parent) - : QDialog(parent) -{ + : QDialog(parent) { mCtx = ctx; mKeyList = keyList; // Buttons @@ -46,21 +47,21 @@ KeyServerImportDialog::KeyServerImportDialog(GpgME::GpgContext *ctx, KeyList *ke icon = new QLabel; // Layout for messagebox - QHBoxLayout *messageLayout= new QHBoxLayout; + auto *messageLayout = new QHBoxLayout; messageLayout->addWidget(icon); messageLayout->addWidget(message); messageLayout->addStretch(); // Layout for import and close button - QHBoxLayout *buttonsLayout = new QHBoxLayout; + auto *buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(); buttonsLayout->addWidget(importButton); buttonsLayout->addWidget(closeButton); - QGridLayout *mainLayout = new QGridLayout; + auto *mainLayout = new QGridLayout; mainLayout->addWidget(searchLabel, 1, 0); mainLayout->addWidget(searchLineEdit, 1, 1); - mainLayout->addWidget(searchButton,1, 2); + mainLayout->addWidget(searchButton, 1, 2); mainLayout->addWidget(keyServerLabel, 2, 0); mainLayout->addWidget(keyServerComboBox, 2, 1); mainLayout->addWidget(keysTable, 3, 0, 1, 3); @@ -73,16 +74,14 @@ KeyServerImportDialog::KeyServerImportDialog(GpgME::GpgContext *ctx, KeyList *ke this->setModal(true); } -QPushButton *KeyServerImportDialog::createButton(const QString &text, const char *member) -{ - QPushButton *button = new QPushButton(text); +QPushButton *KeyServerImportDialog::createButton(const QString &text, const char *member) { + auto *button = new QPushButton(text); connect(button, SIGNAL(clicked()), this, member); return button; } -QComboBox *KeyServerImportDialog::createComboBox() -{ - QComboBox *comboBox = new QComboBox; +QComboBox *KeyServerImportDialog::createComboBox() { + auto *comboBox = new QComboBox; comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); // Read keylist from ini-file and fill it into combobox @@ -96,8 +95,7 @@ QComboBox *KeyServerImportDialog::createComboBox() return comboBox; } -void KeyServerImportDialog::createKeysTable() -{ +void KeyServerImportDialog::createKeysTable() { keysTable = new QTableWidget(); keysTable->setColumnCount(4); @@ -109,41 +107,39 @@ void KeyServerImportDialog::createKeysTable() keysTable->setSelectionMode(QAbstractItemView::SingleSelection); QStringList labels; - labels << tr("UID") << tr("Creation date") << tr("KeyID") << tr("Tag"); + labels << tr("UID") << tr("Creation date") << tr("KeyID") << tr("Tag"); keysTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); keysTable->setHorizontalHeaderLabels(labels); keysTable->verticalHeader()->hide(); - connect(keysTable, SIGNAL(cellActivated(int,int)), + connect(keysTable, SIGNAL(cellActivated(int, int)), this, SLOT(slotImport())); } -void KeyServerImportDialog::setMessage(const QString &text, bool error) -{ +void KeyServerImportDialog::setMessage(const QString &text, bool error) { message->setText(text); if (error) { QIcon undoicon = QIcon::fromTheme("dialog-error"); - QPixmap pixmap = undoicon.pixmap(QSize(32,32),QIcon::Normal,QIcon::On); + QPixmap pixmap = undoicon.pixmap(QSize(32, 32), QIcon::Normal, QIcon::On); icon->setPixmap(pixmap); } else { QIcon undoicon = QIcon::fromTheme("dialog-information"); - QPixmap pixmap = undoicon.pixmap(QSize(32,32),QIcon::Normal,QIcon::On); + QPixmap pixmap = undoicon.pixmap(QSize(32, 32), QIcon::Normal, QIcon::On); icon->setPixmap(pixmap); } } -void KeyServerImportDialog::slotSearch() -{ - QUrl url = keyServerComboBox->currentText()+":11371/pks/lookup?search="+searchLineEdit->text()+"&op=index&options=mr"; +void KeyServerImportDialog::slotSearch() { + QUrl urlFromRemote = keyServerComboBox->currentText() + ":11371/pks/lookup?search=" + searchLineEdit->text() + + "&op=index&options=mr"; qnam = new QNetworkAccessManager(this); - QNetworkReply* reply = qnam->get(QNetworkRequest(url)); + QNetworkReply *reply = qnam->get(QNetworkRequest(urlFromRemote)); connect(reply, SIGNAL(finished()), this, SLOT(slotSearchFinished())); } -void KeyServerImportDialog::slotSearchFinished() -{ - QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); +void KeyServerImportDialog::slotSearchFinished() { + auto *reply = qobject_cast<QNetworkReply *>(sender()); keysTable->clearContents(); keysTable->setRowCount(0); @@ -151,72 +147,72 @@ void KeyServerImportDialog::slotSearchFinished() QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (reply->error()) { - setMessage(tr("Couldn't contact keyserver!"),true); + setMessage(tr("Couldn't contact keyserver!"), true); //setMessage(reply->error()); qDebug() << reply->error(); } - if (firstLine.contains("Error")) - { - QString text= QString(reply->readLine(1024)); + if (firstLine.contains("Error")) { + QString text = QString(reply->readLine(1024)); if (text.contains("Too many responses")) { - setMessage(tr("Too many responses from keyserver!"),true); + setMessage(tr("Too many responses from keyserver!"), true); } else if (text.contains("No keys found")) { // if string looks like hex string, search again with 0x prepended QRegExp rx("[0-9A-Fa-f]*"); QString query = searchLineEdit->text(); if (rx.exactMatch(query)) { - setMessage(tr("No keys found, input may be kexId, retrying search with 0x."),true); - searchLineEdit->setText(query.prepend("0x")); - this->slotSearch(); + setMessage(tr("No keys found, input may be kexId, retrying search with 0x."), true); + searchLineEdit->setText(query.prepend("0x")); + this->slotSearch(); } else { - setMessage(tr("No keys found containing the search string!"),true); + setMessage(tr("No keys found containing the search string!"), true); } } else if (text.contains("Insufficiently specific words")) { - setMessage(tr("Insufficiently specific search string!"),true); + setMessage(tr("Insufficiently specific search string!"), true); } else { setMessage(text, true); } } else { int row = 0; char buff[1024]; - bool strikeout=false; - while (reply->readLine(buff,sizeof(buff)) !=-1) { + bool strikeout = false; + while (reply->readLine(buff, sizeof(buff)) != -1) { QString decoded = QString::fromUtf8(QByteArray::fromPercentEncoding(buff)); QStringList line = decoded.split(":"); //TODO: have a look at two following pub lines if (line[0] == "pub") { - strikeout=false; + strikeout = false; - QString flags = line[line.size()-1]; + QString flags = line[line.size() - 1]; - keysTable->setRowCount(row+1); + keysTable->setRowCount(row + 1); // flags can be "d" for disabled, "r" for revoked // or "e" for expired if (flags.contains("r") or flags.contains("d") or flags.contains("e")) { - strikeout=true; + strikeout = true; if (flags.contains("e")) { - keysTable->setItem(row, 3, new QTableWidgetItem( QString("expired"))); + keysTable->setItem(row, 3, new QTableWidgetItem(QString("expired"))); } if (flags.contains("r")) { - keysTable->setItem(row, 3, new QTableWidgetItem( QString(tr("revoked")))); + keysTable->setItem(row, 3, new QTableWidgetItem(QString(tr("revoked")))); } if (flags.contains("d")) { - keysTable->setItem(row, 3, new QTableWidgetItem( QString(tr("disabled")))); + keysTable->setItem(row, 3, new QTableWidgetItem(QString(tr("disabled")))); } } QStringList line2 = QString(reply->readLine()).split(":"); - QTableWidgetItem *uid = new QTableWidgetItem(); + auto *uid = new QTableWidgetItem(); if (line2.size() > 1) { uid->setText(line2[1]); keysTable->setItem(row, 0, uid); } - QTableWidgetItem *creationdate = new QTableWidgetItem(QDateTime::fromTime_t(line[4].toInt()).toString("dd. MMM. yyyy")); + auto *creationdate = new QTableWidgetItem( + QDateTime::fromTime_t(line[4].toInt()).toString("dd. MMM. yyyy")); keysTable->setItem(row, 1, creationdate); - QTableWidgetItem *keyid = new QTableWidgetItem(line[1]); + auto *keyid = new QTableWidgetItem(line[1]); keysTable->setItem(row, 2, keyid); if (strikeout) { QFont strike = uid->font(); @@ -229,12 +225,12 @@ void KeyServerImportDialog::slotSearchFinished() } else { if (line[0] == "uid") { QStringList l; - int height=keysTable->rowHeight(row-1); - keysTable->setRowHeight(row-1,height+16); - QString tmp=keysTable->item(row-1,0)->text(); - tmp.append(QString("\n")+line[1]); - QTableWidgetItem *tmp1 = new QTableWidgetItem(tmp); - keysTable->setItem(row-1,0,tmp1); + int height = keysTable->rowHeight(row - 1); + keysTable->setRowHeight(row - 1, height + 16); + QString tmp = keysTable->item(row - 1, 0)->text(); + tmp.append(QString("\n") + line[1]); + auto *tmp1 = new QTableWidgetItem(tmp); + keysTable->setItem(row - 1, 0, tmp1); if (strikeout) { QFont strike = tmp1->font(); strike.setStrikeOut(true); @@ -242,72 +238,65 @@ void KeyServerImportDialog::slotSearchFinished() } } } - setMessage(tr("%1 keys found. Doubleclick a key to import it.").arg(row),false); + setMessage(tr("%1 keys found. Doubleclick a key to import it.").arg(row), false); } keysTable->resizeColumnsToContents(); } reply->deleteLater(); - reply = 0; } -void KeyServerImportDialog::slotImport() -{ - if ( keysTable->currentRow() > -1 ) { - QString keyid = keysTable->item(keysTable->currentRow(),2)->text(); - QUrl url = keyServerComboBox->currentText(); - slotImport(QStringList(keyid), url); - } +void KeyServerImportDialog::slotImport() { + if (keysTable->currentRow() > -1) { + QString keyid = keysTable->item(keysTable->currentRow(), 2)->text(); + slotImport(QStringList(keyid), keyServerComboBox->currentText()); + } } -void KeyServerImportDialog::slotImport(QStringList keyIds) -{ +void KeyServerImportDialog::slotImport(QStringList keyIds) { QSettings settings; - QString keyserver=settings.value("keyserver/defaultKeyServer").toString(); - QUrl url(keyserver); - slotImport(keyIds, url); + QString keyserver = settings.value("keyserver/defaultKeyServer").toString();; + slotImport(std::move(keyIds), QUrl(keyserver)); } -void KeyServerImportDialog::slotImport(QStringList keyIds, QUrl keyServerUrl) -{ - foreach(QString keyId, keyIds) { - QUrl reqUrl(keyServerUrl.scheme() + "://" + keyServerUrl.host() + ":11371/pks/lookup?op=get&search=0x"+keyId+"&options=mr"); - //qDebug() << "req to " << reqUrl; - qnam = new QNetworkAccessManager(this); - QNetworkReply *reply = qnam->get(QNetworkRequest(reqUrl)); - connect(reply, SIGNAL(finished()), - this, SLOT(slotImportFinished())); - } +void KeyServerImportDialog::slotImport(QStringList keyIds, const QUrl &keyServerUrl) { + foreach(QString keyId, keyIds) { + QUrl reqUrl( + keyServerUrl.scheme() + "://" + keyServerUrl.host() + ":11371/pks/lookup?op=get&search=0x" + keyId + + "&options=mr"); + //qDebug() << "req to " << reqUrl; + qnam = new QNetworkAccessManager(this); + QNetworkReply *reply = qnam->get(QNetworkRequest(reqUrl)); + connect(reply, SIGNAL(finished()), + this, SLOT(slotImportFinished())); + } } -void KeyServerImportDialog::slotImportFinished() -{ - QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); +void KeyServerImportDialog::slotImportFinished() { + auto *reply = qobject_cast<QNetworkReply *>(sender()); QByteArray key = reply->readAll(); QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (reply->error()) { - setMessage(tr("Error while contacting keyserver!"),true); + setMessage(tr("Error while contacting keyserver!"), true); return; } this->importKeys(key.constData()); - setMessage(tr("Key imported"),false); + setMessage(tr("Key imported"), false); // Add keyserver to list in config-file, if it isn't contained QSettings settings; QStringList keyServerList = settings.value("keyserver/keyServerList").toStringList(); - if (!keyServerList.contains(keyServerComboBox->currentText())) - { + if (!keyServerList.contains(keyServerComboBox->currentText())) { keyServerList.append(keyServerComboBox->currentText()); settings.setValue("keyserver/keyServerList", keyServerList); } reply->deleteLater(); - reply = 0; + reply = nullptr; } -void KeyServerImportDialog::importKeys(QByteArray inBuffer) -{ - GpgImportInformation result = mCtx->importKey(inBuffer); +void KeyServerImportDialog::importKeys(QByteArray inBuffer) { + GpgImportInformation result = mCtx->importKey(std::move(inBuffer)); new KeyImportDetailDialog(mCtx, result, this); } diff --git a/src/main.cpp b/src/main.cpp index 0fbdef1b..846f4143 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -19,12 +19,10 @@ * along with gpg4usb. If not, see <http://www.gnu.org/licenses/> */ -#include <QApplication> #include "mainwindow.h" #include "gpgconstants.h" -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { Q_INIT_RESOURCE(gpg4usb); @@ -33,11 +31,11 @@ int main(int argc, char *argv[]) // get application path QString appPath = qApp->applicationDirPath(); - app.setApplicationVersion("0.3.3"); - app.setApplicationName("gpg4usb"); + QApplication::setApplicationVersion("0.3.3"); + QApplication::setApplicationName("gpg4usb"); // dont show icons in menus - app.setAttribute(Qt::AA_DontShowIconsInMenus); + QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); // unicode in source QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8")); @@ -46,23 +44,23 @@ int main(int argc, char *argv[]) // TODO: // - unsetenv on windows? // - wputenv or wputenv_s on windows? http://msdn.microsoft.com/en-us/library/d6dtz42k(v=vs.80).aspx - #ifndef _WIN32 - // do not use GPG_AGENTS like seahorse, because they may save - // a password an pc's not owned by user - unsetenv("GPG_AGENT_INFO"); - #endif +#ifndef _WIN32 + // do not use GPG_AGENTS like seahorse, because they may save + // a password an pc's not owned by user + unsetenv("GPG_AGENT_INFO"); +#endif // qDebug() << getenv("GNUPGHOME"); #ifndef GPG4USB_NON_PORTABLE // take care of gpg not creating directorys on harddisk putenv(QString("GNUPGHOME=" + appPath + "/keydb").toUtf8().data()); - + // this may help with newer gpgme versions on windows //putenv(QString("GPGME_GPGPATH=" + appPath.replace("/", "\\") + "\\bin\\gpg.exe").toUtf8().data()); // QSettings uses org-name for automatically setting path... - app.setOrganizationName("conf"); + QApplication::setOrganizationName("conf"); // specify default path & format for QSettings QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, appPath); @@ -94,27 +92,27 @@ int main(int argc, char *argv[]) int return_from_event_loop_code; do { - app.removeTranslator(&translator); - app.removeTranslator(&translator2); + QApplication::removeTranslator(&translator); + QApplication::removeTranslator(&translator2); QString lang = settings.value("int/lang", QLocale::system().name()).toString(); if (lang.isEmpty()) { lang = QLocale::system().name(); } - translator.load("ts/gpg4usb_" + lang, appPath); - app.installTranslator(&translator); + translator.load("ts/gpg4usb_" + lang, appPath); + QApplication::installTranslator(&translator); // set qt translations translator2.load("ts/qt_" + lang, appPath); - app.installTranslator(&translator2); + QApplication::installTranslator(&translator2); MainWindow window; - return_from_event_loop_code = app.exec(); + return_from_event_loop_code = QApplication::exec(); - } while( return_from_event_loop_code == RESTART_CODE); + } while (return_from_event_loop_code == RESTART_CODE); - return return_from_event_loop_code; + return return_from_event_loop_code; } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index b43cedcd..81703cd9 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -21,8 +21,7 @@ #include "mainwindow.h" -MainWindow::MainWindow() -{ +MainWindow::MainWindow() { mCtx = new GpgME::GpgContext(); /* get path were app was started */ @@ -44,7 +43,7 @@ MainWindow::MainWindow() keyMgmt = new KeyMgmt(mCtx, this); keyMgmt->hide(); /* test attachmentdir for files alll 15s */ - QTimer *timer = new QTimer(this); + auto *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(slotCheckAttachmentFolder())); timer->start(5000); @@ -54,7 +53,7 @@ MainWindow::MainWindow() createStatusBar(); createDockWindows(); - connect(edit->tabWidget,SIGNAL(currentChanged(int)),this,SLOT(slotDisableTabActions(int))); + connect(edit->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(slotDisableTabActions(int))); mKeyList->addMenuAction(appendSelectedKeysAct); mKeyList->addMenuAction(copyMailAddressToClipboardAct); @@ -78,14 +77,13 @@ MainWindow::MainWindow() // Show wizard, if the don't show wizard message box wasn't checked // and keylist doesn't contain a private key - QSettings settings; - if (settings.value("wizard/showWizard",true).toBool() || !settings.value("wizard/nextPage").isNull()) { + QSettings qSettings; + if (qSettings.value("wizard/showWizard", true).toBool() || !qSettings.value("wizard/nextPage").isNull()) { slotStartWizard(); } } -void MainWindow::restoreSettings() -{ +void MainWindow::restoreSettings() { // state sets pos & size of dock-widgets this->restoreState(settings.value("window/windowState").toByteArray()); @@ -120,7 +118,8 @@ void MainWindow::restoreSettings() settings.setValue("keyserver/defaultKeyServer", defaultKeyServer); // Iconstyle - Qt::ToolButtonStyle buttonStyle = static_cast<Qt::ToolButtonStyle>(settings.value("toolbar/iconstyle", Qt::ToolButtonTextUnderIcon).toUInt()); + Qt::ToolButtonStyle buttonStyle = static_cast<Qt::ToolButtonStyle>(settings.value("toolbar/iconstyle", + Qt::ToolButtonTextUnderIcon).toUInt()); this->setToolButtonStyle(buttonStyle); importButton->setToolButtonStyle(buttonStyle); fileEncButton->setToolButtonStyle(buttonStyle); @@ -132,8 +131,7 @@ void MainWindow::restoreSettings() } } -void MainWindow::saveSettings() -{ +void MainWindow::saveSettings() { // window position and size settings.setValue("window/windowState", saveState()); settings.setValue("window/pos", pos()); @@ -147,20 +145,19 @@ void MainWindow::saveSettings() } else { settings.setValue("keys/keyList", ""); } - } else { + } else { settings.remove("keys/keyList"); } } -void MainWindow::createActions() -{ +void MainWindow::createActions() { /* Main Menu */ newTabAct = new QAction(tr("&New"), this); newTabAct->setIcon(QIcon(":misc_doc.png")); QList<QKeySequence> newTabActShortcutList; - newTabActShortcutList.append(QKeySequence (Qt::CTRL + Qt::Key_N)); - newTabActShortcutList.append(QKeySequence (Qt::CTRL + Qt::Key_T)); + newTabActShortcutList.append(QKeySequence(Qt::CTRL + Qt::Key_N)); + newTabActShortcutList.append(QKeySequence(Qt::CTRL + Qt::Key_T)); newTabAct->setShortcuts(newTabActShortcutList); newTabAct->setToolTip(tr("Open a new file")); connect(newTabAct, SIGNAL(triggered()), edit, SLOT(slotNewTab())); @@ -177,7 +174,7 @@ void MainWindow::createActions() saveAct->setToolTip(tr("Save the current File")); connect(saveAct, SIGNAL(triggered()), edit, SLOT(slotSave())); - saveAsAct = new QAction(tr("Save &As")+"...", this); + saveAsAct = new QAction(tr("Save &As") + "...", this); saveAsAct->setIcon(QIcon(":filesaveas.png")); saveAsAct->setShortcut(QKeySequence::SaveAs); saveAsAct->setToolTip(tr("Save the current File as...")); @@ -345,7 +342,7 @@ void MainWindow::createActions() openTranslateAct->setToolTip(tr("Translate gpg4usb yourself")); connect(openTranslateAct, SIGNAL(triggered()), this, SLOT(slotOpenTranslate())); - startWizardAct= new QAction(tr("Open &Wizard"), this); + startWizardAct = new QAction(tr("Open &Wizard"), this); startWizardAct->setToolTip(tr("Open the wizard")); connect(startWizardAct, SIGNAL(triggered()), this, SLOT(slotStartWizard())); @@ -371,8 +368,8 @@ void MainWindow::createActions() uploadKeyToServerAct = new QAction(tr("Upload Key(s) To Server"), this); uploadKeyToServerAct->setToolTip(tr("Upload The Selected Keys To Server")); connect(uploadKeyToServerAct, SIGNAL(triggered()), this, SLOT(uploadKeyToServer())); - /* Key-Shortcuts for Tab-Switchung-Action - */ + /* Key-Shortcuts for Tab-Switchung-Action + */ switchTabUpAct = new QAction(this); switchTabUpAct->setShortcut(QKeySequence::NextChild); connect(switchTabUpAct, SIGNAL(triggered()), edit, SLOT(slotSwitchTabUp())); @@ -390,14 +387,13 @@ void MainWindow::createActions() connect(addPgpHeaderAct, SIGNAL(triggered()), this, SLOT(slotAddPgpHeader())); } -void MainWindow::slotDisableTabActions(int number) -{ +void MainWindow::slotDisableTabActions(int number) { bool disable; - if (number == -1 ) { + if (number == -1) { disable = true; } else { - disable= false; + disable = false; } printAct->setDisabled(disable); saveAct->setDisabled(disable); @@ -427,8 +423,7 @@ void MainWindow::slotDisableTabActions(int number) addPgpHeaderAct->setDisabled(disable); } -void MainWindow::createMenus() -{ +void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(newTabAct); fileMenu->addAction(openAct); @@ -489,7 +484,7 @@ void MainWindow::createMenus() steganoMenu->addAction(addPgpHeaderAct); // Hide menu, when steganography menu is disabled in settings - if(!settings.value("advanced/steganography").toBool()) { + if (!settings.value("advanced/steganography").toBool()) { this->menuBar()->removeAction(steganoMenu->menuAction()); } @@ -506,8 +501,7 @@ void MainWindow::createMenus() } -void MainWindow::createToolBars() -{ +void MainWindow::createToolBars() { fileToolBar = addToolBar(tr("File")); fileToolBar->setObjectName("fileToolBar"); fileToolBar->addAction(newTabAct); @@ -564,10 +558,9 @@ void MainWindow::createToolBars() } -void MainWindow::createStatusBar() -{ - QWidget *statusBarBox = new QWidget(); - QHBoxLayout *statusBarBoxLayout = new QHBoxLayout(); +void MainWindow::createStatusBar() { + auto *statusBarBox = new QWidget(); + auto *statusBarBoxLayout = new QHBoxLayout(); QPixmap *pixmap; // icon which should be shown if there are files in attachments-folder @@ -576,14 +569,13 @@ void MainWindow::createStatusBar() statusBar()->addWidget(statusBarIcon); statusBarIcon->setPixmap(*pixmap); - statusBar()->insertPermanentWidget(0,statusBarIcon,0); + statusBar()->insertPermanentWidget(0, statusBarIcon, 0); statusBarIcon->hide(); - statusBar()->showMessage(tr("Ready"),2000); + statusBar()->showMessage(tr("Ready"), 2000); statusBarBox->setLayout(statusBarBoxLayout); } -void MainWindow::createDockWindows() -{ +void MainWindow::createDockWindows() { /* KeyList-Dockwindow */ keylistDock = new QDockWidget(tr("Encrypt for:"), this); @@ -595,7 +587,7 @@ void MainWindow::createDockWindows() /* Attachments-Dockwindow */ - if(settings.value("mime/parseMime").toBool()) { + if (settings.value("mime/parseMime").toBool()) { createAttachmentDock(); } } @@ -625,8 +617,7 @@ void MainWindow::closeAttachmentDock() { attachmentDockCreated = false; } -void MainWindow::closeEvent(QCloseEvent *event) -{ +void MainWindow::closeEvent(QCloseEvent *event) { /* * ask to save changes, if there are * modified documents in any tab @@ -642,18 +633,15 @@ void MainWindow::closeEvent(QCloseEvent *event) mCtx->clearPasswordCache(); } -void MainWindow::slotAbout() -{ +void MainWindow::slotAbout() { new AboutDialog(this); } -void MainWindow::slotOpenTranslate() -{ +void MainWindow::slotOpenTranslate() { QDesktopServices::openUrl(QUrl("http://gpg4usb.cpunk.de/docu_translate.html")); } -void MainWindow::slotOpenTutorial() -{ +void MainWindow::slotOpenTutorial() { QDesktopServices::openUrl(QUrl("http://gpg4usb.cpunk.de/docu.html")); } @@ -661,19 +649,16 @@ void MainWindow::slotOpenHelp() { slotOpenHelp("docu.html"); } -void MainWindow::slotOpenHelp(const QString page) -{ +void MainWindow::slotOpenHelp(const QString &page) { edit->slotNewHelpTab("help", "file:" + qApp->applicationDirPath() + "/help/" + page); } -void MainWindow::slotSetStatusBarText(QString text) -{ - statusBar()->showMessage(text,20000); +void MainWindow::slotSetStatusBarText(const QString &text) { + statusBar()->showMessage(text, 20000); } -void MainWindow::slotStartWizard() -{ - Wizard *wizard = new Wizard(mCtx,keyMgmt,this); +void MainWindow::slotStartWizard() { + auto *wizard = new Wizard(mCtx, keyMgmt, this); wizard->show(); wizard->setModal(true); } @@ -682,8 +667,7 @@ void MainWindow::slotStartWizard() * if this is mime, split text and attachments... * message contains only text afterwards */ -void MainWindow::parseMime(QByteArray *message) -{ +void MainWindow::parseMime(QByteArray *message) { /*if (! Mime::isMultipart(message)) { qDebug() << "no multipart"; return; @@ -694,22 +678,22 @@ void MainWindow::parseMime(QByteArray *message) bool showmadock = false; Mime *mime = new Mime(message); - foreach(MimePart tmp, mime->parts()) { - if (tmp.header.getValue("Content-Type") == "text/plain" + foreach(MimePart tmp, mime->parts()) { + if (tmp.header.getValue("Content-Type") == "text/plain" && tmp.header.getValue("Content-Transfer-Encoding") != "base64") { - QByteArray body; - if (tmp.header.getValue("Content-Transfer-Encoding") == "quoted-printable") { - Mime::quotedPrintableDecode(tmp.body, body); + QByteArray body; + if (tmp.header.getValue("Content-Transfer-Encoding") == "quoted-printable") { + Mime::quotedPrintableDecode(tmp.body, body); + } else { + body = tmp.body; + } + pText.append(QString(body)); } else { - body = tmp.body; + (mAttachments->addMimePart(&tmp)); + showmadock = true; } - pText.append(QString(body)); - } else { - (mAttachments->addMimePart(&tmp)); - showmadock = true; } - } *message = pText.toUtf8(); if (showmadock) { attachmentDock->show(); @@ -718,19 +702,19 @@ void MainWindow::parseMime(QByteArray *message) void MainWindow::slotCheckAttachmentFolder() { // TODO: always check? - if(!settings.value("mime/parseMime").toBool()) { + if (!settings.value("mime/parseMime").toBool()) { return; } QString attachmentDir = qApp->applicationDirPath() + "/attachments/"; // filenum minus . and .. - int filenum = QDir(attachmentDir).count() - 2 ; - if(filenum > 0) { + uint filenum = QDir(attachmentDir).count() - 2; + if (filenum > 0) { QString statusText; - if(filenum == 1) { + if (filenum == 1) { statusText = tr("There is one unencrypted file in attachment folder"); } else { - statusText = tr("There are ") + QString::number(filenum) + tr(" unencrypted files in attachment folder"); + statusText = tr("There are ") + QString::number(filenum) + tr(" unencrypted files in attachment folder"); } statusBarIcon->setStatusTip(statusText); statusBarIcon->show(); @@ -739,64 +723,59 @@ void MainWindow::slotCheckAttachmentFolder() { } } -void MainWindow::slotImportKeyFromEdit() -{ - if (edit->tabCount()==0 || edit->slotCurPage() == 0) { +void MainWindow::slotImportKeyFromEdit() { + if (edit->tabCount() == 0 || edit->slotCurPage() == 0) { return; } keyMgmt->slotImportKeys(edit->curTextPage()->toPlainText().toUtf8()); } -void MainWindow::slotOpenKeyManagement() -{ +void MainWindow::slotOpenKeyManagement() { keyMgmt->show(); keyMgmt->raise(); keyMgmt->activateWindow(); } -void MainWindow::slotEncrypt() -{ - if (edit->tabCount()==0 || edit->slotCurPage() == 0) { +void MainWindow::slotEncrypt() { + if (edit->tabCount() == 0 || edit->slotCurPage() == nullptr) { return; } QStringList *uidList = mKeyList->getChecked(); - QByteArray *tmp = new QByteArray(); + auto *tmp = new QByteArray(); if (mCtx->encrypt(uidList, edit->curTextPage()->toPlainText().toUtf8(), tmp)) { - QString *tmp2 = new QString(*tmp); + auto *tmp2 = new QString(*tmp); edit->slotFillTextEditWithText(*tmp2); } } -void MainWindow::slotSign() -{ - if (edit->tabCount()==0 || edit->slotCurPage() == 0) { +void MainWindow::slotSign() { + if (edit->tabCount() == 0 || edit->slotCurPage() == nullptr) { return; } QStringList *uidList = mKeyList->getPrivateChecked(); - QByteArray *tmp = new QByteArray(); + auto *tmp = new QByteArray(); if (mCtx->sign(uidList, edit->curTextPage()->toPlainText().toUtf8(), tmp)) { edit->slotFillTextEditWithText(QString::fromUtf8(*tmp)); } } -void MainWindow::slotDecrypt() -{ - if (edit->tabCount()== 0 || edit->slotCurPage() == 0) { +void MainWindow::slotDecrypt() { + if (edit->tabCount() == 0 || edit->slotCurPage() == 0) { return; } - QByteArray *decrypted = new QByteArray(); - QByteArray text = edit->curTextPage()->toPlainText().toUtf8(); // TODO: toUtf8() here? - mCtx->preventNoDataErr(&text); + auto *decrypted = new QByteArray(); + QByteArray text = edit->curTextPage()->toPlainText().toUtf8(); + GpgME::GpgContext::preventNoDataErr(&text); // try decrypt, if fail do nothing, especially don't replace text - if(!mCtx->decrypt(text, decrypted)) { + if (!mCtx->decrypt(text, decrypted)) { return; } @@ -805,16 +784,16 @@ void MainWindow::slotDecrypt() * 2) parse header * 2) choose action depending on content-type */ - if(Mime::isMime(decrypted)) { + if (Mime::isMime(decrypted)) { Header header = Mime::getHeader(decrypted); // is it multipart, is multipart-parsing enabled - if(header.getValue("Content-Type") == "multipart/mixed" - && settings.value("mime/parseMime").toBool()) { + if (header.getValue("Content-Type") == "multipart/mixed" + && settings.value("mime/parseMime").toBool()) { parseMime(decrypted); - } else if(header.getValue("Content-Type") == "text/plain" - && settings.value("mime/parseQP").toBool()){ + } else if (header.getValue("Content-Type") == "text/plain" + && settings.value("mime/parseQP").toBool()) { if (header.getValue("Content-Transfer-Encoding") == "quoted-printable") { - QByteArray *decoded = new QByteArray(); + auto *decoded = new QByteArray(); Mime::quotedPrintableDecode(*decrypted, *decoded); //TODO: remove header decrypted = decoded; @@ -824,23 +803,21 @@ void MainWindow::slotDecrypt() edit->slotFillTextEditWithText(QString::fromUtf8(*decrypted)); } -void MainWindow::slotFind() -{ - if (edit->tabCount()==0 || edit->curTextPage() == 0) { +void MainWindow::slotFind() { + if (edit->tabCount() == 0 || edit->curTextPage() == nullptr) { return; } // At first close verifynotification, if existing edit->slotCurPage()->closeNoteByClass("findwidget"); - FindWidget *fw = new FindWidget(this,edit->curTextPage()); + auto *fw = new FindWidget(this, edit->curTextPage()); edit->slotCurPage()->showNotificationWidget(fw, "findWidget"); } -void MainWindow::slotVerify() -{ - if (edit->tabCount()==0 || edit->slotCurPage() == 0) { +void MainWindow::slotVerify() { + if (edit->tabCount() == 0 || edit->slotCurPage() == 0) { return; } @@ -848,7 +825,7 @@ void MainWindow::slotVerify() edit->slotCurPage()->closeNoteByClass("verifyNotification"); // create new verfiy notification - VerifyNotification *vn = new VerifyNotification(this, mCtx, mKeyList, edit->curTextPage()); + auto *vn = new VerifyNotification(this, mCtx, mKeyList, edit->curTextPage()); // if signing information is found, show the notification, otherwise close it if (vn->slotRefresh()) { @@ -861,19 +838,17 @@ void MainWindow::slotVerify() /* * Append the selected (not checked!) Key(s) To Textedit */ -void MainWindow::slotAppendSelectedKeys() -{ - if (edit->tabCount()==0 || edit->slotCurPage() == 0) { +void MainWindow::slotAppendSelectedKeys() { + if (edit->tabCount() == 0 || edit->slotCurPage() == 0) { return; } - QByteArray *keyArray = new QByteArray(); + auto *keyArray = new QByteArray(); mCtx->exportKeys(mKeyList->getSelected(), keyArray); edit->curTextPage()->append(*keyArray); } -void MainWindow::slotCopyMailAddressToClipboard() -{ +void MainWindow::slotCopyMailAddressToClipboard() { if (mKeyList->getSelected()->isEmpty()) { return; } @@ -884,8 +859,7 @@ void MainWindow::slotCopyMailAddressToClipboard() cb->setText(mail); } -void MainWindow::slotShowKeyDetails() -{ +void MainWindow::slotShowKeyDetails() { if (mKeyList->getSelected()->isEmpty()) { return; } @@ -895,55 +869,49 @@ void MainWindow::slotShowKeyDetails() new KeyDetailsDialog(mCtx, key, this); } } -void MainWindow::refreshKeysFromKeyserver() -{ + +void MainWindow::refreshKeysFromKeyserver() { if (mKeyList->getSelected()->isEmpty()) { return; } - KeyServerImportDialog *ksid = new KeyServerImportDialog(mCtx,mKeyList,this); + auto *ksid = new KeyServerImportDialog(mCtx, mKeyList, this); ksid->slotImport(*mKeyList->getSelected()); } -void MainWindow::uploadKeyToServer() -{ - QByteArray *keyArray = new QByteArray(); +void MainWindow::uploadKeyToServer() { + auto *keyArray = new QByteArray(); mCtx->exportKeys(mKeyList->getSelected(), keyArray); mKeyList->uploadKeyToServer(keyArray); } -void MainWindow::slotFileEncrypt() -{ - QStringList *keyList; - keyList = mKeyList->getChecked(); - new FileEncryptionDialog(mCtx, *keyList, FileEncryptionDialog::Encrypt, this); +void MainWindow::slotFileEncrypt() { + QStringList *keyList; + keyList = mKeyList->getChecked(); + new FileEncryptionDialog(mCtx, *keyList, FileEncryptionDialog::Encrypt, this); } -void MainWindow::slotFileDecrypt() -{ - QStringList *keyList; - keyList = mKeyList->getChecked(); - new FileEncryptionDialog(mCtx, *keyList, FileEncryptionDialog::Decrypt, this); +void MainWindow::slotFileDecrypt() { + QStringList *keyList; + keyList = mKeyList->getChecked(); + new FileEncryptionDialog(mCtx, *keyList, FileEncryptionDialog::Decrypt, this); } -void MainWindow::slotFileSign() -{ - QStringList *keyList; - keyList = mKeyList->getChecked(); - new FileEncryptionDialog(mCtx, *keyList, FileEncryptionDialog::Sign, this); +void MainWindow::slotFileSign() { + QStringList *keyList; + keyList = mKeyList->getChecked(); + new FileEncryptionDialog(mCtx, *keyList, FileEncryptionDialog::Sign, this); } -void MainWindow::slotFileVerify() -{ - QStringList *keyList; - keyList = mKeyList->getChecked(); - new FileEncryptionDialog(mCtx, *keyList, FileEncryptionDialog::Verify, this); +void MainWindow::slotFileVerify() { + QStringList *keyList; + keyList = mKeyList->getChecked(); + new FileEncryptionDialog(mCtx, *keyList, FileEncryptionDialog::Verify, this); } -void MainWindow::slotOpenSettingsDialog() -{ +void MainWindow::slotOpenSettingsDialog() { QString preLang = settings.value("int/lang").toString(); QString preKeydbPath = settings.value("gpgpaths/keydbpath").toString(); @@ -956,28 +924,29 @@ void MainWindow::slotOpenSettingsDialog() fileEncButton->setIconSize(iconSize); // Iconstyle - Qt::ToolButtonStyle buttonStyle = static_cast<Qt::ToolButtonStyle>(settings.value("toolbar/iconstyle", Qt::ToolButtonTextUnderIcon).toUInt()); + Qt::ToolButtonStyle buttonStyle = static_cast<Qt::ToolButtonStyle>(settings.value("toolbar/iconstyle", + Qt::ToolButtonTextUnderIcon).toUInt()); this->setToolButtonStyle(buttonStyle); importButton->setToolButtonStyle(buttonStyle); fileEncButton->setToolButtonStyle(buttonStyle); // Mime-settings - if(settings.value("mime/parseMime").toBool()) { + if (settings.value("mime/parseMime").toBool()) { createAttachmentDock(); - } else if(attachmentDockCreated) { + } else if (attachmentDockCreated) { closeAttachmentDock(); } // restart mainwindow if necessary - if(getRestartNeeded()) { - if(edit->maybeSaveAnyTab()) { + if (getRestartNeeded()) { + if (edit->maybeSaveAnyTab()) { saveSettings(); qApp->exit(RESTART_CODE); } } // steganography hide/show - if(!settings.value("advanced/steganography").toBool()) { + if (!settings.value("advanced/steganography").toBool()) { this->menuBar()->removeAction(steganoMenu->menuAction()); } else { this->menuBar()->insertAction(viewMenu->menuAction(), steganoMenu->menuAction()); @@ -985,9 +954,8 @@ void MainWindow::slotOpenSettingsDialog() } -void MainWindow::slotCleanDoubleLinebreaks() -{ - if (edit->tabCount()==0 || edit->slotCurPage() == 0) { +void MainWindow::slotCleanDoubleLinebreaks() { + if (edit->tabCount() == 0 || edit->slotCurPage() == nullptr) { return; } @@ -997,7 +965,7 @@ void MainWindow::slotCleanDoubleLinebreaks() } void MainWindow::slotAddPgpHeader() { - if (edit->tabCount()==0 || edit->slotCurPage() == 0) { + if (edit->tabCount() == 0 || edit->slotCurPage() == nullptr) { return; } @@ -1011,7 +979,7 @@ void MainWindow::slotAddPgpHeader() { void MainWindow::slotCutPgpHeader() { - if (edit->tabCount()==0 || edit->slotCurPage() == 0) { + if (edit->tabCount() == 0 || edit->slotCurPage() == nullptr) { return; } @@ -1019,13 +987,13 @@ void MainWindow::slotCutPgpHeader() { int start = content.indexOf(GpgConstants::PGP_CRYPT_BEGIN); int end = content.indexOf(GpgConstants::PGP_CRYPT_END); - if(start < 0 || end < 0) { + if (start < 0 || end < 0) { return; } // remove head - int headEnd = content.indexOf("\n\n", start) + 2 ; - content.remove(start, headEnd-start); + int headEnd = content.indexOf("\n\n", start) + 2; + content.remove(start, headEnd - start); // remove tail end = content.indexOf(GpgConstants::PGP_CRYPT_END); @@ -1034,12 +1002,10 @@ void MainWindow::slotCutPgpHeader() { edit->slotFillTextEditWithText(content.trimmed()); } -void MainWindow::slotSetRestartNeeded(bool needed) -{ +void MainWindow::slotSetRestartNeeded(bool needed) { this->restartNeeded = needed; } -bool MainWindow::getRestartNeeded() -{ +bool MainWindow::getRestartNeeded() const { return this->restartNeeded; } diff --git a/src/mime.cpp b/src/mime.cpp index 51e6a8cb..98caf3e0 100644 --- a/src/mime.cpp +++ b/src/mime.cpp @@ -33,8 +33,7 @@ #include "mime.h" -Mime::Mime(QByteArray *message) -{ +Mime::Mime(QByteArray *message) { splitParts(message); /* mMessage = message; @@ -78,40 +77,36 @@ Mime::Mime(QByteArray *message) } Mime::~Mime() -{ += default; -} - -void Mime::splitParts(QByteArray *message) -{ +void Mime::splitParts(QByteArray *message) { int pos1, pos2, headEnd; MimePart p_tmp; // find the boundary - pos1 = message->indexOf("boundary=\"") + 10 ; + pos1 = message->indexOf("boundary=\"") + 10; pos2 = message->indexOf("\"\n", pos1); QByteArray boundary = message->mid(pos1, pos2 - pos1); //qDebug() << "boundary: " << boundary; while (pos2 > pos1) { - pos1 = message->indexOf(boundary, pos2) + boundary.length() + 1 ; + pos1 = message->indexOf(boundary, pos2) + boundary.length() + 1; headEnd = message->indexOf("\n\n", pos1); if (headEnd < 0) break; - QByteArray header = message->mid(pos1 , headEnd - pos1); + QByteArray header = message->mid(pos1, headEnd - pos1); p_tmp.header = parseHeader(&header); pos2 = message->indexOf(boundary, headEnd); - p_tmp.body = message->mid(headEnd , pos2 - headEnd); + p_tmp.body = message->mid(headEnd, pos2 - headEnd); mPartList.append(p_tmp); } } -Header Mime::parseHeader(QByteArray *header) -{ +Header Mime::parseHeader(QByteArray *header) { QList<HeadElem> ret; @@ -122,25 +117,25 @@ Header Mime::parseHeader(QByteArray *header) header->replace("\n ", " "); //split header at newlines - foreach(QByteArray line , header->split(* "\n")) { - HeadElem elem; - //split lines at : - QList<QByteArray> tmp2 = line.split(* ":"); - elem.name = tmp2[0].trimmed(); - if (tmp2[1].contains(';')) { - // split lines at ; - // TODO: what if ; is inside "" - QList<QByteArray> tmp3 = tmp2[1].split(* ";"); - elem.value = QString(tmp3.takeFirst().trimmed()); - foreach(QByteArray tmp4, tmp3) { - QList<QByteArray> tmp5 = tmp4.split(* "="); - elem.params.insert(QString(tmp5[0].trimmed()), QString(tmp5[1].trimmed())); + foreach(QByteArray line, header->split(*"\n")) { + HeadElem elem; + //split lines at : + QList<QByteArray> tmp2 = line.split(*":"); + elem.name = tmp2[0].trimmed(); + if (tmp2[1].contains(';')) { + // split lines at ; + // TODO: what if ; is inside "" + QList<QByteArray> tmp3 = tmp2[1].split(*";"); + elem.value = QString(tmp3.takeFirst().trimmed()); + foreach(QByteArray tmp4, tmp3) { + QList<QByteArray> tmp5 = tmp4.split(*"="); + elem.params.insert(QString(tmp5[0].trimmed()), QString(tmp5[1].trimmed())); + } + } else { + elem.value = tmp2[1].trimmed(); } - } else { - elem.value = tmp2[1].trimmed(); + ret.append(elem); } - ret.append(elem); - } return Header(ret); } @@ -150,8 +145,7 @@ Header Mime::getHeader(const QByteArray *message) { return parseHeader(&header); } -[[maybe_unused]] bool Mime::isMultipart(QByteArray *message) -{ +[[maybe_unused]] bool Mime::isMultipart(QByteArray *message) { return message->startsWith("Content-Type: multipart/mixed;"); } @@ -159,8 +153,7 @@ Header Mime::getHeader(const QByteArray *message) { * if Content-Type is specified, it should be mime * */ -bool Mime::isMime(const QByteArray *message) -{ +bool Mime::isMime(const QByteArray *message) { return message->startsWith("Content-Type:"); } @@ -173,28 +166,30 @@ bool Mime::isMime(const QByteArray *message) */ static const char hexChars[16] = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /******************************** KCodecs ********************************/ // strchr(3) for broken systems. -static int rikFindChar(register const char * _s, const char c) -{ - register const char * s = _s; +static int rikFindChar(const char *_s, const char c) { + const char *s = _s; while (true) { - if ((0 == *s) || (c == *s)) break; ++s; - if ((0 == *s) || (c == *s)) break; ++s; - if ((0 == *s) || (c == *s)) break; ++s; - if ((0 == *s) || (c == *s)) break; ++s; + if ((0 == *s) || (c == *s)) break; + ++s; + if ((0 == *s) || (c == *s)) break; + ++s; + if ((0 == *s) || (c == *s)) break; + ++s; + if ((0 == *s) || (c == *s)) break; + ++s; } - return s - _s; + return static_cast<int>(s - _s); } -void Mime::quotedPrintableDecode(const QByteArray& in, QByteArray& out) -{ +void Mime::quotedPrintableDecode(const QByteArray &in, QByteArray &out) { // clear out the output buffer out.resize(0); if (in.isEmpty()) @@ -202,10 +197,10 @@ void Mime::quotedPrintableDecode(const QByteArray& in, QByteArray& out) char *cursor; const char *data; - const unsigned int length = in.size(); + const size_t length = in.size(); data = in.data(); - out.resize(length); + out.resize(static_cast<int>(length)); cursor = out.data(); for (unsigned int i = 0; i < length; i++) { @@ -239,5 +234,5 @@ void Mime::quotedPrintableDecode(const QByteArray& in, QByteArray& out) } } - out.truncate(cursor - out.data()); + out.truncate(static_cast<int>(cursor - out.data())); } diff --git a/src/quitdialog.cpp b/src/quitdialog.cpp index e32369b8..a26dab6a 100755 --- a/src/quitdialog.cpp +++ b/src/quitdialog.cpp @@ -22,17 +22,16 @@ #include "quitdialog.h" -QuitDialog::QuitDialog(QWidget *parent, QHash<int, QString> unsavedDocs) - : QDialog(parent) -{ +QuitDialog::QuitDialog(QWidget *parent, const QHash<int, QString>& unsavedDocs) + : QDialog(parent) { setWindowTitle(tr("Unsaved files")); setModal(true); - discarded =false; + discarded = false; /* * Table of unsaved documents */ - QHashIterator<int, QString> i (unsavedDocs); + QHashIterator<int, QString> i(unsavedDocs); int row = 0; mFileList = new QTableWidget(this); mFileList->horizontalHeader()->hide(); @@ -43,61 +42,63 @@ QuitDialog::QuitDialog(QWidget *parent, QHash<int, QString> unsavedDocs) mFileList->setShowGrid(false); mFileList->setEditTriggers(QAbstractItemView::NoEditTriggers); mFileList->setFocusPolicy(Qt::NoFocus); - mFileList->horizontalHeader()->setStretchLastSection( true ); + mFileList->horizontalHeader()->setStretchLastSection(true); // fill the table i.toBack(); //jump to the end of list to fill the table backwards while (i.hasPrevious()) { i.previous(); - mFileList->setRowCount(mFileList->rowCount()+1); + mFileList->setRowCount(mFileList->rowCount() + 1); // checkbox in front of filename - QTableWidgetItem *tmp0 = new QTableWidgetItem(); - tmp0->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled ); + auto *tmp0 = new QTableWidgetItem(); + tmp0->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); tmp0->setCheckState(Qt::Checked); mFileList->setItem(row, 0, tmp0); // filename - QTableWidgetItem *tmp1 = new QTableWidgetItem(i.value()); + auto *tmp1 = new QTableWidgetItem(i.value()); mFileList->setItem(row, 1, tmp1); // tab-index in hidden column - QTableWidgetItem *tmp2 = new QTableWidgetItem(QString::number(i.key())); + auto *tmp2 = new QTableWidgetItem(QString::number(i.key())); mFileList->setItem(row, 2, tmp2); ++row; } /* * Warnbox with icon and text */ - QPixmap *pixmap = new QPixmap(":error.png"); - QLabel *warnicon = new QLabel(); + auto *pixmap = new QPixmap(":error.png"); + auto *warnicon = new QLabel(); warnicon->setPixmap(*pixmap); - QLabel *warnlabel = new QLabel(tr("<h3>%1 files contain unsaved information.<br/>Save the changes before closing?</h3>").arg(row)); - QHBoxLayout *warnBoxLayout = new QHBoxLayout(); + auto *warnlabel = new QLabel( + tr("<h3>%1 files contain unsaved information.<br/>Save the changes before closing?</h3>").arg(row)); + auto *warnBoxLayout = new QHBoxLayout(); warnBoxLayout->addWidget(warnicon); warnBoxLayout->addWidget(warnlabel); warnBoxLayout->setAlignment(Qt::AlignLeft); - QWidget *warnBox = new QWidget(this); + auto *warnBox = new QWidget(this); warnBox->setLayout(warnBoxLayout); /* * Two labels on top and under the filelist */ - QLabel *checkLabel = new QLabel(tr("Check the files you want to save:")); - QLabel *notelabel = new QLabel(tr("<b>Note:</b> If you don't save these files, all changes are lost.<br/>")); + auto *checkLabel = new QLabel(tr("Check the files you want to save:")); + auto *notelabel = new QLabel(tr("<b>Note:</b> If you don't save these files, all changes are lost.<br/>")); /* * Buttonbox */ - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Discard |QDialogButtonBox::Save | QDialogButtonBox::Cancel); + auto *buttonBox = new QDialogButtonBox( + QDialogButtonBox::Discard | QDialogButtonBox::Save | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - QPushButton* btnNoKey = buttonBox->button(QDialogButtonBox::Discard); + QPushButton *btnNoKey = buttonBox->button(QDialogButtonBox::Discard); connect(btnNoKey, SIGNAL(clicked()), SLOT(slotMyDiscard())); /* * Set the layout */ - QVBoxLayout *vbox = new QVBoxLayout(); + auto *vbox = new QVBoxLayout(); vbox->addWidget(warnBox); vbox->addWidget(checkLabel); vbox->addWidget(mFileList); @@ -107,20 +108,17 @@ QuitDialog::QuitDialog(QWidget *parent, QHash<int, QString> unsavedDocs) } -void QuitDialog::slotMyDiscard() -{ - discarded =true; +void QuitDialog::slotMyDiscard() { + discarded = true; reject(); } -bool QuitDialog::isDiscarded() -{ +bool QuitDialog::isDiscarded() const { return discarded; } -QList <int> QuitDialog::getTabIdsToSave() -{ - QList <int> tabIdsToSave; +QList<int> QuitDialog::getTabIdsToSave() { + QList<int> tabIdsToSave; for (int i = 0; i < mFileList->rowCount(); i++) { if (mFileList->item(i, 0)->checkState() == Qt::Checked) { tabIdsToSave << mFileList->item(i, 2)->text().toInt(); diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index a99b832b..212287d9 100755 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -22,9 +22,8 @@ #include "settingsdialog.h" SettingsDialog::SettingsDialog(GpgME::GpgContext *ctx, QWidget *parent) - : QDialog(parent) -{ - mCtx=ctx; + : QDialog(parent) { + mCtx = ctx; tabWidget = new QTabWidget; generalTab = new GeneralTab(mCtx); appearanceTab = new AppearanceTab; @@ -46,7 +45,7 @@ SettingsDialog::SettingsDialog(GpgME::GpgContext *ctx, QWidget *parent) connect(buttonBox, SIGNAL(accepted()), this, SLOT(slotAccept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(tabWidget); mainLayout->addWidget(buttonBox); setLayout(mainLayout); @@ -63,21 +62,18 @@ SettingsDialog::SettingsDialog(GpgME::GpgContext *ctx, QWidget *parent) connect(this, SIGNAL(signalRestartNeeded(bool)), parent, SLOT(slotSetRestartNeeded(bool))); - exec(); + exec(); } -bool SettingsDialog::getRestartNeeded() -{ +bool SettingsDialog::getRestartNeeded() const { return this->restartNeeded; } -void SettingsDialog::slotSetRestartNeeded(bool needed) -{ +void SettingsDialog::slotSetRestartNeeded(bool needed) { this->restartNeeded = needed; } -void SettingsDialog::slotAccept() -{ +void SettingsDialog::slotAccept() { generalTab->applySettings(); mimeTab->applySettings(); appearanceTab->applySettings(); @@ -92,8 +88,7 @@ void SettingsDialog::slotAccept() // http://www.informit.com/articles/article.aspx?p=1405555&seqNum=3 // http://developer.qt.nokia.com/wiki/How_to_create_a_multi_language_application -QHash<QString, QString> SettingsDialog::listLanguages() -{ +QHash<QString, QString> SettingsDialog::listLanguages() { QHash<QString, QString> languages; languages.insert("", tr("System Default")); @@ -110,28 +105,27 @@ QHash<QString, QString> SettingsDialog::listLanguages() // this works in qt 4.8 QLocale qloc(locale); - #if QT_VERSION < 0x040800 - QString language = QLocale::languageToString(qloc.language()) +" (" + locale + ")"; //+ " (" + QLocale::languageToString(qloc.language()) + ")"; - #else - QString language = qloc.nativeLanguageName() +" (" + locale + ")"; //+ " (" + QLocale::languageToString(qloc.language()) + ")"; - #endif +#if QT_VERSION < 0x040800 + QString language = QLocale::languageToString(qloc.language()) +" (" + locale + ")"; //+ " (" + QLocale::languageToString(qloc.language()) + ")"; +#else + QString language = qloc.nativeLanguageName() + " (" + locale + + ")"; //+ " (" + QLocale::languageToString(qloc.language()) + ")"; +#endif languages.insert(locale, language); } return languages; } - -GeneralTab::GeneralTab(GpgME::GpgContext *ctx,QWidget *parent) - : QWidget(parent) -{ - mCtx=ctx; +GeneralTab::GeneralTab(GpgME::GpgContext *ctx, QWidget *parent) + : QWidget(parent) { + mCtx = ctx; /***************************************** * remember Password-Box *****************************************/ - QGroupBox *rememberPasswordBox = new QGroupBox(tr("Remember Password")); - QHBoxLayout *rememberPasswordBoxLayout = new QHBoxLayout(); + auto *rememberPasswordBox = new QGroupBox(tr("Remember Password")); + auto *rememberPasswordBoxLayout = new QHBoxLayout(); rememberPasswordCheckBox = new QCheckBox(tr("Remember password until closing gpg4usb"), this); rememberPasswordBoxLayout->addWidget(rememberPasswordCheckBox); rememberPasswordBox->setLayout(rememberPasswordBoxLayout); @@ -139,43 +133,45 @@ GeneralTab::GeneralTab(GpgME::GpgContext *ctx,QWidget *parent) /***************************************** * Save-Checked-Keys-Box *****************************************/ - QGroupBox *saveCheckedKeysBox = new QGroupBox(tr("Save Checked Keys")); - QHBoxLayout *saveCheckedKeysBoxLayout = new QHBoxLayout(); - saveCheckedKeysCheckBox = new QCheckBox(tr("Save checked private keys on exit and restore them on next start."), this); + auto *saveCheckedKeysBox = new QGroupBox(tr("Save Checked Keys")); + auto *saveCheckedKeysBoxLayout = new QHBoxLayout(); + saveCheckedKeysCheckBox = new QCheckBox(tr("Save checked private keys on exit and restore them on next start."), + this); saveCheckedKeysBoxLayout->addWidget(saveCheckedKeysCheckBox); saveCheckedKeysBox->setLayout(saveCheckedKeysBoxLayout); /***************************************** * Key-Impport-Confirmation Box *****************************************/ - QGroupBox *importConfirmationBox = new QGroupBox(tr("Confirm drag'n'drop key import")); - QHBoxLayout *importConfirmationBoxLayout = new QHBoxLayout(); - importConfirmationCheckBox= new QCheckBox(tr("Import files dropped on the keylist without confirmation."), this); + auto *importConfirmationBox = new QGroupBox(tr("Confirm drag'n'drop key import")); + auto *importConfirmationBoxLayout = new QHBoxLayout(); + importConfirmationCheckBox = new QCheckBox(tr("Import files dropped on the keylist without confirmation."), this); importConfirmationBoxLayout->addWidget(importConfirmationCheckBox); importConfirmationBox->setLayout(importConfirmationBoxLayout); /***************************************** * Language Select Box *****************************************/ - QGroupBox *langBox = new QGroupBox(tr("Language")); - QVBoxLayout *langBoxLayout = new QVBoxLayout(); + auto *langBox = new QGroupBox(tr("Language")); + auto *langBoxLayout = new QVBoxLayout(); langSelectBox = new QComboBox; lang = SettingsDialog::listLanguages(); - foreach(QString l , lang) { - langSelectBox->addItem(l); - } + foreach(QString l, lang) { + langSelectBox->addItem(l); + } langBoxLayout->addWidget(langSelectBox); - langBoxLayout->addWidget(new QLabel(tr("<b>NOTE: </b> Gpg4usb will restart automatically if you change the language!"))); + langBoxLayout->addWidget( + new QLabel(tr("<b>NOTE: </b> Gpg4usb will restart automatically if you change the language!"))); langBox->setLayout(langBoxLayout); - connect(langSelectBox,SIGNAL(currentIndexChanged(int)),this,SLOT(slotLanguageChanged())); + connect(langSelectBox, SIGNAL(currentIndexChanged(int)), this, SLOT(slotLanguageChanged())); /***************************************** * Own Key Select Box *****************************************/ - QGroupBox *ownKeyBox = new QGroupBox(tr("Own key")); - QVBoxLayout *ownKeyBoxLayout = new QVBoxLayout(); + auto *ownKeyBox = new QGroupBox(tr("Own key")); + auto *ownKeyBoxLayout = new QVBoxLayout(); ownKeySelectBox = new QComboBox; ownKeyBox->setLayout(ownKeyBoxLayout); @@ -184,21 +180,21 @@ GeneralTab::GeneralTab(GpgME::GpgContext *ctx,QWidget *parent) // Fill the keyid hashmap keyIds.insert("", tr("<none>")); - foreach (QString keyid, *mKeyList->getAllPrivateKeys()) { - gpgme_key_t key = mCtx->getKeyDetails(keyid); - QString newKey = " (" + keyid + ")"; - if (! QString(key->uids->email).isEmpty()) { - newKey.prepend( " <"+ QString::fromUtf8(key->uids->email) +">"); + foreach (QString keyid, *mKeyList->getAllPrivateKeys()) { + gpgme_key_t key = mCtx->getKeyDetails(keyid); + QString newKey = " (" + keyid + ")"; + if (!QString(key->uids->email).isEmpty()) { + newKey.prepend(" <" + QString::fromUtf8(key->uids->email) + ">"); + } + if (!QString(key->uids->name).isEmpty()) { + newKey.prepend(" " + QString::fromUtf8(key->uids->name)); + } + keyIds.insert(key->uids->uid, newKey); } - if (! QString(key->uids->name).isEmpty()) { - newKey.prepend( " "+ QString::fromUtf8(key->uids->name)); + foreach(QString k, keyIds) { + ownKeySelectBox->addItem(k); } - keyIds.insert(key->uids->uid, newKey); - } - foreach(QString k , keyIds) { - ownKeySelectBox->addItem(k); - } - connect(ownKeySelectBox,SIGNAL(currentIndexChanged(int)),this,SLOT(slotOwnKeyIdChanged())); + connect(ownKeySelectBox, SIGNAL(currentIndexChanged(int)), this, SLOT(slotOwnKeyIdChanged())); ownKeyBoxLayout->addWidget(new QLabel(tr("Encrypt all messages additionally to the chosen key:"))); ownKeyBoxLayout->addWidget(ownKeySelectBox); @@ -206,7 +202,7 @@ GeneralTab::GeneralTab(GpgME::GpgContext *ctx,QWidget *parent) /***************************************** * Mainlayout *****************************************/ - QVBoxLayout *mainLayout = new QVBoxLayout; + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(rememberPasswordBox); mainLayout->addWidget(saveCheckedKeysBox); mainLayout->addWidget(importConfirmationBox); @@ -223,8 +219,7 @@ GeneralTab::GeneralTab(GpgME::GpgContext *ctx,QWidget *parent) * and set the buttons and checkboxes * appropriately **********************************/ -void GeneralTab::setSettings() -{ +void GeneralTab::setSettings() { QSettings settings; // Keysaving if (settings.value("keys/keySave").toBool()) { @@ -246,14 +241,13 @@ void GeneralTab::setSettings() // Get own key information from keydb/gpg.conf (if contained) QFile gpgConfFile(qApp->applicationDirPath() + "/keydb/gpg.conf"); gpgConfFile.open(QFile::ReadOnly); - while (!gpgConfFile.atEnd()) - { + while (!gpgConfFile.atEnd()) { QString line = gpgConfFile.readLine(); - if (line.startsWith("recipient")){ + if (line.startsWith("recipient")) { QStringList args; // get key id from gpg.conf - args=line.split(" "); + args = line.split(" "); ownKeyId = args.at(1); // remove linebreak at end of id ownKeyId.remove("\n"); @@ -267,7 +261,7 @@ void GeneralTab::setSettings() ownKeySelectBox->setCurrentIndex(ownKeySelectBox->findText(ownKeyId, Qt::MatchContains)); } - if (settings.value("general/confirmImportKeys",Qt::Checked).toBool()){ + if (settings.value("general/confirmImportKeys", Qt::Checked).toBool()) { importConfirmationCheckBox->setCheckState(Qt::Checked); } } @@ -276,8 +270,7 @@ void GeneralTab::setSettings() * get the values of the buttons and * write them to settings-file *************************************/ -void GeneralTab::applySettings() -{ +void GeneralTab::applySettings() { QSettings settings; settings.setValue("keys/keySave", saveCheckedKeysCheckBox->isChecked()); // TODO: clear passwordCache instantly on unset rememberPassword @@ -286,13 +279,11 @@ void GeneralTab::applySettings() settings.setValue("general/confirmImportKeys", importConfirmationCheckBox->isChecked()); } -void GeneralTab::slotLanguageChanged() -{ +void GeneralTab::slotLanguageChanged() { emit signalRestartNeeded(true); } -void GeneralTab::slotOwnKeyIdChanged() -{ +void GeneralTab::slotOwnKeyIdChanged() { // Set ownKeyId to currently selected QHashIterator<QString, QString> i(keyIds); @@ -312,8 +303,7 @@ void GeneralTab::slotOwnKeyIdChanged() gpgConfTempFile.open(QFile::WriteOnly); // remove line with the hidden-encrypt-to - while (!gpgConfFile.atEnd()) - { + while (!gpgConfFile.atEnd()) { QByteArray line = gpgConfFile.readLine(); if (!line.startsWith("recipient")) { gpgConfTempFile.write(line); @@ -333,35 +323,34 @@ void GeneralTab::slotOwnKeyIdChanged() // move the temporary gpg.conffile to the actual one gpgConfFile.remove(); - gpgConfTempFile.copy(gpgConfTempFile.fileName(),gpgConfFile.fileName()); + QFile::copy(gpgConfTempFile.fileName(), gpgConfFile.fileName()); gpgConfTempFile.remove(); } MimeTab::MimeTab(QWidget *parent) - : QWidget(parent) -{ + : QWidget(parent) { /***************************************** * MIME-Parsing-Box *****************************************/ - QGroupBox *mimeQPBox = new QGroupBox(tr("Decode quoted printable")); - QVBoxLayout *mimeQPBoxLayout = new QVBoxLayout(); + auto *mimeQPBox = new QGroupBox(tr("Decode quoted printable")); + auto *mimeQPBoxLayout = new QVBoxLayout(); mimeQPCheckBox = new QCheckBox(tr("Try to recognize quoted printable."), this); mimeQPBoxLayout->addWidget(mimeQPCheckBox); mimeQPBox->setLayout(mimeQPBoxLayout); - QGroupBox *mimeParseBox = new QGroupBox(tr("Parse PGP/MIME (Experimental)")); - QVBoxLayout *mimeParseBoxLayout = new QVBoxLayout(); + auto *mimeParseBox = new QGroupBox(tr("Parse PGP/MIME (Experimental)")); + auto *mimeParseBoxLayout = new QVBoxLayout(); mimeParseCheckBox = new QCheckBox(tr("Try to split attachments from PGP-MIME ecrypted messages."), this); mimeParseBoxLayout->addWidget(mimeParseCheckBox); mimeParseBox->setLayout(mimeParseBoxLayout); - QGroupBox *mimeOpenAttachmentBox = new QGroupBox(tr("Open with external application (Experimental)")); - QVBoxLayout *mimeOpenAttachmentBoxLayout = new QVBoxLayout(); - QLabel *mimeOpenAttachmentText = new QLabel(tr("Open attachments with default application for the filetype.<br> " - "There are at least two possible problems with this behaviour:" - "<ol><li>File needs to be saved unencrypted to attachments folder.<br> " - "Its your job to clean this folder.</li>" - "<li>The external application may have its own temp files.</li></ol>")); + auto *mimeOpenAttachmentBox = new QGroupBox(tr("Open with external application (Experimental)")); + auto *mimeOpenAttachmentBoxLayout = new QVBoxLayout(); + auto *mimeOpenAttachmentText = new QLabel(tr("Open attachments with default application for the filetype.<br> " + "There are at least two possible problems with this behaviour:" + "<ol><li>File needs to be saved unencrypted to attachments folder.<br> " + "Its your job to clean this folder.</li>" + "<li>The external application may have its own temp files.</li></ol>")); //mimeOpenAttachmentBox->setDisabled(true); mimeOpenAttachmentCheckBox = new QCheckBox(tr("Enable opening with external applications."), this); @@ -370,7 +359,7 @@ MimeTab::MimeTab(QWidget *parent) mimeOpenAttachmentBoxLayout->addWidget(mimeOpenAttachmentCheckBox); mimeOpenAttachmentBox->setLayout(mimeOpenAttachmentBoxLayout); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(mimeParseBox); mainLayout->addWidget(mimeOpenAttachmentBox); mainLayout->addWidget(mimeQPBox); @@ -384,15 +373,14 @@ MimeTab::MimeTab(QWidget *parent) * and set the buttons and checkboxes * appropriately **********************************/ -void MimeTab::setSettings() -{ +void MimeTab::setSettings() { QSettings settings; // MIME-Parsing if (settings.value("mime/parsemime").toBool()) mimeParseCheckBox->setCheckState(Qt::Checked); // Qouted Printable - if (settings.value("mime/parseQP",true).toBool()) mimeQPCheckBox->setCheckState(Qt::Checked); + if (settings.value("mime/parseQP", true).toBool()) mimeQPCheckBox->setCheckState(Qt::Checked); // Open Attachments with external app if (settings.value("mime/openAttachment").toBool()) mimeOpenAttachmentCheckBox->setCheckState(Qt::Checked); @@ -403,22 +391,20 @@ void MimeTab::setSettings() * get the values of the buttons and * write them to settings-file *************************************/ -void MimeTab::applySettings() -{ +void MimeTab::applySettings() { QSettings settings; - settings.setValue("mime/parsemime" , mimeParseCheckBox->isChecked()); - settings.setValue("mime/parseQP" , mimeQPCheckBox->isChecked()); - settings.setValue("mime/openAttachment" , mimeOpenAttachmentCheckBox->isChecked()); + settings.setValue("mime/parsemime", mimeParseCheckBox->isChecked()); + settings.setValue("mime/parseQP", mimeQPCheckBox->isChecked()); + settings.setValue("mime/openAttachment", mimeOpenAttachmentCheckBox->isChecked()); } AppearanceTab::AppearanceTab(QWidget *parent) - : QWidget(parent) -{ + : QWidget(parent) { /***************************************** * Icon-Size-Box *****************************************/ - QGroupBox *iconSizeBox = new QGroupBox(tr("Iconsize")); + auto *iconSizeBox = new QGroupBox(tr("Iconsize")); iconSizeGroup = new QButtonGroup(); iconSizeSmall = new QRadioButton(tr("small")); iconSizeMedium = new QRadioButton(tr("medium")); @@ -428,7 +414,7 @@ AppearanceTab::AppearanceTab(QWidget *parent) iconSizeGroup->addButton(iconSizeMedium, 2); iconSizeGroup->addButton(iconSizeLarge, 3); - QHBoxLayout *iconSizeBoxLayout = new QHBoxLayout(); + auto *iconSizeBoxLayout = new QHBoxLayout(); iconSizeBoxLayout->addWidget(iconSizeSmall); iconSizeBoxLayout->addWidget(iconSizeMedium); iconSizeBoxLayout->addWidget(iconSizeLarge); @@ -438,7 +424,7 @@ AppearanceTab::AppearanceTab(QWidget *parent) /***************************************** * Icon-Style-Box *****************************************/ - QGroupBox *iconStyleBox = new QGroupBox(tr("Iconstyle")); + auto *iconStyleBox = new QGroupBox(tr("Iconstyle")); iconStyleGroup = new QButtonGroup(); iconTextButton = new QRadioButton(tr("just text")); iconIconsButton = new QRadioButton(tr("just icons")); @@ -448,7 +434,7 @@ AppearanceTab::AppearanceTab(QWidget *parent) iconStyleGroup->addButton(iconIconsButton, 2); iconStyleGroup->addButton(iconAllButton, 3); - QHBoxLayout *iconStyleBoxLayout = new QHBoxLayout(); + auto *iconStyleBoxLayout = new QHBoxLayout(); iconStyleBoxLayout->addWidget(iconTextButton); iconStyleBoxLayout->addWidget(iconIconsButton); iconStyleBoxLayout->addWidget(iconAllButton); @@ -458,13 +444,13 @@ AppearanceTab::AppearanceTab(QWidget *parent) /***************************************** * Window-Size-Box *****************************************/ - QGroupBox *windowSizeBox = new QGroupBox(tr("Windowstate")); - QHBoxLayout *windowSizeBoxLayout = new QHBoxLayout(); + auto *windowSizeBox = new QGroupBox(tr("Windowstate")); + auto *windowSizeBoxLayout = new QHBoxLayout(); windowSizeCheckBox = new QCheckBox(tr("Save window size and position on exit."), this); windowSizeBoxLayout->addWidget(windowSizeCheckBox); windowSizeBox->setLayout(windowSizeBoxLayout); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(iconSizeBox); mainLayout->addWidget(iconStyleBox); mainLayout->addWidget(windowSizeBox); @@ -478,31 +464,37 @@ AppearanceTab::AppearanceTab(QWidget *parent) * and set the buttons and checkboxes * appropriately **********************************/ -void AppearanceTab::setSettings() -{ +void AppearanceTab::setSettings() { QSettings settings; //Iconsize QSize iconSize = settings.value("toolbar/iconsize", QSize(24, 24)).toSize(); switch (iconSize.height()) { - case 12: iconSizeSmall->setChecked(true); - break; - case 24:iconSizeMedium->setChecked(true); - break; - case 32:iconSizeLarge->setChecked(true); - break; + case 12: + iconSizeSmall->setChecked(true); + break; + case 24: + iconSizeMedium->setChecked(true); + break; + case 32: + iconSizeLarge->setChecked(true); + break; } // Iconstyle - Qt::ToolButtonStyle iconStyle = static_cast<Qt::ToolButtonStyle>(settings.value("toolbar/iconstyle", Qt::ToolButtonTextUnderIcon).toUInt()); + Qt::ToolButtonStyle iconStyle = static_cast<Qt::ToolButtonStyle>(settings.value("toolbar/iconstyle", + Qt::ToolButtonTextUnderIcon).toUInt()); switch (iconStyle) { - case Qt::ToolButtonTextOnly: iconTextButton->setChecked(true); - break; - case Qt::ToolButtonIconOnly:iconIconsButton->setChecked(true); - break; - case Qt::ToolButtonTextUnderIcon:iconAllButton->setChecked(true); - break; - default: - break; + case Qt::ToolButtonTextOnly: + iconTextButton->setChecked(true); + break; + case Qt::ToolButtonIconOnly: + iconIconsButton->setChecked(true); + break; + case Qt::ToolButtonTextUnderIcon: + iconAllButton->setChecked(true); + break; + default: + break; } // Window Save and Position @@ -514,46 +506,50 @@ void AppearanceTab::setSettings() * get the values of the buttons and * write them to settings-file *************************************/ -void AppearanceTab::applySettings() -{ +void AppearanceTab::applySettings() { QSettings settings; switch (iconSizeGroup->checkedId()) { - case 1: settings.setValue("toolbar/iconsize", QSize(12, 12)); - break; - case 2:settings.setValue("toolbar/iconsize", QSize(24, 24)); - break; - case 3:settings.setValue("toolbar/iconsize", QSize(32, 32)); - break; + case 1: + settings.setValue("toolbar/iconsize", QSize(12, 12)); + break; + case 2: + settings.setValue("toolbar/iconsize", QSize(24, 24)); + break; + case 3: + settings.setValue("toolbar/iconsize", QSize(32, 32)); + break; } switch (iconStyleGroup->checkedId()) { - case 1: settings.setValue("toolbar/iconstyle", Qt::ToolButtonTextOnly); - break; - case 2:settings.setValue("toolbar/iconstyle", Qt::ToolButtonIconOnly); - break; - case 3:settings.setValue("toolbar/iconstyle", Qt::ToolButtonTextUnderIcon); - break; + case 1: + settings.setValue("toolbar/iconstyle", Qt::ToolButtonTextOnly); + break; + case 2: + settings.setValue("toolbar/iconstyle", Qt::ToolButtonIconOnly); + break; + case 3: + settings.setValue("toolbar/iconstyle", Qt::ToolButtonTextUnderIcon); + break; } settings.setValue("window/windowSave", windowSizeCheckBox->isChecked()); } KeyserverTab::KeyserverTab(QWidget *parent) - : QWidget(parent) -{ - QVBoxLayout *mainLayout = new QVBoxLayout(this); + : QWidget(parent) { + auto *mainLayout = new QVBoxLayout(this); - QLabel *label = new QLabel(tr("Default Keyserver for import:")); + auto *label = new QLabel(tr("Default Keyserver for import:")); comboBox = new QComboBox; comboBox->setEditable(false); comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - QWidget *addKeyServerBox = new QWidget(this); - QHBoxLayout *addKeyServerLayout = new QHBoxLayout(addKeyServerBox); - QLabel *http = new QLabel("http://"); + auto *addKeyServerBox = new QWidget(this); + auto *addKeyServerLayout = new QHBoxLayout(addKeyServerBox); + auto *http = new QLabel("http://"); newKeyServerEdit = new QLineEdit(this); - QPushButton *newKeyServerButton = new QPushButton(tr("Add to keyserverlist"), this); - connect(newKeyServerButton,SIGNAL(clicked()), this, SLOT(addKeyServer())); + auto *newKeyServerButton = new QPushButton(tr("Add to keyserverlist"), this); + connect(newKeyServerButton, SIGNAL(clicked()), this, SLOT(addKeyServer())); addKeyServerLayout->addWidget(http); addKeyServerLayout->addWidget(newKeyServerEdit); addKeyServerLayout->addWidget(newKeyServerButton); @@ -573,50 +569,47 @@ KeyserverTab::KeyserverTab(QWidget *parent) * and set the buttons and checkboxes * appropriately **********************************/ -void KeyserverTab::setSettings() -{ +void KeyserverTab::setSettings() { QSettings settings; QString defKeyserver = settings.value("keyserver/defaultKeyServer").toString(); - QStringList *keyServerList = new QStringList(); - for(int i=0; i < comboBox->count(); i++) { + auto *keyServerList = new QStringList(); + for (int i = 0; i < comboBox->count(); i++) { keyServerList->append(comboBox->itemText(i)); } settings.setValue("keyserver/keyServerList", *keyServerList); } -void KeyserverTab::addKeyServer() -{ +void KeyserverTab::addKeyServer() { if (newKeyServerEdit->text().startsWith("http://")) { comboBox->addItem(newKeyServerEdit->text()); } else { - comboBox->addItem("http://" +newKeyServerEdit->text()); + comboBox->addItem("http://" + newKeyServerEdit->text()); } - comboBox->setCurrentIndex(comboBox->count()-1); + comboBox->setCurrentIndex(comboBox->count() - 1); } + /*********************************** * get the values of the buttons and * write them to settings-file *************************************/ -void KeyserverTab::applySettings() -{ +void KeyserverTab::applySettings() { QSettings settings; - settings.setValue("keyserver/defaultKeyServer",comboBox->currentText()); + settings.setValue("keyserver/defaultKeyServer", comboBox->currentText()); } AdvancedTab::AdvancedTab(QWidget *parent) - : QWidget(parent) -{ + : QWidget(parent) { /***************************************** * Steganography Box *****************************************/ - QGroupBox *steganoBox = new QGroupBox(tr("Show Steganography Options [Advanced]")); - QHBoxLayout *steganoBoxLayout = new QHBoxLayout(); - steganoCheckBox= new QCheckBox(tr("Show Steganographic Options."), this); + auto *steganoBox = new QGroupBox(tr("Show Steganography Options [Advanced]")); + auto *steganoBoxLayout = new QHBoxLayout(); + steganoCheckBox = new QCheckBox(tr("Show Steganographic Options."), this); steganoBoxLayout->addWidget(steganoCheckBox); steganoBox->setLayout(steganoBoxLayout); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(steganoBox); setSettings(); mainLayout->addStretch(1); @@ -624,54 +617,52 @@ AdvancedTab::AdvancedTab(QWidget *parent) } -void AdvancedTab::setSettings() -{ +void AdvancedTab::setSettings() { QSettings settings; - if (settings.value("advanced/steganography").toBool()){ + if (settings.value("advanced/steganography").toBool()) { steganoCheckBox->setCheckState(Qt::Checked); } } -void AdvancedTab::applySettings() -{ +void AdvancedTab::applySettings() { QSettings settings; settings.setValue("advanced/steganography", steganoCheckBox->isChecked()); } GpgPathsTab::GpgPathsTab(QWidget *parent) - : QWidget(parent) -{ + : QWidget(parent) { setSettings(); /***************************************** * Keydb Box *****************************************/ - QGroupBox *keydbBox = new QGroupBox(tr("Relative path to keydb")); - QGridLayout *keydbBoxLayout = new QGridLayout(); + auto *keydbBox = new QGroupBox(tr("Relative path to keydb")); + auto *keydbBoxLayout = new QGridLayout(); // Label containing the current keydbpath relative to default keydb path - keydbLabel = new QLabel(accKeydbPath,this); + keydbLabel = new QLabel(accKeydbPath, this); - QPushButton *keydbButton = new QPushButton("Change keydb path",this); + auto *keydbButton = new QPushButton("Change keydb path", this); connect(keydbButton, SIGNAL(clicked()), this, SLOT(chooseKeydbDir())); - QPushButton *keydbDefaultButton = new QPushButton("Set keydb to default path",this); + auto *keydbDefaultButton = new QPushButton("Set keydb to default path", this); connect(keydbDefaultButton, SIGNAL(clicked()), this, SLOT(setKeydbPathToDefault())); keydbBox->setLayout(keydbBoxLayout); - keydbBoxLayout->addWidget(new QLabel(tr("Current keydb path: ")),1,1); - keydbBoxLayout->addWidget(keydbLabel,1,2); - keydbBoxLayout->addWidget(keydbButton,1,3); - keydbBoxLayout->addWidget(keydbDefaultButton,2,3); - keydbBoxLayout->addWidget(new QLabel(tr("<b>NOTE: </b> Gpg4usb will restart automatically if you change the keydb path!")),3,1,1,3); - - QVBoxLayout *mainLayout = new QVBoxLayout; + keydbBoxLayout->addWidget(new QLabel(tr("Current keydb path: ")), 1, 1); + keydbBoxLayout->addWidget(keydbLabel, 1, 2); + keydbBoxLayout->addWidget(keydbButton, 1, 3); + keydbBoxLayout->addWidget(keydbDefaultButton, 2, 3); + keydbBoxLayout->addWidget( + new QLabel(tr("<b>NOTE: </b> Gpg4usb will restart automatically if you change the keydb path!")), 3, 1, 1, + 3); + + auto *mainLayout = new QVBoxLayout; mainLayout->addWidget(keydbBox); mainLayout->addStretch(1); setLayout(mainLayout); } -QString GpgPathsTab::getRelativePath(const QString dir1,const QString dir2) -{ +QString GpgPathsTab::getRelativePath(const QString &dir1, const QString &dir2) { QDir dir(dir1); QString s; @@ -683,23 +674,21 @@ QString GpgPathsTab::getRelativePath(const QString dir1,const QString dir2) return s; } -void GpgPathsTab::setKeydbPathToDefault() -{ +void GpgPathsTab::setKeydbPathToDefault() { accKeydbPath = "."; keydbLabel->setText("."); } -QString GpgPathsTab::chooseKeydbDir() -{ - QString dir = QFileDialog::getExistingDirectory(this,tr ("Choose keydb directory"),accKeydbPath,QFileDialog::ShowDirsOnly); +QString GpgPathsTab::chooseKeydbDir() { + QString dir = QFileDialog::getExistingDirectory(this, tr("Choose keydb directory"), accKeydbPath, + QFileDialog::ShowDirsOnly); accKeydbPath = getRelativePath(defKeydbPath, dir); keydbLabel->setText(accKeydbPath); return ""; } -void GpgPathsTab::setSettings() -{ +void GpgPathsTab::setSettings() { defKeydbPath = qApp->applicationDirPath() + "/keydb"; QSettings settings; @@ -709,8 +698,7 @@ void GpgPathsTab::setSettings() } } -void GpgPathsTab::applySettings() -{ +void GpgPathsTab::applySettings() { QSettings settings; - settings.setValue("gpgpaths/keydbpath",accKeydbPath); + settings.setValue("gpgpaths/keydbpath", accKeydbPath); } diff --git a/src/textedit.cpp b/src/textedit.cpp index e28304d5..52fdaf17 100644 --- a/src/textedit.cpp +++ b/src/textedit.cpp @@ -21,15 +21,14 @@ #include "textedit.h" -TextEdit::TextEdit() -{ +TextEdit::TextEdit() { countPage = 0; tabWidget = new QTabWidget(this); tabWidget->setMovable(true); tabWidget->setTabsClosable(true); tabWidget->setDocumentMode(true); - QVBoxLayout *layout = new QVBoxLayout; + auto *layout = new QVBoxLayout; layout->addWidget(tabWidget); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); @@ -40,64 +39,61 @@ TextEdit::TextEdit() setAcceptDrops(false); } -void TextEdit::slotNewTab() -{ +void TextEdit::slotNewTab() { QString header = tr("untitled") + - QString::number(++countPage)+".txt"; + QString::number(++countPage) + ".txt"; - EditorPage *page = new EditorPage(); + auto *page = new EditorPage(); tabWidget->addTab(page, header); tabWidget->setCurrentIndex(tabWidget->count() - 1); page->getTextPage()->setFocus(); connect(page->getTextPage()->document(), SIGNAL(modificationChanged(bool)), this, SLOT(slotShowModified())); - } +} -void TextEdit::slotNewHelpTab(QString title, QString path) -{ +void TextEdit::slotNewHelpTab(const QString &title, const QString &path) const { - HelpPage *page = new HelpPage(path); + auto *page = new HelpPage(path); tabWidget->addTab(page, title); tabWidget->setCurrentIndex(tabWidget->count() - 1); } -void TextEdit::slotOpen() -{ +void TextEdit::slotOpen() { QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open file"), QDir::currentPath()); - foreach (QString fileName,fileNames){ - if (!fileName.isEmpty()) { - QFile file(fileName); - - if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { - EditorPage *page = new EditorPage(fileName); - - QTextStream in(&file); - QApplication::setOverrideCursor(Qt::WaitCursor); - page->getTextPage()->setPlainText(in.readAll()); - page->setFilePath(fileName); - QTextDocument *document = page->getTextPage()->document(); - document->setModified(false); - - tabWidget->addTab(page, strippedName(fileName)); - tabWidget->setCurrentIndex(tabWidget->count() - 1); - QApplication::restoreOverrideCursor(); - page->getTextPage()->setFocus(); - connect(page->getTextPage()->document(), SIGNAL(modificationChanged(bool)), this, SLOT(slotShowModified())); - //enableAction(true) - file.close(); - } else { - QMessageBox::warning(this, tr("Application"), - tr("Cannot read file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + foreach (QString fileName, fileNames) { + if (!fileName.isEmpty()) { + QFile file(fileName); + + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { + auto *page = new EditorPage(fileName); + + QTextStream in(&file); + QApplication::setOverrideCursor(Qt::WaitCursor); + page->getTextPage()->setPlainText(in.readAll()); + page->setFilePath(fileName); + QTextDocument *document = page->getTextPage()->document(); + document->setModified(false); + + tabWidget->addTab(page, strippedName(fileName)); + tabWidget->setCurrentIndex(tabWidget->count() - 1); + QApplication::restoreOverrideCursor(); + page->getTextPage()->setFocus(); + connect(page->getTextPage()->document(), SIGNAL(modificationChanged(bool)), this, + SLOT(slotShowModified())); + //enableAction(true) + file.close(); + } else { + QMessageBox::warning(this, tr("Application"), + tr("Cannot read file %1:\n%2.") + .arg(fileName) + .arg(file.errorString())); + } } } - } } -void TextEdit::slotSave() -{ +void TextEdit::slotSave() { if (tabWidget->count() == 0 || slotCurPage() == 0) { return; } @@ -113,8 +109,7 @@ void TextEdit::slotSave() } } -bool TextEdit::saveFile(const QString &fileName) -{ +bool TextEdit::saveFile(const QString &fileName) { if (fileName.isEmpty()) { return false; } @@ -135,31 +130,30 @@ bool TextEdit::saveFile(const QString &fileName) int curIndex = tabWidget->currentIndex(); tabWidget->setTabText(curIndex, strippedName(fileName)); page->setFilePath(fileName); - // statusBar()->showMessage(tr("File saved"), 2000); + // statusBar()->showMessage(tr("File saved"), 2000); file.close(); return true; } else { QMessageBox::warning(this, tr("File"), tr("Cannot write file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + .arg(fileName) + .arg(file.errorString())); return false; } } -bool TextEdit::slotSaveAs() -{ +bool TextEdit::slotSaveAs() { if (tabWidget->count() == 0 || slotCurPage() == 0) { return true; } EditorPage *page = slotCurPage(); QString path; - if(page->getFilePath() != "") { + if (page->getFilePath() != "") { path = page->getFilePath(); } else { - path = tabWidget->tabText(tabWidget->currentIndex()).remove(0,2); + path = tabWidget->tabText(tabWidget->currentIndex()).remove(0, 2); } QString fileName = QFileDialog::getSaveFileName(this, tr("Save file "), @@ -167,16 +161,14 @@ bool TextEdit::slotSaveAs() return saveFile(fileName); } -void TextEdit::slotCloseTab() -{ +void TextEdit::slotCloseTab() { removeTab(tabWidget->currentIndex()); if (tabWidget->count() != 0) { slotCurPage()->getTextPage()->setFocus(); } } -void TextEdit::removeTab(int index) -{ +void TextEdit::removeTab(int index) { // Do nothing, if no tab is opened if (tabWidget->count() == 0) { return; @@ -191,30 +183,30 @@ void TextEdit::removeTab(int index) if (maybeSaveCurrentTab(true)) { tabWidget->removeTab(index); - if(index >= lastIndex) { + if (index >= lastIndex) { tabWidget->setCurrentIndex(lastIndex); } else { - tabWidget->setCurrentIndex(lastIndex-1); + tabWidget->setCurrentIndex(lastIndex - 1); } } if (tabWidget->count() == 0) { - // enableAction(false); + // enableAction(false); } } - /** - * Check if current may need to be saved. - * Call this function before closing the currently active tab- - * - * If it returns false, the close event should be aborted. - */ +/** + * Check if current may need to be saved. + * Call this function before closing the currently active tab- + * + * If it returns false, the close event should be aborted. + */ bool TextEdit::maybeSaveCurrentTab(bool askToSave) { EditorPage *page = slotCurPage(); // if this page is no textedit, there should be nothing to save - if(page == 0) { + if (page == nullptr) { return true; } QTextDocument *document = page->getTextPage()->document(); @@ -224,14 +216,15 @@ bool TextEdit::maybeSaveCurrentTab(bool askToSave) { // write title of tab to docname and remove the leading * QString docname = tabWidget->tabText(tabWidget->currentIndex()); - docname.remove(0,2); + docname.remove(0, 2); - QString filePath = page->getFilePath(); + const QString &filePath = page->getFilePath(); if (askToSave) { result = QMessageBox::warning(this, tr("Unsaved document"), - tr("<h3>The document \"%1\" has been modified.<br/>Do you want to save your changes?</h3>").arg(docname)+ - tr("<b>Note:</b> If you don't save these files, all changes are lost.<br/>"), - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + tr("<h3>The document \"%1\" has been modified.<br/>Do you want to save your changes?</h3>").arg( + docname) + + tr("<b>Note:</b> If you don't save these files, all changes are lost.<br/>"), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); } if ((result == QMessageBox::Save) || (!askToSave)) { if (filePath == "") { @@ -250,22 +243,21 @@ bool TextEdit::maybeSaveCurrentTab(bool askToSave) { return true; } -bool TextEdit::maybeSaveAnyTab() -{ +bool TextEdit::maybeSaveAnyTab() { // get a list of all unsaved documents and their tabids QHash<int, QString> unsavedDocs = this->unsavedDocuments(); /* * no unsaved documents, so app can be closed */ - if (unsavedDocs.size() == 0) { + if (unsavedDocs.empty()) { return true; } /* * only 1 unsaved document -> set modified tab as current * and show normal unsaved doc dialog */ - if(unsavedDocs.size() == 1) { + if (unsavedDocs.size() == 1) { int modifiedTab = unsavedDocs.keys().at(0); tabWidget->setCurrentIndex(modifiedTab); return maybeSaveCurrentTab(true); @@ -274,31 +266,31 @@ bool TextEdit::maybeSaveAnyTab() /* * more than one unsaved documents */ - if(unsavedDocs.size() > 1) { - QHashIterator<int, QString> i (unsavedDocs); + if (unsavedDocs.size() > 1) { + QHashIterator<int, QString> i(unsavedDocs); QuitDialog *dialog; - dialog=new QuitDialog(this, unsavedDocs); + dialog = new QuitDialog(this, unsavedDocs); int result = dialog->exec(); // if result is QDialog::Rejected, discard or cancel was clicked - if (result == QDialog::Rejected){ + if (result == QDialog::Rejected) { // return true, if discard is clicked, so app can be closed - if (dialog->isDiscarded()){ + if (dialog->isDiscarded()) { return true; } else { return false; } } else { - bool allsaved=true; - QList <int> tabIdsToSave = dialog->getTabIdsToSave(); - - foreach (int tabId, tabIdsToSave) { - tabWidget->setCurrentIndex(tabId); - if (! maybeSaveCurrentTab(false)) { - allsaved=false; + bool allsaved = true; + QList<int> tabIdsToSave = dialog->getTabIdsToSave(); + + foreach (int tabId, tabIdsToSave) { + tabWidget->setCurrentIndex(tabId); + if (!maybeSaveCurrentTab(false)) { + allsaved = false; + } } - } if (allsaved) { return true; } else { @@ -311,39 +303,35 @@ bool TextEdit::maybeSaveAnyTab() } -QTextEdit* TextEdit::curTextPage() -{ - EditorPage *curTextPage = qobject_cast<EditorPage *>(tabWidget->currentWidget()); - if(curTextPage != 0) { +QTextEdit *TextEdit::curTextPage() const { + auto *curTextPage = qobject_cast<EditorPage *>(tabWidget->currentWidget()); + if (curTextPage != nullptr) { return curTextPage->getTextPage(); } else { - return 0; + return nullptr; } } -QTextBrowser* TextEdit::curHelpPage() { - HelpPage *curHelpPage = qobject_cast<HelpPage *>(tabWidget->currentWidget()); - if(curHelpPage != 0) { +QTextBrowser *TextEdit::curHelpPage() const { + auto *curHelpPage = qobject_cast<HelpPage *>(tabWidget->currentWidget()); + if (curHelpPage != nullptr) { return curHelpPage->getBrowser(); } else { - return 0; + return nullptr; } } -int TextEdit::tabCount() -{ +int TextEdit::tabCount() const { return tabWidget->count(); } -EditorPage* TextEdit::slotCurPage() -{ - EditorPage *curPage = qobject_cast<EditorPage *>(tabWidget->currentWidget()); +EditorPage *TextEdit::slotCurPage() const { + auto *curPage = qobject_cast<EditorPage *>(tabWidget->currentWidget()); return curPage; } -void TextEdit::slotQuote() -{ - if (tabWidget->count() == 0 || curTextPage() == 0) { +void TextEdit::slotQuote() const { + if (tabWidget->count() == 0 || curTextPage() == nullptr) { return; } @@ -356,14 +344,14 @@ void TextEdit::slotQuote() while (!cursor.isNull() && !cursor.atEnd()) { cursor.movePosition(QTextCursor::EndOfLine); cursor.movePosition(QTextCursor::NextCharacter); - if(!cursor.atEnd()) { + if (!cursor.atEnd()) { cursor.insertText("> "); } } cursor.endEditBlock(); } -void TextEdit::slotFillTextEditWithText(QString text) { +void TextEdit::slotFillTextEditWithText(const QString &text) const { QTextCursor cursor(curTextPage()->document()); cursor.beginEditBlock(); this->curTextPage()->selectAll(); @@ -371,14 +359,13 @@ void TextEdit::slotFillTextEditWithText(QString text) { cursor.endEditBlock(); } -void TextEdit::loadFile(const QString &fileName) -{ +void TextEdit::loadFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("Application"), tr("Cannot read file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + .arg(fileName) + .arg(file.errorString())); return; } QTextStream in(&file); @@ -388,30 +375,28 @@ void TextEdit::loadFile(const QString &fileName) slotCurPage()->setFilePath(fileName); tabWidget->setTabText(tabWidget->currentIndex(), strippedName(fileName)); file.close(); - // statusBar()->showMessage(tr("File loaded"), 2000); + // statusBar()->showMessage(tr("File loaded"), 2000); } -QString TextEdit::strippedName(const QString &fullFileName) -{ +QString TextEdit::strippedName(const QString &fullFileName) { return QFileInfo(fullFileName).fileName(); } -void TextEdit::slotPrint() -{ +void TextEdit::slotPrint() { if (tabWidget->count() == 0) { return; } #ifndef QT_NO_PRINTER - QTextDocument *document; - if(curTextPage() == 0) { + QTextDocument *document; + if (curTextPage() == nullptr) { document = curHelpPage()->document(); } else { document = curTextPage()->document(); } QPrinter printer; - QPrintDialog *dlg = new QPrintDialog(&printer, this); + auto *dlg = new QPrintDialog(&printer, this); if (dlg->exec() != QDialog::Accepted) { return; } @@ -421,28 +406,28 @@ void TextEdit::slotPrint() #endif } -void TextEdit::slotShowModified() { - int index=tabWidget->currentIndex(); - QString title= tabWidget->tabText(index); +void TextEdit::slotShowModified() const { + int index = tabWidget->currentIndex(); + QString title = tabWidget->tabText(index); // if doc is modified now, add leading * to title, // otherwise remove the leading * from the title - if(curTextPage()->document()->isModified()) { + if (curTextPage()->document()->isModified()) { tabWidget->setTabText(index, title.prepend("* ")); } else { - tabWidget->setTabText(index, title.remove(0,2)); + tabWidget->setTabText(index, title.remove(0, 2)); } } -void TextEdit::slotSwitchTabUp() { +void TextEdit::slotSwitchTabUp() const { if (tabWidget->count() > 1) { - int newindex=(tabWidget->currentIndex()+1)%(tabWidget->count()); + int newindex = (tabWidget->currentIndex() + 1) % (tabWidget->count()); tabWidget->setCurrentIndex(newindex); } } -void TextEdit::slotSwitchTabDown() { +void TextEdit::slotSwitchTabDown() const { if (tabWidget->count() > 1) { - int newindex=(tabWidget->currentIndex()-1+tabWidget->count())%tabWidget->count(); + int newindex = (tabWidget->currentIndex() - 1 + tabWidget->count()) % tabWidget->count(); tabWidget->setCurrentIndex(newindex); } } @@ -450,37 +435,35 @@ void TextEdit::slotSwitchTabDown() { /* * return a hash of tabindexes and title of unsaved tabs */ -QHash<int, QString> TextEdit::unsavedDocuments() { +QHash<int, QString> TextEdit::unsavedDocuments() const { QHash<int, QString> unsavedDocs; // this list could be used to implement gedit like "unsaved changed"-dialog - for(int i=0; i < tabWidget->count(); i++) { - EditorPage *ep = qobject_cast<EditorPage *> (tabWidget->widget(i)); - if(ep != 0 && ep->getTextPage()->document()->isModified()) { + for (int i = 0; i < tabWidget->count(); i++) { + auto *ep = qobject_cast<EditorPage *>(tabWidget->widget(i)); + if (ep != nullptr && ep->getTextPage()->document()->isModified()) { QString docname = tabWidget->tabText(i); // remove * before name of modified doc - docname.remove(0,2); + docname.remove(0, 2); unsavedDocs.insert(i, docname); } } return unsavedDocs; } -void TextEdit::slotCut() -{ - if (tabWidget->count() == 0 || curTextPage() == 0) { +void TextEdit::slotCut() const { + if (tabWidget->count() == 0 || curTextPage() == nullptr) { return; } curTextPage()->cut(); } -void TextEdit::slotCopy() -{ +void TextEdit::slotCopy() const { if (tabWidget->count() == 0) { return; } - if(curTextPage() != 0) { + if (curTextPage() != nullptr) { curTextPage()->copy(); } else { curHelpPage()->copy(); @@ -489,40 +472,36 @@ void TextEdit::slotCopy() } -void TextEdit::slotPaste() -{ - if (tabWidget->count() == 0 || curTextPage() == 0) { +void TextEdit::slotPaste() const { + if (tabWidget->count() == 0 || curTextPage() == nullptr) { return; } curTextPage()->paste(); } -void TextEdit::slotUndo() -{ - if (tabWidget->count() == 0 || curTextPage() == 0) { +void TextEdit::slotUndo() const { + if (tabWidget->count() == 0 || curTextPage() == nullptr) { return; } curTextPage()->undo(); } -void TextEdit::slotRedo() -{ - if (tabWidget->count() == 0 || curTextPage() == 0) { +void TextEdit::slotRedo() const { + if (tabWidget->count() == 0 || curTextPage() == nullptr) { return; } curTextPage()->redo(); } -void TextEdit::slotZoomIn() -{ - if (tabWidget->count() == 0 ) { +void TextEdit::slotZoomIn() const { + if (tabWidget->count() == 0) { return; } - if(curTextPage() != 0) { + if (curTextPage() != nullptr) { curTextPage()->zoomIn(); } else { curHelpPage()->zoomIn(); @@ -530,22 +509,20 @@ void TextEdit::slotZoomIn() } -void TextEdit::slotZoomOut() -{ - if (tabWidget->count() == 0 ) { +void TextEdit::slotZoomOut() const { + if (tabWidget->count() == 0) { return; } - if(curTextPage() != 0) { + if (curTextPage() != nullptr) { curTextPage()->zoomOut(); } else { curHelpPage()->zoomOut(); } } -void TextEdit::slotSelectAll() -{ - if (tabWidget->count() == 0 || curTextPage() == 0) { +void TextEdit::slotSelectAll() const { + if (tabWidget->count() == 0 || curTextPage() == nullptr) { return; } diff --git a/src/verifydetailsdialog.cpp b/src/verifydetailsdialog.cpp index fc9ab6cc..2c4ab880 100644 --- a/src/verifydetailsdialog.cpp +++ b/src/verifydetailsdialog.cpp @@ -21,9 +21,9 @@ #include "verifydetailsdialog.h" -VerifyDetailsDialog::VerifyDetailsDialog(QWidget *parent, GpgME::GpgContext* ctx, KeyList* keyList, QByteArray* inputData, QByteArray* inputSignature) : - QDialog(parent) -{ +VerifyDetailsDialog::VerifyDetailsDialog(QWidget *parent, GpgME::GpgContext *ctx, KeyList *keyList, + QByteArray *inputData, QByteArray *inputSignature) : + QDialog(parent) { mCtx = ctx; mKeyList = keyList; //mTextpage = edit; @@ -42,12 +42,11 @@ VerifyDetailsDialog::VerifyDetailsDialog(QWidget *parent, GpgME::GpgContext* ctx this->exec(); } -void VerifyDetailsDialog::slotRefresh() -{ +void VerifyDetailsDialog::slotRefresh() { mVbox->close(); mVbox = new QWidget(); - QVBoxLayout *mVboxLayout = new QVBoxLayout(mVbox); + auto *mVboxLayout = new QVBoxLayout(mVbox); mainLayout->addWidget(mVbox); // Button Box for close button @@ -58,16 +57,16 @@ void VerifyDetailsDialog::slotRefresh() //QByteArray text = mTextpage->toPlainText().toUtf8(); //mCtx->preventNoDataErr(&text); gpgme_signature_t sign; - if(mInputSignature != 0) { + if (mInputSignature != nullptr) { sign = mCtx->verify(mInputData, mInputSignature); } else { sign = mCtx->verify(mInputData); } - if(sign==0) { - mVboxLayout->addWidget(new QLabel(tr("No valid input found"))); - mVboxLayout->addWidget(buttonBox); - return; + if (sign == nullptr) { + mVboxLayout->addWidget(new QLabel(tr("No valid input found"))); + mVboxLayout->addWidget(buttonBox); + return; } // Get timestamp of signature of current text @@ -75,26 +74,28 @@ void VerifyDetailsDialog::slotRefresh() timestamp.setTime_t(sign->timestamp); // Set the title widget depending on sign status - if(gpg_err_code(sign->status) == GPG_ERR_BAD_SIGNATURE) { + if (gpg_err_code(sign->status) == GPG_ERR_BAD_SIGNATURE) { mVboxLayout->addWidget(new QLabel(tr("Error Validating signature"))); - } else if (mInputSignature != 0) { - mVboxLayout->addWidget(new QLabel(tr("File was signed on <br/> %1 by:<br/>").arg(timestamp.toString(Qt::SystemLocaleLongDate)))); + } else if (mInputSignature != nullptr) { + mVboxLayout->addWidget(new QLabel( + tr("File was signed on <br/> %1 by:<br/>").arg(timestamp.toString(Qt::SystemLocaleLongDate)))); } else { - switch (mCtx->textIsSigned(*mInputData)) - { - case 2: - { - mVboxLayout->addWidget(new QLabel(tr("Text was completely signed on <br/> %1 by:<br/>").arg(timestamp.toString(Qt::SystemLocaleLongDate)))); break; + switch (GpgME::GpgContext::textIsSigned(*mInputData)) { + case 2: { + mVboxLayout->addWidget(new QLabel(tr("Text was completely signed on <br/> %1 by:<br/>").arg( + timestamp.toString(Qt::SystemLocaleLongDate)))); + break; } - case 1: - { - mVboxLayout->addWidget(new QLabel(tr("Text was partially signed on <br/> %1 by:<br/>").arg(timestamp.toString(Qt::SystemLocaleLongDate)))); break; + case 1: { + mVboxLayout->addWidget(new QLabel(tr("Text was partially signed on <br/> %1 by:<br/>").arg( + timestamp.toString(Qt::SystemLocaleLongDate)))); + break; } } } // Add informationbox for every single key while (sign) { - VerifyKeyDetailBox *sbox = new VerifyKeyDetailBox(this,mCtx,mKeyList,sign); + auto *sbox = new VerifyKeyDetailBox(this, mCtx, mKeyList, sign); sign = sign->next; mVboxLayout->addWidget(sbox); } diff --git a/src/verifykeydetailbox.cpp b/src/verifykeydetailbox.cpp index b040d4f9..e5f88aaa 100644 --- a/src/verifykeydetailbox.cpp +++ b/src/verifykeydetailbox.cpp @@ -21,20 +21,18 @@ #include "verifykeydetailbox.h" -VerifyKeyDetailBox::VerifyKeyDetailBox(QWidget *parent, GpgME::GpgContext* ctx, KeyList* keyList, gpgme_signature_t signature) : - QGroupBox(parent) -{ +VerifyKeyDetailBox::VerifyKeyDetailBox(QWidget *parent, GpgME::GpgContext *ctx, KeyList *keyList, + gpgme_signature_t signature) : + QGroupBox(parent) { this->mCtx = ctx; this->mKeyList = keyList; - this->fpr=signature->fpr; + this->fpr = signature->fpr; - QGridLayout *grid = new QGridLayout(); + auto *grid = new QGridLayout(); - switch (gpg_err_code(signature->status)) - { - case GPG_ERR_NO_PUBKEY: - { - QPushButton *importButton = new QPushButton(tr("Import from keyserver")); + switch (gpg_err_code(signature->status)) { + case GPG_ERR_NO_PUBKEY: { + auto *importButton = new QPushButton(tr("Import from keyserver")); connect(importButton, SIGNAL(clicked()), this, SLOT(slotImportFormKeyserver())); this->setTitle(tr("Key not present with id 0x") + signature->fpr); @@ -43,11 +41,10 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(QWidget *parent, GpgME::GpgContext* ctx, //grid->addWidget(new QLabel(tr("Fingerprint:")), 1, 0); grid->addWidget(new QLabel(tr("Key not present in keylist")), 0, 1); //grid->addWidget(new QLabel(signature->fpr), 1, 1); - grid->addWidget(importButton, 2,0,2,1); + grid->addWidget(importButton, 2, 0, 2, 1); break; } - case GPG_ERR_NO_ERROR: - { + case GPG_ERR_NO_ERROR: { GpgKey key = mCtx->getKeyByFpr(signature->fpr); this->setTitle(key.name); @@ -63,8 +60,7 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(QWidget *parent, GpgME::GpgContext* ctx, break; } - default: - { + default: { GpgKey key = mCtx->getKeyById(signature->fpr); this->setTitle(tr("Error for key with id 0x") + fpr); grid->addWidget(new QLabel(tr("Name:")), 0, 0); @@ -83,17 +79,15 @@ VerifyKeyDetailBox::VerifyKeyDetailBox(QWidget *parent, GpgME::GpgContext* ctx, this->setLayout(grid); } -void VerifyKeyDetailBox::slotImportFormKeyserver() -{ - KeyServerImportDialog *importDialog =new KeyServerImportDialog(mCtx,mKeyList,this); +void VerifyKeyDetailBox::slotImportFormKeyserver() { + auto *importDialog = new KeyServerImportDialog(mCtx, mKeyList, this); importDialog->slotImport(QStringList(fpr)); } -QString VerifyKeyDetailBox::beautifyFingerprint(QString fingerprint) -{ +QString VerifyKeyDetailBox::beautifyFingerprint(QString fingerprint) { uint len = fingerprint.length(); if ((len > 0) && (len % 4 == 0)) - for (uint n = 0; 4 *(n + 1) < len; ++n) - fingerprint.insert(5 * n + 4, ' '); + for (uint n = 0; 4 * (n + 1) < len; ++n) + fingerprint.insert(static_cast<int>(5u * n + 4u), ' '); return fingerprint; } diff --git a/src/verifynotification.cpp b/src/verifynotification.cpp index 6e739610..746fa1ed 100644 --- a/src/verifynotification.cpp +++ b/src/verifynotification.cpp @@ -21,9 +21,8 @@ #include "verifynotification.h" -VerifyNotification::VerifyNotification(QWidget *parent, GpgME::GpgContext *ctx, KeyList *keyList,QTextEdit *edit) : - QWidget(parent) -{ +VerifyNotification::VerifyNotification(QWidget *parent, GpgME::GpgContext *ctx, KeyList *keyList, QTextEdit *edit) : + QWidget(parent) { mCtx = ctx; mKeyList = keyList; mTextpage = edit; @@ -44,109 +43,103 @@ VerifyNotification::VerifyNotification(QWidget *parent, GpgME::GpgContext *ctx, importFromKeyserverAct->setVisible(false); keysNotInList = new QStringList(); - detailsButton = new QPushButton(tr("Details"),this); + detailsButton = new QPushButton(tr("Details"), this); detailsButton->setMenu(detailMenu); - QHBoxLayout *notificationWidgetLayout = new QHBoxLayout(this); - notificationWidgetLayout->setContentsMargins(10,0,0,0); - notificationWidgetLayout->addWidget(verifyLabel,2); + auto *notificationWidgetLayout = new QHBoxLayout(this); + notificationWidgetLayout->setContentsMargins(10, 0, 0, 0); + notificationWidgetLayout->addWidget(verifyLabel, 2); notificationWidgetLayout->addWidget(detailsButton); this->setLayout(notificationWidgetLayout); } -void VerifyNotification::slotImportFromKeyserver() -{ - KeyServerImportDialog *importDialog =new KeyServerImportDialog(mCtx,mKeyList, this); +void VerifyNotification::slotImportFromKeyserver() { + auto *importDialog = new KeyServerImportDialog(mCtx, mKeyList, this); importDialog->slotImport(*keysNotInList); } -void VerifyNotification::setVerifyLabel(QString text, verify_label_status verifyLabelStatus) -{ +void VerifyNotification::setVerifyLabel(const QString &text, verify_label_status verifyLabelStatus) { QString color; verifyLabel->setText(text); switch (verifyLabelStatus) { - case VERIFY_ERROR_OK: color="#ccffcc"; - break; - case VERIFY_ERROR_WARN: color="#ececba"; - break; - case VERIFY_ERROR_CRITICAL: color="#ff8080"; - break; - default: - break; + case VERIFY_ERROR_OK: + color = "#ccffcc"; + break; + case VERIFY_ERROR_WARN: + color = "#ececba"; + break; + case VERIFY_ERROR_CRITICAL: + color = "#ff8080"; + break; + default: + break; } verifyLabel->setAutoFillBackground(true); QPalette status = verifyLabel->palette(); status.setColor(QPalette::Background, color); verifyLabel->setPalette(status); -} +} -void VerifyNotification::showImportAction(bool visible) -{ +void VerifyNotification::showImportAction(bool visible) { importFromKeyserverAct->setVisible(visible); } -void VerifyNotification::slotShowVerifyDetails() -{ +void VerifyNotification::slotShowVerifyDetails() { QByteArray text = mTextpage->toPlainText().toUtf8(); - mCtx->preventNoDataErr(&text); + GpgME::GpgContext::preventNoDataErr(&text); new VerifyDetailsDialog(this, mCtx, mKeyList, &text); } -bool VerifyNotification::slotRefresh() -{ - verify_label_status verifyStatus=VERIFY_ERROR_OK; +bool VerifyNotification::slotRefresh() { + verify_label_status verifyStatus = VERIFY_ERROR_OK; QByteArray text = mTextpage->toPlainText().toUtf8(); - mCtx->preventNoDataErr(&text); - int textIsSigned = mCtx->textIsSigned(text); + GpgME::GpgContext::preventNoDataErr(&text); + int textIsSigned = GpgME::GpgContext::textIsSigned(text); gpgme_signature_t sign = mCtx->verify(&text); - if (sign == NULL) { + if (sign == nullptr) { return false; } QString verifyLabelText; - bool unknownKeyFound=false; + bool unknownKeyFound = false; while (sign) { - switch (gpg_err_code(sign->status)) - { - case GPG_ERR_NO_PUBKEY: - { - verifyStatus=VERIFY_ERROR_WARN; - verifyLabelText.append(tr("Key not present with id 0x")+QString(sign->fpr)); + switch (gpg_err_code(sign->status)) { + case GPG_ERR_NO_PUBKEY: { + verifyStatus = VERIFY_ERROR_WARN; + verifyLabelText.append(tr("Key not present with id 0x") + QString(sign->fpr)); this->keysNotInList->append(sign->fpr); - unknownKeyFound=true; + unknownKeyFound = true; break; } - case GPG_ERR_NO_ERROR: - { + case GPG_ERR_NO_ERROR: { GpgKey key = mCtx->getKeyByFpr(sign->fpr); verifyLabelText.append(key.name); if (!key.email.isEmpty()) { - verifyLabelText.append("<"+key.email+">"); + verifyLabelText.append("<" + key.email + ">"); } break; } - case GPG_ERR_BAD_SIGNATURE: - { + case GPG_ERR_BAD_SIGNATURE: { textIsSigned = 3; - verifyStatus=VERIFY_ERROR_CRITICAL; + verifyStatus = VERIFY_ERROR_CRITICAL; GpgKey key = mCtx->getKeyById(sign->fpr); verifyLabelText.append(key.name); if (!key.email.isEmpty()) { - verifyLabelText.append("<"+key.email+">"); + verifyLabelText.append("<" + key.email + ">"); } break; } - default: - { + default: { //textIsSigned = 3; - verifyStatus=VERIFY_ERROR_WARN; + verifyStatus = VERIFY_ERROR_WARN; //GpgKey key = mKeyList->getKeyByFpr(sign->fpr); - verifyLabelText.append(tr("Error for key with fingerprint ")+mCtx->beautifyFingerprint(QString(sign->fpr))); + verifyLabelText.append(tr("Error for key with fingerprint ") + + GpgME::GpgContext::beautifyFingerprint(QString(sign->fpr))); break; } } @@ -154,32 +147,28 @@ bool VerifyNotification::slotRefresh() sign = sign->next; } - switch (textIsSigned) - { + switch (textIsSigned) { case 3: - { - verifyLabelText.prepend(tr("Error validating signature by: ")); - break; - } + verifyLabelText.prepend(tr("Error validating signature by: ")); + break; + case 2: - { - verifyLabelText.prepend(tr("Text was completely signed by: ")); - break; - } + verifyLabelText.prepend(tr("Text was completely signed by: ")); + break; + case 1: - { - verifyLabelText.prepend(tr("Text was partially signed by: ")); - break; - } + verifyLabelText.prepend(tr("Text was partially signed by: ")); + break; + } // If an unknown key is found, enable the importfromkeyserveraction this->showImportAction(unknownKeyFound); // Remove the last linebreak - verifyLabelText.remove(verifyLabelText.length()-1,1); + verifyLabelText.remove(verifyLabelText.length() - 1, 1); - this->setVerifyLabel(verifyLabelText,verifyStatus); + this->setVerifyLabel(verifyLabelText, verifyStatus); return true; } diff --git a/src/wizard.cpp b/src/wizard.cpp index 82e8235e..ed94ac8d 100644 --- a/src/wizard.cpp +++ b/src/wizard.cpp @@ -18,8 +18,6 @@ * along with gpg4usb. If not, see <http://www.gnu.org/licenses/> */ -#include <QtGui> - #include "wizard.h" #ifdef Q_OS_WIN @@ -27,17 +25,16 @@ #endif Wizard::Wizard(GpgME::GpgContext *ctx, KeyMgmt *keyMgmt, QWidget *parent) - : QWizard(parent) -{ - mCtx=ctx; - mKeyMgmt=keyMgmt; + : QWizard(parent) { + mCtx = ctx; + mKeyMgmt = keyMgmt; - setPage(Page_Intro,new IntroPage(this)); + setPage(Page_Intro, new IntroPage(this)); setPage(Page_Choose, new ChoosePage(this)); - setPage(Page_ImportFromGpg4usb,new ImportFromGpg4usbPage(mCtx, mKeyMgmt, this)); - setPage(Page_ImportFromGnupg,new ImportFromGnupgPage(mCtx, mKeyMgmt, this)); - setPage(Page_GenKey,new KeyGenPage(mCtx, this)); - setPage(Page_Conclusion,new ConclusionPage(this)); + setPage(Page_ImportFromGpg4usb, new ImportFromGpg4usbPage(mCtx, mKeyMgmt, this)); + setPage(Page_ImportFromGnupg, new ImportFromGnupgPage(mCtx, mKeyMgmt, this)); + setPage(Page_GenKey, new KeyGenPage(mCtx, this)); + setPage(Page_Conclusion, new ConclusionPage(this)); #ifndef Q_WS_MAC setWizardStyle(ModernStyle); #endif @@ -62,15 +59,14 @@ void Wizard::slotWizardAccepted() { // Don't show is mapped to show -> negation settings.setValue("wizard/showWizard", !field("showWizard").toBool()); - if(field("openHelp").toBool()) { + if (field("openHelp").toBool()) { emit signalOpenHelp("docu.html#content"); } } -bool Wizard::importPubAndSecKeysFromDir(const QString dir, KeyMgmt *keyMgmt) -{ - QFile secRingFile(dir+"/secring.gpg"); - QFile pubRingFile(dir+"/pubring.gpg"); +bool Wizard::importPubAndSecKeysFromDir(const QString &dir, KeyMgmt *keyMgmt) { + QFile secRingFile(dir + "/secring.gpg"); + QFile pubRingFile(dir + "/pubring.gpg"); // Return, if no keyrings are found in subdir of chosen dir if (!(pubRingFile.exists() or secRingFile.exists())) { @@ -82,7 +78,8 @@ bool Wizard::importPubAndSecKeysFromDir(const QString dir, KeyMgmt *keyMgmt) if (secRingFile.exists()) { // write content of secringfile to inBuffer if (!secRingFile.open(QIODevice::ReadOnly)) { - QMessageBox::critical(0, tr("Import error"), tr("Couldn't open private keyringfile: %1").arg(secRingFile.fileName())); + QMessageBox::critical(nullptr, tr("Import error"), + tr("Couldn't open private keyringfile: %1").arg(secRingFile.fileName())); return false; } inBuffer = secRingFile.readAll(); @@ -92,7 +89,8 @@ bool Wizard::importPubAndSecKeysFromDir(const QString dir, KeyMgmt *keyMgmt) if (pubRingFile.exists()) { // try to import public keys if (!pubRingFile.open(QIODevice::ReadOnly)) { - QMessageBox::critical(0, tr("Import error"), tr("Couldn't open public keyringfile: %1").arg(pubRingFile.fileName())); + QMessageBox::critical(nullptr, tr("Import error"), + tr("Couldn't open public keyringfile: %1").arg(pubRingFile.fileName())); return false; } inBuffer.append(pubRingFile.readAll()); @@ -105,29 +103,28 @@ bool Wizard::importPubAndSecKeysFromDir(const QString dir, KeyMgmt *keyMgmt) } IntroPage::IntroPage(QWidget *parent) - : QWizardPage(parent) -{ + : QWizardPage(parent) { setTitle(tr("Getting started...")); setSubTitle(tr("... with gpg4usb")); - QLabel *topLabel = new QLabel(tr("To use gpg4usb for decrypting and signing messages, you need a " - "private key. The next page will help you with " - "key generation or import.<br><br>" - "For more information have a look at the <a href='docu_concepts.html'>concepts</a> " - "(by clicking the link, the page will open in the main window). <br>")); + auto *topLabel = new QLabel(tr("To use gpg4usb for decrypting and signing messages, you need a " + "private key. The next page will help you with " + "key generation or import.<br><br>" + "For more information have a look at the <a href='docu_concepts.html'>concepts</a> " + "(by clicking the link, the page will open in the main window). <br>")); topLabel->setWordWrap(true); - connect(topLabel, SIGNAL(linkActivated(const QString&)), parentWidget()->parentWidget(), SLOT(openHelp(const QString&))); + connect(topLabel, SIGNAL(linkActivated(QString)), parentWidget()->parentWidget(), SLOT(openHelp(QString))); // QComboBox for language selection - QLabel *langLabel = new QLabel(tr("Choose a Language")); + auto *langLabel = new QLabel(tr("Choose a Language")); langLabel->setWordWrap(true); languages = SettingsDialog::listLanguages(); - QComboBox *langSelectBox = new QComboBox(); + auto *langSelectBox = new QComboBox(); - foreach(QString l, languages) { - langSelectBox->addItem(l); - } + foreach(QString l, languages) { + langSelectBox->addItem(l); + } // selected entry from config QSettings settings; QString langKey = settings.value("int/lang").toString(); @@ -139,63 +136,60 @@ IntroPage::IntroPage(QWidget *parent) connect(langSelectBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotLangChange(QString))); // set layout and add widgets - QVBoxLayout *layout = new QVBoxLayout; + auto *layout = new QVBoxLayout; layout->addWidget(topLabel); layout->addWidget(langLabel); layout->addWidget(langSelectBox); setLayout(layout); } -void IntroPage::slotLangChange(QString lang) { +void IntroPage::slotLangChange(const QString &lang) { QSettings settings; settings.setValue("int/lang", languages.key(lang)); settings.setValue("wizard/nextPage", this->wizard()->currentId()); qApp->exit(RESTART_CODE); } -int IntroPage::nextId() const -{ +int IntroPage::nextId() const { return Wizard::Page_Choose; } + ChoosePage::ChoosePage(QWidget *parent) - : QWizardPage(parent) -{ + : QWizardPage(parent) { setTitle(tr("Choose your action...")); setSubTitle(tr("...by clicking on the apropriate link.")); - QLabel *keygenLabel = new QLabel(tr("If you have never used gpg4usb before and also don't own a gpg key yet you " - "may possibly want to ")+"<a href=""Wizard::Page_GenKey"">" - +tr("create a new keypair")+"</a><hr>"); + auto *keygenLabel = new QLabel(tr("If you have never used gpg4usb before and also don't own a gpg key yet you " + "may possibly want to ") + "<a href=""Wizard::Page_GenKey"">" + + tr("create a new keypair") + "</a><hr>"); keygenLabel->setWordWrap(true); - connect(keygenLabel, SIGNAL(linkActivated(const QString&)), this, SLOT(slotJumpPage(const QString&))); + connect(keygenLabel, SIGNAL(linkActivated(QString)), this, SLOT(slotJumpPage(Qtring))); - QLabel *importGpg4usbLabel = new QLabel(tr("If you upgrade from an older version of gpg4usb you may want to ") - +"<a href=""Wizard::Page_ImportFromGpg4usb"">" - +tr("import settings and/or keys from gpg4usb")+"</a>"); + auto *importGpg4usbLabel = new QLabel(tr("If you upgrade from an older version of gpg4usb you may want to ") + + "<a href=""Wizard::Page_ImportFromGpg4usb"">" + + tr("import settings and/or keys from gpg4usb") + "</a>"); importGpg4usbLabel->setWordWrap(true); - connect(importGpg4usbLabel, SIGNAL(linkActivated(const QString&)), this, SLOT(slotJumpPage(const QString&))); + connect(importGpg4usbLabel, SIGNAL(linkActivated(QString)), this, SLOT(slotJumpPage(QString))); - QLabel *importGnupgLabel = new QLabel(tr("If you are already using GnuPG you may want to ") - +"<a href=""Wizard::Page_ImportFromGnupg"">" - +tr("import keys from GnuPG")+"</a><hr>"); + auto *importGnupgLabel = new QLabel(tr("If you are already using GnuPG you may want to ") + + "<a href=""Wizard::Page_ImportFromGnupg"">" + + tr("import keys from GnuPG") + "</a><hr>"); importGnupgLabel->setWordWrap(true); - connect(importGnupgLabel, SIGNAL(linkActivated(const QString&)), this, SLOT(slotJumpPage(const QString&))); + connect(importGnupgLabel, SIGNAL(linkActivated(QString)), this, SLOT(slotJumpPage(QString))); - QVBoxLayout *layout = new QVBoxLayout(); + auto *layout = new QVBoxLayout(); layout->addWidget(keygenLabel); layout->addWidget(importGnupgLabel); layout->addWidget(importGpg4usbLabel); setLayout(layout); - nextPage=Wizard::Page_Conclusion; + nextPage = Wizard::Page_Conclusion; } -int ChoosePage::nextId() const -{ +int ChoosePage::nextId() const { return nextPage; } -void ChoosePage::slotJumpPage(const QString& page) -{ +void ChoosePage::slotJumpPage(const QString &page) { QMetaObject qmo = Wizard::staticMetaObject; int index = qmo.indexOfEnumerator("WizardPages"); QMetaEnum m = qmo.enumerator(index); @@ -205,43 +199,41 @@ void ChoosePage::slotJumpPage(const QString& page) } ImportFromGpg4usbPage::ImportFromGpg4usbPage(GpgME::GpgContext *ctx, KeyMgmt *keyMgmt, QWidget *parent) - : QWizardPage(parent) -{ - mCtx=ctx; - mKeyMgmt=keyMgmt; + : QWizardPage(parent) { + mCtx = ctx; + mKeyMgmt = keyMgmt; setTitle(tr("Import from...")); setSubTitle(tr("...existing gpg4usb")); - QLabel *topLabel = new QLabel(tr("You can import keys and/or settings from existing gpg4usb. <br><br>" - "Just check what you want to import, click the import button and choose " - "the directory of your other gpg4usb in the appearing file dialog."), this); + auto *topLabel = new QLabel(tr("You can import keys and/or settings from existing gpg4usb. <br><br>" + "Just check what you want to import, click the import button and choose " + "the directory of your other gpg4usb in the appearing file dialog."), this); topLabel->setWordWrap(true); gpg4usbKeyCheckBox = new QCheckBox(); gpg4usbKeyCheckBox->setChecked(true); - QLabel *keyLabel = new QLabel(tr("Keys")); + auto *keyLabel = new QLabel(tr("Keys")); gpg4usbConfigCheckBox = new QCheckBox(); gpg4usbConfigCheckBox->setChecked(true); - QLabel *configLabel = new QLabel(tr("Configuration")); + auto *configLabel = new QLabel(tr("Configuration")); - QPushButton *importFromGpg4usbButton = new QPushButton(tr("Import from gpg4usb")); + auto *importFromGpg4usbButton = new QPushButton(tr("Import from gpg4usb")); connect(importFromGpg4usbButton, SIGNAL(clicked()), this, SLOT(slotImportFromOlderGpg4usb())); - QGridLayout *gpg4usbLayout = new QGridLayout(); - gpg4usbLayout->addWidget(topLabel,1,1,1,2); - gpg4usbLayout->addWidget(gpg4usbKeyCheckBox,2,1,Qt::AlignRight); - gpg4usbLayout->addWidget(keyLabel,2,2); - gpg4usbLayout->addWidget(gpg4usbConfigCheckBox,3,1,Qt::AlignRight); - gpg4usbLayout->addWidget(configLabel,3,2); - gpg4usbLayout->addWidget(importFromGpg4usbButton,4,2); + auto *gpg4usbLayout = new QGridLayout(); + gpg4usbLayout->addWidget(topLabel, 1, 1, 1, 2); + gpg4usbLayout->addWidget(gpg4usbKeyCheckBox, 2, 1, Qt::AlignRight); + gpg4usbLayout->addWidget(keyLabel, 2, 2); + gpg4usbLayout->addWidget(gpg4usbConfigCheckBox, 3, 1, Qt::AlignRight); + gpg4usbLayout->addWidget(configLabel, 3, 2); + gpg4usbLayout->addWidget(importFromGpg4usbButton, 4, 2); this->setLayout(gpg4usbLayout); } -void ImportFromGpg4usbPage::slotImportFromOlderGpg4usb() -{ - QString dir = QFileDialog::getExistingDirectory(this,tr("Other gpg4usb directory")); +void ImportFromGpg4usbPage::slotImportFromOlderGpg4usb() { + QString dir = QFileDialog::getExistingDirectory(this, tr("Other gpg4usb directory")); // Return, if cancel was hit if (dir.isEmpty()) { @@ -250,7 +242,7 @@ void ImportFromGpg4usbPage::slotImportFromOlderGpg4usb() // try to import keys, if appropriate box is checked, return, if import was unsuccessful if (gpg4usbKeyCheckBox->isChecked()) { - if (!Wizard::importPubAndSecKeysFromDir(dir+"/keydb",mKeyMgmt)) { + if (!Wizard::importPubAndSecKeysFromDir(dir + "/keydb", mKeyMgmt)) { return; } } @@ -261,69 +253,66 @@ void ImportFromGpg4usbPage::slotImportFromOlderGpg4usb() QSettings settings; settings.setValue("wizard/nextPage", this->nextId()); - QMessageBox::information(0,tr("Configuration Imported"),tr("Imported Configuration from old gpg4usb.<br>" - "Will now restart to activate the configuration.")); + QMessageBox::information(nullptr, tr("Configuration Imported"), + tr("Imported Configuration from old gpg4usb.<br>" + "Will now restart to activate the configuration.")); // TODO: edit->maybesave? qApp->exit(RESTART_CODE); } wizard()->next(); } -bool ImportFromGpg4usbPage::slotImportConfFromGpg4usb(QString dir) { - QString path = dir+"/conf/gpg4usb.ini"; +bool ImportFromGpg4usbPage::slotImportConfFromGpg4usb(const QString &dir) { + QString path = dir + "/conf/gpg4usb.ini"; QSettings oldconf(path, QSettings::IniFormat, this); QSettings actualConf; - foreach(QString key, oldconf.allKeys()) { - actualConf.setValue(key, oldconf.value(key)); - } + foreach(QString key, oldconf.allKeys()) { + actualConf.setValue(key, oldconf.value(key)); + } return true; } -int ImportFromGpg4usbPage::nextId() const -{ +int ImportFromGpg4usbPage::nextId() const { return Wizard::Page_Conclusion; } ImportFromGnupgPage::ImportFromGnupgPage(GpgME::GpgContext *ctx, KeyMgmt *keyMgmt, QWidget *parent) - : QWizardPage(parent) -{ - mCtx=ctx; - mKeyMgmt=keyMgmt; + : QWizardPage(parent) { + mCtx = ctx; + mKeyMgmt = keyMgmt; setTitle(tr("Import keys...")); setSubTitle(tr("...from existing GnuPG installation")); - QLabel *gnupgLabel = new QLabel(tr("You can import keys from a locally installed GnuPG.<br><br> The location is read " - "from registry in Windows or assumed to be the .gnupg folder in the your home directory in Linux.<br>")); + auto *gnupgLabel = new QLabel(tr("You can import keys from a locally installed GnuPG.<br><br> The location is read " + "from registry in Windows or assumed to be the .gnupg folder in the your home directory in Linux.<br>")); gnupgLabel->setWordWrap(true); importFromGnupgButton = new QPushButton(tr("Import keys from GnuPG")); connect(importFromGnupgButton, SIGNAL(clicked()), this, SLOT(slotrImportKeysFromGnupg())); - QGridLayout *layout = new QGridLayout(); + auto *layout = new QGridLayout(); layout->addWidget(gnupgLabel); layout->addWidget(importFromGnupgButton); this->setLayout(layout); } -void ImportFromGnupgPage::slotrImportKeysFromGnupg() -{ +void ImportFromGnupgPage::slotrImportKeysFromGnupg() { // first get gnupghomedir and check, if it exists QString gnuPGHome = getGnuPGHome(); - if (gnuPGHome == NULL) { + if (gnuPGHome == nullptr) { QMessageBox::critical(0, tr("Import Error"), tr("Couldn't locate GnuPG home directory")); return; } // Try to import the keyring files and return the return value of the method - Wizard::importPubAndSecKeysFromDir(gnuPGHome,mKeyMgmt); + Wizard::importPubAndSecKeysFromDir(gnuPGHome, mKeyMgmt); wizard()->next(); } -QString ImportFromGnupgPage::getGnuPGHome() -{ - QString gnuPGHome=""; - #ifdef _WIN32 +QString ImportFromGnupgPage::getGnuPGHome() { + QString gnuPGHome = ""; +#ifdef _WIN32 bool existsAndSuccess = false; HKEY hKey; @@ -338,45 +327,43 @@ QString ImportFromGnupgPage::getGnuPGHome() return NULL; } } - #else - gnuPGHome=QDir::homePath()+"/.gnupg"; - if (! QFile(gnuPGHome).exists()) { - return NULL; - } - #endif +#else + gnuPGHome = QDir::homePath() + "/.gnupg"; + if (!QFile(gnuPGHome).exists()) { + return nullptr; + } +#endif return gnuPGHome; } -int ImportFromGnupgPage::nextId() const -{ +int ImportFromGnupgPage::nextId() const { return Wizard::Page_Conclusion; } KeyGenPage::KeyGenPage(GpgME::GpgContext *ctx, QWidget *parent) - : QWizardPage(parent) -{ - mCtx=ctx; + : QWizardPage(parent) { + mCtx = ctx; setTitle(tr("Create a keypair...")); setSubTitle(tr("...for decrypting and signing messages")); - QLabel *topLabel = new QLabel(tr("You should create a new keypair." - "The pair consists of a public and a private key.<br>" - "Other users can use the public key to encrypt messages for you " - "and verify messages signed by you." - "You can use the private key to decrypt and sign messages.<br>" - "For more information have a look at the offline tutorial (which then is shown in the main window):")); + auto *topLabel = new QLabel(tr("You should create a new keypair." + "The pair consists of a public and a private key.<br>" + "Other users can use the public key to encrypt messages for you " + "and verify messages signed by you." + "You can use the private key to decrypt and sign messages.<br>" + "For more information have a look at the offline tutorial (which then is shown in the main window):")); topLabel->setWordWrap(true); - QLabel *linkLabel = new QLabel("<a href=""docu_keygen.html#content"">"+tr("Offline tutorial")+"</a>"); + auto *linkLabel = new QLabel("<a href=""docu_keygen.html#content"">" + tr("Offline tutorial") + "</a>"); //linkLabel->setOpenExternalLinks(true); - connect(linkLabel, SIGNAL(linkActivated(const QString&)), parentWidget()->parentWidget(), SLOT(openHelp(const QString&))); + connect(linkLabel, SIGNAL(linkActivated(QString)), parentWidget()->parentWidget(), SLOT(openHelp(QString))); - QWidget *createKeyButtonBox = new QWidget(this); - QHBoxLayout *createKeyButtonBoxLayout = new QHBoxLayout(createKeyButtonBox); - QPushButton *createKeyButton = new QPushButton(tr("Create New Key")); + auto *createKeyButtonBox = new QWidget(this); + auto *createKeyButtonBoxLayout = new QHBoxLayout(createKeyButtonBox); + auto *createKeyButton = new QPushButton(tr("Create New Key")); createKeyButtonBoxLayout->addWidget(createKeyButton); createKeyButtonBoxLayout->addStretch(1); - QVBoxLayout *layout = new QVBoxLayout(); + auto *layout = new QVBoxLayout(); layout->addWidget(topLabel); layout->addWidget(linkLabel); layout->addWidget(createKeyButtonBox); @@ -385,27 +372,24 @@ KeyGenPage::KeyGenPage(GpgME::GpgContext *ctx, QWidget *parent) setLayout(layout); } -int KeyGenPage::nextId() const -{ +int KeyGenPage::nextId() const { return Wizard::Page_Conclusion; } -void KeyGenPage::slotGenerateKeyDialog() -{ - KeyGenDialog *keyGenDialog = new KeyGenDialog(mCtx, this); +void KeyGenPage::slotGenerateKeyDialog() { + auto *keyGenDialog = new KeyGenDialog(mCtx, this); keyGenDialog->exec(); wizard()->next(); } ConclusionPage::ConclusionPage(QWidget *parent) - : QWizardPage(parent) -{ + : QWizardPage(parent) { setTitle(tr("Ready.")); setSubTitle(tr("Have fun with gpg4usb!")); - QLabel *bottomLabel = new QLabel(tr("You are ready to use gpg4usb now.<br><br>" - "The offline help will get you started with gpg4usb. " - "It will open in the main window.<br>")); + auto *bottomLabel = new QLabel(tr("You are ready to use gpg4usb now.<br><br>" + "The offline help will get you started with gpg4usb. " + "It will open in the main window.<br>")); bottomLabel->setWordWrap(true); openHelpCheckBox = new QCheckBox(tr("Open offline help.")); @@ -417,7 +401,7 @@ ConclusionPage::ConclusionPage(QWidget *parent) registerField("showWizard", dontShowWizardCheckBox); registerField("openHelp", openHelpCheckBox); - QVBoxLayout *layout = new QVBoxLayout; + auto *layout = new QVBoxLayout; layout->addWidget(bottomLabel); layout->addWidget(openHelpCheckBox); layout->addWidget(dontShowWizardCheckBox); @@ -425,7 +409,6 @@ ConclusionPage::ConclusionPage(QWidget *parent) setVisible(true); } -int ConclusionPage::nextId() const -{ +int ConclusionPage::nextId() const { return -1; } |