author | Michael Krelin <hacker@klever.net> | 2007-07-04 11:23:42 (UTC) |
---|---|---|
committer | Michael Krelin <hacker@klever.net> | 2007-07-04 11:23:42 (UTC) |
commit | a08aff328d4393031d5ba7d622c2b05705a89d73 (patch) (side-by-side diff) | |
tree | 8ee90d686081c52e7c69b5ce946e9b1a7d690001 /pwmanager | |
parent | 11edc920afe4f274c0964436633aa632c8288a40 (diff) | |
download | kdepimpi-a08aff328d4393031d5ba7d622c2b05705a89d73.zip kdepimpi-a08aff328d4393031d5ba7d622c2b05705a89d73.tar.gz kdepimpi-a08aff328d4393031d5ba7d622c2b05705a89d73.tar.bz2 |
initial public commit of qt4 portp1
68 files changed, 483 insertions, 364 deletions
diff --git a/pwmanager/libcrypt/cipher/cipher.pro b/pwmanager/libcrypt/cipher/cipher.pro index ad96201..7e1a330 100644 --- a/pwmanager/libcrypt/cipher/cipher.pro +++ b/pwmanager/libcrypt/cipher/cipher.pro @@ -1,70 +1,72 @@ ###################################################################### # Automatically generated by qmake (1.07a) Tue Oct 19 14:06:16 2004 ###################################################################### TEMPLATE = lib INCLUDEPATH += . .. ../crypt ../error CONFIG += staticlib OBJECTS_DIR = obj/$(PLATFORM) MOC_DIR = moc/$(PLATFORM) DESTDIR= ../$(PLATFORM) TARGET = kpmicrocipher # Input HEADERS += bithelp.h rand-internal.h random.h rmd.h SOURCES += ac.c \ arcfour.c \ blowfish.c \ cast5.c \ cipher.c \ crc.c \ des.c \ dsa.c \ elgamal.c \ md.c \ md4.c \ md5.c \ primegen.c \ pubkey.c \ random.c \ rfc2268.c \ rijndael.c \ rmd160.c \ rndegd.c \ rndlinux.c \ rndunix.c \ rsa.c \ serpent.c \ sha1.c \ sha256.c \ sha512.c \ tiger.c \ twofish.c # rndw32.c \ HEADERS += ../crypt/ath.h \ ../crypt/cipher.h \ ../crypt/g10lib.h \ ../crypt/gcrypt-module.h \ ../crypt/gcrypt.h \ ../crypt/mpi.h \ ../crypt/secmem.h \ ../crypt/stdmem.h \ ../crypt/types.h SOURCES += ../crypt/ath.c \ ../crypt/global.c \ ../crypt/misc.c \ ../crypt/missing-string.c \ ../crypt/module.c \ ../crypt/secmem.c \ ../crypt/sexp.c \ ../crypt/stdmem.c #LIBS += -L../$(PLATFORM) #LIBS += -lgcrypt -lmpi -lerror +#The following line was inserted by qt3to4 +QT += xml qt3support diff --git a/pwmanager/libcrypt/error/error.pro b/pwmanager/libcrypt/error/error.pro index 8c5f667..e96bcee 100644 --- a/pwmanager/libcrypt/error/error.pro +++ b/pwmanager/libcrypt/error/error.pro @@ -1,32 +1,34 @@ ###################################################################### # Automatically generated by qmake (1.07a) Tue Oct 19 15:09:32 2004 ###################################################################### TEMPLATE = lib CONFIG += staticlib INCLUDEPATH += . OBJECTS_DIR = obj/$(PLATFORM) MOC_DIR = moc/$(PLATFORM) DESTDIR= ../$(PLATFORM) TARGET = kpmicroerror # Input HEADERS += code-from-errno.h \ code-to-errno.h \ err-codes-sym.h \ err-codes.h \ err-sources-sym.h \ err-sources.h \ errnos-sym.h \ gettext.h SOURCES += code-from-errno.c \ code-to-errno.c \ strerror-sym.c \ strerror.c \ strsource-sym.c \ strsource.c # gpg-error.c \ # gpg-error.h \ # mkerrcodes.h - # mkerrcodes.c \
\ No newline at end of file + # mkerrcodes.c \ +#The following line was inserted by qt3to4 +QT += xml qt3support diff --git a/pwmanager/libcrypt/mpi/mpi.pro b/pwmanager/libcrypt/mpi/mpi.pro index 4eb6346..d213bc3 100644 --- a/pwmanager/libcrypt/mpi/mpi.pro +++ b/pwmanager/libcrypt/mpi/mpi.pro @@ -1,42 +1,44 @@ ###################################################################### # Automatically generated by qmake (1.07a) Tue Oct 19 15:37:52 2004 ###################################################################### TEMPLATE = lib CONFIG += staticlib DEPENDPATH += generic INCLUDEPATH += . .. ../crypt ../error OBJECTS_DIR = obj/$(PLATFORM) MOC_DIR = moc/$(PLATFORM) DESTDIR= ../$(PLATFORM) TARGET = kpmicrompi # Input HEADERS += asm-syntax.h \ longlong.h \ generic/mpi-asm-defs.h \ mpi-inline.h \ mpi-internal.h \ sysdep.h SOURCES += mpi-add.c \ mpi-bit.c \ mpi-cmp.c \ mpi-div.c \ mpi-gcd.c \ mpi-inline.c \ mpi-inv.c \ mpi-mpow.c \ mpi-mul.c \ mpi-pow.c \ mpi-scan.c \ mpicoder.c \ mpih-div.c \ mpih-mul.c \ mpiutil.c \ generic/mpih-add1.c \ generic/mpih-lshift.c \ generic/mpih-mul1.c \ generic/mpih-mul2.c \ generic/mpih-mul3.c \ generic/mpih-rshift.c \ generic/mpih-sub1.c \ generic/udiv-w-sdiv.c +#The following line was inserted by qt3to4 +QT += xml qt3support diff --git a/pwmanager/libcrypt/zlib/zlib.pro b/pwmanager/libcrypt/zlib/zlib.pro index 2841aaf..7ba44e3 100644 --- a/pwmanager/libcrypt/zlib/zlib.pro +++ b/pwmanager/libcrypt/zlib/zlib.pro @@ -1,36 +1,38 @@ ###################################################################### # Automatically generated by qmake (1.07a) Tue Oct 19 14:18:17 2004 ###################################################################### TEMPLATE = lib CONFIG += staticlib INCLUDEPATH += . TARGET = zlib OBJECTS_DIR = obj/$(PLATFORM) MOC_DIR = moc/$(PLATFORM) DESTDIR= ../$(PLATFORM) # Input HEADERS += deflate.h \ infblock.h \ infcodes.h \ inffast.h \ inffixed.h \ inftrees.h \ infutil.h \ trees.h \ zconf.h \ zlib.h \ zutil.h SOURCES += adler32.c \ compress.c \ crc32.c \ deflate.c \ infblock.c \ infcodes.c \ inffast.c \ inflate.c \ inftrees.c \ infutil.c \ trees.c \ uncompr.c \ zutil.c +#The following line was inserted by qt3to4 +QT += xml qt3support diff --git a/pwmanager/pwmanager/addentrywnd_emb.cpp b/pwmanager/pwmanager/addentrywnd_emb.cpp index 2fa9e8a..f76d33b 100644 --- a/pwmanager/pwmanager/addentrywnd_emb.cpp +++ b/pwmanager/pwmanager/addentrywnd_emb.cpp @@ -1,233 +1,236 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #include "addentrywnd_emb.h" #include "pwmdoc.h" #include <qlayout.h> #include <qlabel.h> #include <qtabwidget.h> -#include <qgroupbox.h> +#include <q3groupbox.h> +//Added by qt3to4: +#include <Q3GridLayout> +#include <Q3VBoxLayout> #include <klocale.h> #include <kcombobox.h> #include <klineedit.h> #include <qpushbutton.h> -#include <qmultilineedit.h> +#include <q3multilineedit.h> /* * Constructs a addEntryWnd as a child of 'parent', with the * name 'name' and widget flags set to 'f'. * * The dialog will by default be modeless, unless you set 'modal' to * TRUE to construct a modal dialog. */ addEntryWnd::addEntryWnd( PwMDoc* d, QWidget* parent, const char* name) : KDialogBase( KDialogBase::Plain, i18n( "edit/add a password entry" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, parent, name, true ), doc(d) { QWidget *page = plainPage(); - QVBoxLayout *pageLayout = new QVBoxLayout( page ); + Q3VBoxLayout *pageLayout = new Q3VBoxLayout( page ); QTabWidget* mTabWidget = new QTabWidget( page ); pageLayout->addWidget( mTabWidget ); //////////////////////////////////////////////////////////////////// // This is the Password tab QWidget *tab1 = new QWidget( mTabWidget ); - QGridLayout *layout = new QGridLayout( tab1, 3, 1 ); + Q3GridLayout *layout = new Q3GridLayout( tab1, 3, 1 ); layout->setMargin( KDialogBase::marginHint() ); layout->setSpacing( KDialogBase::spacingHint() ); int i = 0; descLineEdit = new KLineEdit( tab1, "descLineEdit" ); descLineLabel = new QLabel( descLineEdit, i18n("Description:"), tab1 ); layout->addWidget( descLineLabel, i, 0 ); layout->addWidget( descLineEdit, i, 1 ); i++; categoryComboBox = new KComboBox( tab1 ); QLabel* label = new QLabel( categoryComboBox, i18n("Category:"), tab1 ); layout->addWidget( label, i, 0 ); layout->addWidget( categoryComboBox, i, 1 ); i++; categoryComboBox->setEditable( TRUE ); - categoryComboBox->setSizeLimit( 8 ); + categoryComboBox->setMaxVisibleItems( 8 ); categoryComboBox->setAutoCompletion( TRUE ); categoryComboBox->setDuplicatesEnabled( FALSE ); connect(categoryComboBox,SIGNAL(activated(const QString&)), SLOT(categorySelected(const QString&))); usernameLineEdit = new KLineEdit( tab1, "usernameLineEdit" ); usernameLineLabel = new QLabel( usernameLineEdit, i18n("Username:"), tab1 ); layout->addWidget( usernameLineLabel, i, 0 ); layout->addWidget( usernameLineEdit, i, 1 ); i++; pwLineEdit = new KLineEdit( tab1, "pwLineEdit" ); pwLineEdit->setEchoMode( QLineEdit::Password ); pwLineLabel = new QLabel( pwLineEdit, i18n("Password:"), tab1 ); layout->addWidget( pwLineLabel, i, 0 ); layout->addWidget( pwLineEdit, i, 1 ); i++; revealButton = new QPushButton( i18n("&Reveal"), tab1, "revealButton" ); revealButton->setToggleButton( TRUE ); layout->addWidget( revealButton, i, 0 ); generateButton = new QPushButton( i18n("&Generate"), tab1, "generateButton" ); layout->addWidget( generateButton, i, 1 ); i++; urlLineEdit = new KLineEdit( tab1, "urlLineEdit" ); label = new QLabel( urlLineEdit, i18n("URL:"), tab1 ); layout->addWidget( label, i, 0 ); layout->addWidget( urlLineEdit, i, 1 ); i++; mTabWidget->addTab( tab1, i18n( "&Password" ) ); //////////////////////////////////////////////////////////////////// // This is the Comment tab QWidget *tab2 = new QWidget( mTabWidget ); - layout = new QGridLayout( tab2, 3, 1 ); + layout = new Q3GridLayout( tab2, 3, 1 ); layout->setMargin( KDialogBase::marginHintSmall() ); layout->setSpacing( KDialogBase::spacingHintSmall() ); i = 0; - commentTextEdit = new QMultiLineEdit(tab2); + commentTextEdit = new Q3MultiLineEdit(tab2); layout->addMultiCellWidget( commentTextEdit, i, i, 0, 0 ); i++; mTabWidget->addTab( tab2, i18n( "&Comments" ) ); //////////////////////////////////////////////////////////////////// // This is the Launcher tab QWidget *tab3 = new QWidget( mTabWidget ); - layout = new QGridLayout( tab3, 3, 1 ); + layout = new Q3GridLayout( tab3, 3, 1 ); layout->setMargin( KDialogBase::marginHintSmall() ); layout->setSpacing( KDialogBase::spacingHintSmall() ); i = 0; launcherLineEdit = new KLineEdit( tab3, "launcherLineEdit" ); label = new QLabel( launcherLineEdit, i18n("Launcher:"), tab3 ); QLabel* label1 = new QLabel( launcherLineEdit, i18n("$d = Description"), tab3 ); QLabel* label2 = new QLabel( launcherLineEdit, i18n("$n = Username"), tab3 ); QLabel* label3 = new QLabel( launcherLineEdit, i18n("$c = Comment"), tab3 ); QLabel* label4 = new QLabel( launcherLineEdit, i18n("$u = URL"), tab3 ); QLabel* label5 = new QLabel( launcherLineEdit, i18n("$p = Password"), tab3 ); label = new QLabel( launcherLineEdit, i18n("Launcher:"), tab3 ); layout->addWidget( label1, i, 0 ); layout->addWidget( label2, i, 1 ); i++; layout->addWidget( label3, i, 0 ); layout->addWidget( label4, i, 1 ); i++; layout->addWidget( label5, i, 0 ); i++; layout->addWidget( label, i, 0 ); layout->addWidget( launcherLineEdit, i, 1 ); i++; mTabWidget->addTab( tab3, i18n( "&Launcher" ) ); // signals and slots connections connect( generateButton, SIGNAL( clicked() ), this, SLOT( generateButton_slot() ) ); connect( revealButton, SIGNAL( toggled(bool) ), this, SLOT( revealButton_slot() ) ); #if 0 if ( QApplication::desktop()->width() <= 640 && QApplication::desktop()->width() >= 480 ) { resize ( 440, 400 ); } #endif } /* * Destroys the object and frees any allocated resources */ addEntryWnd::~addEntryWnd() { // no need to delete child widgets, Qt does it all for us } void addEntryWnd::slotOk() { qWarning( "addEntryWnd::slotOk(): Not implemented yet" ); } void addEntryWnd::revealButton_slot() { qWarning( "addEntryWnd::revealButton_slot(): Not implemented yet" ); } void addEntryWnd::generateButton_slot() { qWarning( "addEntryWnd::generateButton_slot(): Not implemented yet" ); } void addEntryWnd::advancedCommentButton_slot(bool) { qWarning( "addEntryWnd::advancedCommentButton_slot(bool): Not implemented yet" ); } void addEntryWnd::categorySelected ( const QString & string ) { unsigned int idx; bool found = doc->findCategory(string, &idx); if (found == true) { qDebug("addEntryWnd::categorySelected found"); PwMCategoryItem* catitem = doc->getCategoryEntry(idx); descLineLabel->setText(catitem->desc_text.c_str()); usernameLineLabel->setText(catitem->name_text.c_str()); pwLineLabel->setText(catitem->pw_text.c_str()); return; } else { qDebug("addEntryWnd::categorySelected NOT found"); BUG(); } } diff --git a/pwmanager/pwmanager/addentrywnd_emb.h b/pwmanager/pwmanager/addentrywnd_emb.h index 966d9d2..ad7d30c 100644 --- a/pwmanager/pwmanager/addentrywnd_emb.h +++ b/pwmanager/pwmanager/addentrywnd_emb.h @@ -1,78 +1,83 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #ifndef ADDENTRYWND_EMB_H #define ADDENTRYWND_EMB_H #include <qvariant.h> +//Added by qt3to4: +#include <Q3VBoxLayout> +#include <Q3GridLayout> +#include <Q3HBoxLayout> +#include <QLabel> #include <kdialogbase.h> -class QVBoxLayout; -class QHBoxLayout; -class QGridLayout; +class Q3VBoxLayout; +class Q3HBoxLayout; +class Q3GridLayout; class QSpacerItem; class KLineEdit; class QPushButton; class KComboBox; class QLabel; -class QGroupBox; -class QMultiLineEdit; +class Q3GroupBox; +class Q3MultiLineEdit; class PwMDoc; class addEntryWnd : public KDialogBase { Q_OBJECT public: addEntryWnd( PwMDoc* doc, QWidget* parent = 0, const char* name = 0); ~addEntryWnd(); KLineEdit* launcherLineEdit; QPushButton* generateButton; KLineEdit* descLineEdit; KComboBox* categoryComboBox; KLineEdit* usernameLineEdit; KLineEdit* pwLineEdit; KLineEdit* urlLineEdit; QLabel* descLineLabel; QLabel* usernameLineLabel; QLabel* pwLineLabel; QPushButton* revealButton; - QMultiLineEdit* commentTextEdit; + Q3MultiLineEdit* commentTextEdit; PwMDoc* doc; public slots: virtual void revealButton_slot(); virtual void generateButton_slot(); virtual void advancedCommentButton_slot(bool on); protected slots: virtual void slotOk(); virtual void categorySelected ( const QString & string ); }; #endif // ADDENTRYWND_H diff --git a/pwmanager/pwmanager/addentrywndimpl.cpp b/pwmanager/pwmanager/addentrywndimpl.cpp index 09efd1c..c952ead 100644 --- a/pwmanager/pwmanager/addentrywndimpl.cpp +++ b/pwmanager/pwmanager/addentrywndimpl.cpp @@ -1,221 +1,221 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * Many very good improvements and the original implementations of * * them came from Matt Scifo <mscifo@o1.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "addentrywndimpl.h" #include "pwmexception.h" #include "pwgenwndimpl.h" #ifndef PWM_EMBEDDED #include "advcommeditimpl.h" #endif #include "htmlgen.h" #include <kmessagebox.h> #include <klocale.h> #include <qpushbutton.h> #include <qlabel.h> #include <qlayout.h> #ifndef PWM_EMBEDDED AddEntryWndImpl::AddEntryWndImpl() : addEntryWnd( 0, "AddEntryWndImpl", TRUE) #else AddEntryWndImpl::AddEntryWndImpl( PwMDoc* doc, QWidget* parent, const char* name) : addEntryWnd( doc, parent, name) #endif { categoryComboBox->setSizePolicy( QSizePolicy( QSizePolicy::Expanding,QSizePolicy::Preferred )); #ifndef PWM_EMBEDDED editAdvCommentButton = 0; commentTextEdit = 0; #endif switchComment(false); pwGen = new PwGenWndImpl(this); } AddEntryWndImpl::~AddEntryWndImpl() { #ifndef PWM_EMBEDDED delete_ifnot_null(editAdvCommentButton); delete_ifnot_null(commentTextEdit); #endif delete pwGen; } #ifdef PWM_EMBEDDED void AddEntryWndImpl::slotOk() { slotApply(); if (pwLineEdit->text().isEmpty()) { KMessageBox::error(this, i18n("Sorry, you haven't set a password."), i18n("no password")); return; } if (descLineEdit->text().isEmpty()) { KMessageBox::error(this, i18n("You haven't set a \"Description\"."), i18n("Description not set")); return; } KDialogBase::slotOk(); } #else void AddEntryWndImpl::okButton_slot() { if (pwLineEdit->text().isEmpty()) { KMessageBox::error(this, i18n("Sorry, you haven't set a password."), i18n("no password")); return; } if (descLineEdit->text().isEmpty()) { KMessageBox::error(this, i18n ("You haven't set a \"Description\"."), i18n("Description not set")); return; } done(1); } void AddEntryWndImpl::cancelButton_slot() { done(2); } #endif void AddEntryWndImpl::setCurrCategory(const QString &cat) { int i, count = categoryComboBox->count(); for (i = 0; i < count; ++i) { if (categoryComboBox->text(i) == cat) { categoryComboBox->setCurrentItem(i); #ifdef PWM_EMBEDDED categorySelected(cat); #endif return; } } BUG(); } void AddEntryWndImpl::revealButton_slot() { if (revealButton->isOn()) { pwLineEdit->setEchoMode(QLineEdit::Normal); } else { pwLineEdit->setEchoMode(QLineEdit::Password); } } void AddEntryWndImpl::generateButton_slot() { if (!pwGen->exec()) return; setPassword(pwGen->getPassword()); } QString AddEntryWndImpl::getComment() { #ifndef PWM_EMBEDDED if (isAdvancedComment()) { return advCommentDta; } #endif return commentTextEdit->text(); } void AddEntryWndImpl::setComment(const QString &comm) { #ifndef PWM_EMBEDDED if (HtmlGen::isHtml(comm)) { advancedCommentButton->setOn(true); advCommentDta = comm; } else { advancedCommentButton->setOn(false); commentTextEdit->setText(comm); } #else commentTextEdit->setText(comm); #endif } void AddEntryWndImpl::advancedCommentButton_slot(bool on) { #ifndef PWM_EMBEDDED switchComment(on); #endif } void AddEntryWndImpl::switchComment(bool toAdvanced) { #ifndef PWM_EMBEDDED useAdvComment = toAdvanced; if (toAdvanced) { if (commentTextEdit) { savedCommentText = commentTextEdit->text(); delete_and_null(commentTextEdit); } if (editAdvCommentButton) return; editAdvCommentButton = new QPushButton(i18n("Edit advanced comment..."), commentDummy); editAdvCommentButton->resize(commentDummy->size().width(), 50); connect(editAdvCommentButton, SIGNAL(clicked()), this, SLOT(editAdvCommentButton_slot())); editAdvCommentButton->show(); } else { delete_ifnot_null(editAdvCommentButton); if (commentTextEdit) return; - commentTextEdit = new QTextEdit(commentDummy); + commentTextEdit = new Q3TextEdit(commentDummy); commentTextEdit->setTextFormat(Qt::PlainText); commentTextEdit->resize(commentDummy->size()); commentTextEdit->setText(savedCommentText); commentTextEdit->show(); } #endif } void AddEntryWndImpl::editAdvCommentButton_slot() { #ifndef PWM_EMBEDDED AdvCommEditImpl editor(this); editor.setHtmlDta(advCommentDta); if (editor.exec()) return; advCommentDta = editor.getHtmlDta(); #endif } -#ifndef PWM_EMBEDDED -#include "addentrywndimpl.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_addentrywndimpl.cpp" #endif diff --git a/pwmanager/pwmanager/addentrywndimpl.h b/pwmanager/pwmanager/addentrywndimpl.h index e13eb54..c5f4bb1 100644 --- a/pwmanager/pwmanager/addentrywndimpl.h +++ b/pwmanager/pwmanager/addentrywndimpl.h @@ -1,127 +1,127 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __ADDENTRYWNDIMPL_H #define __ADDENTRYWNDIMPL_H #ifndef PWM_EMBEDDED #include <qlineedit.h> -#include <qtextedit.h> +#include <q3textedit.h> #include <qcombobox.h> #include "addentrywnd.h" #else #include <klineedit.h> #include <kcombobox.h> -#include <qmultilineedit.h> +#include <q3multilineedit.h> #include "addentrywnd_emb.h" #endif #include <qpushbutton.h> class PwGenWndImpl; /** "add/edit" Window */ class AddEntryWndImpl : public addEntryWnd { Q_OBJECT public: #ifndef PWM_EMBEDDED AddEntryWndImpl(); #else AddEntryWndImpl( PwMDoc* doc, QWidget* parent = 0, const char* name = 0); #endif ~AddEntryWndImpl(); /* get... functions */ QString getDescription() { return descLineEdit->text(); } QString getCategory() { return categoryComboBox->currentText(); } QString getUsername() { return usernameLineEdit->text(); } QString getPassword() { return pwLineEdit->text(); } QString getUrl() { return urlLineEdit->text(); } QString getLauncher() { return launcherLineEdit->text(); } QString getComment(); /* set... functions */ void setDescription(const QString &desc) { descLineEdit->setText(desc); } void setCurrCategory(const QString &cat); void addCategory(const QString &cat) { categoryComboBox->insertItem(cat); } void setUsername(const QString &name) { usernameLineEdit->setText(name); } void setPassword(const QString &pw) { pwLineEdit->setText(pw); } void setUrl(const QString &url) { urlLineEdit->setText(url); } void setLauncher(const QString launcher) { launcherLineEdit->setText(launcher); } void setComment(const QString &comm); /** are we using an advanced comment */ bool isAdvancedComment() { return useAdvComment; } public slots: #ifndef PWM_EMBEDDED -//MOC_SKIP_BEGIN +#ifndef Q_MOC_RUN /** OK button pressed */ void okButton_slot(); /** cancel button pressed */ void cancelButton_slot(); -//MOC_SKIP_END +#endif #else virtual void slotOk(); #endif /** Reveal button pressed */ void revealButton_slot(); /** Generate button pressed */ void generateButton_slot(); /** advanced comment button pressed */ void advancedCommentButton_slot(bool on); /** edit advanced comment button pressed */ void editAdvCommentButton_slot(); protected: void switchComment(bool toAdvanced); protected: QPushButton *editAdvCommentButton; #ifndef PWM_EMBEDDED - QTextEdit *commentTextEdit; + Q3TextEdit *commentTextEdit; #else //nothing here #endif /** saved data from normal comment text edit box */ QString savedCommentText; /** use an advanced comment? */ bool useAdvComment; /** data of advanced comment (if available) */ QString advCommentDta; /** password generation object */ PwGenWndImpl *pwGen; }; #endif diff --git a/pwmanager/pwmanager/binentrygen.h b/pwmanager/pwmanager/binentrygen.h index 49288aa..9263cdc 100644 --- a/pwmanager/pwmanager/binentrygen.h +++ b/pwmanager/pwmanager/binentrygen.h @@ -1,65 +1,65 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __BINENTRYGEN_H #define __BINENTRYGEN_H -#include <qcstring.h> +#include <q3cstring.h> #include "pwmdoc.h" /** Binary entry generator. * This generator generates a normal struct PwMDataItem * from binary data (using base64 encoding). * This mechanism is used to support the binary interface functions * of the KWallet emulation, for example. * * The format of the encoded binary data as a PwMDataItem is as follows: * * PwMDataItem::desc contains the normal description string for * this entry. Nothing surprising. * PwMDataItem::name contains the "DataType" number in ascii format. * PwMDataItem::pw contains the base64 encoded data stream. * PwMDataItem::binary is always true for binary entries. * All other PwMDataItems are currently unused by BinEntryGen. */ class BinEntryGen { public: enum DataType { None = 0, KWalletMap, KWalletStream }; public: BinEntryGen() { } /** Encode the binary "data" and return it in "ret" */ void encode(const QByteArray &data, PwMDataItem *ret, DataType type); /** Decode the "data" and return it as binary "ret" */ void decode(const PwMDataItem &data, QByteArray *ret, DataType *type); /** Return the data type for this binary data item */ DataType binType(const PwMDataItem &data); }; #endif // __BINENTRYGEN_H diff --git a/pwmanager/pwmanager/commentbox.cpp b/pwmanager/pwmanager/commentbox.cpp index 5416856..a60440d 100644 --- a/pwmanager/pwmanager/commentbox.cpp +++ b/pwmanager/pwmanager/commentbox.cpp @@ -1,283 +1,283 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "commentbox.h" #include "pwmexception.h" #include "htmlgen.h" #include <klocale.h> #ifndef PWM_EMBEDDED #include <khtml_part.h> #include <khtmlview.h> -#include <qtextedit.h> +#include <q3textedit.h> #else -#include <qmultilineedit.h> +#include <q3multilineedit.h> #endif #ifndef PWM_EMBEDDED CommentBox::CommentBox(QWidget *_parentWidget) { PWM_ASSERT(_parentWidget); parentWidget = _parentWidget; textDta = 0; htmlDta = 0; mode = mode_notSet; setFont( prefs->mViewFont ); } CommentBox::~CommentBox() { clearText(); clearHtml(); } void CommentBox::clear() { clearText(); clearHtml(); mode = mode_notSet; this->hide(); } void CommentBox::clearText() { delete_ifnot_null(textDta); } void CommentBox::clearHtml() { delete_ifnot_null(htmlDta); } void CommentBox::setText(const QString &text) { switchTo(mode_text); PWM_ASSERT(textDta); textDta->setText( text); if (!textDta->isVisible()) textDta->show(); } bool CommentBox::getText(QString *text) { if (mode != mode_text) return false; PWM_ASSERT(text); if (!textDta) { *text = ""; return true; } *text = textDta->text(); return true; } void CommentBox::setHtml(QString code) { switchTo(mode_html); PWM_ASSERT(htmlDta); if (!HtmlGen::replaceSSDummy(&code)) printWarn("CommentBox::setHtml(): replaceSSDummy() failed!"); htmlDta->begin(); htmlDta->write(code); htmlDta->end(); htmlDta->show(); } void CommentBox::setContent(const QString &dta) { // if there's no data, hide the comment-box if (dta.isEmpty()) { clear(); return; } if (HtmlGen::isHtml(dta)) { setHtml(dta); return; } // we assume it's plain text setText(dta); } void CommentBox::switchTo(commentBoxMode newMode) { if (newMode == mode) return; // cleanup old mode switch (mode) { case mode_text: clearText(); break; case mode_html: clearHtml(); break; default: break; } // setup new mode switch (newMode) { case mode_text: - textDta = new QTextEdit(parentWidget); + textDta = new Q3TextEdit(parentWidget); textDta->setTextFormat(Qt::PlainText); textDta->setReadOnly(true); textDta->show(); break; case mode_html: htmlDta = new KHTMLPart(parentWidget, 0, parentWidget); htmlDta->show(); break; default: BUG(); break; } mode = newMode; } void CommentBox::show() { switch (mode) { case mode_text: PWM_ASSERT(textDta); textDta->show(); break; case mode_html: PWM_ASSERT(htmlDta); htmlDta->show(); break; default: break; } } void CommentBox::hide() { switch (mode) { case mode_text: PWM_ASSERT(textDta); textDta->hide(); break; case mode_html: PWM_ASSERT(htmlDta); htmlDta->hide(); break; default: break; } } void CommentBox::resize(const QSize &size) { switch (mode) { case mode_text: PWM_ASSERT(textDta); textDta->resize(size); break; case mode_html: PWM_ASSERT(htmlDta); htmlDta->view()->resize(size); break; default: break; } } QSize CommentBox::size() { switch (mode) { case mode_text: PWM_ASSERT(textDta); return textDta->size(); break; case mode_html: PWM_ASSERT(htmlDta); return htmlDta->view()->size(); break; default: break; } return QSize(); } //////////////////////////////////////////////////////////////////////// #else CommentBox::CommentBox(QWidget *_parentWidget) - : QTextBrowser(_parentWidget) + : Q3TextBrowser(_parentWidget) { //this->setReadOnly(true); - setFocusPolicy( QWidget::ClickFocus ); + setFocusPolicy( Qt::ClickFocus ); } CommentBox::~CommentBox() { } void CommentBox::clear() { this->hide(); } void CommentBox::setText(const QString &text) { - QTextBrowser::setText( text); + Q3TextBrowser::setText( text); if (!isVisible()) show(); } bool CommentBox::getText(QString *text) { *text = this->text(); return true; } void CommentBox::setContent(const QString &dta) { // if there's no data, hide the comment-box if (dta.isEmpty()) { clear(); return; } // we assume it's plain text setText(dta); } #endif diff --git a/pwmanager/pwmanager/commentbox.h b/pwmanager/pwmanager/commentbox.h index 3103353..d14ba13 100644 --- a/pwmanager/pwmanager/commentbox.h +++ b/pwmanager/pwmanager/commentbox.h @@ -1,124 +1,124 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef COMMENTBOX_H #define COMMENTBOX_H #include <qstring.h> #include <qsize.h> class QWidget; -class QTextEdit; +class Q3TextEdit; class KHTMLPart; #ifndef PWM_EMBEDDED class CommentBox { protected: enum commentBoxMode { mode_notSet = 0, mode_text, mode_html }; public: CommentBox(QWidget *_parentWidget); ~CommentBox(); /** clear all data in the comment box */ void clear(); /** show the comment box */ void show(); /** hide the comment box */ void hide(); /** resize the comment box */ void resize(const QSize &size); void resize(int w, int h) { resize(QSize(w, h)); } /** get the size of the comment box */ QSize size(); /** if neccessary switch to text-mode and * insert this text into the comment box */ void setText(const QString &text); /** get the text of the comment box. * If it's not in text-mode it returns false */ bool getText(QString *text); /** if neccessary switch to HTML-mode and * insert this html code into the comment box */ void setHtml(QString code); /** checks "dta" for its type, sets the correct * mode and writes "dta" to the comment box */ void setContent(const QString &dta); protected: /** switch the current mode */ void switchTo(commentBoxMode newMode); /** clear all text data */ void clearText(); /** clear all HTML data */ void clearHtml(); protected: /** parent widget for this comment box */ QWidget *parentWidget; /** current comment box usage type */ commentBoxMode mode; /** if the comment box is a normal textbox, data is stored here */ - QTextEdit *textDta; + Q3TextEdit *textDta; /** if the comment box is a HTML box, data is stored here */ KHTMLPart *htmlDta; }; #else -#include <qtextbrowser.h> +#include <q3textbrowser.h> /** Implementation of the advanced HTML comment box */ //US ENH: CommentBox must be derived from QWidget, to allow the splitter to set a initial size // without conflicting with the two display modes -class CommentBox : public QTextBrowser +class CommentBox : public Q3TextBrowser { public: CommentBox(QWidget *_parentWidget); ~CommentBox(); /** clear all data in the comment box */ void clear(); /** if neccessary switch to text-mode and * insert this text into the comment box */ void setText(const QString &text); /** get the text of the comment box. * If it's not in text-mode it returns false */ bool getText(QString *text); /** if neccessary switch to HTML-mode and * insert this html code into the comment box */ void setContent(const QString &dta); }; #endif #endif diff --git a/pwmanager/pwmanager/csv.cpp b/pwmanager/pwmanager/csv.cpp index 194edf2..226cc08 100644 --- a/pwmanager/pwmanager/csv.cpp +++ b/pwmanager/pwmanager/csv.cpp @@ -1,428 +1,430 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.1 of pwmanager * and was modified to run on embedded devices that run microkde * The original file version was 1.2 * $Id$ **************************************************************************/ #include "csv.h" #include "pwmdoc.h" #include "pwmexception.h" #include <kmessagebox.h> #include <klocale.h> +//Added by qt3to4: +#include <Q3CString> #define MAX_CSV_FILE_SIZE (50 * 1024 * 1024) // bytes Csv::Csv(QWidget *_parent) : parent (_parent) { } Csv::~Csv() { } bool Csv::importData(const QString &filepath, PwMDoc *doc) { bool ret = true; QByteArray d; QFile f(filepath); - if (!f.open(IO_ReadOnly)) { + if (!f.open(QIODevice::ReadOnly)) { KMessageBox::error(parent, i18n("Could not open file.\n" "Does the file exist?"), i18n("Open error.")); ret = false; goto out; } if (f.size() > MAX_CSV_FILE_SIZE) { KMessageBox::error(parent, i18n("File too big.\nMaximum file size is 1 Byte.", "File too big.\nMaximum file size is %n Bytes.", MAX_CSV_FILE_SIZE), i18n("File too big.")); ret = false; goto out_close; } d = f.readAll(); if (d.isEmpty()) { KMessageBox::error(parent, i18n("Could not read file or file empty."), i18n("Reading failed.")); ret = false; goto out_close; } if (!doImport(d, doc)) { KMessageBox::error(parent, i18n("Import failed.\n" "Corrupt CSV data format."), i18n("File corrupt.")); ret = false; goto out_close; } out_close: f.close(); out: return ret; } bool Csv::doImport(const QByteArray &d, PwMDoc *doc) { PwMDataItem di; //US ENH: initialize all members: di.clear(); int refIndex = 0; int ret; - QCString s, curCat; + Q3CString s, curCat; int fieldIndex = 0; bool inRecord = false; /* fieldIndex is a reference count to see which * value we are attaching to di. * Valid counts are: * 0 -> category * 1 -> desc * 2 -> name * 3 -> pw * 4 -> url * 5 -> launcher * 6 -> comment */ while (1) { ret = nextField(&s, d, inRecord, &refIndex); switch (ret) { case 0: // successfully got next field. inRecord = true; switch (fieldIndex) { case 0: // category if (s.isEmpty()) { /* This is special case. It's the category * list terminating empty field. */ ++fieldIndex; } else curCat = s; break; case 1: // desc - di.desc = s; + di.desc = std::string(s); ++fieldIndex; break; case 2: // name - di.name = s; + di.name = std::string(s); ++fieldIndex; break; case 3: // pw - di.pw = s; + di.pw = std::string(s); ++fieldIndex; break; case 4: // url - di.url = s; + di.url = std::string(s); ++fieldIndex; break; case 5: // launcher - di.launcher = s; + di.launcher = std::string(s); ++fieldIndex; break; case 6: // comment - di.comment = s; + di.comment = std::string(s); ++fieldIndex; break; default: /* Too many fields in a record. * We simply throw it away. */ break; } break; case 1: // record complete. if (fieldIndex == 6) - di.comment = s; + di.comment = std::string(s); inRecord = false; fieldIndex = 0; doc->addEntry(curCat, &di, true); //US ENH: clear di for the next row di.clear(); break; case 2: // data completely parsed. doc->flagDirty(); return true; case -1: // parse error doc->flagDirty(); return false; } } BUG(); return false; } -int Csv::nextField(QCString *ret, +int Csv::nextField(Q3CString *ret, const QByteArray &in, bool inRecord, int *_refIndex) { int rv = -2; char c; bool inField = false; bool isQuoted = false; bool searchingTerminator = false; int refIndex; int inSize = static_cast<int>(in.size()); ret->truncate(0); for (refIndex = *_refIndex; refIndex < inSize; ++refIndex) { c = in.at(refIndex); if (!inField) { // we have to search the field beginning, now. switch (c) { case ' ': // space case ' ': // tab // hm, still not the beginning. Go on.. break; case '\r': case '\n': if (inRecord) { /* This is the end of the last field in * the record. */ PWM_ASSERT(ret->isEmpty()); rv = 1; // record end goto out; } else { // hm, still not the beginning. Go on.. break; } case ',': // Oh, an empty field. How sad. PWM_ASSERT(ret->isEmpty()); rv = 0; // field end goto out; case '\"': // this is the quoted beginning. inField = true; isQuoted = true; if (refIndex + 1 >= inSize) goto unexp_eof; break; default: // this is the unquoted beginning. inField = true; isQuoted = false; *ret += c; break; } } else { // we are in the field now. Search the end. if (isQuoted) { if (searchingTerminator) { switch (c) { case '\r': case '\n': rv = 1; // record end goto out; case ',': // found it. rv = 0; // field end goto out; default: // go on. continue; } } switch (c) { case '\"': /* check if this is the end of the * entry, or just an inline escaped quote. */ char next; if (refIndex + 1 >= inSize) { // This is the last char, so it's the end. rv = 2; // data end goto out; } next = in.at(refIndex + 1); switch (next) { case '\"': // This is an escaped double quote. // So skip next iteration. refIndex += 1; *ret += c; break; default: /* end of field. * We have to search the comma (or newline...), * which officially terminates the entry. */ searchingTerminator = true; break; } break; default: // nothing special about the char. Go on! *ret += c; break; } } else { switch (c) { case '\"': // This is not allowed here. return -1; // parser error case '\r': case '\n': rv = 1; // record end goto out; case ',': rv = 0; // field end goto out; default: // nothing special about the char. Go on! *ret += c; break; } } } } // we are at the end of the stream, now! if (searchingTerminator) { /* Ok, there's no terminating comma (or newline...), * because we are at the end. That's perfectly fine. */ PWM_ASSERT(inField); rv = 2; // data end goto out; } if (!isQuoted && inField) { // That's the end of the last unquoted field. rv = 2; // data end goto out; } if (!inField) { // This is expected EOF rv = 2; // data end goto out; } unexp_eof: printDebug("unexpected EOF :("); return -1; // parser error out: if (!isQuoted) *ret = ret->stripWhiteSpace(); *_refIndex = refIndex + 1; return rv; } bool Csv::exportData(const QString &filepath, PwMDoc *doc) { PWM_ASSERT(!doc->isDocEmpty()); bool ret = true; if (QFile::exists(filepath)) { int ret; ret = KMessageBox::questionYesNo(parent, i18n("This file does already exist.\n" "Do you want to overwrite it?"), i18n("Overwrite file?")); if (ret == KMessageBox::No) return false; if (!QFile::remove(filepath)) { KMessageBox::error(parent, i18n("Could not delete the old file."), i18n("Delete error.")); return false; } } QFile f(filepath); - if (!f.open(IO_ReadWrite)) { + if (!f.open(QIODevice::ReadWrite)) { KMessageBox::error(parent, i18n("Could not open file for writing."), i18n("Open error.")); ret = false; goto out; } doc->unlockAll_tempoary(); if (!doExport(f, doc)) ret = false; doc->unlockAll_tempoary(true); f.close(); out: return ret; } bool Csv::doExport(QFile &f, PwMDoc *doc) { unsigned int numCat = doc->numCategories(); unsigned int numEntr; unsigned int i, j; PwMDataItem d; - QCString s, catName; + Q3CString s, catName; QByteArray b; for (i = 0; i < numCat; ++i) { numEntr = doc->numEntries(i); catName = newField(doc->getCategory(i)->c_str()); for (j = 0; j < numEntr; ++j) { doc->getEntry(i, j, &d); s = catName; s += ",,"; s += newField(d.desc.c_str()); s += ","; s += newField(d.name.c_str()); s += ","; s += newField(d.pw.c_str()); s += ","; s += newField(d.url.c_str()); s += ","; s += newField(d.launcher.c_str()); s += ","; s += newField(d.comment.c_str()); s += "\r\n"; b = s; // remove \0 termination #ifndef PWM_EMBEDDED - b.resize(b.size() - 1, QGArray::SpeedOptim); + b.resize(b.size() - 1, Q3GArray::SpeedOptim); #else b.resize(b.size() - 1); #endif if (!f.writeBlock(b)) return false; } } return true; } -QCString Csv::newField(QCString s) +Q3CString Csv::newField(Q3CString s) { if (s.isEmpty()) - return QCString(); - QCString ret("\""); + return Q3CString(); + Q3CString ret("\""); #ifndef PWM_EMBEDDED s.replace('\"', "\"\""); #else - s.replace(QRegExp("\""), "\"\""); + s.replace("\"", "\"\""); #endif ret += s; ret += "\""; return ret; } diff --git a/pwmanager/pwmanager/csv.h b/pwmanager/pwmanager/csv.h index 6f3c1e1..8049122 100644 --- a/pwmanager/pwmanager/csv.h +++ b/pwmanager/pwmanager/csv.h @@ -1,91 +1,91 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.1 of pwmanager * and was modified to run on embedded devices that run microkde * The original file version was 1.2 * $Id$ **************************************************************************/ #ifndef __PWMANAGER_CSV_H #define __PWMANAGER_CSV_H -#include <qcstring.h> +#include <q3cstring.h> #include <qfile.h> class PwMDoc; class QString; class QWidget; /** class for CSV (Comma Separated Value) export and import. * * http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm * http://en.wikipedia.org/wiki/Comma-separated_values * * There are two types of CSV output we can produce. * One with Category support (recommended): * "Category 1",, "Desc 1", "Username 1", "Password 1", "URL 1", "Launcher 1", "Comment 1" * "Category 1",, "Desc 2", "Username 2", "Password 2", "URL 2", "Launcher 2", "Comment 2" * ... * The empty "" is neccessary, because in future versions we will * support nested Categories. We want to be future compatible, now. * * And one without Category support: *FIXME: it's not implemented, yet. ;) * "Desc 1", "Username 1", "Password 1", "URL 1", "Launcher 1", "Comment 1" * "Desc 2", "Username 2", "Password 2", "URL 2", "Launcher 2", "Comment 2" * ... * */ class Csv { public: Csv(QWidget *_parent); ~Csv(); /** import data from "filepath" into "doc" */ bool importData(const QString &filepath, PwMDoc *doc); /** export data from "doc" to "filepath" */ bool exportData(const QString &filepath, PwMDoc *doc); protected: /** do the import process. */ bool doImport(const QByteArray &d, PwMDoc *doc); /** parse for the next field. * @return Return values are: * 0 -> successfully got the next field. * 1 -> record end. * 2 -> data end. * -1 -> parser error. */ - int nextField(QCString *ret, + int nextField(Q3CString *ret, const QByteArray &in, bool inRecord, int *_refIndex); /** do the export process. */ bool doExport(QFile &f, PwMDoc *doc); /** generate a new data field string. */ - QCString newField(QCString s); + Q3CString newField(Q3CString s); protected: /** current parent widget. */ QWidget *parent; }; #endif // __PWMANAGER_CSV_H diff --git a/pwmanager/pwmanager/editcategory.cpp b/pwmanager/pwmanager/editcategory.cpp index 4e2378c..4f19299 100644 --- a/pwmanager/pwmanager/editcategory.cpp +++ b/pwmanager/pwmanager/editcategory.cpp @@ -1,189 +1,191 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #include "editcategory.h" #include "pwmdoc.h" #include <qlayout.h> #include <qlabel.h> -#include <qgroupbox.h> +#include <q3groupbox.h> +//Added by qt3to4: +#include <Q3GridLayout> #include <klocale.h> #include <kcombobox.h> #include <klineedit.h> #include <qpushbutton.h> /* * Constructs a addEntryWnd as a child of 'parent', with the * name 'name' and widget flags set to 'f'. * * The dialog will by default be modeless, unless you set 'modal' to * TRUE to construct a modal dialog. */ editCategoryWnd::editCategoryWnd( PwMDoc* d, QWidget* parent, const char* name) : KDialogBase( KDialogBase::Plain, i18n( "edit category descriptions" ), Apply | User2 | Ok, Ok, parent, name, true ), doc(d) { findButton( Ok )->setText (i18n("Close" )) ; findButton( User2 )->setText (i18n("Cancel" )) ; connect(this,SIGNAL(user2Clicked()), SLOT(cancel_slot())); enableButton( KDialogBase::Apply, false ); QWidget *page = plainPage(); - QGridLayout *layout = new QGridLayout( page, 3, 1 ); + Q3GridLayout *layout = new Q3GridLayout( page, 3, 1 ); layout->setMargin( KDialogBase::marginHint() ); layout->setSpacing( KDialogBase::spacingHint() ); int i = 0; categoryComboBox = new KComboBox( page ); QLabel* label = new QLabel( categoryComboBox, i18n("Category:"), page ); layout->addWidget( label, i, 0 ); layout->addWidget( categoryComboBox, i, 1 ); i++; categoryComboBox->setEditable( FALSE ); - categoryComboBox->setSizeLimit( 100 ); + categoryComboBox->setMaxVisibleItems( 100 ); connect(categoryComboBox,SIGNAL(activated(const QString&)), SLOT(categorySelected(const QString&))); descLineEdit = new KLineEdit( page, "descLineEdit" ); label = new QLabel( descLineEdit, i18n("Text1 (Description):"), page ); layout->addWidget( label, i, 0 ); layout->addWidget( descLineEdit, i, 1 ); connect( descLineEdit, SIGNAL( textChanged ( const QString & ) ), SLOT( widgetModified(const QString &) ) ); i++; usernameLineEdit = new KLineEdit( page, "usernameLineEdit" ); label = new QLabel( usernameLineEdit, i18n("Text2 (Username):"), page ); layout->addWidget( label, i, 0 ); layout->addWidget( usernameLineEdit, i, 1 ); connect( usernameLineEdit, SIGNAL( textChanged ( const QString & ) ), SLOT( widgetModified(const QString &) ) ); i++; pwLineEdit = new KLineEdit( page, "pwLineEdit" ); label = new QLabel( pwLineEdit, i18n("Text3 (Password):"), page ); layout->addWidget( label, i, 0 ); layout->addWidget( pwLineEdit, i, 1 ); connect( pwLineEdit, SIGNAL( textChanged ( const QString & ) ), SLOT( widgetModified(const QString &) ) ); i++; unsigned int count = doc->numCategories(); for (unsigned int i = 0; i < count; ++i) { categoryComboBox->insertItem(doc->getCategory(i)->c_str()); } // PwMCategoryItem* getCategoryEntry(unsigned int index) // { return &(dti.dta[index]); } } /* * Destroys the object and frees any allocated resources */ editCategoryWnd::~editCategoryWnd() { // no need to delete child widgets, Qt does it all for us } void editCategoryWnd::slotOk() { // qDebug( "addEntryWnd::slotOk(): Not implemented yet" ); slotApply(); accept(); } void editCategoryWnd::slotApply() { QString cat = categoryComboBox->currentText(); unsigned int idx; bool found = doc->findCategory(cat, &idx); if (found == true) { PwMCategoryItem* catitem = doc->getCategoryEntry(idx); catitem->desc_text = descLineEdit->text().latin1(); catitem->name_text = usernameLineEdit->text().latin1(); catitem->pw_text = pwLineEdit->text().latin1(); enableButton( KDialogBase::Apply, false ); return; } BUG(); } void editCategoryWnd::cancel_slot() { QString cat = categoryComboBox->currentText(); categorySelected ( cat ); reject(); } void editCategoryWnd::setCurrCategory(const QString &cat) { int i, count = categoryComboBox->count(); for (i = 0; i < count; ++i) { if (categoryComboBox->text(i) == cat) { categoryComboBox->setCurrentItem(i); categorySelected ( cat ); return; } } BUG(); } void editCategoryWnd::categorySelected ( const QString & string ) { unsigned int idx; bool found = doc->findCategory(string, &idx); if (found == true) { PwMCategoryItem* catitem = doc->getCategoryEntry(idx); descLineEdit->setText(catitem->desc_text.c_str()); usernameLineEdit->setText(catitem->name_text.c_str()); pwLineEdit->setText(catitem->pw_text.c_str()); enableButton( KDialogBase::Apply, false ); return; } BUG(); } void editCategoryWnd::widgetModified(const QString &) { enableButton( KDialogBase::Apply, true ); } diff --git a/pwmanager/pwmanager/editcategory.h b/pwmanager/pwmanager/editcategory.h index 90b685b..10a012b 100644 --- a/pwmanager/pwmanager/editcategory.h +++ b/pwmanager/pwmanager/editcategory.h @@ -1,77 +1,82 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #ifndef EDITCATEGORY_H #define EDITCATEGORY_H #include <qvariant.h> +//Added by qt3to4: +#include <Q3VBoxLayout> +#include <Q3GridLayout> +#include <Q3HBoxLayout> +#include <QLabel> #include <kdialogbase.h> -class QVBoxLayout; -class QHBoxLayout; -class QGridLayout; +class Q3VBoxLayout; +class Q3HBoxLayout; +class Q3GridLayout; class QSpacerItem; class KLineEdit; class QPushButton; class KComboBox; class QLabel; -class QGroupBox; -class QMultiLineEdit; +class Q3GroupBox; +class Q3MultiLineEdit; class PwMDoc; class editCategoryWnd : public KDialogBase { Q_OBJECT public: editCategoryWnd( PwMDoc* doc, QWidget* parent = 0, const char* name = 0); ~editCategoryWnd(); void setCurrCategory(const QString &cat); KComboBox* categoryComboBox; KLineEdit* descLineEdit; KLineEdit* usernameLineEdit; KLineEdit* pwLineEdit; //public slots: // virtual void revealButton_slot(); // virtual void generateButton_slot(); // virtual void advancedCommentButton_slot(bool on); protected slots: virtual void slotOk(); virtual void slotApply(); virtual void cancel_slot(); virtual void categorySelected ( const QString & string ); virtual void widgetModified(const QString &); private: PwMDoc* doc; }; #endif // EDITCATEGORY_H diff --git a/pwmanager/pwmanager/findwnd_emb.cpp b/pwmanager/pwmanager/findwnd_emb.cpp index 6dcabe8..03d4e38 100644 --- a/pwmanager/pwmanager/findwnd_emb.cpp +++ b/pwmanager/pwmanager/findwnd_emb.cpp @@ -1,123 +1,125 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #include "findwnd_emb.h" #include <klocale.h> #include <qcheckbox.h> -#include <qbuttongroup.h> +#include <q3buttongroup.h> #include <qradiobutton.h> #include <qlayout.h> +//Added by qt3to4: +#include <Q3VBoxLayout> #include <klineedit.h> #include <qlabel.h> /* #include <qvariant.h> #include <qlabel.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qcheckbox.h> #include <qbuttongroup.h> #include <qradiobutton.h> #include <qlayout.h> #include <qtooltip.h> #include <qwhatsthis.h> */ /* * Constructs a findWnd as a child of 'parent', with the * name 'name'. */ findWnd::findWnd( QWidget* parent, const char* name ) : KDialogBase( KDialogBase::Plain, i18n( "Find" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, parent, name, true ) { QWidget *page = plainPage(); - QVBoxLayout *layout = new QVBoxLayout( page ); + Q3VBoxLayout *layout = new Q3VBoxLayout( page ); layout->setMargin( KDialogBase::marginHint() ); layout->setSpacing( KDialogBase::spacingHint() ); exactCheckBox = new QCheckBox( i18n( "&Exact match" ), page ); layout->addWidget( exactCheckBox ); caseSensCheckBox = new QCheckBox( i18n( "&Case sensitive" ), page ); layout->addWidget( caseSensCheckBox ); - QButtonGroup* buttonGroup1 = new QButtonGroup(1, Qt::Horizontal, i18n( "Search in Column" ), page ); + Q3ButtonGroup* buttonGroup1 = new Q3ButtonGroup(1, Qt::Horizontal, i18n( "Search in Column" ), page ); layout->addWidget( buttonGroup1 ); descRadioButton = new QRadioButton( i18n( "&Description" ), buttonGroup1 ); pwRadioButton = new QRadioButton( i18n( "&Password" ), buttonGroup1 ); commentRadioButton = new QRadioButton( i18n( "C&omment" ), buttonGroup1 ); nameRadioButton = new QRadioButton( i18n( "&Username" ), buttonGroup1 ); urlRadioButton = new QRadioButton( i18n( "U&RL" ), buttonGroup1 ); launcherRadioButton = new QRadioButton( i18n( "&Launcher" ), buttonGroup1 ); descRadioButton->setChecked( TRUE ); findLineEdit = new KLineEdit( page ); // QLabel* label = new QLabel( findLineEdit, i18n( "Find:" ), page ); //layout->addWidget( label ); layout->addWidget( findLineEdit ); setButtonText( KDialogBase::Ok, "&Find" ); setButtonText( KDialogBase::Cancel, "&Close" ); resize( sizeHint() ); connect( buttonGroup1, SIGNAL( clicked(int) ), this, SLOT( selectionChanged_slot() ) ); connect( findLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( selectionChanged_slot() ) ); connect( caseSensCheckBox, SIGNAL( stateChanged(int) ), this, SLOT( selectionChanged_slot() ) ); connect( exactCheckBox, SIGNAL( stateChanged(int) ), this, SLOT( selectionChanged_slot() ) ); } /* * Destroys the object and frees any allocated resources */ findWnd::~findWnd() { // no need to delete child widgets, Qt does it all for us } void findWnd::findButton_slot() { qWarning( "findWnd::findButton_slot(): Not implemented yet" ); } void findWnd::selectionChanged_slot() { qWarning( "findWnd::selectionChanged_slot(): Not implemented yet" ); } void findWnd::closeButton_slot() { qWarning( "findWnd::closeButton_slot(): Not implemented yet" ); } diff --git a/pwmanager/pwmanager/findwndimpl.cpp b/pwmanager/pwmanager/findwndimpl.cpp index 059219f..d323133 100644 --- a/pwmanager/pwmanager/findwndimpl.cpp +++ b/pwmanager/pwmanager/findwndimpl.cpp @@ -1,138 +1,138 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "findwndimpl.h" #include "pwmexception.h" #include "pwmdoc.h" #include "pwmview.h" #include <qradiobutton.h> #include <qlineedit.h> #include <qcheckbox.h> #include <kmessagebox.h> #include <klocale.h> FindWndImpl::FindWndImpl(PwMView * _parent) : findWnd() { parent = _parent; fAt = 0; refVal = 0; currFoundPos = -1; numEntries = parent->document()->numEntries(parent->getCurrentCategory()); connect(this, SIGNAL(foundAt(int)), parent, SLOT(selAt(int))); } FindWndImpl::~FindWndImpl() { } void FindWndImpl::findButton_slot() { if (findLineEdit->text() == "") return; static vector<unsigned int> foundPositions; PwMDoc *doc = parent->document(); if (currFoundPos < 0) { bool unlockedTempoary = false; foundPositions.clear(); PwMDataItem findThis; unsigned int searchIn = 0; if (descRadioButton->isChecked()) { searchIn = SEARCH_IN_DESC; findThis.desc = findLineEdit->text().latin1(); } else if (nameRadioButton->isChecked()) { searchIn = SEARCH_IN_NAME; findThis.name = findLineEdit->text().latin1(); } else if (pwRadioButton->isChecked()) { searchIn = SEARCH_IN_PW; findThis.pw = findLineEdit->text().latin1(); } else if (commentRadioButton->isChecked()) { searchIn = SEARCH_IN_COMMENT; findThis.comment = findLineEdit->text().latin1(); } else if (urlRadioButton->isChecked()) { searchIn = SEARCH_IN_URL; findThis.url = findLineEdit->text().latin1(); } else if (launcherRadioButton->isChecked()) { searchIn = SEARCH_IN_LAUNCHER; findThis.launcher = findLineEdit->text().latin1(); } if (pwRadioButton->isChecked()) { if (!doc->unlockAll_tempoary()) return; unlockedTempoary = true; } doc->findEntry(parent->getCurrentCategory(), findThis, searchIn, &foundPositions, false, caseSensCheckBox->isChecked(), exactCheckBox->isChecked(), true); if (unlockedTempoary) { doc->unlockAll_tempoary(true); } if (!foundPositions.size()) { KMessageBox::information(this, i18n("No entry found."), i18n("not found")); return; } currFoundPos = 0; } int lvp = doc->getListViewPos(parent->getCurrentCategory(), foundPositions[currFoundPos++]); emit foundAt(numEntries - 1 - lvp); if (currFoundPos + 1 > static_cast<int>(foundPositions.size())) currFoundPos = 0; } #ifdef PWM_EMBEDDED void FindWndImpl::slotOk() { findButton_slot(); //do not call KDialogBase::slotOk() here // user should press the close button instead } #endif void FindWndImpl::closeButton_slot() { #ifndef PWM_EMBEDDED done(0); #endif } void FindWndImpl::selectionChanged_slot() { fAt = 0; refVal = 0; currFoundPos = -1; } -#ifndef PWM_EMBEDDED -#include "findwndimpl.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_findwndimpl.cpp" #endif diff --git a/pwmanager/pwmanager/genpasswd.cpp b/pwmanager/pwmanager/genpasswd.cpp index 41078b3..82f0c06 100644 --- a/pwmanager/pwmanager/genpasswd.cpp +++ b/pwmanager/pwmanager/genpasswd.cpp @@ -1,193 +1,195 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "genpasswd.h" #include "pwmexception.h" #include "randomizer.h" #include "globalstuff.h" +//Added by qt3to4: +#include <Q3PtrList> /* how often can a char of the same charset be reused in order */ #define FILTER_MAX_CHARSET_REUSE 3 /* re-randomize all charsets on every iteration (0/1) */ #define RERAND_CHARSET 0 struct staticCharsetStruct { const char *lower; const char *upper; const char *num; const char *special; const char *blank; }; static struct staticCharsetStruct staticCharset = { "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "0123456789", "!\"§$%&/()=?,.-;:_+", " " }; GenPasswd::GenPasswd() : length (8) , useFilter (true) { dynCharset.setAutoDelete(true); } void GenPasswd::setCharset(bool lower, bool upper, bool num, bool special, bool blank, QString user) { unsigned int sanityCheck = 0; dynCharset_element *tmpElement; dynCharset.clear(); if (lower) { tmpElement = new dynCharset_element; tmpElement->refCnt = 0; tmpElement->data = staticCharset.lower; dynCharset.append(tmpElement); ++sanityCheck; } if (upper) { tmpElement = new dynCharset_element; tmpElement->refCnt = 0; tmpElement->data = staticCharset.upper; dynCharset.append(tmpElement); ++sanityCheck; } if (num) { tmpElement = new dynCharset_element; tmpElement->refCnt = 0; tmpElement->data = staticCharset.num; dynCharset.append(tmpElement); ++sanityCheck; } if (special) { tmpElement = new dynCharset_element; tmpElement->refCnt = 0; tmpElement->data = staticCharset.special; dynCharset.append(tmpElement); ++sanityCheck; } if (blank) { tmpElement = new dynCharset_element; tmpElement->refCnt = 0; tmpElement->data = staticCharset.blank; dynCharset.append(tmpElement); } if (!user.isEmpty()) { tmpElement = new dynCharset_element; tmpElement->refCnt = 0; tmpElement->data = user; dynCharset.append(tmpElement); if (likely(user.length() >= 2)) ++sanityCheck; } BUG_ON(!sanityCheck); rndDynCharset(); } void GenPasswd::rndDynCharset() { QString tmpData; int pos; Randomizer *rnd = Randomizer::obj(); // QPtrList<dynCharset_element>::iterator is not available in QT-3.1 unsigned int i, cnt = dynCharset.count(); dynCharset_element *p; for (i = 0; i < cnt; ++i) { p = dynCharset.at(i); PWM_ASSERT(p); tmpData = QString::null; while (p->data.length()) { pos = rnd->genRndInt() % p->data.length(); tmpData.append(p->data.at(pos)); p->data.remove(pos, 1); } p->data = tmpData; } } QString GenPasswd::gen() { BUG_ON(dynCharset.count() <= 0); BUG_ON(length < 1); dynCharset_element *curCharset; QString ret; int i; for (i = 0; i < length; ++i) { curCharset = selectNextCharset(); #if RERAND_CHARSET != 0 rndDynCharset(); #endif // RERAND_CHARSET ret += genNewRandom(curCharset); } return ret; } GenPasswd::dynCharset_element * GenPasswd::selectNextCharset() { dynCharset_element *ret; int numCharsets = dynCharset.count(); BUG_ON(numCharsets <= 0); if (numCharsets == 1) return dynCharset.at(0); Randomizer *rnd = Randomizer::obj(); if (useFilter) { // find out which charsets are allowed (filtering) - QPtrList<dynCharset_element> allowedCharsets; + Q3PtrList<dynCharset_element> allowedCharsets; // QPtrList<dynCharset_element>::iterator is not available in QT-3.1 unsigned int i, cnt = dynCharset.count(); dynCharset_element *p; for (i = 0; i < cnt; ++i) { p = dynCharset.at(i); PWM_ASSERT(p); if (p->refCnt < FILTER_MAX_CHARSET_REUSE) { allowedCharsets.append(p); } else { p->refCnt = 0; } } int numAllowedCharsets = allowedCharsets.count(); BUG_ON(numAllowedCharsets <= 0); // now get a random charset out of the allowed unsigned int randomPos = rnd->genRndUInt() % numAllowedCharsets; ret = allowedCharsets.at(randomPos); ret->refCnt++; return ret; } // all charsets are allowed here (no filtering). Get a random. unsigned int randomPos = rnd->genRndUInt() % numCharsets; ret = dynCharset.at(randomPos); return ret; } QChar GenPasswd::genNewRandom(const dynCharset_element *charset) { Randomizer *rnd = Randomizer::obj(); int pos = rnd->genRndInt() % charset->data.length(); return charset->data.at(pos); } diff --git a/pwmanager/pwmanager/genpasswd.h b/pwmanager/pwmanager/genpasswd.h index 3fa1607..5493891 100644 --- a/pwmanager/pwmanager/genpasswd.h +++ b/pwmanager/pwmanager/genpasswd.h @@ -1,76 +1,76 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __GENPASSWD_H #define __GENPASSWD_H #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> /** internal password generator of PwManager */ class GenPasswd { protected: struct dynCharset_element { /** charset data */ QString data; /** reference counter for the filter */ unsigned int refCnt; }; public: GenPasswd(); /** set the charset to use */ void setCharset(bool lower, bool upper, bool num, bool special, bool blank, QString user); /** set the password length */ void setLen(int len) { length = len; } /** use the filter? */ void setUseFilter(bool use) { useFilter = use; } /** start to generate a new password and return it. * Returns an empty string on error. */ QString gen(); protected: /** randomize the dynamic charset */ void rndDynCharset(); /** select the next charset (based on useFilter) */ dynCharset_element * selectNextCharset(); /** generate a new random char from the given charset */ QChar genNewRandom(const dynCharset_element *charset); protected: /** password length to generate */ int length; /** use the filter? */ bool useFilter; /** dynamic charset used for generating the password */ - QPtrList<dynCharset_element> dynCharset; + Q3PtrList<dynCharset_element> dynCharset; }; #endif // __GENPASSWD_H diff --git a/pwmanager/pwmanager/getkeycardwnd.cpp b/pwmanager/pwmanager/getkeycardwnd.cpp index 89dada2..b8e6174 100644 --- a/pwmanager/pwmanager/getkeycardwnd.cpp +++ b/pwmanager/pwmanager/getkeycardwnd.cpp @@ -1,67 +1,70 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: fsdeveloper@yahoo.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "getkeycardwnd.h" #include <qmessagebox.h> +//Added by qt3to4: +#include <QResizeEvent> +#include <QLabel> #include <klocale.h> GetKeyCardWnd::GetKeyCardWnd(QWidget *parent, - const char *name, bool modal, WFlags f) + const char *name, bool modal, Qt::WFlags f) : QDialog(parent, name, modal, f) { - vbox1 = new QVBox(this); + vbox1 = new Q3VBox(this); text_label = new QLabel(vbox1); - hbox1 = new QHBox(vbox1); + hbox1 = new Q3HBox(vbox1); okButton = new QPushButton(i18n("&Ok"), hbox1); cancelButton = new QPushButton(i18n("&Cancel"), hbox1); vbox1->setSpacing(10); vbox1->setMargin(10); hbox1->setSpacing(10); resize(500, 100); setCaption(i18n("Insert key-card")); text_label->setText(i18n("Please insert the key-card " "and press the OK button.")); connect(okButton, SIGNAL(clicked()), this, SLOT(okButton_slot())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(close())); } GetKeyCardWnd::~GetKeyCardWnd() { } void GetKeyCardWnd::resizeEvent(QResizeEvent *) { vbox1->resize(size()); } void GetKeyCardWnd::okButton_slot() { done(1); } -#ifndef PWM_EMBEDDED -#include "getkeycardwnd.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_getkeycardwnd.cpp" #endif diff --git a/pwmanager/pwmanager/getkeycardwnd.h b/pwmanager/pwmanager/getkeycardwnd.h index fbe46ee..202e920 100644 --- a/pwmanager/pwmanager/getkeycardwnd.h +++ b/pwmanager/pwmanager/getkeycardwnd.h @@ -1,53 +1,55 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: fsdeveloper@yahoo.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef GETKEYCARDWND_H #define GETKEYCARDWND_H -#include <qvbox.h> -#include <qhbox.h> +#include <q3vbox.h> +#include <q3hbox.h> #include <qdialog.h> #include <qlabel.h> #include <qpushbutton.h> #include <qevent.h> +//Added by qt3to4: +#include <QResizeEvent> /** The equivalent to GetMasterPwWndImpl for chipcards */ class GetKeyCardWnd : public QDialog { Q_OBJECT public: GetKeyCardWnd(QWidget *parent = 0, const char *name = 0, - bool modal = FALSE, WFlags f = 0); + bool modal = FALSE, Qt::WFlags f = 0); ~GetKeyCardWnd(); protected slots: void okButton_slot(); protected: - QVBox *vbox1; - QHBox *hbox1; + Q3VBox *vbox1; + Q3HBox *hbox1; QLabel *text_label; QPushButton *okButton; QPushButton *cancelButton; protected: void resizeEvent(QResizeEvent *); }; #endif diff --git a/pwmanager/pwmanager/getmasterpwwnd_emb.cpp b/pwmanager/pwmanager/getmasterpwwnd_emb.cpp index 678f05f..7e4bbb7 100644 --- a/pwmanager/pwmanager/getmasterpwwnd_emb.cpp +++ b/pwmanager/pwmanager/getmasterpwwnd_emb.cpp @@ -1,208 +1,211 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #include "getmasterpwwnd_emb.h" #include "klocale.h" /* #include <qvariant.h> #include <qpushbutton.h> #include <qlabel.h> #include <qlineedit.h> #include <qlayout.h> #include <qtooltip.h> #include <qwhatsthis.h> */ #include <qwidget.h> #include <qlayout.h> #include <qlabel.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qapplication.h> +//Added by qt3to4: +#include <Q3GridLayout> +#include <Q3VBoxLayout> /* * Constructs a getMasterPwWnd as a child of 'parent', with the * name 'name' */ getMasterPwWnd::getMasterPwWnd( QWidget* parent, const char* name) : KDialogBase( KDialogBase::Plain, i18n( "Master-password" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, parent, name, true ) { QWidget *page = plainPage(); - QVBoxLayout *pageLayout = new QVBoxLayout( page ); + Q3VBoxLayout *pageLayout = new Q3VBoxLayout( page ); pwLineEdit = new QLineEdit( page, "pwLineEdit" ); pwLineEdit->setEchoMode( QLineEdit::Password ); QLabel* textLabel1 = new QLabel( pwLineEdit, i18n("Please enter the master-password:"), page, "textLabel1" ); - textLabel1->setAlignment( int( QLabel::WordBreak | QLabel::AlignCenter ) ); + textLabel1->setAlignment( int( Qt::WordBreak | Qt::AlignCenter ) ); pageLayout->addWidget(textLabel1); pageLayout->addWidget(pwLineEdit); QWidget* numberBox = new QWidget( page ); #ifndef DESKTOP_VERSION if ( QApplication::desktop()->width() > 320 ) { numberBox->setFixedHeight(250); numberBox->setFixedWidth(200); } else{ numberBox->setFixedHeight(150); numberBox->setFixedWidth(150); } #endif - QGridLayout* numberLayout = new QGridLayout( numberBox, 4, 3 ); + Q3GridLayout* numberLayout = new Q3GridLayout( numberBox, 4, 3 ); numberLayout->setMargin( 0 ); numberLayout->setSpacing( 0 ); QPushButton* p1 = new QPushButton( i18n("1"), numberBox ); numberLayout->addWidget( p1, 0, 0 ); QPushButton* p2 = new QPushButton( i18n("2"), numberBox ); numberLayout->addWidget( p2, 0, 1 ); QPushButton* p3 = new QPushButton( i18n("3"), numberBox ); numberLayout->addWidget( p3, 0, 2 ); QPushButton* p4 = new QPushButton( i18n("4"), numberBox ); numberLayout->addWidget( p4, 1, 0 ); QPushButton* p5 = new QPushButton( i18n("5"), numberBox ); numberLayout->addWidget( p5, 1, 1 ); QPushButton* p6 = new QPushButton( i18n("6"), numberBox ); numberLayout->addWidget( p6, 1, 2 ); QPushButton* p7 = new QPushButton( i18n("7"), numberBox ); numberLayout->addWidget( p7, 2, 0 ); QPushButton* p8 = new QPushButton( i18n("8"), numberBox ); numberLayout->addWidget( p8, 2, 1 ); QPushButton* p9 = new QPushButton( i18n("9"), numberBox ); numberLayout->addWidget( p9, 2, 2 ); QPushButton* clear = new QPushButton( i18n("x"), numberBox ); numberLayout->addWidget( clear, 3, 0 ); QPushButton* p0 = new QPushButton( i18n("0"), numberBox ); numberLayout->addWidget( p0, 3, 1 ); QPushButton* backspace = new QPushButton( i18n("-"), numberBox ); numberLayout->addWidget( backspace, 3, 2 ); pageLayout->addWidget(numberBox); #ifdef DESKTOP_VERSION resize( sizeHint() ); #else resize( 200,sizeHint().height() ); #endif connect( p0, SIGNAL( clicked() ), this, SLOT( add0() ) ); connect( p1, SIGNAL( clicked() ), this, SLOT( add1() ) ); connect( p2, SIGNAL( clicked() ), this, SLOT( add2() ) ); connect( p3, SIGNAL( clicked() ), this, SLOT( add3() ) ); connect( p4, SIGNAL( clicked() ), this, SLOT( add4() ) ); connect( p5, SIGNAL( clicked() ), this, SLOT( add5() ) ); connect( p6, SIGNAL( clicked() ), this, SLOT( add6() ) ); connect( p7, SIGNAL( clicked() ), this, SLOT( add7() ) ); connect( p8, SIGNAL( clicked() ), this, SLOT( add8() ) ); connect( p9, SIGNAL( clicked() ), this, SLOT( add9() ) ); connect( backspace, SIGNAL( clicked() ), this, SLOT( backspace() ) ); connect( clear, SIGNAL( clicked() ), this, SLOT( clear() ) ); pwLineEdit->setFocus(); } /* * Destroys the object and frees any allocated resources */ getMasterPwWnd::~getMasterPwWnd() { // no need to delete child widgets, Qt does it all for us } void getMasterPwWnd::okButton_slot() { qWarning( "getMasterPwWnd::okButton_slot(): Not implemented yet" ); } void getMasterPwWnd::cancelButton_slot() { qWarning( "getMasterPwWnd::cancelButton_slot(): Not implemented yet" ); } void getMasterPwWnd::add0() { addCharacter("0"); } void getMasterPwWnd::add1() { addCharacter("1"); } void getMasterPwWnd::add2() { addCharacter("2"); } void getMasterPwWnd::add3() { addCharacter("3"); } void getMasterPwWnd::add4() { addCharacter("4"); } void getMasterPwWnd::add5() { addCharacter("5"); } void getMasterPwWnd::add6() { addCharacter("6"); } void getMasterPwWnd::add7() { addCharacter("7"); } void getMasterPwWnd::add8() { addCharacter("8"); } void getMasterPwWnd::add9() { addCharacter("9"); } void getMasterPwWnd::backspace() { QString old = pwLineEdit->text(); old.truncate(old.length()-1); pwLineEdit->setText(old); } void getMasterPwWnd::clear() { pwLineEdit->setText(""); } void getMasterPwWnd::addCharacter(const QString& s) { QString old = pwLineEdit->text(); pwLineEdit->setText(old + s); } diff --git a/pwmanager/pwmanager/getmasterpwwndimpl.cpp b/pwmanager/pwmanager/getmasterpwwndimpl.cpp index 6be9618..f741f72 100644 --- a/pwmanager/pwmanager/getmasterpwwndimpl.cpp +++ b/pwmanager/pwmanager/getmasterpwwndimpl.cpp @@ -1,60 +1,60 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "getmasterpwwndimpl.h" #include <qlineedit.h> GetMasterPwWndImpl::GetMasterPwWndImpl(QWidget * parent, const char *name) : getMasterPwWnd(parent, name) { } GetMasterPwWndImpl::~GetMasterPwWndImpl() { } void GetMasterPwWndImpl::okButton_slot() { #ifndef PWM_EMBEDDED if (pwLineEdit->text() != "") done(1); #endif } void GetMasterPwWndImpl::cancelButton_slot() { #ifndef PWM_EMBEDDED done(2); #endif } #ifdef PWM_EMBEDDED void GetMasterPwWndImpl::slotOk() { if (pwLineEdit->text() != "") getMasterPwWnd::slotOk(); else return; } #endif -#ifndef PWM_EMBEDDED -#include "getmasterpwwndimpl.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_getmasterpwwndimpl.cpp" #endif diff --git a/pwmanager/pwmanager/globalstuff.h b/pwmanager/pwmanager/globalstuff.h index 090fcda..2e8f287 100644 --- a/pwmanager/pwmanager/globalstuff.h +++ b/pwmanager/pwmanager/globalstuff.h @@ -1,134 +1,134 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __GLOBALSTUFF_H #define __GLOBALSTUFF_H #ifndef PWM_EMBEDDED #include "config.h" #endif #include "compiler.h" //US BUG: the following code caused compile errors with certain gcccompilers (2.95). // Because of that I replaced it with a Qt version, which should do the same. #include <string> #ifndef PWM_EMBEDDED #include <sstream> #else #include <qstring.h> -#include <qtextstream.h> +#include <QTextOStream> #endif #ifndef CONFIG_KEYCARD class QWidget; void no_keycard_support_msg_box(QWidget *parentWidget); #endif // CONFIG_KEYCARD #ifdef PROG_NAME # undef PROG_NAME #endif #define PROG_NAME "PwM/Pi" #ifdef PACKAGE_NAME # undef PACKAGE_NAME #endif #define PACKAGE_NAME "pwm-pi" #ifdef PACKAGE_VER # undef PACKAGE_VER #endif #define PACKAGE_VER "1.0.1" #ifdef CONFIG_DEBUG # define PWM_DEBUG #else # undef PWM_DEBUG #endif #ifdef QT_MAKE_VERSION # undef QT_MAKE_VERSION #endif #define QT_MAKE_VERSION(a,b,c) (((a) << 16) | ((b) << 8) | (c)) /** remove "unused parameter" warnings */ #ifdef PARAM_UNUSED # undef PARAM_UNUSED #endif #define PARAM_UNUSED(x) (void)x /** return the number of elements in an array */ #ifdef array_size # undef array_size #endif #define array_size(x) (sizeof(x) / sizeof((x)[0])) //US BUG: the following code caused compile errors with certain gcccompilers (2.95). // Because of that I replaced it with a Qt version, which should do the same. #ifndef PWM_EMBEDDED /** convert something to string using ostringstream */ template <class T> inline std::string tostr(const T &t) { std::ostringstream s; s << t; return s.str(); } #else /** convert something to string using ostringstream */ template <class T> inline std::string tostr(const T &t) { QString result; - QTextOStream(&result) << t; + QTextOStream tmp(&result); tmp << t; return result.latin1(); } #endif /** delete the memory and NULL the pointer */ template<class T> inline void delete_and_null(T *&p) { delete p; p = 0; } /** delete the memory if the pointer isn't a NULL pointer */ template<class T> inline void delete_ifnot_null(T *&p) { if (p) delete_and_null(p); } template<class T> inline void delete_and_null_array(T *&p) { delete [] p; p = 0; } template<class T> inline void delete_ifnot_null_array(T *&p) { if (p) delete_and_null_array(p); } #endif // GLOBALSTUFF_H diff --git a/pwmanager/pwmanager/htmlgen.cpp b/pwmanager/pwmanager/htmlgen.cpp index bee8198..be3406a 100644 --- a/pwmanager/pwmanager/htmlgen.cpp +++ b/pwmanager/pwmanager/htmlgen.cpp @@ -1,248 +1,248 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "htmlgen.h" #include "pwmexception.h" #include <kstandarddirs.h> /** enable/disable HTML-generator debugging (0/1) */ #define HTMLGEN_DEBUG 0 #define HTML_DOCTYPE_HDR "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" #define HTML_PWM_HDR "<!-- PwManager generated HTML -->" #define HTML_COMMENT_HDR "<!-- type: comment -->" #define HTML_COMMENTVER_HDR "<!-- ver: 0.1 -->" #define HTML_STYLESHEET_DUMMY "@STYLESHEET@" #define HTML_GLOBTBL_CLASS "\"globtable\"" #define HTML_GLOBTITLE_CLASS "\"globtitle\"" #define HTML_SUBTBL_CLASS "\"subtable\"" #define HTML_SUBTITLE_CLASS "\"subtitle\"" #define HTML_ENTRY_CLASS "\"entry\"" #define HTML_VALUE_CLASS "\"value\"" #define PATH_COMMENTSTYLE_CSS "pwmanager/html/htmlcomment_style.css" #if defined(PWM_DEBUG) && HTMLGEN_DEBUG != 0 #define HTML_ENDL "\n" #else // defined(PWM_DEBUG) && ... #define HTML_ENDL "" #endif // defined(PWM_DEBUG) && ... HtmlGen::HtmlGen() { useSSDummy = true; } HtmlGen::~HtmlGen() { } QString HtmlGen::escapeHtmlText(const QString &str) { QString ret; unsigned int len = str.length(), i; char c; for (i = 0; i < len; ++i) { - c = str.at(i); + c = str.at(i).toLatin1(); switch (c) { case '<': ret.append("<"); break; case '>': ret.append(">"); break; case '&': ret.append("&"); break; case '\"': ret.append("""); break; case 'ä': ret.append("ä"); break; case 'Ä': ret.append("Ä"); break; case 'ü': ret.append("ü"); break; case 'Ü': ret.append("Ü"); break; case 'ö': ret.append("ö"); break; case 'Ö': ret.append("Ö"); break; case 'ß': ret.append("ß"); break; case '¿': ret.append("€"); break; default: ret.append(c); } } return ret; } bool HtmlGen::isHtml(const QString &dta) { int ret; ret = dta.find("<html>", 0, false); if (ret == -1) return false; ret = dta.find("<head>", ret, false); if (ret == -1) return false; return true; } QString HtmlGen::getStyleSheetHtml() { QString ret; ret = "<link rel=\"stylesheet\" href=\""; QString cssPath(::locate("data", PATH_COMMENTSTYLE_CSS)); if ((cssPath == QString::null) || (cssPath == "")) { printDebug("HtmlGen::getStyleSheetHtml(): not found"); return ""; } ret += cssPath; ret += "\" type=\"text/css\">" HTML_ENDL; return ret; } bool HtmlGen::replaceSSDummy(QString *doc) { int beginPos = doc->find(HTML_STYLESHEET_DUMMY); if (beginPos == -1) { printDebug("HtmlGen::replaceSSDummy(): not found"); return false; } *doc = doc->replace(beginPos, strlen(HTML_STYLESHEET_DUMMY), getStyleSheetHtml()); return true; } QString HtmlGen::genHtmlComment(const HtmlComment *dta) { QString ret(HTML_DOCTYPE_HDR HTML_PWM_HDR HTML_ENDL HTML_COMMENT_HDR HTML_ENDL HTML_COMMENTVER_HDR HTML_ENDL); ret += "<html>" HTML_ENDL; if (!appendCommentHeader(&ret)) return ""; if (!appendCommentBody(&ret, dta)) return ""; ret += "</html>" HTML_ENDL; #if defined(PWM_DEBUG) && HTMLGEN_DEBUG != 0 printDebug("<BEGIN HtmlGen::genHtmlComment() dump>"); cout << ret << endl; printDebug("<END HtmlGen::genHtmlComment() dump>"); #endif // DEBUG return ret; } bool HtmlGen::appendCommentHeader(QString *str) { *str += "<head>" HTML_ENDL; if (useSSDummy) { *str += HTML_STYLESHEET_DUMMY HTML_ENDL; } else { QString ssLine(getStyleSheetHtml()); if (ssLine.isEmpty()) return false; *str += ssLine; } *str += "</head>" HTML_ENDL; return true; } bool HtmlGen::appendCommentBody(QString *str, const HtmlComment *dta) { *str += "<body>" HTML_ENDL; if (!appendCommentGlobTbl(str, dta)) return false; *str += "</body>" HTML_ENDL; return true; } bool HtmlGen::appendCommentGlobTbl(QString *str, const HtmlComment *dta) { *str += "<table class=" HTML_GLOBTBL_CLASS ">" HTML_ENDL; *str += "<tr><th class=" HTML_GLOBTITLE_CLASS ">"; *str += escapeHtmlText(dta->getTitle()); *str += "</th></tr>" HTML_ENDL; const vector<HtmlComment::SubTable> *subTbls = dta->getSubTableList(); vector<HtmlComment::SubTable>::const_iterator i = subTbls->begin(), end = subTbls->end(); while (i != end) { *str += "<tr><td>" HTML_ENDL; if (!appendCommentSubTbl(str, &(*i))) return false; ++i; *str += "</td></tr>" HTML_ENDL; } *str += "</table>" HTML_ENDL; return true; } bool HtmlGen::appendCommentSubTbl(QString *str, const HtmlComment::SubTable *dta) { *str += "<table class=" HTML_SUBTBL_CLASS ">" HTML_ENDL; *str += "<tr><th colspan=\"2\" class=" HTML_SUBTITLE_CLASS ">"; *str += escapeHtmlText(dta->getTitle()); *str += "</th></tr>" HTML_ENDL; const vector< pair<QString, QString> > *entries = dta->getEntryList(); vector< pair<QString, QString> >::const_iterator i = entries->begin(), end = entries->end(); while (i != end) { *str += "<tr>" HTML_ENDL; if (!appendCommentSubTblEntry(str, &(*i))) return false; *str += "</tr>" HTML_ENDL; ++i; } *str += "</table>" HTML_ENDL; return true; } bool HtmlGen::appendCommentSubTblEntry(QString *str, const pair<QString, QString> *dta) { *str += "<td class=" HTML_ENTRY_CLASS ">"; *str += escapeHtmlText(dta->first); *str += "</td>" HTML_ENDL; *str += "<td class=" HTML_VALUE_CLASS ">"; *str += escapeHtmlText(dta->second); *str += "</td>" HTML_ENDL; return true; } diff --git a/pwmanager/pwmanager/ipc.cpp b/pwmanager/pwmanager/ipc.cpp index 643b022..4c65f1d 100644 --- a/pwmanager/pwmanager/ipc.cpp +++ b/pwmanager/pwmanager/ipc.cpp @@ -1,217 +1,217 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "ipc.h" #include "pwmexception.h" #include <qsocketnotifier.h> #ifndef _WIN32_ #include <sys/socket.h> #endif #ifndef PWM_EMBEDDED #include <sys/types.h> #include <stdio.h> #else -#include <qsocket.h> +#include <q3socket.h> #endif #define END_OF_LINE '\n' #define INIT_LINEBUF_LEN 64 /* byte */ #ifndef PWM_EMBEDDED Ipc::Ipc() : stream (0) , notifier (0) , rdBuf (0) { if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sock)) { throw PwMException(PwMException::EX_GENERIC, "Ipc: socketpair() failed"); } rdBufSize = INIT_LINEBUF_LEN; rdBuf = static_cast<char *>(malloc(rdBufSize)); if (!rdBuf) { close(sock[0]); close(sock[1]); throw PwMException(PwMException::EX_GENERIC, "Ipc: OOM"); } stream = fdopen(sock[0], "r"); if (!stream) { close(sock[0]); close(sock[1]); free(rdBuf); throw PwMException(PwMException::EX_GENERIC, "Ipc: fdopen() failed"); } notifier = new QSocketNotifier(sock[0], QSocketNotifier::Read); connect(notifier, SIGNAL(activated(int)), this, SLOT(receiveData(int))); host = true; } #else Ipc::Ipc() : notifier (0) , rdBuf (0) { #ifndef _WIN32_ if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sock)) { qDebug("Ipc: socketpair() failed"); } #endif - QSocket* qsock = new QSocket(); + Q3Socket* qsock = new Q3Socket(); qsock->setSocket(sock[0]); rdBufSize = INIT_LINEBUF_LEN; rdBuf = (char *)(malloc(rdBufSize)); if (!rdBuf) { close(sock[0]); close(sock[1]); qDebug("Ipc: OOM"); } - qsock = new QSocket(); + qsock = new Q3Socket(); qsock->setSocket(sock[0]); /*US stream = fdopen(sock[0], "r"); if (!stream) { close(sock[0]); close(sock[1]); free(rdBuf); qDebug("Ipc: fdopen() failed"); } */ notifier = new QSocketNotifier(sock[0], QSocketNotifier::Read); connect(notifier, SIGNAL(activated(int)), this, SLOT(receiveData(int))); host = true; } #endif #ifndef PWM_EMBEDDED Ipc::Ipc(const Ipc *ipc) : stream (0) , notifier (0) , rdBuf (0) { rdBufSize = INIT_LINEBUF_LEN; rdBuf = static_cast<char *>(malloc(rdBufSize)); if (!rdBuf) { throw PwMException(PwMException::EX_GENERIC, "Ipc: OOM"); } sock[0] = ipc->sock[1]; sock[1] = ipc->sock[0]; stream = fdopen(sock[0], "r"); if (!stream) { free(rdBuf); throw PwMException(PwMException::EX_GENERIC, "Ipc: fdopen() failed"); } notifier = new QSocketNotifier(sock[0], QSocketNotifier::Read); connect(notifier, SIGNAL(activated(int)), this, SLOT(receiveData(int))); host = false; } #else Ipc::Ipc(const Ipc *ipc) : notifier (0) , rdBuf (0) { rdBufSize = INIT_LINEBUF_LEN; rdBuf = (char *)(malloc(rdBufSize)); if (!rdBuf) { qDebug("Ipc: OOM"); } sock[0] = ipc->sock[1]; sock[1] = ipc->sock[0]; - qSock = new QSocket(); + qSock = new Q3Socket(); qSock->setSocket(sock[0]); /*US stream = fdopen(sock[0], "r"); if (!stream) { free(rdBuf); qDebug("Ipc: fdopen() failed"); } */ notifier = new QSocketNotifier(sock[0], QSocketNotifier::Read); connect(notifier, SIGNAL(activated(int)), this, SLOT(receiveData(int))); host = false; } #endif Ipc::~Ipc() { #ifdef PWM_EMBEDDED delete qSock; #endif delete_ifnot_null(notifier); if (rdBuf) free(rdBuf); #ifndef PWM_EMBEDDED if (stream) fclose(stream); #endif if (host) { close(sock[0]); close(sock[1]); } } void Ipc::receiveData(int s) { PWM_ASSERT(s == sock[0]); PARAM_UNUSED(s); #ifndef PWM_EMBEDDED ssize_t rd; rd = ::getline(&rdBuf, &rdBufSize, stream); if (likely(rd > 0)) { emit lineAvailable(rdBuf, rd); } #else int rd; rd = qSock->readLine(rdBuf, rdBufSize); if (rd > 0) { emit lineAvailable(rdBuf, rd); } #endif qDebug("void Ipc::receiveData(int s) has to be implemented."); } -#ifndef PWM_EMBEDDED -#include "ipc.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_ipc.cpp" #endif diff --git a/pwmanager/pwmanager/ipc.h b/pwmanager/pwmanager/ipc.h index 7bfca02..3248283 100644 --- a/pwmanager/pwmanager/ipc.h +++ b/pwmanager/pwmanager/ipc.h @@ -1,92 +1,92 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __PWM_IPC_H #define __PWM_IPC_H #include <qobject.h> #ifndef _WIN32_ #include <unistd.h> #else #include <io.h> #endif #ifndef PWM_EMBEDDED #include <stdio.h> #else -#include <qsocket.h> +#include <q3socket.h> #endif class QSocketNotifier; /** very simple interprocess communication class */ class Ipc : public QObject { Q_OBJECT public: /** create a new Ipc communication object */ Ipc(); /** create a new Ipc communication object and * connect it to "ipc" */ Ipc(const Ipc *ipc); /** destructor */ ~Ipc(); /** send data to the other socket end * (To the connected ipc object) */ #ifndef PWM_EMBEDDED void send(const char *buf, size_t size) { write(sock[0], buf, size); } #else void send(const char *buf, size_t size) { qSock->writeBlock(buf, size); } #endif signals: /** a line is available */ void lineAvailable(const char *buf, size_t size); protected slots: /** received data on socket */ void receiveData(int s); protected: #ifndef PWM_EMBEDDED /** stream on "this" end of the socket (sock[0]) */ FILE *stream; /** current receive buffer size */ size_t rdBufSize; #else - QSocket* qSock; + Q3Socket* qSock; /** current receive buffer size */ unsigned int rdBufSize; #endif /** full-duplex socket file desciptors */ int sock[2]; /** socket notifier */ QSocketNotifier *notifier; /** are we the host or the client object? */ bool host; /** receive buffer */ char *rdBuf; }; #endif // __PWM_IPC_H diff --git a/pwmanager/pwmanager/kcmconfigs/kcmpwmconfig.cpp b/pwmanager/pwmanager/kcmconfigs/kcmpwmconfig.cpp index b7944c3..1804e88 100644 --- a/pwmanager/pwmanager/kcmconfigs/kcmpwmconfig.cpp +++ b/pwmanager/pwmanager/kcmconfigs/kcmpwmconfig.cpp @@ -1,72 +1,74 @@ /* This file is part of PwManager/Pi Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> +//Added by qt3to4: +#include <Q3VBoxLayout> #include <kdebug.h> #include "pwmconfigwidget.h" #include "kcmpwmconfig.h" #include "pwmprefs.h" #include "kprefs.h" extern "C" { KCModule *create_pwmconfig(QWidget *parent, const char * ) { return new KCMPwmConfig(parent, "kcmpwmconfig" ); } } KCMPwmConfig::KCMPwmConfig(QWidget *parent, const char *name ) : KCModule( PWMPrefs::instance(), parent, name ) { - QVBoxLayout *layout = new QVBoxLayout( this ); + Q3VBoxLayout *layout = new Q3VBoxLayout( this ); mConfigWidget = new PWMConfigWidget( (PWMPrefs*)getPreferences(), this, "mConfigWidget" ); layout->addWidget( mConfigWidget ); layout->setSpacing( 0 ); layout->setMargin( 0 ); connect( mConfigWidget, SIGNAL( changed( bool ) ), SIGNAL( changed( bool ) ) ); } void KCMPwmConfig::load() { mConfigWidget->readConfig(); } void KCMPwmConfig::save() { mConfigWidget->writeConfig(); } void KCMPwmConfig::defaults() { mConfigWidget->setDefaults(); } #ifndef PWM_EMBEDDED #include "kcmkabconfig.moc" #endif //PWM_EMBEDDED diff --git a/pwmanager/pwmanager/kcmconfigs/pwmconfigwidget.cpp b/pwmanager/pwmanager/kcmconfigs/pwmconfigwidget.cpp index 2c5189c..04771b3 100644 --- a/pwmanager/pwmanager/kcmconfigs/pwmconfigwidget.cpp +++ b/pwmanager/pwmanager/kcmconfigs/pwmconfigwidget.cpp @@ -1,365 +1,368 @@ /* This file is part of KAddressBook. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qcheckbox.h> -#include <qframe.h> -#include <qgroupbox.h> +#include <q3frame.h> +#include <q3groupbox.h> #include <qlayout.h> #include <qpushbutton.h> #include <qtabwidget.h> #include <qcombobox.h> #include <qlineedit.h> #include <qspinbox.h> #include <qlabel.h> #include <qfile.h> -#include <qvbox.h> +#include <q3vbox.h> +//Added by qt3to4: +#include <Q3GridLayout> +#include <Q3VBoxLayout> #include <kconfig.h> #include <kdebug.h> #include <kdialog.h> #include <klistview.h> #include <klocale.h> #include <kglobal.h> #include <kmessagebox.h> #include <kstandarddirs.h> #include <kio/kfile/kurlrequester.h> #include "pwmprefs.h" #include "pwmconfigwidget.h" #include "pwmexception.h" PWMConfigWidget::PWMConfigWidget(PWMPrefs *prefs, QWidget *parent, const char *name ) : KPrefsWidget(prefs, parent, name ) { - QVBoxLayout *topLayout = new QVBoxLayout( this, 0, + Q3VBoxLayout *topLayout = new Q3VBoxLayout( this, 0, KDialog::spacingHint() ); QTabWidget *tabWidget = new QTabWidget( this ); topLayout->addWidget( tabWidget ); // windowsStyle page ////////////////////////////////////////////////////// QWidget *windowStylePage = new QWidget( this ); - QGridLayout *windowStyleLayout = new QGridLayout( windowStylePage, 3, 3); + Q3GridLayout *windowStyleLayout = new Q3GridLayout( windowStylePage, 3, 3); int i = 0; KPrefsWidRadios * windowStyle = addWidRadios(i18n("Window-style:") ,&(prefs->mMainViewStyle), windowStylePage); windowStyle->addRadio(i18n("Category on top")); windowStyle->addRadio(i18n("Category-list left/top")); windowStyleLayout->addMultiCellWidget( (QWidget*)windowStyle->groupBox(),i,i,0,2); ++i; QLabel* lab = new QLabel(i18n("Font for Password entries:"), windowStylePage); windowStyleLayout->addMultiCellWidget( lab,i,i,0,2); ++i; KPrefsWidFont *selEntrFont = addWidFont(i18n("Password"),i18n("Font:"), &(prefs->mEntryFont),windowStylePage); windowStyleLayout->addWidget(selEntrFont->label(),i,0); windowStyleLayout->addWidget(selEntrFont->preview(),i,1); windowStyleLayout->addWidget(selEntrFont->button(),i,2); ++i; lab = new QLabel(i18n("Font for Password summary:"), windowStylePage); windowStyleLayout->addMultiCellWidget( lab,i,i,0,2); ++i; selEntrFont = addWidFont(i18n("Summary"),i18n("Font:"), &(prefs->mViewFont),windowStylePage); windowStyleLayout->addWidget(selEntrFont->label(),i,0); windowStyleLayout->addWidget(selEntrFont->preview(),i,1); windowStyleLayout->addWidget(selEntrFont->button(),i,2); ++i; lab = new QLabel(i18n(""), windowStylePage); windowStyleLayout->addMultiCellWidget( lab,i,i,0,2); // File page ////////////////////////////////////////////////////// QWidget *filePage = new QWidget( this ); - QGridLayout *fileLayout = new QGridLayout( filePage, 3, 2); + Q3GridLayout *fileLayout = new Q3GridLayout( filePage, 3, 2); i = 0; QLabel* kcfg_compression_label = new QLabel(i18n("Compression:"), filePage); fileLayout->addWidget(kcfg_compression_label,i,0); kcfg_compression = new QComboBox(filePage, "kcfg_compression"); kcfg_compression->insertItem(i18n("None")); kcfg_compression->insertItem(i18n("gzip")); //US not yet supported: kcfg_compression->insertItem(i18n("bzip2")); fileLayout->addWidget( kcfg_compression,i,1); ++i; QLabel* kcfg_crypt_label = new QLabel(i18n("Encryption:"), filePage); fileLayout->addWidget(kcfg_crypt_label,i,0); kcfg_cryptAlgo = new QComboBox(filePage, "kcfg_cryptAlgo"); kcfg_cryptAlgo->insertItem(i18n("Blowfish (128 bit)")); #ifdef CONFIG_PWMANAGER_GCRY kcfg_cryptAlgo->insertItem(i18n("AES-128, Rijndael (128 bit)")); kcfg_cryptAlgo->insertItem(i18n("AES-192, Rijndael (192 bit)")); kcfg_cryptAlgo->insertItem(i18n("AES-256, Rijndael (256 bit)")); kcfg_cryptAlgo->insertItem(i18n("Triple-DES (168 bit)")); kcfg_cryptAlgo->insertItem(i18n("Twofish (256 bit)")); kcfg_cryptAlgo->insertItem(i18n("Twofish-128 (128 bit)")); #endif // CONFIG_PWMANAGER_GCRY fileLayout->addWidget( kcfg_cryptAlgo,i,1); ++i; QLabel* kcfg_hash_label = new QLabel(i18n("Hashing:"), filePage); fileLayout->addWidget(kcfg_hash_label,i,0); kcfg_hashAlgo = new QComboBox(filePage, "kcfg_hashAlgo"); kcfg_hashAlgo->insertItem(i18n("SHA-160, SHA1 (160 bit)")); #ifdef CONFIG_PWMANAGER_GCRY kcfg_hashAlgo->insertItem(i18n("SHA-256 (256 bit)")); kcfg_hashAlgo->insertItem(i18n("SHA-384 (384 bit)")); kcfg_hashAlgo->insertItem(i18n("SHA-512 (512 bit)")); kcfg_hashAlgo->insertItem(i18n("MD5 (128 bit)")); kcfg_hashAlgo->insertItem(i18n("RIPE-MD-160 (160 bit)")); kcfg_hashAlgo->insertItem(i18n("Tiger (192 bit)")); #endif // CONFIG_PWMANAGER_GCRY fileLayout->addWidget( kcfg_hashAlgo,i,1); ++i; permissionLineEdit = new QLineEdit(filePage); QLabel* permissionLineLabel = new QLabel(permissionLineEdit, i18n("Permissions:"), filePage); fileLayout->addWidget(permissionLineLabel,i,0); fileLayout->addWidget(permissionLineEdit,i,1); ++i; KPrefsWidBool *sb = addWidBool(i18n("Make backup before saving"), &(prefs->mMakeFileBackup),filePage); fileLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; // Timeout page ////////////////////////////////////////////////////// QWidget *timeoutPage = new QWidget( this ); - QGridLayout *timeoutLayout = new QGridLayout( timeoutPage, 3, 2); + Q3GridLayout *timeoutLayout = new Q3GridLayout( timeoutPage, 3, 2); i = 0; pwTimeoutSpinBox = new QSpinBox( 0,600,10,timeoutPage, "pwTimeoutSpinBox" ); QLabel* timeoutLabel = new QLabel(pwTimeoutSpinBox, i18n("<b>Password timeout</b> (timeout to hold password in memory,so you don't have to re-enter it,if you already have entered it) [set to 0 to disable]:"), timeoutPage); timeoutLayout->addMultiCellWidget(timeoutLabel, i, i, 0 ,1); ++i; timeoutLayout->addMultiCellWidget(pwTimeoutSpinBox,i,i,0,1); ++i; pwTimeoutSpinBox->setSuffix ( i18n(" sec") ); lockTimeoutSpinBox = new QSpinBox( 0,600,10,timeoutPage, "lockTimeoutSpinBox" ); QLabel* lockTimeoutLabel = new QLabel(lockTimeoutSpinBox, i18n("<b>Auto-lock timeout</b> (auto lock document after this\namount of seconds) [set to 0 to disable]:"), timeoutPage); timeoutLayout->addMultiCellWidget(lockTimeoutLabel,i, i, 0 ,1); ++i; timeoutLayout->addMultiCellWidget(lockTimeoutSpinBox,i,i,0,1); lockTimeoutSpinBox->setSuffix ( i18n(" sec") ); ++i; sb = addWidBool(i18n("deep-lock on autolock"), &(prefs->mAutoDeeplock),timeoutPage); timeoutLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; sb = addWidBool(i18n("Open document with passwords unlocked"),&(prefs->mUnlockOnOpen),timeoutPage); timeoutLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; // Autostart page ////////////////////////////////////////////////////// QWidget *autostartPage = new QWidget( this ); - QGridLayout *autostartLayout = new QGridLayout( autostartPage, 3, 2); + Q3GridLayout *autostartLayout = new Q3GridLayout( autostartPage, 3, 2); i = 0; autostartLineEdit = new KURLRequester(autostartPage, "autoStartLineEdit"); QLabel* autostartLineLabel = new QLabel(autostartLineEdit, "Open this file automatically on startup:",autostartPage); autostartLayout->addMultiCellWidget(autostartLineLabel,i,i,0,1); ++i; autostartLayout->addMultiCellWidget(autostartLineEdit,i,i,0,1); ++i; sb = addWidBool(i18n("open deeplocked"), &(prefs->mAutostartDeeplocked),autostartPage); autostartLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; // external app page ////////////////////////////////////////////////////// QWidget *externalappPage = new QWidget( this ); - QGridLayout *externalappLayout = new QGridLayout( externalappPage, 3, 2); + Q3GridLayout *externalappLayout = new Q3GridLayout( externalappPage, 3, 2); i = 0; browserLineEdit = new QLineEdit(externalappPage); QLabel* browserLineLabel = new QLabel(browserLineEdit, i18n("Favourite browser:"), externalappPage); externalappLayout->addWidget(browserLineLabel,i,0); externalappLayout->addWidget(browserLineEdit,i,1); ++i; xtermLineEdit = new QLineEdit(externalappPage); QLabel* xtermLineLabel = new QLabel(xtermLineEdit, i18n("Favourite x-terminal:"), externalappPage); externalappLayout->addWidget(xtermLineLabel,i,0); externalappLayout->addWidget(xtermLineEdit,i,1); ++i; #if 0 // miscelaneous page ////////////////////////////////////////////////////// QWidget *miscPage = new QWidget( this ); - QGridLayout *miscLayout = new QGridLayout( miscPage, 3, 2); + Q3GridLayout *miscLayout = new Q3GridLayout( miscPage, 3, 2); i = 0; /*US ENH: PWM/Pi has no tray and con be minimized sb = addWidBool(i18n("Show icon in system-tray"),&(prefs->mTray),miscPage); miscLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; */ sb = addWidBool(i18n("Open document with passwords unlocked"),&(prefs->mUnlockOnOpen),miscPage); miscLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; /*US ENH: PWM/Pi has no tray and con be minimized sb = addWidBool(i18n("auto-minimize to tray on startup"),&(prefs->mAutoMinimizeOnStart),miscPage); miscLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; KPrefsWidRadios * minimizeRadio = addWidRadios(i18n("auto-lock on minimize:") ,&(prefs->mMinimizeLock), miscPage); minimizeRadio->addRadio(i18n("don't lock")); minimizeRadio->addRadio(i18n("normal lock")); minimizeRadio->addRadio(i18n("deep-lock")); miscLayout->addMultiCellWidget( (QWidget*)minimizeRadio->groupBox(),i,i,0,2); ++i; sb = addWidBool(i18n("KWallet emulation"),&(prefs->mKWalletEmu),miscPage); miscLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; sb = addWidBool(i18n("Close instead Minimize into tray"),&(prefs->mClose),miscPage); miscLayout->addMultiCellWidget(sb->checkBox(), i,i,0,1); ++i; */ #endif tabWidget->addTab( windowStylePage, i18n( "Look && feel" ) ); tabWidget->addTab( filePage, i18n( "File" ) ); tabWidget->addTab( timeoutPage, i18n( "Timeout" ) ); tabWidget->addTab( autostartPage, i18n( "Autostart" ) ); tabWidget->addTab( externalappPage, i18n( "External apps" ) ); //tabWidget->addTab( miscPage, i18n( "Miscellaneous" ) ); connect( permissionLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( modified() ) ); connect( pwTimeoutSpinBox, SIGNAL( valueChanged(int) ), this, SLOT( modified() ) ); connect( lockTimeoutSpinBox, SIGNAL( valueChanged(int) ), this, SLOT( modified() ) ); connect( autostartLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( modified() ) ); connect( browserLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( modified() ) ); connect( xtermLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( modified() ) ); } void PWMConfigWidget::usrReadConfig() { PWMPrefs* prefs = PWMPrefs::instance(); setFilePermissions(prefs->mFilePermissions); pwTimeoutSpinBox->setValue(prefs->mPwTimeout); lockTimeoutSpinBox->setValue(prefs->mLockTimeout); autostartLineEdit->setURL(prefs->mAutoStart); browserLineEdit->setText(prefs->mBrowserCommand); xtermLineEdit->setText(prefs->mXTermCommand); kcfg_compression->setCurrentItem(prefs->mCompression); kcfg_cryptAlgo->setCurrentItem(prefs->mCryptAlgo); kcfg_hashAlgo->setCurrentItem(prefs->mHashAlgo); } void PWMConfigWidget::usrWriteConfig() { PWMPrefs* prefs = PWMPrefs::instance(); prefs->mFilePermissions = getFilePermissions(); prefs->mPwTimeout = pwTimeoutSpinBox->value(); prefs->mLockTimeout = lockTimeoutSpinBox->value(); prefs->mAutoStart = autostartLineEdit->url(); prefs->mBrowserCommand = browserLineEdit->text(); prefs->mXTermCommand = xtermLineEdit->text(); prefs->mCompression = kcfg_compression->currentItem(); prefs->mCryptAlgo = kcfg_cryptAlgo->currentItem(); prefs->mHashAlgo = kcfg_hashAlgo->currentItem(); } int PWMConfigWidget::getFilePermissions() { char octalDigits[] = "01234567"; bool isOctal; QString permString(permissionLineEdit->text()); int i, j, length = permString.length(); if (length != 3) { printWarn("Wrong permission string length! Please enter " "the string like the following example: 600"); return CONF_DEFAULT_FILEPERMISSIONS; } for (i = 0; i < length; ++i) { isOctal = false; for (j = 0; j < 8; ++j) { if (permString.at(i) == octalDigits[j]) { isOctal = true; break; } } if (!isOctal) { printWarn("CONFIG: File-permissions: This is " "not an octal number "); return CONF_DEFAULT_FILEPERMISSIONS; } } int ret = strtol(permString.latin1(), 0, 8); if (ret == 0) { /* either an error occured, or the user did really type 000 */ printWarn("CONFIG: File-permissions: Hm, either conversion error, " "or you really typed 000. 8-)"); return CONF_DEFAULT_FILEPERMISSIONS; } return ret; } void PWMConfigWidget::setFilePermissions(int perm) { char tmpBuf[30]; sprintf(tmpBuf, "%o", perm); permissionLineEdit->setText(tmpBuf); } -#ifndef PWM_EMBEDDED -#include "pwmconfigwidget.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwmconfigwidget.cpp" #endif //PWM_EMBEDDED diff --git a/pwmanager/pwmanager/listobjselectwnd.cpp b/pwmanager/pwmanager/listobjselectwnd.cpp index 59729f1..7da7e95 100644 --- a/pwmanager/pwmanager/listobjselectwnd.cpp +++ b/pwmanager/pwmanager/listobjselectwnd.cpp @@ -1,131 +1,134 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "listobjselectwnd.h" #include <klocale.h> +//Added by qt3to4: +#include <QResizeEvent> +#include <QLabel> ListObjSelectWnd::ListObjSelectWnd(const QString &caption, const QString &titleText, QWidget *parent, bool multiSel, const char *name, - bool modal, WFlags f) + bool modal, Qt::WFlags f) : QDialog(parent, name, modal, f) { - vbox1 = new QVBox(this); + vbox1 = new Q3VBox(this); title = new QLabel(vbox1); - list = new QListBox(vbox1); + list = new Q3ListBox(vbox1); if (multiSel) { - hbox2 = new QHBox(vbox1); + hbox2 = new Q3HBox(vbox1); selAllButton = new QPushButton(i18n("&Select all"), hbox2); unselAllButton = new QPushButton(i18n("&Unselect all"), hbox2); } - hbox1 = new QHBox(vbox1); + hbox1 = new Q3HBox(vbox1); okButton = new QPushButton(i18n("&Ok"), hbox1); cancelButton = new QPushButton(i18n("&Cancel"), hbox1); vbox1->setSpacing(10); vbox1->setMargin(10); hbox1->setSpacing(10); resize(250, 300); setCaption(caption); if (multiSel) { - list->setSelectionMode(QListBox::Multi); + list->setSelectionMode(Q3ListBox::Multi); } title->setAlignment(Qt::AlignHCenter | Qt::WordBreak); title->setText(titleText); connect(okButton, SIGNAL(clicked()), this, SLOT(okButton_slot())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancelButton_slot())); if (multiSel) { connect(selAllButton, SIGNAL(clicked()), this, SLOT(selAllButton_slot())); connect(unselAllButton, SIGNAL(clicked()), this, SLOT(unselAllButton_slot())); } } ListObjSelectWnd::~ListObjSelectWnd() { } void ListObjSelectWnd::resizeEvent(QResizeEvent *) { vbox1->resize(size()); } void ListObjSelectWnd::okButton_slot() { unsigned int cnt = list->count(), i; for (i = 0; i < cnt; ++i) { if (list->isSelected(i)) { done(1); return; } } } void ListObjSelectWnd::cancelButton_slot() { done(2); } void ListObjSelectWnd::selAllButton_slot() { unsigned int cnt = list->count(), i; for (i = 0; i < cnt; ++i) { list->setSelected(i, true); } } void ListObjSelectWnd::unselAllButton_slot() { unsigned int cnt = list->count(), i; for (i = 0; i < cnt; ++i) { list->setSelected(i, false); } } QStringList ListObjSelectWnd::getSelectedList() { QStringList ret; unsigned int cnt = list->count(), i; for (i = 0; i < cnt; ++i) { if (list->isSelected(i)) { #ifndef PWM_EMBEDDED ret.push_back(list->text(i)); #else ret.append(list->text(i)); #endif } } return ret; } void ListObjSelectWnd::setList(const QStringList &_list) { list->clear(); list->insertStringList(_list); } -#ifndef PWM_EMBEDDED -#include "listobjselectwnd.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_listobjselectwnd.cpp" #endif diff --git a/pwmanager/pwmanager/listobjselectwnd.h b/pwmanager/pwmanager/listobjselectwnd.h index 3b5f1eb..df3da93 100644 --- a/pwmanager/pwmanager/listobjselectwnd.h +++ b/pwmanager/pwmanager/listobjselectwnd.h @@ -1,85 +1,87 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef LISTOBJSELECTWND_H #define LISTOBJSELECTWND_H #include <qdialog.h> -#include <qvbox.h> -#include <qhbox.h> +#include <q3vbox.h> +#include <q3hbox.h> #include <qlabel.h> -#include <qlistbox.h> +#include <q3listbox.h> #include <qpushbutton.h> #include <qstringlist.h> +//Added by qt3to4: +#include <QResizeEvent> /** Display a list-window for selection of some objects */ class ListObjSelectWnd : public QDialog { Q_OBJECT public: ListObjSelectWnd(const QString &caption, const QString &titleText, QWidget *parent = 0, bool multiSel = false, const char *name = 0, - bool modal = FALSE, WFlags f = 0); + bool modal = FALSE, Qt::WFlags f = 0); ~ListObjSelectWnd(); void setList(const QStringList &_list); void addObj(const QString &name) { list->insertItem(name); } void selectObj(const QString &name) #ifndef PWM_EMBEDDED { list->setCurrentItem(list->findItem(name, Qt::ExactMatch)); } #else { list->setCurrentItem(list->findItem(name)); } #endif QString getSelected() { return list->currentText(); } int getSelectedIndex() #ifndef PWM_EMBEDDED { return list->index(list->selectedItem()); } #else { return list->currentItem(); } #endif QStringList getSelectedList(); void clearObjs() { list->clear(); } protected: - QVBox *vbox1; - QHBox *hbox1; - QHBox *hbox2; + Q3VBox *vbox1; + Q3HBox *hbox1; + Q3HBox *hbox2; QLabel *title; - QListBox *list; + Q3ListBox *list; QPushButton *okButton; QPushButton *cancelButton; QPushButton *selAllButton; QPushButton *unselAllButton; protected: void resizeEvent(QResizeEvent *); protected slots: void okButton_slot(); void cancelButton_slot(); void selAllButton_slot(); void unselAllButton_slot(); }; #endif diff --git a/pwmanager/pwmanager/listviewpwm.cpp b/pwmanager/pwmanager/listviewpwm.cpp index 0df9431..4253ab1 100644 --- a/pwmanager/pwmanager/listviewpwm.cpp +++ b/pwmanager/pwmanager/listviewpwm.cpp @@ -1,129 +1,132 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "listviewpwm.h" #include "pwmexception.h" #include "pwmview.h" #include <qpainter.h> #include <qpixmap.h> +//Added by qt3to4: +#include <QEvent> +#include <QKeyEvent> #include <kiconloader.h> #ifdef PWM_EMBEDDED #include <kglobal.h> #endif ListViewPwM::ListViewPwM(QWidget *parent, const char *name) : KListView(parent, name) { // setResizeMode(QListView::AllColumns); setAllColumnsShowFocus (true ); } bool ListViewPwM::event(QEvent *e) { - if (e->type() == QEvent::LayoutHint) + if (e->type() == QEvent::LayoutRequest) emit layoutChanged(); if (e->type() == QEvent::KeyPress) { QKeyEvent* ke = (QKeyEvent*) e; if ( ke->key() == Qt::Key_Space) { emit toggleOverview(); return true; } if ( ke->key() == Qt::Key_I || ke->key() == Qt::Key_N || ke->key() == Qt::Key_Insert) { emit insertPW(); return true; } if ( ke->key() == Qt::Key_Delete || ke->key() == Qt::Key_Backspace) { emit deletePW(); return true; } } return KListView::event(e); } QPixmap * ListViewItemPwM::onPix = 0; QPixmap * ListViewItemPwM::offPix = 0; -ListViewItemPwM::ListViewItemPwM(QListView *parent) - : QCheckListItem(parent, "", QCheckListItem::CheckBox) +ListViewItemPwM::ListViewItemPwM(Q3ListView *parent) + : Q3CheckListItem(parent, "", Q3CheckListItem::CheckBox) { if (!onPix) { PWM_ASSERT(!offPix); KIconLoader* picons; #ifndef PWM_EMBEDDED KIconLoader il; picons = &il; #else picons = KGlobal::iconLoader(); #endif KIconLoader il; #ifndef PWM_EMBEDDED static QPixmap onP(picons->loadIcon("button_ok", KIcon::Small)); #else static QPixmap onP(picons->loadIcon("decrypted", KIcon::Small)); #endif onPix = &onP; static QPixmap offP(picons->loadIcon("encrypted", KIcon::Small)); offPix = &offP; } } void ListViewItemPwM::paintCell(QPainter *p, const QColorGroup &cg, int column, int width, int align) { // qDebug("ListViewItemPwM::paintCell column=%i", column); if (!p) return; //US BUG: if (column != COLUMN_DESC) { - QCheckListItem::paintCell(p, cg, column, width, align); + Q3CheckListItem::paintCell(p, cg, column, width, align); return; } QPixmap *curPix = isOn() ? onPix : offPix; int pixSpace = curPix->width(); pixSpace += 4; #ifndef PWM_EMBEDDED QRect window(p->viewport()); // clear the rectangle (we have to clear it first. see QT doc) p->eraseRect(0, 0, pixSpace, window.height()); // now draw the pixmap int y = (height() - curPix->height()) / 2; p->drawPixmap(1, y, *curPix); window.moveLeft(pixSpace); p->setViewport(window); #else p->eraseRect(0, 0, pixSpace, height()); // now draw the pixmap int y = (height() - curPix->height()) / 2; p->drawPixmap(1, y, *curPix); p->translate( pixSpace, 0 ); #endif - QListViewItem::paintCell(p, cg, column, width - pixSpace, align); + Q3ListViewItem::paintCell(p, cg, column, width - pixSpace, align); } -#ifndef PWM_EMBEDDED -#include "listviewpwm.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_listviewpwm.cpp" #endif diff --git a/pwmanager/pwmanager/listviewpwm.h b/pwmanager/pwmanager/listviewpwm.h index 51008b8..2652939 100644 --- a/pwmanager/pwmanager/listviewpwm.h +++ b/pwmanager/pwmanager/listviewpwm.h @@ -1,60 +1,63 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __LISTVIEW_H #define __LISTVIEW_H #include <klistview.h> +//Added by qt3to4: +#include <QEvent> +#include <QPixmap> /** PwManager implementation of the list view. * Derived from KListView. */ class ListViewPwM : public KListView { Q_OBJECT public: ListViewPwM(QWidget *parent = 0, const char *name = 0); signals: void layoutChanged(); void toggleOverview(); void insertPW(); void deletePW( ); protected: virtual bool event(QEvent *e); }; -class ListViewItemPwM : public QCheckListItem +class ListViewItemPwM : public Q3CheckListItem { public: - ListViewItemPwM(QListView *parent); + ListViewItemPwM(Q3ListView *parent); protected: void paintCell(QPainter *p, const QColorGroup &cg, int column, int width, int align); protected: /** pixmap to display for an item with state "on" */ static QPixmap *onPix; /** pixmap to display for an item with state "off" */ static QPixmap *offPix; }; #endif diff --git a/pwmanager/pwmanager/main.cpp b/pwmanager/pwmanager/main.cpp index ee26082..acb0011 100644 --- a/pwmanager/pwmanager/main.cpp +++ b/pwmanager/pwmanager/main.cpp @@ -1,223 +1,224 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef PWM_EMBEDDED #include <kcmdlineargs.h> #include <kaboutdata.h> #else #include <qdir.h> #include <kpimglobalprefs.h> #endif #include <klocale.h> #include <kstandarddirs.h> #include "pwmexception.h" #include "pwminit.h" void dumpMissing(); #define LICENSE_FILE (::locate("data", "pwmanager/pwmanager_license_text")) int PwMApplication::newInstance() { static bool initial = true; if (initial) { initial = false; init = new PwMInit(this); init->initializeApp(); } else { BUG_ON(!init); printInfo("passing parameters to old instance."); init->handleCmdLineArgs(false); } return EXIT_SUCCESS; } static const char *description = I18N_NOOP("PwManager\n" "The convenient way of managing passwords"); #ifndef PWM_EMBEDDED static KCmdLineOptions options[] = { { "minimized", I18N_NOOP("Windows minimized"), 0 }, { "mintray", I18N_NOOP("Windows minimized to tray"), 0 }, { "open-deeplocked", I18N_NOOP("Open all \"files\" deeplocked"), 0 }, { "skip-self-test", I18N_NOOP("Don't run a self-test on startup"), 0 }, { "+[files...]", I18N_NOOP("Files to open on startup"), 0 }, { 0, 0, 0 } }; #endif #ifdef PWM_DEBUG static void printDebugConfigureInfo() { cout << "================================" << endl; cout << PROG_NAME " version " PACKAGE_VER << endl; #ifdef CONFIG_KEYCARD cout << "CONFIG_KEYCARD: enabled" << endl; #else cout << "CONFIG_KEYCARD: disabled" << endl; #endif #ifdef CONFIG_KWALLETIF cout << "CONFIG_KWALLETIF: enabled" << endl; #else cout << "CONFIG_KWALLETIF: disabled" << endl; #endif #ifdef BIG_ENDIAN_HOST cout << "Endianess: big-endian" << endl; #else cout << "Endianess: little-endian" << endl; #endif #ifdef WORDS_BIGENDIAN cout << "Endianess 2: big-endian" << endl; #else cout << "Endianess 2: little-endian" << endl; #endif cout << "sizeof(long): " << sizeof(long) << endl; cout << "================================" << endl; } #else // PWM_DEBUG static inline void printDebugConfigureInfo() { /* nothing */ } #endif // PWM_DEBUG #ifndef PWM_EMBEDDED static void addAuthors(KAboutData *aboutData) { aboutData->addAuthor("Michael Buesch", I18N_NOOP( "main programming and current maintainer"), "mbuesch@freenet.de"); aboutData->addAuthor("Matt Scifo", I18N_NOOP( "original implementaion of \n" "\"categories\" and the password-tree \n" "in the system-tray. Original implementations of \n" "numerous view-improvements."), "mscifo@o1.com"); aboutData->addCredit("Elias Probst", I18N_NOOP( "Gentoo ebuild maintainer."), "elias.probst@gmx.de"); aboutData->addCredit("George Staikos", I18N_NOOP("KWallet"), "staikos@kde.org"); aboutData->addCredit("Matthew Palmer", I18N_NOOP("rc2 code"), "mjp16@uow.edu.au"); aboutData->addCredit("Olivier Sessink", I18N_NOOP("gpasman"), "gpasman@nl.linux.org"); aboutData->addCredit("The libgcrypt developers", I18N_NOOP("Blowfish and SHA1 algorithms"), 0, "ftp://ftp.gnupg.org/gcrypt/alpha/libgcrypt/"); aboutData->addCredit("Troy Engel", I18N_NOOP("kpasman"), "tengel@sonic.net"); aboutData->addCredit("Wickey", I18N_NOOP("graphics-design in older versions."), "wickey@gmx.at"); aboutData->addCredit("Ian MacGregor", I18N_NOOP( "original documentation author.")); } #endif int main(int argc, char *argv[]) { + if(!getenv("QPEDIR")) putenv("QPEDIR=/usr/lib/kdepimpi"); printDebugConfigureInfo(); #ifndef PWM_EMBEDDED KAboutData aboutData(PACKAGE_NAME, PROG_NAME, PACKAGE_VER, description, KAboutData::License_File, "(c) 2003, 2004 Michael Buesch and the PwManager Team", 0, "http://passwordmanager.sourceforge.net/", "mbuesch@freenet.de"); addAuthors(&aboutData); KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineArgs::addCmdLineOptions(options); KUniqueApplication::addCmdLineOptions(); if (!KUniqueApplication::start()) { printInfo("already running."); return EXIT_SUCCESS; } PwMApplication a; aboutData.setLicenseTextFile(LICENSE_FILE); return a.exec(); #else bool exitHelp = false; if ( argc > 1 ) { QString command = argv[1]; if ( command == "-help" ){ printf("PWM/PI command line commands:\n"); printf(" no command: Start PWM/PI in usual way\n"); printf(" -help: This output\n"); printf(" PWM/PI is exiting now. Bye!\n"); exitHelp = true; } } if ( ! exitHelp ) { PwMApplication a(argc, argv); KGlobal::setAppName( "pwmanager" ); #ifndef DESKTOP_VERSION //qDebug("width %d ",QApplication::desktop()->width() ); if ( QApplication::desktop()->width() > 320 ) KGlobal::iconLoader()->setIconPath(QString(getenv("QPEDIR"))+"/pics/kdepim/pwmanager/icons22/"); else KGlobal::iconLoader()->setIconPath(QString(getenv("QPEDIR"))+"/pics/kdepim/pwmanager/icons16/"); #else QString fileName ; fileName = qApp->applicationDirPath () + "/kdepim/pwmanager/icons22/"; KGlobal::iconLoader()->setIconPath(QDir::convertSeparators(fileName)); QApplication::addLibraryPath ( qApp->applicationDirPath () ); #endif KStandardDirs::setAppDir( QDir::convertSeparators(locateLocal("data", "pwmanager"))); KPimGlobalPrefs::instance()->setGlobalConfig(); QApplication::setFont( KPimGlobalPrefs::instance()->mApplicationFont ); a.newInstance(); //US KAddressBookMain m ; //US QObject::connect(&a, SIGNAL (appMessage ( const QCString &, const QByteArray & )), ExternalAppHandler::instance(), SLOT (appMessage ( const QCString &, const QByteArray & ))); /*US #ifndef DESKTOP_VERSION a.showMainWidget( &m ); #else a.setMainWidget( &m ); m.resize (640, 480 ); m.show(); #endif */ QObject::connect( &a, SIGNAL( lastWindowClosed()), &a, SLOT (quit())); a.exec(); dumpMissing(); KPimGlobalPrefs::instance()->writeConfig(); } qDebug("PWMPI: Bye! "); #endif } diff --git a/pwmanager/pwmanager/printtext.h b/pwmanager/pwmanager/printtext.h index 82e31b0..71bc2e0 100644 --- a/pwmanager/pwmanager/printtext.h +++ b/pwmanager/pwmanager/printtext.h @@ -1,68 +1,68 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ #ifndef PRINTTEXT_H #define PRINTTEXT_H #include <kprinter.h> #include <qpainter.h> -#include <qpaintdevicemetrics.h> +#include <q3paintdevicemetrics.h> #include <qrect.h> #include <qpoint.h> /** prints text "raw" to a printer */ class PrintText : public KPrinter { public: PrintText(); ~PrintText(); /** begin printing. Call this before drawing to the device! */ void beginPrint(); /** prints a line */ void printLine(QString t); /** returns a pointer to the paint object */ QPainter* getPaint() { return paint; } /** sets the header-text */ void setHeader(const QString &left, const QString &middle); /** returns the header-text */ void getHeader(QString *left, QString *middle); protected: /** painter object */ QPainter *paint; /** metrics */ - QPaintDeviceMetrics *metrics; + Q3PaintDeviceMetrics *metrics; /** left field of header */ QString headerLeft; /** middle field of header */ QString headerMiddle; /** right field of header */ QString headerRight; /** current Y-Position */ int curYPos; /** text-body rectangle */ QRect body; /** line-spacing */ int ls; /** top-left point for beginning printing */ QPoint topLeft; /** current page number */ int page; protected: /** prints the header on the page */ void printHeader(); }; #endif diff --git a/pwmanager/pwmanager/pwgenwnd_emb.cpp b/pwmanager/pwmanager/pwgenwnd_emb.cpp index 429904c..21e0af4 100644 --- a/pwmanager/pwmanager/pwgenwnd_emb.cpp +++ b/pwmanager/pwmanager/pwgenwnd_emb.cpp @@ -1,134 +1,137 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #include "pwgenwnd_emb.h" #include <qpushbutton.h> -#include <qgroupbox.h> +#include <q3groupbox.h> #include <qcheckbox.h> #include <qlabel.h> #include <qlineedit.h> #include <qspinbox.h> #include <qlayout.h> +//Added by qt3to4: +#include <Q3HBoxLayout> +#include <Q3VBoxLayout> #include "klocale.h" /* * Constructs a pwGenWnd as a child of 'parent', with the * name 'name'. * */ pwGenWnd::pwGenWnd( QWidget* parent, const char* name) : KDialogBase( KDialogBase::Plain, i18n( "Password generator" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, parent, name, true ) { QWidget *page = plainPage(); - QVBoxLayout* pwGenWndLayout = new QVBoxLayout( page, 11, 6, "pwGenWndLayout"); + Q3VBoxLayout* pwGenWndLayout = new Q3VBoxLayout( page, 11, 6, "pwGenWndLayout"); - QGroupBox* groupBox1 = new QGroupBox( page, "groupBox1" ); + Q3GroupBox* groupBox1 = new Q3GroupBox( page, "groupBox1" ); groupBox1->setTitle( i18n( "Character set:" ) ); groupBox1->setColumnLayout(0, Qt::Vertical ); groupBox1->layout()->setSpacing( 6 ); groupBox1->layout()->setMargin( 11 ); - QVBoxLayout* groupBox1Layout = new QVBoxLayout( groupBox1->layout() ); + Q3VBoxLayout* groupBox1Layout = new Q3VBoxLayout( groupBox1->layout() ); groupBox1Layout->setAlignment( Qt::AlignTop ); int_charLowerCheckBox = new QCheckBox( i18n("Lowercase (abc)"), groupBox1, "int_charLowerCheckBox" ); int_charLowerCheckBox->setChecked( TRUE ); groupBox1Layout->addWidget( int_charLowerCheckBox ); int_charUpperCheckBox = new QCheckBox( i18n("Uppercase (ABC)"), groupBox1, "int_charUpperCheckBox" ); int_charUpperCheckBox->setChecked( TRUE ); groupBox1Layout->addWidget( int_charUpperCheckBox ); int_charNumCheckBox = new QCheckBox( i18n("Numbers (123)"), groupBox1, "int_charNumCheckBox" ); int_charNumCheckBox->setChecked( TRUE ); groupBox1Layout->addWidget( int_charNumCheckBox ); int_charSpecCheckBox = new QCheckBox( i18n("Special characters:"), groupBox1, "int_charSpecCheckBox" ); groupBox1Layout->addWidget( int_charSpecCheckBox ); QLabel* textLabel7 = new QLabel( groupBox1, "textLabel7" ); QString st("\x21\x22\xc2\xa7\x24\x25\x26\x2f\x28\x29\x3d\x3f\x2c\x2e\x2d\x3b\x3a\x5f\x2b"); textLabel7->setText( st.utf8() ); groupBox1Layout->addWidget( textLabel7 ); int_charBlankCheckBox = new QCheckBox( i18n( "Spaces (blank characters)"), groupBox1, "int_charBlankCheckBox" ); groupBox1Layout->addWidget( int_charBlankCheckBox ); - QHBoxLayout* layout7 = new QHBoxLayout( 0, 0, 6, "layout7"); + Q3HBoxLayout* layout7 = new Q3HBoxLayout( 0, 0, 6, "layout7"); int_charUserCheckBox = new QCheckBox( i18n("User defined:"), groupBox1, "int_charUserCheckBox" ); layout7->addWidget( int_charUserCheckBox ); int_userDefLineEdit = new QLineEdit( groupBox1, "int_userDefLineEdit" ); int_userDefLineEdit->setEnabled( FALSE ); layout7->addWidget( int_userDefLineEdit ); groupBox1Layout->addLayout( layout7 ); pwGenWndLayout->addWidget( groupBox1 ); - QHBoxLayout* layout8 = new QHBoxLayout( 0, 0, 6, "layout8"); + Q3HBoxLayout* layout8 = new Q3HBoxLayout( 0, 0, 6, "layout8"); int_lenSpinBox = new QSpinBox( page, "int_lenSpinBox" ); QLabel* textLabel2 = new QLabel( int_lenSpinBox, i18n("Password Length:"), page, "textLabel2" ); layout8->addWidget( textLabel2 ); int_lenSpinBox->setMaxValue( 9999 ); int_lenSpinBox->setMinValue( 1 ); int_lenSpinBox->setValue( 8 ); layout8->addWidget( int_lenSpinBox ); pwGenWndLayout->addLayout( layout8 ); int_filterCheckBox = new QCheckBox( i18n( "Enable Filtering to get better passwords" ), page, "int_filterCheckBox" ); int_filterCheckBox->setChecked( TRUE ); pwGenWndLayout->addWidget( int_filterCheckBox ); setButtonText( KDialogBase::Ok, "&Generate now" ); // signals and slots connections connect( int_charUserCheckBox, SIGNAL( toggled(bool) ), int_userDefLineEdit, SLOT( setEnabled(bool) ) ); } /* * Destroys the object and frees any allocated resources */ pwGenWnd::~pwGenWnd() { // no need to delete child widgets, Qt does it all for us } void pwGenWnd::cancelButton_slot() { qWarning( "pwGenWnd::cancelButton_slot(): Not implemented yet" ); } void pwGenWnd::genButton_slot() { qWarning( "pwGenWnd::genButton_slot(): Not implemented yet" ); } diff --git a/pwmanager/pwmanager/pwgenwndimpl.cpp b/pwmanager/pwmanager/pwgenwndimpl.cpp index 5313060..0eb7043 100644 --- a/pwmanager/pwmanager/pwgenwndimpl.cpp +++ b/pwmanager/pwmanager/pwgenwndimpl.cpp @@ -1,137 +1,137 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwgenwndimpl.h" #include "pwmexception.h" #include "genpasswd.h" #include <qtabwidget.h> #include <qspinbox.h> #include <qcheckbox.h> #include <qlineedit.h> #include <klocale.h> #include <kmessagebox.h> #ifndef PWM_EMBEDDED PwGenWndImpl::PwGenWndImpl(QWidget *parent, const char *name, bool modal, - WFlags fl) + Qt::WFlags fl) : pwGenWnd(parent, name, modal, fl) { } #else PwGenWndImpl::PwGenWndImpl( QWidget* parent, const char* name) : pwGenWnd( parent, name) { } #endif PwGenWndImpl::~PwGenWndImpl() { } #ifdef PWM_EMBEDDED void PwGenWndImpl::slotOk() { // internal generator if (!optionsSanityIntGen()) return; if (!startIntGen()) return; KDialogBase::slotOk(); } #endif void PwGenWndImpl::genButton_slot() { #ifndef PWM_EMBEDDED // internal generator if (!optionsSanityIntGen()) return; if (startIntGen()) goto exit_success; done(0); exit_success: done(1); #endif } void PwGenWndImpl::cancelButton_slot() { #ifndef PWM_EMBEDDED done(0); #endif } bool PwGenWndImpl::optionsSanityIntGen() { if (int_charLowerCheckBox->isChecked()) return true; if (int_charUpperCheckBox->isChecked()) return true; if (int_charNumCheckBox->isChecked()) return true; if (int_charSpecCheckBox->isChecked()) return true; if (int_charUserCheckBox->isChecked()) { if (int_userDefLineEdit->text().length() >= 2) return true; if (int_charBlankCheckBox->isChecked()) return true; } KMessageBox::error(this, i18n("Incorrect Charset selection!\n" "It's impossible to generate a sane " "password with the selected charset(s).\n" "Please select more charsets."), i18n("Incorrect Charset selection")); return false; } bool PwGenWndImpl::startIntGen() { GenPasswd gen; gen.setLen(int_lenSpinBox->value()); gen.setUseFilter(int_filterCheckBox->isChecked()); gen.setCharset(int_charLowerCheckBox->isChecked(), int_charUpperCheckBox->isChecked(), int_charNumCheckBox->isChecked(), int_charSpecCheckBox->isChecked(), int_charBlankCheckBox->isChecked(), int_charUserCheckBox->isChecked() ? int_userDefLineEdit->text() : QString::null); QString pw(gen.gen()); if (pw.isEmpty()) return false; password = pw; return true; } QString PwGenWndImpl::getPassword() { QString ret(password); password = QString::null; return ret; } diff --git a/pwmanager/pwmanager/pwgenwndimpl.h b/pwmanager/pwmanager/pwgenwndimpl.h index 994ff2f..1e706a1 100644 --- a/pwmanager/pwmanager/pwgenwndimpl.h +++ b/pwmanager/pwmanager/pwgenwndimpl.h @@ -1,66 +1,66 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __PWGENWNDIMPL_H #define __PWGENWNDIMPL_H #ifndef PWM_EMBEDDED #include "pwgenwnd.h" #else #include "pwgenwnd_emb.h" #endif class PwGenWndImpl : public pwGenWnd { public: #ifndef PWM_EMBEDDED PwGenWndImpl(QWidget *parent = 0, const char *name = 0, bool modal = FALSE, - WFlags fl = 0); + Qt::WFlags fl = 0); #else PwGenWndImpl( QWidget* parent = 0, const char* name = 0); #endif ~PwGenWndImpl(); /** returns the generated password */ QString getPassword(); protected slots: /** generate button pressed */ void genButton_slot(); #ifdef PWM_EMBEDDED virtual void slotOk(); #endif /** cancel button pressed */ void cancelButton_slot(); protected: /** start the internal generator */ bool startIntGen(); /** check all options of the internal generator */ bool optionsSanityIntGen(); protected: /** the generated password */ QString password; }; #endif // __PWGENWNDIMPL_H diff --git a/pwmanager/pwmanager/pwm.cpp b/pwmanager/pwmanager/pwm.cpp index 8373850..694fb13 100644 --- a/pwmanager/pwmanager/pwm.cpp +++ b/pwmanager/pwmanager/pwm.cpp @@ -1,1599 +1,1605 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include <klocale.h> #include <klistview.h> #include <ktoolbar.h> #include <kfiledialog.h> #include <kiconloader.h> #include <kmessagebox.h> #include <qstatusbar.h> +#include <QDesktopWidget> +//Added by qt3to4: +#include <Q3ValueList> +#include <QHideEvent> +#include <QFocusEvent> +#include <QCloseEvent> #ifndef PWM_EMBEDDED #include <kmenubar.h> #include <kstatusbar.h> #include <dcopclient.h> #include "configwndimpl.h" #include "configuration.h" #else #include <qmenubar.h> #include <qmessagebox.h> #include <pwmprefs.h> #include <kpimglobalprefs.h> #include <kprefsdialog.h> #include <kcmconfigs/kcmpwmconfig.h> #include <kcmconfigs/kcmkdepimconfig.h> #include <kcmultidialog.h> #include "editcategory.h" #endif #ifndef DESKTOP_VERSION #include <qpe/global.h> #endif #include <qpixmap.h> #include <qcheckbox.h> #include <qspinbox.h> #include <qlineedit.h> #include <qfileinfo.h> #include <qclipboard.h> #include <stdio.h> #include "pwm.h" #include "pwminit.h" #include "pwmprint.h" #include "addentrywndimpl.h" #include "globalstuff.h" #include "findwndimpl.h" #include "csv.h" #ifdef CONFIG_KWALLETIF # include "kwalletif.h" # include "kwalletemu.h" #endif #ifdef CONFIG_KEYCARD # include "pwmkeycard.h" #endif #define DEFAULT_SIZE (QSize(700, 400)) // Button IDs for "file" popup menu enum { BUTTON_POPUP_FILE_NEW = 0, BUTTON_POPUP_FILE_OPEN, BUTTON_POPUP_FILE_CLOSE, BUTTON_POPUP_FILE_SAVE, BUTTON_POPUP_FILE_SAVEAS, BUTTON_POPUP_FILE_EXPORT, BUTTON_POPUP_FILE_IMPORT, BUTTON_POPUP_FILE_PRINT, BUTTON_POPUP_FILE_QUIT }; // Button IDs for "manage" popup menu enum { BUTTON_POPUP_MANAGE_ADD = 0, BUTTON_POPUP_MANAGE_EDIT, BUTTON_POPUP_MANAGE_DEL, BUTTON_POPUP_MANAGE_CHANGEMP }; // Button IDs for chipcard popup menu enum { #ifdef CONFIG_KEYCARD BUTTON_POPUP_CHIPCARD_GENNEW = 0, BUTTON_POPUP_CHIPCARD_DEL, BUTTON_POPUP_CHIPCARD_READID, BUTTON_POPUP_CHIPCARD_SAVEBACKUP, BUTTON_POPUP_CHIPCARD_REPLAYBACKUP #else // CONFIG_KEYCARD BUTTON_POPUP_CHIPCARD_NO = 0 #endif // CONFIG_KEYCARD }; // Button IDs for "view" popup menu enum { BUTTON_POPUP_VIEW_FIND = 0, BUTTON_POPUP_VIEW_LOCK, BUTTON_POPUP_VIEW_DEEPLOCK, BUTTON_POPUP_VIEW_UNLOCK }; // Button IDs for "options" popup menu enum { BUTTON_POPUP_OPTIONS_CONFIG = 0, BUTTON_POPUP_OPTIONS_GLOBAL_CONFIG #ifdef PWM_EMBEDDED ,BUTTON_POPUP_OPTIONS_CATEGORY #endif }; // Button IDs for "export" popup menu (in "file" popup menu) enum { BUTTON_POPUP_EXPORT_TEXT = 0, BUTTON_POPUP_EXPORT_GPASMAN, BUTTON_POPUP_EXPORT_CSV #ifdef CONFIG_KWALLETIF ,BUTTON_POPUP_EXPORT_KWALLET #endif }; // Button IDs for "import" popup menu (in "file" popup menu) enum { BUTTON_POPUP_IMPORT_TEXT = 0, BUTTON_POPUP_IMPORT_GPASMAN, BUTTON_POPUP_IMPORT_CSV #ifdef CONFIG_KWALLETIF ,BUTTON_POPUP_IMPORT_KWALLET #endif }; #ifdef PWM_EMBEDDED // Button IDs for "help" popup menu enum { BUTTON_POPUP_HELP_LICENSE = 0, BUTTON_POPUP_HELP_FAQ, BUTTON_POPUP_HELP_ABOUT, BUTTON_POPUP_HELP_SYNC, BUTTON_POPUP_HELP_WHATSNEW }; #endif // Button IDs for toolbar enum { BUTTON_TOOL_NEW = 0, BUTTON_TOOL_OPEN, BUTTON_TOOL_SAVE, BUTTON_TOOL_SAVEAS, BUTTON_TOOL_PRINT, BUTTON_TOOL_ADD, BUTTON_TOOL_EDIT, BUTTON_TOOL_DEL, BUTTON_TOOL_FIND, BUTTON_TOOL_LOCK, BUTTON_TOOL_DEEPLOCK, BUTTON_TOOL_UNLOCK }; PwM::PwM(PwMInit *_init, PwMDoc *doc, bool virginity, QWidget *parent, const char *name) : KMainWindow(parent, "HALLO") , forceQuit (false) , forceMinimizeToTray (false) { syncManager = 0; virgin = !virginity; init = _init; connect(doc, SIGNAL(docClosed(PwMDoc *)), this, SLOT(docClosed(PwMDoc *))); initMenubar(); initToolbar(); initMetrics(); setVirgin(virginity); - setFocusPolicy(QWidget::WheelFocus); + setFocusPolicy(Qt::WheelFocus); #ifndef PWM_EMBEDDED statusBar()->show(); #endif view = makeNewListView(doc); setCentralWidget(view); updateCaption(); showStatMsg(i18n("Ready.")); } PwM::~PwM() { //qDebug("PwM::~PwM() %x", this); disconnect(curDoc(), SIGNAL(docClosed(PwMDoc *)), this, SLOT(docClosed(PwMDoc *))); conf()->confWndMainWndSize(size()); //LR closing of windows changed //needed for fastload option on PDA //emit closed(this); //qDebug("PwM::~PwM() emited closed(this)"); delete view; delete syncManager; } void PwM::initMenubar() { KIconLoader* picons; #ifndef PWM_EMBEDDED KIconLoader icons; picons = &icons; #else picons = KGlobal::iconLoader(); syncPopup = new KPopupMenu(this); syncManager = new KSyncManager((QWidget*)this, (KSyncInterface*)this, KSyncManager::PWMPI, PWMPrefs::instance(), syncPopup); syncManager->setBlockSave(false); connect ( syncPopup, SIGNAL( activated ( int ) ), syncManager, SLOT (slotSyncMenu( int ) ) ); syncManager->fillSyncMenu(); #endif filePopup = new KPopupMenu(this); importPopup = new KPopupMenu(filePopup); exportPopup = new KPopupMenu(filePopup); managePopup = new KPopupMenu(this); #ifdef CONFIG_KEYCARD chipcardPopup = new KPopupMenu(this); #endif // CONFIG_KEYCARD viewPopup = new KPopupMenu(this); optionsPopup = new KPopupMenu(this); // "file" popup menu - filePopup->insertItem(QIconSet(picons->loadIcon("filenew", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("filenew", KIcon::Small)), i18n("&New"), this, SLOT(new_slot()), 0, BUTTON_POPUP_FILE_NEW); - filePopup->insertItem(QIconSet(picons->loadIcon("fileopen", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("fileopen", KIcon::Small)), i18n("&Open"), this, SLOT(open_slot()), 0, BUTTON_POPUP_FILE_OPEN); - filePopup->insertItem(QIconSet(picons->loadIcon("fileclose", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("fileclose", KIcon::Small)), i18n("&Close"), this, SLOT(close_slot()), 0, BUTTON_POPUP_FILE_CLOSE); filePopup->insertSeparator(); - filePopup->insertItem(QIconSet(picons->loadIcon("filesave", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("filesave", KIcon::Small)), i18n("&Save"), this, SLOT(save_slot()), 0, BUTTON_POPUP_FILE_SAVE); - filePopup->insertItem(QIconSet(picons->loadIcon("filesaveas", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("filesaveas", KIcon::Small)), i18n("Save &as..."), this, SLOT(saveAs_slot()), 0, BUTTON_POPUP_FILE_SAVEAS); filePopup->insertSeparator(); // "file/export" popup menu exportPopup->insertItem(i18n("&Text-file..."), this, SLOT(exportToText()), 0, BUTTON_POPUP_EXPORT_TEXT); exportPopup->insertItem(i18n("&Gpasman / Kpasman ..."), this, SLOT(exportToGpasman()), 0, BUTTON_POPUP_EXPORT_GPASMAN); exportPopup->insertItem(i18n("&CSV (Comma Separated Value) ..."), this, SLOT(exportToCsv()), 0, BUTTON_POPUP_EXPORT_CSV); #ifdef CONFIG_KWALLETIF exportPopup->insertItem(i18n("&KWallet..."), this, SLOT(exportToKWallet()), 0, BUTTON_POPUP_EXPORT_KWALLET); #endif - filePopup->insertItem(QIconSet(picons->loadIcon("fileexport", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("fileexport", KIcon::Small)), i18n("E&xport"), exportPopup, BUTTON_POPUP_FILE_EXPORT); // "file/import" popup menu importPopup->insertItem(i18n("&Text-file..."), this, SLOT(importFromText()), 0, BUTTON_POPUP_IMPORT_TEXT); importPopup->insertItem(i18n("&Gpasman / Kpasman ..."), this, SLOT(importFromGpasman()), 0, BUTTON_POPUP_IMPORT_GPASMAN); importPopup->insertItem(i18n("&CSV (Comma Separated Value) ..."), this, SLOT(importCsv()), 0, BUTTON_POPUP_IMPORT_CSV); #ifdef CONFIG_KWALLETIF importPopup->insertItem(i18n("&KWallet..."), this, SLOT(importKWallet()), 0, BUTTON_POPUP_IMPORT_KWALLET); #endif - filePopup->insertItem(QIconSet(picons->loadIcon("fileimport", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("fileimport", KIcon::Small)), i18n("I&mport"), importPopup, BUTTON_POPUP_FILE_IMPORT); filePopup->insertSeparator(); #if 0 - filePopup->insertItem(QIconSet(picons->loadIcon("fileprint", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("fileprint", KIcon::Small)), i18n("&Print..."), this, SLOT(print_slot()), 0, BUTTON_POPUP_FILE_PRINT); filePopup->insertSeparator(); #endif - filePopup->insertItem(QIconSet(picons->loadIcon("exit", KIcon::Small)), + filePopup->insertItem(QIcon(picons->loadIcon("exit", KIcon::Small)), i18n("&Quit"), this, SLOT(quitButton_slot()), 0, BUTTON_POPUP_FILE_QUIT); menuBar()->insertItem(i18n("&File"), filePopup); // "manage" popup menu - managePopup->insertItem(QIconSet(picons->loadIcon("pencil", KIcon::Small)), + managePopup->insertItem(QIcon(picons->loadIcon("pencil", KIcon::Small)), i18n("&Add password"), this, SLOT(addPwd_slot()), 0, BUTTON_POPUP_MANAGE_ADD); managePopup->insertSeparator(); - managePopup->insertItem(QIconSet(picons->loadIcon("edit", KIcon::Small)), + managePopup->insertItem(QIcon(picons->loadIcon("edit", KIcon::Small)), i18n("&Edit"), this, SLOT(editPwd_slot()), 0, BUTTON_POPUP_MANAGE_EDIT); - managePopup->insertItem(QIconSet(picons->loadIcon("editdelete", KIcon::Small)), + managePopup->insertItem(QIcon(picons->loadIcon("editdelete", KIcon::Small)), i18n("&Delete"), this, SLOT(deletePwd_slot()), 0, BUTTON_POPUP_MANAGE_DEL); managePopup->insertSeparator(); - managePopup->insertItem(QIconSet(picons->loadIcon("rotate", KIcon::Small)), + managePopup->insertItem(QIcon(picons->loadIcon("rotate", KIcon::Small)), i18n("Change &Master Password"), this, SLOT(changeMasterPwd_slot()), 0, BUTTON_POPUP_MANAGE_CHANGEMP); menuBar()->insertItem(i18n("&Manage"), managePopup); // "chipcard" popup menu #ifdef CONFIG_KEYCARD - chipcardPopup->insertItem(QIconSet(picons->loadIcon("filenew", KIcon::Small)), + chipcardPopup->insertItem(QIcon(picons->loadIcon("filenew", KIcon::Small)), i18n("&Generate new key-card"), this, SLOT(genNewCard_slot()), 0, BUTTON_POPUP_CHIPCARD_GENNEW); - chipcardPopup->insertItem(QIconSet(picons->loadIcon("editdelete", KIcon::Small)), + chipcardPopup->insertItem(QIcon(picons->loadIcon("editdelete", KIcon::Small)), i18n("&Erase key-card"), this, SLOT(eraseCard_slot()), 0, BUTTON_POPUP_CHIPCARD_DEL); - chipcardPopup->insertItem(QIconSet(picons->loadIcon("", KIcon::Small)), + chipcardPopup->insertItem(QIcon(picons->loadIcon("", KIcon::Small)), i18n("Read card-&ID"), this, SLOT(readCardId_slot()), 0, BUTTON_POPUP_CHIPCARD_READID); chipcardPopup->insertSeparator(); - chipcardPopup->insertItem(QIconSet(picons->loadIcon("2rightarrow", KIcon::Small)), + chipcardPopup->insertItem(QIcon(picons->loadIcon("2rightarrow", KIcon::Small)), i18n("&Make card backup-image"), this, SLOT(makeCardBackup_slot()), 0, BUTTON_POPUP_CHIPCARD_SAVEBACKUP); - chipcardPopup->insertItem(QIconSet(picons->loadIcon("2leftarrow", KIcon::Small)), + chipcardPopup->insertItem(QIcon(picons->loadIcon("2leftarrow", KIcon::Small)), i18n("&Replay card backup-image"), this, SLOT(replayCardBackup_slot()), 0, BUTTON_POPUP_CHIPCARD_REPLAYBACKUP); menuBar()->insertItem(i18n("&Chipcard manager"), chipcardPopup); #endif // CONFIG_KEYCARD // "view" popup menu - viewPopup->insertItem(QIconSet(picons->loadIcon("find", KIcon::Small)), + viewPopup->insertItem(QIcon(picons->loadIcon("find", KIcon::Small)), i18n("&Find"), this, SLOT(find_slot()), 0, BUTTON_POPUP_VIEW_FIND); viewPopup->insertSeparator(); - viewPopup->insertItem(QIconSet(picons->loadIcon("halfencrypted", KIcon::Small)), + viewPopup->insertItem(QIcon(picons->loadIcon("halfencrypted", KIcon::Small)), i18n("&Lock all entries"), this, SLOT(lockWnd_slot()), 0, BUTTON_POPUP_VIEW_LOCK); - viewPopup->insertItem(QIconSet(picons->loadIcon("encrypted", KIcon::Small)), + viewPopup->insertItem(QIcon(picons->loadIcon("encrypted", KIcon::Small)), i18n("&Deep-lock all entries"), this, SLOT(deepLockWnd_slot()), 0, BUTTON_POPUP_VIEW_DEEPLOCK); - viewPopup->insertItem(QIconSet(picons->loadIcon("decrypted", KIcon::Small)), + viewPopup->insertItem(QIcon(picons->loadIcon("decrypted", KIcon::Small)), i18n("&Unlock all entries"), this, SLOT(unlockWnd_slot()), 0, BUTTON_POPUP_VIEW_UNLOCK); menuBar()->insertItem(i18n("&View"), viewPopup); // "options" popup menu - optionsPopup->insertItem(QIconSet(picons->loadIcon("configure", KIcon::Small)), + optionsPopup->insertItem(QIcon(picons->loadIcon("configure", KIcon::Small)), i18n("&Configure PwM/Pi..."), this, SLOT(config_slot()),0, BUTTON_POPUP_OPTIONS_CONFIG); - optionsPopup->insertItem(QIconSet(picons->loadIcon("configure", KIcon::Small)), + optionsPopup->insertItem(QIcon(picons->loadIcon("configure", KIcon::Small)), i18n("Global Settings..."), this, SLOT(config_global_slot()),0, BUTTON_POPUP_OPTIONS_GLOBAL_CONFIG); if ( QApplication::desktop()->width() <= 240 ) { managePopup->insertSeparator(); managePopup->insertItem(i18n("&Options"), optionsPopup); } else menuBar()->insertItem(i18n("&Options"), optionsPopup); // "help" popup menu #ifndef PWM_EMBEDDED helpPopup = helpMenu(QString::null, false); #else - optionsPopup->insertItem(QIconSet(picons->loadIcon("configure", KIcon::Small)), + optionsPopup->insertItem(QIcon(picons->loadIcon("configure", KIcon::Small)), i18n("C&ategories..."), this, SLOT(category_slot()),0, BUTTON_POPUP_OPTIONS_CATEGORY); menuBar()->insertItem(i18n("&Sync"), syncPopup); helpPopup = new KPopupMenu(this); helpPopup->insertItem(i18n("&License"), this, SLOT(showLicense_slot()), 0, BUTTON_POPUP_HELP_LICENSE); helpPopup->insertItem(i18n("&Faq"), this, SLOT(faq_slot()), 0, BUTTON_POPUP_HELP_FAQ); helpPopup->insertItem(i18n("&About PwManager"), this, SLOT(createAboutData_slot()), 0, BUTTON_POPUP_HELP_ABOUT); helpPopup->insertItem(i18n("&Sync HowTo"), this, SLOT(syncHowTo_slot()), 0, BUTTON_POPUP_HELP_SYNC); helpPopup->insertItem(i18n("&What's New"), this, SLOT(whatsnew_slot()), 0, BUTTON_POPUP_HELP_WHATSNEW); #endif menuBar()->insertItem(i18n("&Help"), helpPopup); } void PwM::initToolbar() { KIconLoader* picons; #ifndef PWM_EMBEDDED KIconLoader icons; picons = &icons; #else picons = KGlobal::iconLoader(); #endif #if 0 toolBar()->insertButton(picons->loadIcon("filenew", KIcon::Toolbar), BUTTON_TOOL_NEW, SIGNAL(clicked(int)), this, SLOT(new_slot()), true, i18n("New")); #endif toolBar()->insertButton(picons->loadIcon("fileopen", KIcon::Toolbar), BUTTON_TOOL_OPEN, SIGNAL(clicked(int)), this, SLOT(open_slot()), true, i18n("Open")); toolBar()->insertButton(picons->loadIcon("pencil", KIcon::Toolbar), BUTTON_TOOL_ADD, SIGNAL(clicked(int)), this, SLOT(addPwd_slot()), true, i18n("Add password")); toolBar()->insertSeparator(); toolBar()->insertButton(picons->loadIcon("find", KIcon::Toolbar), BUTTON_TOOL_FIND, SIGNAL(clicked(int)), this, SLOT(find_slot()), true, i18n("Find entry")); toolBar()->insertSeparator(); toolBar()->insertButton(picons->loadIcon("filesave", KIcon::Toolbar), BUTTON_TOOL_SAVE, SIGNAL(clicked(int)), this, SLOT(save_slot()), true, i18n("Save")); #if 0 toolBar()->insertButton(picons->loadIcon("filesaveas", KIcon::Toolbar), BUTTON_TOOL_SAVEAS, SIGNAL(clicked(int)), this, SLOT(saveAs_slot()), true, i18n("Save as")); #endif #if 0 toolBar()->insertButton(picons->loadIcon("fileprint", KIcon::Toolbar), BUTTON_TOOL_PRINT, SIGNAL(clicked(int)), this, SLOT(print_slot()), true, i18n("Print...")); #endif toolBar()->insertSeparator(); toolBar()->insertButton(picons->loadIcon("edit", KIcon::Toolbar), BUTTON_TOOL_EDIT, SIGNAL(clicked(int)), this, SLOT(editPwd_slot()), true, i18n("Edit password")); toolBar()->insertButton(picons->loadIcon("editdelete", KIcon::Toolbar), BUTTON_TOOL_DEL, SIGNAL(clicked(int)), this, SLOT(deletePwd_slot()), true, i18n("Delete password")); toolBar()->insertSeparator(); toolBar()->insertButton(picons->loadIcon("halfencrypted", KIcon::Toolbar), BUTTON_TOOL_LOCK, SIGNAL(clicked(int)), this, SLOT(lockWnd_slot()), true, i18n("Lock all entries")); toolBar()->insertButton(picons->loadIcon("encrypted", KIcon::Toolbar), BUTTON_TOOL_DEEPLOCK, SIGNAL(clicked(int)), this, SLOT(deepLockWnd_slot()), true, i18n("Deep-Lock all entries")); toolBar()->insertButton(picons->loadIcon("decrypted", KIcon::Toolbar), BUTTON_TOOL_UNLOCK, SIGNAL(clicked(int)), this, SLOT(unlockWnd_slot()), true, i18n("Unlock all entries")); } void PwM::initMetrics() { QSize s = conf()->confWndMainWndSize(); if (s.isValid()) resize(s); else resize(DEFAULT_SIZE); } void PwM::updateCaption() { QString s = curDoc()->getTitle(); int maxlen = 50; if ( QApplication::desktop()->width() < 640 ) { if ( QApplication::desktop()->width() < 320 ) maxlen = 22; else maxlen = 35; } if ( s.length() > maxlen ) { s = "..."+s.right(maxlen -3); } setPlainCaption( s ); } void PwM::hideEvent(QHideEvent *) { if (isMinimized()) { if (init->tray()) { forceMinimizeToTray = true; close(); } int mmlock = conf()->confGlobMinimizeLock(); switch (mmlock) { case 0: // don't lock anything break; case 1: { // normal lock curDoc()->lockAll(true); break; } case 2: { // deep-lock curDoc()->deepLock(); break; } default: WARN(); } } } void PwM::setVirgin(bool v) { if (virgin == v) return; virgin = v; filePopup->setItemEnabled(BUTTON_POPUP_FILE_SAVE, !v); filePopup->setItemEnabled(BUTTON_POPUP_FILE_SAVEAS, !v); filePopup->setItemEnabled(BUTTON_POPUP_FILE_EXPORT, !v); filePopup->setItemEnabled(BUTTON_POPUP_FILE_PRINT, !v); managePopup->setItemEnabled(BUTTON_POPUP_MANAGE_EDIT, !v); managePopup->setItemEnabled(BUTTON_POPUP_MANAGE_DEL, !v); managePopup->setItemEnabled(BUTTON_POPUP_MANAGE_CHANGEMP, !v); viewPopup->setItemEnabled(BUTTON_POPUP_VIEW_LOCK, !v); viewPopup->setItemEnabled(BUTTON_POPUP_VIEW_DEEPLOCK, !v); viewPopup->setItemEnabled(BUTTON_POPUP_VIEW_UNLOCK, !v); viewPopup->setItemEnabled(BUTTON_POPUP_VIEW_FIND, !v); toolBar()->setItemEnabled(BUTTON_TOOL_SAVE, !v); toolBar()->setItemEnabled(BUTTON_TOOL_SAVEAS, !v); toolBar()->setItemEnabled(BUTTON_TOOL_PRINT, !v); toolBar()->setItemEnabled(BUTTON_TOOL_EDIT, !v); toolBar()->setItemEnabled(BUTTON_TOOL_DEL, !v); toolBar()->setItemEnabled(BUTTON_TOOL_LOCK, !v); toolBar()->setItemEnabled(BUTTON_TOOL_DEEPLOCK, !v); toolBar()->setItemEnabled(BUTTON_TOOL_UNLOCK, !v); toolBar()->setItemEnabled(BUTTON_TOOL_FIND, !v); } void PwM::new_slot() { init->createMainWnd(); } //US ENH void PwM::open_slot() { open_slot(""); } void PwM::open_slot(QString fn) { openDoc(fn); } PwMDoc * PwM::openDoc(QString filename, bool openDeepLocked) { if (!isVirgin()) { // open the document in a new window. PwM *newInstance = init->createMainWnd(); PwMDoc *newDoc = newInstance->openDoc(filename, openDeepLocked); if (!newDoc) { newInstance->setForceQuit(true); delete_and_null(newInstance); } return newDoc; } if (!curDoc()->openDocUi(curDoc(), filename, openDeepLocked)) return 0; showStatMsg(i18n("Successfully opened file.")); updateCaption(); setVirgin(false); return curDoc(); } PwMView * PwM::makeNewListView(PwMDoc *doc) { PwMView *ret = new PwMView(this, this, doc); ret->setFont(conf()->confGlobEntryFont()); ret->show(); return ret; } void PwM::close_slot() { close(); } void PwM::quitButton_slot() { init->shutdownApp(0); } void PwM::save_slot() { save(); } bool PwM::save() { if (!curDoc()->saveDocUi(curDoc())) return false; showStatMsg(i18n("Successfully saved data.")); updateCaption(); return true; } void PwM::saveAs_slot() { saveAs(); } bool PwM::saveAs() { if (!curDoc()->saveAsDocUi(curDoc())) return false; showStatMsg(i18n("Successfully saved data.")); updateCaption(); return true; } //US ENH : changed code to run with older MOC void PwM::addPwd_slot() { addPwd_slot1(0, 0); } void PwM::addPwd_slot1(QString *pw, PwMDoc *_doc) { PwMDoc *doc; if (_doc) { doc = _doc; } else { doc = curDoc(); } PWM_ASSERT(doc); doc->timer()->getLock(DocTimer::id_autoLockTimer); #ifndef PWM_EMBEDDED AddEntryWndImpl w; #else AddEntryWndImpl w(doc, this, "addentrywndimpl"); #endif w.setCaption( i18n ("Add new password") ); vector<string> catList; doc->getCategoryList(&catList); unsigned i, size = catList.size(); for (i = 0; i < size; ++i) { w.addCategory(catList[i].c_str()); } w.setCurrCategory(view->getCurrentCategory()); if (pw) w.pwLineEdit->setText(*pw); tryAgain: w.descLineEdit->setFocus(); if (w.exec() == 1) { PwMDataItem d; //US BUG: to initialize all values of curEntr with meaningfulldata, // we call clear on it. Reason: Metadata will be uninitialized otherwise. // another option would be to create a constructor for PwMDataItem d.clear(true); d.desc = w.getDescription().latin1(); d.name = w.getUsername().latin1(); d.pw = w.getPassword().latin1(); d.comment = w.getComment().latin1(); d.url = w.getUrl().latin1(); d.launcher = w.getLauncher().latin1(); PwMerror ret = doc->addEntry(w.getCategory(), &d); if (ret == e_entryExists) { KMessageBox::error(this, i18n ("An entry with this \"Description\",\n" "does already exist.\n" "Please select another description."), i18n("entry already exists.")); goto tryAgain; } else if (ret == e_maxAllowedEntr) { KMessageBox::error(this, i18n("The maximum possible number of\nentries" "has been reached.\nYou can't add more entries."), i18n("maximum number of entries")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return; } } setVirgin(false); doc->timer()->putLock(DocTimer::id_autoLockTimer); } //US ENH : changed code to run with older MOC void PwM::editPwd_slot() { editPwd_slot3(0,0,0); } void PwM::editPwd_slot1(const QString *category) { editPwd_slot3(category, 0, 0); } void PwM::editPwd_slot3(const QString *category, const int *index, PwMDoc *_doc) { PwMDoc *doc; if (_doc) { doc = _doc; } else { doc = curDoc(); } PWM_ASSERT(doc); if (doc->isDocEmpty()) return; if (doc->isDeepLocked()) return; doc->timer()->getLock(DocTimer::id_autoLockTimer); unsigned int curEntryIndex; if (index) { curEntryIndex = *index; } else { if (!(view->getCurEntryIndex(&curEntryIndex))) { qDebug("couldn't get index. Maybe we have a binary entry here. "); printDebug("couldn't get index. Maybe we have a binary entry here."); doc->timer()->putLock(DocTimer::id_autoLockTimer); return; } } QString curCategory; if (category) { curCategory = *category; } else { curCategory = view->getCurrentCategory(); } PwMDataItem currItem; if (!doc->getEntry(curCategory, curEntryIndex, &currItem, true)) { doc->timer()->putLock(DocTimer::id_autoLockTimer); return; } BUG_ON(currItem.binary); AddEntryWndImpl w(doc); w.setCaption( i18n ("Edit password") ); vector<string> catList; doc->getCategoryList(&catList); unsigned i, size = catList.size(); for (i = 0; i < size; ++i) { w.addCategory(catList[i].c_str()); } w.setCurrCategory(curCategory); w.setDescription(currItem.desc.c_str()); w.setUsername(currItem.name.c_str()); w.setPassword(currItem.pw.c_str()); w.setUrl(currItem.url.c_str()); w.setLauncher(currItem.launcher.c_str()); w.setComment(currItem.comment.c_str()); w.descLineEdit->setFocus(); if (w.exec() == 1) { currItem.desc = w.getDescription().latin1(); currItem.name = w.getUsername().latin1(); currItem.pw = w.getPassword().latin1(); currItem.comment = w.getComment().latin1(); currItem.url = w.getUrl().latin1(); currItem.launcher = w.getLauncher().latin1(); if (!doc->editEntry(curCategory, w.getCategory(), curEntryIndex, &currItem)) { KMessageBox::error(this, i18n("Couldn't edit the entry.\n" "Maybe you changed the category and\n" "this entry is already present\nin the new " "category?"), i18n("couldn't edit entry.")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return; } } doc->timer()->putLock(DocTimer::id_autoLockTimer); } void PwM::deletePwd_slot() { PWM_ASSERT(curDoc()); if (curDoc()->isDocEmpty()) return; if (curDoc()->isDeepLocked()) return; curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); unsigned int curEntryIndex = 0; if (!(view->getCurEntryIndex(&curEntryIndex))) { printDebug("couldn't get index"); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return; } PwMDataItem currItem; QString curCategory = view->getCurrentCategory(); if (!curDoc()->getEntry(curCategory, curEntryIndex, &currItem)) { printDebug("couldn't get entry"); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return; } if (KMessageBox:: questionYesNo(this, i18n ("Do you really want to delete\nthe selected entry") + " \n\"" + QString(currItem.desc.c_str()) + "\" ?", i18n("delete?")) == KMessageBox::Yes) { curDoc()->delEntry(curCategory, curEntryIndex); } curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); } void PwM::changeMasterPwd_slot() { PWM_ASSERT(curDoc()); curDoc()->changeCurrentPw(); } void PwM::lockWnd_slot() { PWM_ASSERT(curDoc()); curDoc()->lockAll(true); } void PwM::deepLockWnd_slot() { PWM_ASSERT(curDoc()); curDoc()->deepLock(); } void PwM::unlockWnd_slot() { PWM_ASSERT(curDoc()); curDoc()->lockAll(false); } void PwM::config_global_slot() { KPimPrefsGlobalDialog gc ( this ); gc.exec(); } void PwM::config_slot() { int oldStyle = conf()->confWndMainViewStyle(); #if 0 KCMultiDialog* ConfigureDialog = new KCMultiDialog( "PIM", this ,"pwmconfigdialog", true ); KCMPwmConfig* pwmcfg = new KCMPwmConfig( ConfigureDialog->getNewVBoxPage(i18n( "PwManager")) , "KCMPwmConfig" ); ConfigureDialog->addModule(pwmcfg ); KCMKdePimConfig* kdelibcfg = new KCMKdePimConfig( ConfigureDialog->getNewVBoxPage(i18n( "Global")) , "KCMKdeLibConfig" ); ConfigureDialog->addModule(kdelibcfg ); #endif KDialogBase * ConfigureDialog = new KDialogBase ( KDialogBase::Plain , i18n("Configure KA/Pi"), KDialogBase::Default |KDialogBase::Cancel | KDialogBase::Apply | KDialogBase::Ok, KDialogBase::Ok,0, "name", true, true); KCMPwmConfig* kabcfg = new KCMPwmConfig( ConfigureDialog , "KCMpwmConfig" ); ConfigureDialog->setMainWidget( kabcfg ); connect( ConfigureDialog, SIGNAL( applyClicked() ), kabcfg, SLOT( save() ) ); connect( ConfigureDialog, SIGNAL( acceptClicked() ), kabcfg, SLOT( save() ) ); connect( ConfigureDialog, SIGNAL( defaultClicked() ), kabcfg, SLOT( defaults() ) ); //saveSettings(); kabcfg->load(); #ifndef DESKTOP_VERSION if ( QApplication::desktop()->height() <= 480 ) ;// ConfigureDialog->hideButtons(); ConfigureDialog->showMaximized(); #endif if ( ConfigureDialog->exec() ) KMessageBox::information( this, i18n("Some changes are only\neffective after a restart!\n") ); delete ConfigureDialog; int newStyle = conf()->confWndMainViewStyle(); // reinitialize tray init->initTray(); // reinitialize KWallet emulation init->initKWalletEmu(); PwMDocList *_dl = PwMDoc::getOpenDocList(); const vector<PwMDocList::listItem> *dl = _dl->getList(); vector<PwMDocList::listItem>::const_iterator i = dl->begin(), end = dl->end(); PwMDoc *doc; while (i != end) { doc = (*i).doc; // unlock-without-mpw timeout doc->timer()->start(DocTimer::id_mpwTimer); // auto-lock timeout doc->timer()->start(DocTimer::id_autoLockTimer); ++i; } - const QValueList<PwM *> *ml = init->mainWndList(); + const Q3ValueList<PwM *> *ml = init->mainWndList(); #ifndef PWM_EMBEDDED - QValueList<PwM *>::const_iterator i2 = ml->begin(), + Q3ValueList<PwM *>::const_iterator i2 = ml->begin(), end2 = ml->end(); #else - QValueList<PwM *>::ConstIterator i2 = ml->begin(), + Q3ValueList<PwM *>::ConstIterator i2 = ml->begin(), end2 = ml->end(); #endif PwM *pwm; while (i2 != end2) { pwm = *i2; // reinitialize the window style. if (oldStyle != newStyle) pwm->curView()->initStyle(newStyle); // set the new font pwm->curView()->setFont(conf()->confGlobEntryFont()); ++i2; } } void PwM::activateMpButton(bool activate) { managePopup->setItemEnabled(BUTTON_POPUP_MANAGE_CHANGEMP, activate); } void PwM::closeEvent(QCloseEvent *e) { //qDebug("PwM::closeEvent "); emit closed( this ); return; e->accept(); } void PwM::docClosed(PwMDoc *doc) { //qDebug("PwM::docClosed "); PARAM_UNUSED(doc); PWM_ASSERT(doc == curDoc()); close(); } void PwM::find_slot() { PWM_ASSERT(curDoc()); if (curDoc()->isDocEmpty()) return; if (curDoc()->isDeepLocked()) return; curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); FindWndImpl findWnd(view); findWnd.exec(); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); } void PwM::exportToText() { PWM_ASSERT(curDoc()); if (curDoc()->isDocEmpty()) { KMessageBox::information(this, i18n ("Sorry, there's nothing to export.\n" "Please first add some passwords."), i18n("nothing to do")); return; } curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); QString fn(KFileDialog::getSaveFileName(QString::null, i18n("*|plain-text file"), this)); if (fn == "") { curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return; } PwMerror ret = curDoc()->exportToText(&fn); if (ret != e_success) { KMessageBox::error(this, i18n("Error: Couldn't write to file.\n" "Please check if you have permission to write\n" "to the file in that directory."), i18n("error while writing")); } else showStatMsg(i18n("Successfully exported data.")); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); } bool PwM::importFromText() { if (!isVirgin()) { if (KMessageBox::questionYesNo(this, i18n("Do you want to import the data\n" "into the current document? (If you\n" "select \"no\", a new document will be\n" "opened.)"), i18n("import into this document?")) == KMessageBox::No) { // import the data to a new window. PwM *newInstance = init->createMainWnd(); bool ok = newInstance->importFromText(); if (!ok) { newInstance->setForceQuit(true); delete_and_null(newInstance); } return ok; } } curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); PwMerror ret; QString path(KFileDialog::getOpenFileName(QString::null, i18n("*|PWM-exported text file"), this)); if (path == "") goto cancelImport; ret = curDoc()->importFromText(&path, 0); if (ret == e_fileFormat) { KMessageBox::error(this, i18n("Could not read file-format.\n" "This seems to be _not_ a valid file\n" "exported by PwM."), i18n("invalid file-format")); goto cancelImport; } else if (ret == e_invalidArg) { BUG(); goto cancelImport; } else if (ret != e_success) { KMessageBox::error(this, i18n("Could not import file!\n" "Do you have permission to read this file?\n" "Do you have enough free memory?"), i18n("import failed")); goto cancelImport; } setVirgin(false); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return true; cancelImport: curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return false; } void PwM::exportToGpasman() { PWM_ASSERT(curDoc()); if (curDoc()->isDocEmpty()) { KMessageBox::information(this, i18n ("Sorry, there's nothing to export.\n" "Please first add some passwords."), i18n("nothing to do")); return; } curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); QString fn(KFileDialog::getSaveFileName(QString::null, i18n("*|Gpasman or Kpasman file"), this)); if (fn == "") { curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return; } PwMerror ret = curDoc()->exportToGpasman(&fn); if (ret != e_success) { if (ret == e_noPw) { curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return; } KMessageBox::error(this, i18n("Error: Couldn't write to file.\n" "Please check if you have permission to write " "to the file in that directory."), i18n("error while writing")); } else showStatMsg(i18n("Successfully exported data.")); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); } void PwM::exportToCsv() { PWM_ASSERT(curDoc()); if (curDoc()->isDocEmpty()) { KMessageBox::information(this, i18n ("Sorry, there is nothing to export;\n" "please add some passwords first."), i18n("Nothing to Do")); return; } curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); QString fn(KFileDialog::getSaveFileName("*.csv", i18n("*|CSV Text File"), this)); if (fn.isEmpty()) { curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return; } Csv csv(this); if (!csv.exportData(fn, curDoc())) { curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); showStatMsg(i18n("CSV file export failed.")); return; } showStatMsg(i18n("Successfully exported data.")); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); } bool PwM::importCsv() { Csv csv(this); if (!isVirgin()) { if (KMessageBox::questionYesNo(this, i18n("Do you want to import the data\n" "into the current document? (If you\n" "select \"no\", a new document will be\n" "opened.)"), i18n("Import into This Document?")) == KMessageBox::No) { // import the data to a new window. PwM *newInstance = init->createMainWnd(); bool ok = newInstance->importCsv(); if (!ok) { newInstance->setForceQuit(true); delete_and_null(newInstance); } return ok; } } QString filename = KFileDialog::getOpenFileName("*.csv", i18n("*|CSV Text File"), this); if (filename.isEmpty()) return false; curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); if (!csv.importData(filename, curDoc())) { curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); showStatMsg(i18n("CSV file import failed.")); return false; } curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); KMessageBox::information(this, i18n("Successfully imported the CSV data\n" "into the current document."), i18n("Successfully Imported")); showStatMsg(i18n("Successfully imported")); setVirgin(false); return true; } void PwM::exportToKWallet() { #ifdef CONFIG_KWALLETIF if (!checkAndAskForKWalletEmu()) return; PWM_ASSERT(curDoc()); if (curDoc()->isDocEmpty()) { KMessageBox::information(this, i18n ("Sorry, there's nothing to export.\n" "Please first add some passwords."), i18n("nothing to do")); init->initKWalletEmu(); return; } curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); KWalletIf walletIf(this); if (walletIf.kwalletExport(curDoc())) { KMessageBox::information(this, i18n("Successfully exported the data of the current " "document to KWallet."), i18n("Successfully exported data.")); showStatMsg(i18n("Successfully exported data.")); } init->initKWalletEmu(); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); #endif // CONFIG_KWALLETIF } bool PwM::importFromGpasman() { if (!isVirgin()) { if (KMessageBox::questionYesNo(this, i18n("Do you want to import the data\n" "into the current document? (If you\n" "select \"no\", a new document will be\n" "opened.)"), i18n("import into this document?")) == KMessageBox::No) { // import the data to a new window. PwM *newInstance = init->createMainWnd(); bool ok = newInstance->importFromGpasman(); if (!ok) { newInstance->setForceQuit(true); delete_and_null(newInstance); } return ok; } } curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); PwMerror ret; QString path(KFileDialog::getOpenFileName(QString::null, i18n("*|Gpasman or Kpasman file"), this)); if (path == "") goto cancelImport; ret = curDoc()->importFromGpasman(&path); if (ret == e_wrongPw) { if (KMessageBox::questionYesNo(this, i18n ("This is probably the wrong master-password\n" "you have typed in.\n" "There is no real way to determine the\n" "correctness of the password in the Gpasman\n" "file-format. But I think this\n" "password ist wrong.\n" "Do you want to continue nevertheless?"), i18n("password error")) == KMessageBox::No) { goto cancelImport; } } else if (ret != e_success) { KMessageBox::error(this, i18n("Could not import file!\n" "Do you have permission to read this file?"), i18n("import failed")); goto cancelImport; } setVirgin(false); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return true; cancelImport: curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); return false; } #ifdef CONFIG_KWALLETIF bool PwM::checkAndAskForKWalletEmu() { if (init->kwalletEmu()) { /* KWallet emulation is enabled. We can't import/export * data from/to it, while emulation is active. */ if (KMessageBox::questionYesNo(this, i18n("KWallet emulation is enabled.\n" "You can't import or export data from/to " "the original KWallet, while the emulation " "is active.\n" "Do you want to tempoarly disable the KWallet emulation?"), i18n("Tempoarly disable KWallet emulation?")) == KMessageBox::Yes) { init->initKWalletEmu(true); PWM_ASSERT(!init->kwalletEmu()); return true; } return false; } return true; } #endif // CONFIG_KWALLETIF bool PwM::importKWallet() { #ifdef CONFIG_KWALLETIF if (!checkAndAskForKWalletEmu()) return false; KWalletIf walletIf(this); if (!isVirgin()) { if (KMessageBox::questionYesNo(this, i18n("Do you want to import the data " "into the current document? (If you " "select \"no\", a new document will be " "opened.)"), i18n("import into this document?")) == KMessageBox::No) { // import the data to a new window. PwM *newInstance = init->createMainWnd(); bool ok = newInstance->importKWallet(); if (!ok) { newInstance->setForceQuit(true); delete_and_null(newInstance); goto exit_fail; } else { goto exit_ok; } } } curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); if (!walletIf.kwalletImport(curDoc())) { curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); showStatMsg(i18n("KWallet import failed")); goto exit_fail; } KMessageBox::information(this, i18n("Successfully imported the KWallet data " "into the current document."), i18n("successfully imported")); showStatMsg(i18n("successfully imported")); setVirgin(false); curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); exit_ok: init->initKWalletEmu(); return true; exit_fail: init->initKWalletEmu(); #endif // CONFIG_KWALLETIF return false; } void PwM::print_slot() { curDoc()->timer()->getLock(DocTimer::id_autoLockTimer); #ifndef PWM_EMBEDDED PwMPrint p(curDoc(), this); p.printNow(); #else qDebug("PwM::print_slot , PRINTING IS NOT IMPLEMENTED"); #endif curDoc()->timer()->putLock(DocTimer::id_autoLockTimer); } void PwM::genNewCard_slot() { #ifdef CONFIG_KEYCARD init->keycard()->genNewCard(); #endif } void PwM::eraseCard_slot() { #ifdef CONFIG_KEYCARD init->keycard()->eraseCard(); #endif } void PwM::readCardId_slot() { #ifdef CONFIG_KEYCARD init->keycard()->displayKey(); #endif } void PwM::makeCardBackup_slot() { #ifdef CONFIG_KEYCARD init->keycard()->makeBackupImage(); #endif } void PwM::replayCardBackup_slot() { #ifdef CONFIG_KEYCARD init->keycard()->replayBackupImage(); #endif } void PwM::execLauncher_slot() { PWM_ASSERT(curDoc()); if (curDoc()->isDeepLocked()) return; unsigned int curEntryIndex; if (!view->getCurEntryIndex(&curEntryIndex)) return; bool ret = curDoc()->execLauncher(view->getCurrentCategory(), curEntryIndex); if (ret) showStatMsg(i18n("Executed the \"Launcher\".")); else showStatMsg(i18n("ERROR: Couldn't execute the \"Launcher\"!")); } void PwM::goToURL_slot() { PWM_ASSERT(curDoc()); if (curDoc()->isDeepLocked()) return; unsigned int curEntryIndex; if (!view->getCurEntryIndex(&curEntryIndex)) return; bool ret = curDoc()->goToURL(view->getCurrentCategory(), curEntryIndex); if (ret) showStatMsg(i18n("started browser with current URL.")); else showStatMsg(i18n("ERROR: Couldn't start browser! Maybe invalid URL?")); } void PwM::copyToClipboard(const QString &s) { QClipboard *cb = QApplication::clipboard(); #ifndef PWM_EMBEDDED if (cb->supportsSelection()) cb->setText(s, QClipboard::Selection); cb->setText(s, QClipboard::Clipboard); #else cb->setText(s); #endif } void PwM::showStatMsg(const QString &msg) { #ifdef DESKTOP_VERSION statusBar()->message(msg, STATUSBAR_MSG_TIMEOUT * 1000); #else //qDebug("Statusbar : %s",msg.latin1()); Global::statusMessage(msg); #endif } void PwM::focusInEvent(QFocusEvent *e) { if (e->gotFocus()) { emit gotFocus(this); } else if (e->lostFocus()) { emit lostFocus(this); } } #ifdef PWM_EMBEDDED void PwM::category_slot() { PwMDoc *doc = curDoc(); PWM_ASSERT(doc); doc->timer()->getLock(DocTimer::id_autoLockTimer); editCategoryWnd w(doc, this, "editcategory"); /* vector<string> catList; doc->getCategoryList(&catList); unsigned i, size = catList.size(); for (i = 0; i < size; ++i) { w.addCategory(catList[i].c_str()); } w.setCurrCategory(view->getCurrentCategory()); if (pw) w.pwLineEdit->setText(*pw); */ w.setCurrCategory(view->getCurrentCategory()); tryAgain: if (w.exec() == 1) { PwMDataItem d; //US BUG: to initialize all values of curEntr with meaningfulldata, // we call clear on it. Reason: Metadata will be uninitialized otherwise. // another option would be to create a constructor for PwMDataItem d.clear(true); /* d.desc = w.getDescription().latin1(); d.name = w.getUsername().latin1(); d.pw = w.getPassword().latin1(); d.comment = w.getComment().latin1(); d.url = w.getUrl().latin1(); d.launcher = w.getLauncher().latin1(); PwMerror ret = doc->addEntry(w.getCategory(), &d); if (ret == e_entryExists) { KMessageBox::error(this, i18n ("An entry with this \"Description\",\n" "does already exist.\n" "Please select another description."), i18n("entry already exists.")); goto tryAgain; } else if (ret == e_maxAllowedEntr) { KMessageBox::error(this, i18n("The maximum possible number of\nentries" "has been reached.\nYou can't add more entries."), i18n("maximum number of entries")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return; } */ } setVirgin(false); doc->timer()->putLock(DocTimer::id_autoLockTimer); } void PwM::whatsnew_slot() { KApplication::showFile( "KDE-Pim/Pi Version Info", "kdepim/WhatsNew.txt" ); } void PwM::showLicense_slot() { KApplication::showLicence(); } void PwM::faq_slot() { KApplication::showFile( "PWM/Pi FAQ", "kdepim/pwmanager/pwmanagerFAQ.txt" ); } void PwM::syncHowTo_slot() { KApplication::showFile( "KDE-Pim/Pi Synchronization HowTo", "kdepim/SyncHowto.txt" ); } void PwM::createAboutData_slot() { QString version; #include <../version> ; QMessageBox::about( this, "About PwManager/Pi", "PwManager/Platform-independent\n" "(PWM/Pi) " +version + " - " + #ifdef DESKTOP_VERSION "Desktop Edition\n" #else "PDA-Edition\n" "for: Zaurus 5500 / 7x0 / 8x0\n" #endif "(c) 2004 Ulf Schenk\n" "(c) 2004 Lutz Rogowski\n" "(c) 1997-2004, The KDE PIM Team\n" "(c) Michael Buesch - main programming\nand current maintainer\nmbuesch@freenet.de\n" "Matt Scifo - mscifo@o1.com\n" "Elias Probst - elias.probst@gmx.de\n" "George Staikos - staikos@kde.org\n" "Matthew Palmer - mjp16@uow.edu.au\n" "Olivier Sessink - gpasman@nl.linux.org\n" "The libgcrypt developers -\nBlowfish and SHA1 algorithms\nftp://ftp.gnupg.org/gcrypt/alpha/libgcrypt/\n" "Troy Engel - tengel@sonic.net\n" "Wickey - wickey@gmx.at\n" "Ian MacGregor - original documentation author.\n" ); } //this are the overwritten callbackmethods from the syncinterface bool PwM::sync(KSyncManager* manager, QString filename, int mode,QString resource) { PWM_ASSERT(curDoc()); bool ret = curDoc()->sync(manager, filename, mode,resource); qDebug("PwM::sync save now: ret=%i", ret); if (ret == true) { //US BUG: what can we call here to update the view of the current doc? //mViewManager->refreshView(); //US curDoc()->sync sets the dirtyFlag in case the sync was successfull. save(); } return ret; } void PwM::removeSyncInfo( QString syncProfile) { qDebug("PWM:removeSyncInfo for profile %s ", syncProfile.latin1()); curDoc()->removeSyncInfo( syncProfile ); //US curDoc()->removeSyncInfo sets the dirtyFlag. } #endif -#ifndef PWM_EMBEDDED -#include "pwm.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwm.cpp" #endif diff --git a/pwmanager/pwmanager/pwm.h b/pwmanager/pwmanager/pwm.h index c4bbb4e..450d13f 100644 --- a/pwmanager/pwmanager/pwm.h +++ b/pwmanager/pwmanager/pwm.h @@ -1,300 +1,305 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __PWM_H #define __PWM_H #include <kpopupmenu.h> #include <klistview.h> #include <kmainwindow.h> #ifndef PWM_EMBEDDED #include <kwin.h> #include <kapp.h> #include <kdeversion.h> #else #include <ksyncmanager.h> #endif #include <kaction.h> #include <qglobal.h> +//Added by qt3to4: +#include <QCloseEvent> +#include <QFocusEvent> +#include <Q3PopupMenu> +#include <QHideEvent> #include "pwmview.h" #include "pwmexception.h" /** timeout for displaying a message on the status-bar (in seconds) */ #define STATUSBAR_MSG_TIMEOUT 5 class PwMInit; class KSyncManager; /** PwM is the base class of the project */ #ifndef PWM_EMBEDDED -//MOC_SKIP_BEGIN +#ifndef Q_MOC_RUN class PwM : public KMainWindow -//MOC_SKIP_END +#endif #else class PwM : public KMainWindow, public KSyncInterface #endif { Q_OBJECT public: friend class PwMView; /** construtor */ PwM(PwMInit *_init, PwMDoc *doc, bool virginity = true, QWidget* parent = 0, const char *name = 0); /** destructor */ ~PwM(); /** copy some text to the global clipboard */ static void copyToClipboard(const QString &s); /** returns pointer to the view */ PwMView * curView() { return view; } /** returns pointer to the currently using document. */ PwMDoc * curDoc() { return curView()->document(); } /** open a new doc with the given filename */ PwMDoc * openDoc(QString filename, bool openDeepLocked = false); /** show a message on the global status bar. * The message times out after some seconds. */ void showStatMsg(const QString &msg); /** ask the user where to save the doc (if it has not been saved, yet) * and write the data to disk. */ bool save(); /** ask the user where to save the doc * and write the data to disk. */ bool saveAs(); /** force quit. Quit this window, always! Don't minimize it */ bool isForceQuit() { return forceQuit; } /** set forceQuit */ void setForceQuit(bool force) { forceQuit = force; } /** force minimize this window */ bool isForceMinimizeToTray() { return forceMinimizeToTray; } /** set forceMinimizeToTray */ void setForceMinimizeToTray(bool force) { forceMinimizeToTray = force; } public slots: /** file/new triggered */ void new_slot(); /** file/open triggered */ //US ENH void open_slot(); void open_slot(QString fn); /** file/close triggered */ void close_slot(); /** file/quit triggered */ void quitButton_slot(); /** file/save triggered */ void save_slot(); /** file/saveAs triggered */ void saveAs_slot(); /** file/export/text triggered */ void exportToText(); /** file/export/gpasman triggered */ void exportToGpasman(); /** file/export/kwallet triggered */ void exportToKWallet(); /** file/export/csv triggered */ void exportToCsv(); /** file/import/text triggered */ bool importFromText(); /** file/import/gpasman triggered */ bool importFromGpasman(); /** file/import/kwallet triggered */ bool importKWallet(); /** file/import/csv triggered */ bool importCsv(); /** file/print triggered */ void print_slot(); /** manage/add triggered */ //US ENH : changed code to run with older MOC void addPwd_slot(); void addPwd_slot1(QString *pw, PwMDoc *_doc); /** manage/edit triggered */ //US ENH : changed code to run with older MOC void editPwd_slot(); void editPwd_slot1(const QString *category); void editPwd_slot3(const QString *category, const int *index ,PwMDoc *_doc ); /** manage/delete triggered */ void deletePwd_slot(); /** execute the "Launcher" entry */ void execLauncher_slot(); /** open browser with URL entry */ void goToURL_slot(); /** manage/changeMasterPwd triggered */ void changeMasterPwd_slot(); /** lock current document */ void lockWnd_slot(); /** deeplock current document */ void deepLockWnd_slot(); /** window/unlock triggered */ void unlockWnd_slot(); /** find item */ void find_slot(); /** configure clicked */ void config_slot(); void config_global_slot(); /** (de)activate the "change master pw" button in the menu-bar */ void activateMpButton(bool activate = true); /** generate a new chipcard */ void genNewCard_slot(); /** completely erase the current card */ void eraseCard_slot(); /** returns the ID number of the current card */ void readCardId_slot(); /** make backup image of the current card */ void makeCardBackup_slot(); /** write backup image to current card */ void replayCardBackup_slot(); #ifdef PWM_EMBEDDED void category_slot(); void whatsnew_slot(); void showLicense_slot(); void faq_slot(); void createAboutData_slot(); void syncHowTo_slot(); #endif protected: /** is this window virgin? */ bool isVirgin() { return virgin; } /** add/remove virginity */ void setVirgin(bool v); /** initialize the menubar */ void initMenubar(); /** initialize the toolbar */ void initToolbar(); /** initialize the window-metrics */ void initMetrics(); /** close-event */ void closeEvent(QCloseEvent *e); /** creates a new PwM-ListView and returns it */ PwMView * makeNewListView(PwMDoc *doc); /** Window hide-event */ void hideEvent(QHideEvent *); /** is this window minimized? */ bool isMinimized() { #ifndef PWM_EMBEDDED #if KDE_VERSION >= KDE_MAKE_VERSION(3, 2, 0) return KWin::windowInfo(winId()).isMinimized(); #else // KDE_VERSION return KWin::info(winId()).isIconified(); #endif // KDE_VERSION #else return false; #endif } /** window got the focus */ void focusInEvent(QFocusEvent *e); /** update the caption string */ void updateCaption(); #ifdef CONFIG_KWALLETIF /** check if kwalletemu is enabled and ask the user what to do */ bool checkAndAskForKWalletEmu(); #endif // CONFIG_KWALLETIF protected slots: /** doc got closed */ void docClosed(PwMDoc *doc); signals: /** window got closed (by user or someone else) */ void closed(PwM *wnd); /** window got the focus (was brought to foreground) */ void gotFocus(PwM *wnd); /** window lost the focus */ void lostFocus(PwM *wnd); protected: /** pointer to the view active in this KMainWindow */ PwMView *view; /** pointer to the init class */ PwMInit *init; /** has this window already lost its virginity? * Means is there an open working document */ bool virgin; /** "file" popup-menu */ KPopupMenu *filePopup; /** "manage" popup-menu */ KPopupMenu *managePopup; #ifdef CONFIG_KEYCARD /** "chipcard" popup-menu */ KPopupMenu *chipcardPopup; #endif // CONFIG_KEYCARD /** "view" popup-menu */ KPopupMenu *viewPopup; /** "options" popup-menu */ KPopupMenu *optionsPopup; /** "help" popup-menu */ KPopupMenu *helpPopup; /** "export" popup-menu */ KPopupMenu *exportPopup; /** "import" popup-menu */ KPopupMenu *importPopup; /** force quit this window? */ bool forceQuit; /** force minimize this window to the tray */ bool forceMinimizeToTray; private: #ifdef PWM_EMBEDDED //this are the overwritten callbackmethods from the syncinterface virtual bool sync(KSyncManager* manager, QString filename, int mode,QString resource); virtual void removeSyncInfo( QString syncProfile); // LR ******************************* // sync stuff! - QPopupMenu *syncPopup; + Q3PopupMenu *syncPopup; KSyncManager* syncManager; #endif }; #endif diff --git a/pwmanager/pwmanager/pwmanager.pro b/pwmanager/pwmanager/pwmanager.pro index 7efe45c..d6d8dbe 100644 --- a/pwmanager/pwmanager/pwmanager.pro +++ b/pwmanager/pwmanager/pwmanager.pro @@ -1,177 +1,179 @@ TEMPLATE = app CONFIG += qt warn_off DESTDIR= ../../bin TARGET = pwmpi include( ../../variables.pri ) INCLUDEPATH += . ../../ ../../libkdepim ../../microkde ../../microkde/kdecore ../../microkde/kdeui ../../microkde/kutils ../libcrypt/crypt ../libcrypt/error ../libcrypt/zlib DEFINES += PWM_EMBEDDED CONFIG_PWMANAGER_GCRY DESKTOP_VERSION #enable this setting if you want debugoutput for pwmanager #DEFINES += CONFIG_DEBUG LIBS += -L../libcrypt/ LIBS += -L../../bin/ -LIBS += -lmicrokde -LIBS += -lmicrokdepim +LIBS += -lxmicrokde +LIBS += -lxmicrokdepim LIBS += -lzlib LIBS += -lkpmicrocipher LIBS += -lkpmicroerror LIBS += -lkpmicrompi LIBS += -lstdc++ unix:{ OBJECTS_DIR = obj/unix MOC_DIR = moc/unix } win32:{ DEFINES += _WIN32_ OBJECTS_DIR = obj/win MOC_DIR = moc/win QMAKE_LINK += /NODEFAULTLIB:LIBC QMAKE_CXXFLAGS += /TP /GX /GR /Ehsc } #INTERFACES = \ #addentrywnd.ui \ #configwnd.ui \ #findwnd.ui \ #getmasterpwwnd.ui \ #pwgenwnd.ui \ #setmasterpwwnd.ui \ #subtbledit.ui #INTERFACES = \ #subtbledit.ui \ #HEADERS = \ #configuration_31compat.h \ #configuration.h \ #configwnd.h \ #configwndimpl.h \ #selftest.h #subtbledit.h \ #subtbleditimpl.h \ #compressbzip2.h \ HEADERS = \ addentrywnd_emb.h \ addentrywndimpl.h \ base64.h \ binentrygen.h \ blowfish.h \ commentbox.h \ compiler.h \ compressgzip.h \ csv.h \ editcategory.h \ findwnd_emb.h \ findwndimpl.h \ genpasswd.h \ getkeycardwnd.h \ getmasterpwwnd_emb.h \ getmasterpwwndimpl.h \ globalstuff.h \ gpasmanfile.h \ htmlgen.h \ htmlparse.h \ ipc.h \ libgcryptif.h \ listobjselectwnd.h \ listviewpwm.h \ printtext.h \ pwgenwnd_emb.h \ pwgenwndimpl.h \ pwmdoc.h \ pwmdocui.h \ pwmexception.h \ pwm.h \ pwminit.h \ pwmprefs.h \ pwmprint.h \ pwmtray.h \ pwmview.h \ pwmviewstyle_0.h \ pwmviewstyle_1.h \ pwmviewstyle.h \ randomizer.h \ rc2.h \ rencatwnd.h \ serializer.h \ setmasterpwwnd_emb.h \ setmasterpwwndimpl.h \ sha1.h \ waitwnd.h \ kcmconfigs/kcmpwmconfig.h \ kcmconfigs/pwmconfigwidget.h #sources that need not be build #SOURCES = \ #advcommeditimpl.cpp \ #configuration.cpp \ #configwnd.cpp \ #configwndimpl.cpp \ #configuration_31compat.cpp \ #htmlparse.cpp \ #printtext.cpp \ #selftest.cpp \ #pwmprint.cpp \ #spinforsignal.cpp #subtbledit.cpp \ #subtbleditimpl.cpp \ #compressbzip2.cpp SOURCES = \ addentrywnd_emb.cpp \ addentrywndimpl.cpp \ base64.cpp \ binentrygen.cpp \ blowfish.cpp \ commentbox.cpp \ compressgzip.cpp \ csv.cpp \ editcategory.cpp \ findwnd_emb.cpp \ findwndimpl.cpp \ genpasswd.cpp \ getkeycardwnd.cpp \ getmasterpwwnd_emb.cpp \ getmasterpwwndimpl.cpp \ globalstuff.cpp \ gpasmanfile.cpp \ htmlgen.cpp \ ipc.cpp \ libgcryptif.cpp \ listobjselectwnd.cpp \ listviewpwm.cpp \ main.cpp \ pwgenwnd_emb.cpp \ pwgenwndimpl.cpp \ pwm.cpp \ pwmdoc.cpp \ pwmdocui.cpp \ pwmexception.cpp \ pwminit.cpp \ pwmprefs.cpp \ pwmtray.cpp \ pwmview.cpp \ pwmviewstyle_0.cpp \ pwmviewstyle_1.cpp \ pwmviewstyle.cpp \ randomizer.cpp \ rc2.cpp \ rencatwnd.cpp \ serializer.cpp \ setmasterpwwnd_emb.cpp \ setmasterpwwndimpl.cpp \ sha1.cpp \ waitwnd.cpp \ kcmconfigs/kcmpwmconfig.cpp \ kcmconfigs/pwmconfigwidget.cpp +#The following line was inserted by qt3to4 +QT += xml qt3support diff --git a/pwmanager/pwmanager/pwmanagerE.pro b/pwmanager/pwmanager/pwmanagerE.pro index 6b68514..e80d1ae 100644 --- a/pwmanager/pwmanager/pwmanagerE.pro +++ b/pwmanager/pwmanager/pwmanagerE.pro @@ -1,175 +1,175 @@ TEMPLATE = app CONFIG += qt warn_on TARGET = pwmpi OBJECTS_DIR = obj/$(PLATFORM) MOC_DIR = moc/$(PLATFORM) DESTDIR=$(QPEDIR)/bin INCLUDEPATH += . ../../ ../../qtcompat ../../qtcompat/xml ../../libkdepim ../../microkde ../../microkde/kdecore ../../microkde/kdeui ../../microkde/kutils ../libcrypt/crypt ../libcrypt/error $(QPEDIR)/include DEFINES += PWM_EMBEDDED CONFIG_PWMANAGER_GCRY #enable this setting if you want debugoutput for pwmanager #DEFINES += CONFIG_DEBUG LIBS += -L../libcrypt/$(PLATFORM) -LIBS += -lmicrokde +LIBS += -lxmicrokde LIBS += -lmicroqtcompat -LIBS += -lmicrokdepim +LIBS += -lxmicrokdepim LIBS += -L$(QPEDIR)/lib LIBS += -lqpe LIBS += -lzlib #LIBS += -lbz2 #LIBS += -lkpmicrogcrypt LIBS += -ljpeg LIBS += $(QTOPIALIB) LIBS += -lkpmicrocipher LIBS += -lkpmicroerror LIBS += -lkpmicrompi LIBS += -lstdc++ LIBS += $(GCC3EXTRALIB1) LIBS += $(GCC3EXTRALIB2) #INTERFACES = \ #addentrywnd.ui \ #configwnd.ui \ #findwnd.ui \ #getmasterpwwnd.ui \ #pwgenwnd.ui \ #setmasterpwwnd.ui \ #subtbledit.ui #INTERFACES = \ #subtbledit.ui \ #HEADERS = \ #configuration_31compat.h \ #configuration.h \ #configwnd.h \ #configwndimpl.h \ #selftest.h #subtbledit.h \ #subtbleditimpl.h \ #compressbzip2.h \ HEADERS = \ addentrywnd_emb.h \ addentrywndimpl.h \ base64.h \ binentrygen.h \ blowfish.h \ commentbox.h \ compiler.h \ compressgzip.h \ csv.h \ editcategory.h \ findwnd_emb.h \ findwndimpl.h \ genpasswd.h \ getkeycardwnd.h \ getmasterpwwnd_emb.h \ getmasterpwwndimpl.h \ globalstuff.h \ gpasmanfile.h \ htmlgen.h \ htmlparse.h \ ipc.h \ libgcryptif.h \ listobjselectwnd.h \ listviewpwm.h \ printtext.h \ pwgenwnd_emb.h \ pwgenwndimpl.h \ pwmdoc.h \ pwmdocui.h \ pwmexception.h \ pwm.h \ pwminit.h \ pwmprefs.h \ pwmprint.h \ pwmtray.h \ pwmview.h \ pwmviewstyle_0.h \ pwmviewstyle_1.h \ pwmviewstyle.h \ randomizer.h \ rc2.h \ rencatwnd.h \ serializer.h \ setmasterpwwnd_emb.h \ setmasterpwwndimpl.h \ sha1.h \ waitwnd.h \ kcmconfigs/kcmpwmconfig.h \ kcmconfigs/pwmconfigwidget.h #sources that need not be build #SOURCES = \ #advcommeditimpl.cpp \ #configuration.cpp \ #configwnd.cpp \ #configwndimpl.cpp \ #configuration_31compat.cpp \ #htmlparse.cpp \ #printtext.cpp \ #selftest.cpp \ #pwmprint.cpp \ #spinforsignal.cpp #subtbledit.cpp \ #subtbleditimpl.cpp \ #compressbzip2.cpp SOURCES = \ addentrywnd_emb.cpp \ addentrywndimpl.cpp \ base64.cpp \ binentrygen.cpp \ blowfish.cpp \ commentbox.cpp \ compressgzip.cpp \ csv.cpp \ editcategory.cpp \ findwnd_emb.cpp \ findwndimpl.cpp \ genpasswd.cpp \ getkeycardwnd.cpp \ getmasterpwwnd_emb.cpp \ getmasterpwwndimpl.cpp \ globalstuff.cpp \ gpasmanfile.cpp \ htmlgen.cpp \ ipc.cpp \ libgcryptif.cpp \ listobjselectwnd.cpp \ listviewpwm.cpp \ main.cpp \ pwgenwnd_emb.cpp \ pwgenwndimpl.cpp \ pwm.cpp \ pwmdoc.cpp \ pwmdocui.cpp \ pwmexception.cpp \ pwminit.cpp \ pwmprefs.cpp \ pwmtray.cpp \ pwmview.cpp \ pwmviewstyle_0.cpp \ pwmviewstyle_1.cpp \ pwmviewstyle.cpp \ randomizer.cpp \ rc2.cpp \ rencatwnd.cpp \ serializer.cpp \ setmasterpwwnd_emb.cpp \ setmasterpwwndimpl.cpp \ sha1.cpp \ waitwnd.cpp \ kcmconfigs/kcmpwmconfig.cpp \ kcmconfigs/pwmconfigwidget.cpp diff --git a/pwmanager/pwmanager/pwmdoc.cpp b/pwmanager/pwmanager/pwmdoc.cpp index b58d7e2..9213360 100644 --- a/pwmanager/pwmanager/pwmdoc.cpp +++ b/pwmanager/pwmanager/pwmdoc.cpp @@ -1,3634 +1,3636 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmdoc.h" #include "pwmview.h" #include "blowfish.h" #include "sha1.h" #include "globalstuff.h" #include "gpasmanfile.h" #include "serializer.h" #include "compressgzip.h" //US#include "compressbzip2.h" #include "randomizer.h" #include "pwminit.h" #include "libgcryptif.h" #ifdef PWM_EMBEDDED #include "pwmprefs.h" #include "kglobal.h" #endif #include <kmessagebox.h> #include <kconfig.h> #include <kglobalsettings.h> #include <libkcal/syncdefines.h> #ifdef CONFIG_KWALLETIF # include "kwalletemu.h" #endif // CONFIG_KWALLETIF #include <qdatetime.h> #include <qsize.h> #include <qfileinfo.h> #include <qfile.h> +#include <QDesktopWidget> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> //US#include <iostream> #include <algorithm> #include <sys/types.h> #include <sys/stat.h> #ifndef _WIN32_ #include <unistd.h> #include <stdint.h> #endif #ifdef PWM_EMBEDDED #ifndef Q_LONG #define Q_LONG long #endif #ifndef Q_ULONG #define Q_ULONG unsigned long #endif #endif //PWM_EMBEDDED //TODO: reset to its normal value. //LR set to 5 min #define META_CHECK_TIMER_INTERVAL 300 /* 10 300*/ /* sek */ using namespace std; void PwMDocList::add(PwMDoc *doc, const string &id) { #ifdef PWM_DEBUG // check for existance of object in debug mode only. vector<listItem>::iterator begin = docList.begin(), end = docList.end(), i = begin; while (i != end) { if (i->doc == doc) { BUG(); return; } ++i; } #endif listItem newItem; newItem.doc = doc; newItem.docId = id; docList.push_back(newItem); } void PwMDocList::edit(PwMDoc *doc, const string &newId) { vector<listItem>::iterator begin = docList.begin(), end = docList.end(), i = begin; while (i != end) { if (i->doc == doc) { i->docId = newId; return; } ++i; } } void PwMDocList::del(PwMDoc *doc) { vector<listItem>::iterator begin = docList.begin(), end = docList.end(), i = begin; while (i != end) { if (i->doc == doc) { docList.erase(i); return; } ++i; } } bool PwMDocList::find(const string &id, listItem *ret) { vector<listItem>::iterator begin = docList.begin(), end = docList.end(), i = begin; while (i != end) { if (i->docId == id) { if (ret) *ret = *i; return true; } ++i; } return false; } DocTimer::DocTimer(PwMDoc *_doc) : doc (_doc) , mpwLock (0) , autoLockLock (0) , metaCheckLock (0) { mpwTimer = new QTimer; autoLockTimer = new QTimer; metaCheckTimer = new QTimer; connect(mpwTimer, SIGNAL(timeout()), this, SLOT(mpwTimeout())); connect(autoLockTimer, SIGNAL(timeout()), this, SLOT(autoLockTimeout())); connect(metaCheckTimer, SIGNAL(timeout()), this, SLOT(metaCheckTimeout())); } DocTimer::~DocTimer() { delete mpwTimer; delete autoLockTimer; delete metaCheckTimer; } void DocTimer::start(TimerIDs timer) { switch (timer) { case id_mpwTimer: if (mpwTimer->isActive()) mpwTimer->stop(); doc->setDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW); mpwTimer->start(conf()->confGlobPwTimeout() * 1000, true); break; case id_autoLockTimer: if (autoLockTimer->isActive()) autoLockTimer->stop(); if (conf()->confGlobLockTimeout() > 0) autoLockTimer->start(conf()->confGlobLockTimeout() * 1000, true); break; case id_metaCheckTimer: if (metaCheckTimer->isActive()) metaCheckTimer->stop(); metaCheckTimer->start(META_CHECK_TIMER_INTERVAL * 1000, true); break; } } void DocTimer::stop(TimerIDs timer) { switch (timer) { case id_mpwTimer: mpwTimer->stop(); break; case id_autoLockTimer: autoLockTimer->stop(); break; case id_metaCheckTimer: metaCheckTimer->stop(); break; } } void DocTimer::getLock(TimerIDs timer) { switch (timer) { case id_mpwTimer: ++mpwLock; break; case id_autoLockTimer: ++autoLockLock; break; case id_metaCheckTimer: ++metaCheckLock; break; } } void DocTimer::putLock(TimerIDs timer) { switch (timer) { case id_mpwTimer: if (mpwLock) --mpwLock; break; case id_autoLockTimer: if (autoLockLock) --autoLockLock; break; case id_metaCheckTimer: if (metaCheckLock) --metaCheckLock; break; } } void DocTimer::mpwTimeout() { if (mpwLock) { mpwTimer->start(1000, true); return; } doc->unsetDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW); } void DocTimer::autoLockTimeout() { if (autoLockLock) { autoLockTimer->start(1000, true); return; } if (conf()->confGlobAutoDeepLock() && doc->filename != QString::null && doc->filename != "") { doc->deepLock(true); } else { doc->lockAll(true); } } void DocTimer::metaCheckTimeout() { if (metaCheckLock) { // check again in one second. metaCheckTimer->start(1000, true); return; } if (doc->isDeepLocked()) { metaCheckTimer->start(META_CHECK_TIMER_INTERVAL * 1000, true); return; } if (doc->isDocEmpty()) { metaCheckTimer->start(META_CHECK_TIMER_INTERVAL * 1000, true); return; } #ifdef CONFIG_KWALLETIF KWalletEmu *kwlEmu = doc->init->kwalletEmu(); if (kwlEmu) kwlEmu->suspendDocSignals(); #endif // CONFIG_KWALLETIF /* We simply trigger all views to update their * displayed values. This way they have a chance * to get notified when some meta changes over time. * (for example an entry expired). * The _view_ is responsive for not updating its * contents if nothing really changed! */ emit doc->dataChanged(doc); #ifdef CONFIG_KWALLETIF if (kwlEmu) kwlEmu->resumeDocSignals(); #endif // CONFIG_KWALLETIF metaCheckTimer->start(META_CHECK_TIMER_INTERVAL * 1000, true); } PwMDocList PwMDoc::openDocList; unsigned int PwMDocList::unnamedDocCnt = 1; PwMDoc::PwMDoc(QObject *parent, const char *name) : PwMDocUi(parent, name) , dataChangedLock (0) { deleted = false; unnamedNum = 0; getOpenDocList()->add(this, getTitle().latin1()); curDocStat = 0; setMaxNumEntries(); _timer = new DocTimer(this); timer()->start(DocTimer::id_mpwTimer); timer()->start(DocTimer::id_autoLockTimer); timer()->start(DocTimer::id_metaCheckTimer); addCategory(DEFAULT_CATEGORY, 0, false); listView = 0; emit docCreated(this); } PwMDoc::~PwMDoc() { emit docClosed(this); getOpenDocList()->del(this); delete _timer; } PwMerror PwMDoc::saveDoc(char compress, const QString *file) { PwMerror ret, e; string serialized; QFile f; QString tmpFileMoved(QString::null); bool wasDeepLocked; QString savedFilename(filename); if (!file) { if (filename == "") return e_filename; if (isDeepLocked()) { /* We don't need to save any data. * It's already all on disk, because * we are deeplocked. */ unsetDocStatFlag(DOC_STAT_DISK_DIRTY); ret = e_success; return ret; } } else { if (*file == "" && filename == "") return e_filename; if (*file != "") filename = *file; } wasDeepLocked = isDeepLocked(); if (wasDeepLocked) { /* We are deeplocked. That means all data is already * on disk. BUT we need to do saving procedure, * because *file != savedFilename. * Additionally we need to tempoarly restore * the old "filename", because deepLock() references it. */ QString newFilename(filename); filename = savedFilename; getDataChangedLock(); e = deepLock(false); putDataChangedLock(); filename = newFilename; switch (e) { case e_success: break; case e_wrongPw: case e_noPw: emitDataChanged(this); return e; default: emitDataChanged(this); return e_openFile; } } if (!isPwAvailable()) { /* password is not available. This means, the * document wasn't saved, yet. */ bool useChipcard = getDocStatFlag(DOC_STAT_USE_CHIPCARD); QString pw(requestNewMpw(&useChipcard)); if (pw != "") { currentPw = pw; } else { return e_noPw; } if (useChipcard) { setDocStatFlag(DOC_STAT_USE_CHIPCARD); } else { unsetDocStatFlag(DOC_STAT_USE_CHIPCARD); } } int _cryptAlgo = conf()->confGlobCryptAlgo(); int _hashAlgo = conf()->confGlobHashAlgo(); // sanity check for the selected algorithms if (_cryptAlgo < PWM_CRYPT_BLOWFISH || _cryptAlgo > PWM_CRYPT_TWOFISH128) { printWarn("Invalid Crypto-Algorithm selected! " "Config-file seems to be corrupt. " "Falling back to Blowfish."); _cryptAlgo = PWM_CRYPT_BLOWFISH; } if (_hashAlgo < PWM_HASH_SHA1 || _hashAlgo > PWM_HASH_TIGER) { printWarn("Invalid Hash-Algorithm selected! " "Config-file seems to be corrupt. " "Falling back to SHA1."); _hashAlgo = PWM_HASH_SHA1; } char cryptAlgo = static_cast<char>(_cryptAlgo); char hashAlgo = static_cast<char>(_hashAlgo); if (conf()->confGlobMakeFileBackup()) { if (!backupFile(filename)) return e_fileBackup; } int mLastBackupDate = 0; KConfig configGlobal (locateLocal("config","pwmanagerbuprc")); QFileInfo fileInfo ( filename ); mLastBackupDate = configGlobal.readNumEntry( "LastBackupDate-"+ fileInfo.fileName (), 0 ); KConfig config (locateLocal("config","microkdeglobalrc")); config.setGroup( "BackupSettings" ); bool b_enabled = config.readBoolEntry( "BackupEnabled" ); if ( b_enabled && QFile::exists(filename)) { int num = config.readNumEntry( "BackupNumbers" ); int d_count = config.readNumEntry( "BackupDayCount" ); bool stdDir = config.readBoolEntry( "BackupUseDefaultDir" ); QString bupDir = config.readEntry( "BackupDatadir" ); QDate reference ( 2000,1,1 ); int daysTo = reference.daysTo ( QDate::currentDate() ); bool saveDate = false; if ( daysTo - d_count >= mLastBackupDate ) { qDebug("KA: Last backup was %d days ago ", daysTo - mLastBackupDate ); if ( stdDir ) bupDir = KGlobalSettings::backupDataDir(); int retval = KApplication::createBackup( filename, bupDir, num ); if ( retval == 0 ) { qDebug("KO: Backup cancelled. Will try again tomorrow "); // retval == 0 : backup skipped for today, try again tomorrow mLastBackupDate = daysTo - d_count+1; saveDate = true; } else if ( retval == 1 ){ qDebug("KO: Backup created."); // backup ok mLastBackupDate = daysTo; saveDate = true; } else if ( retval == 2 ){ qDebug("KO: Backup globally cancelled."); // backup globally cancelled b_enabled = false; } if ( !b_enabled ) { config.writeEntry( "mBackupEnabled", false ); } if ( saveDate ) { configGlobal.writeEntry( "LastBackupDate-"+ fileInfo.fileName (), mLastBackupDate ); } } } if (QFile::exists(filename)) { /* Move the existing file to some tmp file. * When saving file succeeds, delete tmp file. Otherwise * move tmp file back. See below. */ Randomizer *rnd = Randomizer::obj(); char rnd_buf[5]; sprintf(rnd_buf, "%X%X%X%X", rnd->genRndChar() & 0xFF, rnd->genRndChar() & 0xFF, rnd->genRndChar() & 0xFF, rnd->genRndChar() & 0xFF); - tmpFileMoved = filename + "." + rnd_buf + ".mv"; + tmpFileMoved = filename; tmpFileMoved += '.'; + tmpFileMoved += rnd_buf; tmpFileMoved += ".mv"; if (!copyFile(filename, tmpFileMoved)) return e_openFile; if (!QFile::remove(filename)) { printWarn(string("removing orig file ") + filename.latin1() + " failed!"); } } f.setName(filename); - if (!f.open(IO_ReadWrite)) { + if (!f.open(QIODevice::ReadWrite)) { ret = e_openFile; goto out_moveback; } e = writeFileHeader(hashAlgo, hashAlgo, cryptAlgo, compress, ¤tPw, &f); if (e == e_hashNotImpl) { printDebug("PwMDoc::saveDoc(): writeFileHeader() failed: e_hashNotImpl"); f.close(); ret = e_hashNotImpl; goto out_moveback; } else if (e != e_success) { printDebug("PwMDoc::saveDoc(): writeFileHeader() failed"); f.close(); ret = e_writeHeader; goto out_moveback; } if (!serializeDta(&serialized)) { printDebug("PwMDoc::saveDoc(): serializeDta() failed"); f.close(); ret = e_serializeDta; goto out_moveback; } e = writeDataHash(hashAlgo, &serialized, &f); if (e == e_hashNotImpl) { printDebug("PwMDoc::saveDoc(): writeDataHash() failed: e_hashNotImpl"); f.close(); ret = e_hashNotImpl; goto out_moveback; } else if (e != e_success) { printDebug("PwMDoc::saveDoc(): writeDataHash() failed"); f.close(); ret = e_writeHeader; goto out_moveback; } if (!compressDta(&serialized, compress)) { printDebug("PwMDoc::saveDoc(): compressDta() failed"); f.close(); ret = e_enc; goto out_moveback; } e = encrypt(&serialized, ¤tPw, &f, cryptAlgo, hashAlgo); if (e == e_weakPw) { printDebug("PwMDoc::saveDoc(): encrypt() failed: e_weakPw"); f.close(); ret = e_weakPw; goto out_moveback; } else if (e == e_cryptNotImpl) { printDebug("PwMDoc::saveDoc(): encrypt() failed: e_cryptNotImpl"); f.close(); ret = e_cryptNotImpl; goto out_moveback; } else if (e != e_success) { printDebug("PwMDoc::saveDoc(): encrypt() failed"); f.close(); ret = e_enc; goto out_moveback; } unsetDocStatFlag(DOC_STAT_DISK_DIRTY); f.close(); #ifndef _WIN32_ if (chmod(filename.latin1(), conf()->confGlobFilePermissions())) { printWarn(string("chmod failed: ") + strerror(errno)); } #endif openDocList.edit(this, getTitle().latin1()); if (wasDeepLocked) { /* Do _not_ save the data with the deepLock() * call, because this will recurse * into saveDoc() */ deepLock(true, false); /* We don't check return value here, because * it won't fail. See NOTE in deepLock() */ } if (tmpFileMoved != QString::null) { // now remove the moved file. if (!QFile::remove(tmpFileMoved)) { printWarn(string("removing file ") + tmpFileMoved.latin1() + " failed!"); } } ret = e_success; printDebug(string("writing file { name: ") + filename.latin1() + " compress: " + tostr(static_cast<int>(compress)) + " cryptAlgo: " + tostr(static_cast<int>(cryptAlgo)) + " hashAlgo: " + tostr(static_cast<int>(hashAlgo)) + " }"); goto out; out_moveback: if (tmpFileMoved != QString::null) { if (copyFile(tmpFileMoved, filename)) { if (!QFile::remove(tmpFileMoved)) { printWarn(string("removing tmp file ") + filename.latin1() + " failed!"); } } else { printWarn(string("couldn't copy file ") + tmpFileMoved.latin1() + " back to " + filename.latin1()); } } out: return ret; } PwMerror PwMDoc::openDoc(const QString *file, int openLocked) { PWM_ASSERT(file); PWM_ASSERT(openLocked == 0 || openLocked == 1 || openLocked == 2); string decrypted, dataHash; PwMerror ret; char cryptAlgo, dataHashType, compress; unsigned int headerLen; if (*file == "") return e_readFile; filename = *file; /* check if this file is already open. * This does not catch symlinks! */ if (!isDeepLocked()) { if (getOpenDocList()->find(filename.latin1())) return e_alreadyOpen; } QFile f(filename); if (openLocked == 2) { // open deep-locked if (!QFile::exists(filename)) return e_openFile; if (deepLock(true, false) != e_success) return e_openFile; goto out_success; } - if (!f.open(IO_ReadOnly)) + if (!f.open(QIODevice::ReadOnly)) return e_openFile; ret = checkHeader(&cryptAlgo, ¤tPw, &compress, &headerLen, &dataHashType, &dataHash, &f); if (ret != e_success) { printDebug("PwMDoc::openDoc(): checkHeader() failed"); f.close(); if (ret == e_wrongPw) { wrongMpwMsgBox(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); return ret; } else if (ret == e_noPw || ret == e_fileVer || ret == e_fileFormat || ret == e_hashNotImpl) { return ret; } else return e_readFile; } ret = decrypt(&decrypted, headerLen, ¤tPw, cryptAlgo, dataHashType, &f); if (ret == e_cryptNotImpl) { printDebug("PwMDoc::openDoc(): decrypt() failed: e_cryptNotImpl"); f.close(); return e_cryptNotImpl; } else if (ret != e_success) { printDebug("PwMDoc::openDoc(): decrypt() failed"); f.close(); return e_readFile; } if (!decompressDta(&decrypted, compress)) { printDebug("PwMDoc::openDoc(): decompressDta() failed"); f.close(); return e_fileCorrupt; } ret = checkDataHash(dataHashType, &dataHash, &decrypted); if (ret == e_hashNotImpl) { printDebug("PwMDoc::openDoc(): checkDataHash() failed: e_hashNotImpl"); f.close(); return e_hashNotImpl; } else if (ret != e_success) { printDebug("PwMDoc::openDoc(): checkDataHash() failed"); f.close(); return e_fileCorrupt; } if (!deSerializeDta(&decrypted, openLocked == 1)) { printDebug("PwMDoc::openDoc(): deSerializeDta() failed"); f.close(); return e_readFile; } f.close(); timer()->start(DocTimer::id_mpwTimer); timer()->start(DocTimer::id_autoLockTimer); out_success: openDocList.edit(this, getTitle().latin1()); emit docOpened(this); return e_success; } PwMerror PwMDoc::writeFileHeader(char keyHash, char dataHash, char crypt, char compress, QString *pw, QFile *f) { PWM_ASSERT(pw); PWM_ASSERT(f); //US ENH: or maybe a bug: checking here for listView does not make sense because we do not check anywhere else //Wenn I sync, I open a doc without a view => listView is 0 => Assertion //US PWM_ASSERT(listView); if (f->writeBlock(FILE_ID_HEADER, strlen(FILE_ID_HEADER)) != static_cast<Q_LONG>(strlen(FILE_ID_HEADER))) { return e_writeFile; } if (f->putch(PWM_FILE_VER) == -1 || f->putch(keyHash) == -1 || f->putch(dataHash) == -1 || f->putch(crypt) == -1 || f->putch(compress) == -1 || f->putch((getDocStatFlag(DOC_STAT_USE_CHIPCARD)) ? (static_cast<char>(0x01)) : (static_cast<char>(0x00))) == -1) { return e_writeFile; } // write bytes of NUL-data. These bytes are reserved for future-use. const int bufSize = 64; char tmp_buf[bufSize]; memset(tmp_buf, 0x00, bufSize); if (f->writeBlock(tmp_buf, bufSize) != bufSize) return e_writeFile; switch (keyHash) { case PWM_HASH_SHA1: { const int hashlen = SHA1_HASH_LEN_BYTE; Sha1 hash; hash.sha1_write(reinterpret_cast<const byte *>(pw->latin1()), pw->length()); string ret = hash.sha1_read(); if (f->writeBlock(ret.c_str(), hashlen) != hashlen) return e_writeFile; break; } case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *buf; size_t hashLen; err = gc.hash(&buf, &hashLen, reinterpret_cast<const unsigned char *>(pw->latin1()), pw->length(), keyHash); if (err != e_success) return e_hashNotImpl; if (f->writeBlock(reinterpret_cast<const char *>(buf), hashLen) != static_cast<Q_LONG>(hashLen)) { delete [] buf; return e_hashNotImpl; } delete [] buf; break; } default: { return e_hashNotImpl; } } return e_success; } PwMerror PwMDoc::checkHeader(char *cryptAlgo, QString *pw, char *compress, unsigned int *headerLength, char *dataHashType, string *dataHash, QFile *f) { PWM_ASSERT(cryptAlgo); PWM_ASSERT(pw); PWM_ASSERT(headerLength); PWM_ASSERT(dataHashType); PWM_ASSERT(dataHash); PWM_ASSERT(f); int tmpRet; // check "magic" header const char magicHdr[] = FILE_ID_HEADER; const int hdrLen = array_size(magicHdr) - 1; char tmp[hdrLen]; if (f->readBlock(tmp, hdrLen) != hdrLen) return e_readFile; if (memcmp(tmp, magicHdr, hdrLen) != 0) return e_fileFormat; // read and check file ver int fileV = f->getch(); if (fileV == -1) return e_fileFormat; if (fileV != PWM_FILE_VER) return e_fileVer; // read hash hash type int keyHash = f->getch(); if (keyHash == -1) return e_fileFormat; // read data hash type tmpRet = f->getch(); if (tmpRet == -1) return e_fileFormat; *dataHashType = tmpRet; // read crypt algo tmpRet = f->getch(); if (tmpRet == -1) return e_fileFormat; *cryptAlgo = tmpRet; // get compression-algo tmpRet = f->getch(); if (tmpRet == -1) return e_fileFormat; *compress = tmpRet; // get the MPW-flag int mpw_flag = f->getch(); if (mpw_flag == -1) return e_fileFormat; if (mpw_flag == 0x01) setDocStatFlag(DOC_STAT_USE_CHIPCARD); else unsetDocStatFlag(DOC_STAT_USE_CHIPCARD); // skip the "RESERVED"-bytes if (!(f->at(f->at() + 64))) return e_fileFormat; *pw = requestMpw(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); if (*pw == "") { /* the user didn't give a master-password * or didn't insert a chipcard */ return e_noPw; } // verify key-hash switch (keyHash) { case PWM_HASH_SHA1: { // read hash from header const int hashLen = SHA1_HASH_LEN_BYTE; string readHash; int i; for (i = 0; i < hashLen; ++i) readHash.push_back(f->getch()); Sha1 hash; hash.sha1_write(reinterpret_cast<const byte *>(pw->latin1()), pw->length()); string ret = hash.sha1_read(); if (ret != readHash) return e_wrongPw; // hash doesn't match (wrong key) break; } case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *buf; size_t hashLen; err = gc.hash(&buf, &hashLen, reinterpret_cast<const unsigned char *>(pw->latin1()), pw->length(), keyHash); if (err != e_success) return e_hashNotImpl; string calcHash(reinterpret_cast<const char *>(buf), static_cast<string::size_type>(hashLen)); delete [] buf; // read hash from header string readHash; size_t i; for (i = 0; i < hashLen; ++i) readHash.push_back(f->getch()); if (calcHash != readHash) return e_wrongPw; // hash doesn't match (wrong key) break; } default: { return e_hashNotImpl; } } // read the data-hash from the file unsigned int hashLen, i; switch (*dataHashType) { case PWM_HASH_SHA1: hashLen = SHA1_HASH_LEN_BYTE; break; case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; hashLen = gc.hashLength(*dataHashType); if (hashLen == 0) return e_hashNotImpl; break; } default: return e_hashNotImpl; } *dataHash = ""; for (i = 0; i < hashLen; ++i) { tmpRet = f->getch(); if (tmpRet == -1) return e_fileFormat; dataHash->push_back(static_cast<char>(tmpRet)); } *headerLength = f->at(); #ifndef PWM_EMBEDDED printDebug(string("opening file { compress: ") + tostr(static_cast<int>(*compress)) + " cryptAlgo: " + tostr(static_cast<int>(*cryptAlgo)) + " keyHashAlgo: " + tostr(static_cast<int>(keyHash)) + " }"); #else printDebug(string("opening file { compress: ") + tostr((int)(*compress)) + " cryptAlgo: " + tostr((int)(*cryptAlgo)) + " keyHashAlgo: " + tostr((int)(keyHash)) + " }"); #endif return e_success; } PwMerror PwMDoc::writeDataHash(char dataHash, string *d, QFile *f) { PWM_ASSERT(d); PWM_ASSERT(f); switch (dataHash) { case PWM_HASH_SHA1: { const int hashLen = SHA1_HASH_LEN_BYTE; Sha1 h; h.sha1_write(reinterpret_cast<const byte *>(d->c_str()), d->size()); string hRet = h.sha1_read(); if (f->writeBlock(hRet.c_str(), hashLen) != hashLen) return e_writeFile; break; } case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *buf; size_t hashLen; err = gc.hash(&buf, &hashLen, reinterpret_cast<const unsigned char *>(d->c_str()), d->size(), dataHash); if (err != e_success) return e_hashNotImpl; if (f->writeBlock(reinterpret_cast<const char *>(buf), hashLen) != static_cast<Q_LONG>(hashLen)) { delete [] buf; return e_hashNotImpl; } delete [] buf; break; } default: { return e_hashNotImpl; } } return e_success; } bool PwMDoc::backupFile(const QString &filePath) { QFileInfo fi(filePath); if (!fi.exists()) return true; // Yes, true is correct. QString pathOnly(fi.dirPath(true)); QString nameOnly(fi.fileName()); QString backupPath = pathOnly + "/~" + nameOnly + ".backup"; return copyFile(filePath, backupPath); } bool PwMDoc::copyFile(const QString &src, const QString &dst) { QFileInfo fi(src); if (!fi.exists()) return false; if (QFile::exists(dst)) { if (!QFile::remove(dst)) return false; } QFile srcFd(src); - if (!srcFd.open(IO_ReadOnly)) + if (!srcFd.open(QIODevice::ReadOnly)) return false; QFile dstFd(dst); - if (!dstFd.open(IO_ReadWrite)) { + if (!dstFd.open(QIODevice::ReadWrite)) { srcFd.close(); return false; } const int tmpBuf_size = 512; char tmpBuf[tmpBuf_size]; Q_LONG bytesRead, bytesWritten; while (!srcFd.atEnd()) { bytesRead = srcFd.readBlock(tmpBuf, static_cast<Q_ULONG>(tmpBuf_size)); if (bytesRead == -1) { srcFd.close(); dstFd.close(); return false; } bytesWritten = dstFd.writeBlock(tmpBuf, static_cast<Q_ULONG>(bytesRead)); if (bytesWritten != bytesRead) { srcFd.close(); dstFd.close(); return false; } } srcFd.close(); dstFd.close(); return true; } PwMerror PwMDoc::addEntry(const QString &category, PwMDataItem *d, bool dontFlagDirty, bool updateMeta) { PWM_ASSERT(d); unsigned int cat = 0; if (isDeepLocked()) { PwMerror ret; ret = deepLock(false); if (ret != e_success) return e_lock; } addCategory(category, &cat); if (numEntries(category) >= maxEntries) return e_maxAllowedEntr; vector<unsigned int> foundPositions; /* historically this was: * const int searchIn = SEARCH_IN_DESC | SEARCH_IN_NAME | * SEARCH_IN_URL | SEARCH_IN_LAUNCHER; * But for now we only search in desc. * That's a tweak to be KWallet compatible. But it should not add * usability-drop onto PwManager, does it? * (And yes, "int" was a bug. Correct is "unsigned int") */ const unsigned int searchIn = SEARCH_IN_DESC; findEntry(cat, *d, searchIn, &foundPositions, true); if (foundPositions.size()) { // DOH! We found this entry. return e_entryExists; } d->listViewPos = -1; d->lockStat = conf()->confGlobNewEntrLockStat(); if (updateMeta) { d->meta.create = QDateTime::currentDateTime(); d->meta.update = d->meta.create; } dti.dta[cat].d.push_back(*d); delAllEmptyCat(true); if (!dontFlagDirty) flagDirty(); return e_success; } PwMerror PwMDoc::addCategory(const QString &category, unsigned int *categoryIndex, bool checkIfExist) { if (isDeepLocked()) { PwMerror ret; ret = deepLock(false); if (ret != e_success) return e_lock; } if (checkIfExist) { if (findCategory(category, categoryIndex)) return e_categoryExists; } PwMCategoryItem item; //US ENH: clear item to initialize with default values, or create a constructor item.clear(); item.name = category.latin1(); dti.dta.push_back(item); if (categoryIndex) *categoryIndex = dti.dta.size() - 1; return e_success; } bool PwMDoc::delEntry(const QString &category, unsigned int index, bool dontFlagDirty) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return false; } return delEntry(cat, index, dontFlagDirty); } bool PwMDoc::delEntry(unsigned int category, unsigned int index, bool dontFlagDirty) { if (isDeepLocked()) return false; if (index > dti.dta[category].d.size() - 1) return false; getDataChangedLock(); if (!lockAt(category, index, false)) { putDataChangedLock(); return false; } putDataChangedLock(); int lvPos = dti.dta[category].d[index].listViewPos; // delete entry dti.dta[category].d.erase(dti.dta[category].d.begin() + index); unsigned int i, entries = numEntries(category); if (!entries) { // no more entries in this category, so // we can delete it, too. BUG_ON(!delCategory(category)); // delCategory() flags it dirty, so we need not to do so. return true; } for (i = 0; i < entries; ++i) { // decrement all listViewPositions that are greater than the deleted. if (dti.dta[category].d[i].listViewPos > lvPos) --dti.dta[category].d[i].listViewPos; } if (!dontFlagDirty) flagDirty(); return true; } bool PwMDoc::editEntry(const QString &oldCategory, const QString &newCategory, unsigned int index, PwMDataItem *d, bool updateMeta) { PWM_ASSERT(d); unsigned int oldCat = 0; if (!findCategory(oldCategory, &oldCat)) { BUG(); return false; } return editEntry(oldCat, newCategory, index, d, updateMeta); } bool PwMDoc::editEntry(unsigned int oldCategory, const QString &newCategory, unsigned int index, PwMDataItem *d, bool updateMeta) { if (isDeepLocked()) return false; if (updateMeta) { d->meta.update = QDateTime::currentDateTime(); if (d->meta.create.isNull()) { d->meta.create = d->meta.update; } } if (dti.dta[oldCategory].name != newCategory.latin1()) { // the user changed the category. PwMerror ret; d->rev = 0; ret = addEntry(newCategory, d, true, false); if (ret != e_success) return false; if (!delEntry(oldCategory, index, true)) return false; } else { d->rev = dti.dta[oldCategory].d[index].rev + 1; // increment revision counter. dti.dta[oldCategory].d[index] = *d; } flagDirty(); return true; } unsigned int PwMDoc::numEntries(const QString &category) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return 0; } return numEntries(cat); } bool PwMDoc::serializeDta(string *d) { PWM_ASSERT(d); Serializer ser; if (!ser.serialize(dti)) return false; d->assign(ser.getXml()); if (!d->size()) return false; return true; } bool PwMDoc::deSerializeDta(const string *d, bool entriesLocked) { PWM_ASSERT(d); #ifndef PWM_EMBEDDED try { Serializer ser(d->c_str()); ser.setDefaultLockStat(entriesLocked); if (!ser.deSerialize(&dti)) return false; } catch (PwMException) { return false; } #else Serializer ser(d->c_str()); ser.setDefaultLockStat(entriesLocked); if (!ser.deSerialize(&dti)) return false; #endif emitDataChanged(this); return true; } bool PwMDoc::getEntry(const QString &category, unsigned int index, PwMDataItem * d, bool unlockIfLocked) { PWM_ASSERT(d); unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return false; } return getEntry(cat, index, d, unlockIfLocked); } bool PwMDoc::getEntry(unsigned int category, unsigned int index, PwMDataItem *d, bool unlockIfLocked) { if (index > dti.dta[category].d.size() - 1) return false; bool locked = isLocked(category, index); if (locked) { /* this entry is locked. We don't return a password, * until it's unlocked by the user by inserting * chipcard or entering the mpw */ if (unlockIfLocked) { if (!lockAt(category, index, false)) { return false; } locked = false; } } *d = dti.dta[category].d[index]; if (locked) d->pw = LOCKED_STRING.latin1(); return true; } PwMerror PwMDoc::getCommentByLvp(const QString &category, int listViewPos, string *foundComment) { PWM_ASSERT(foundComment); unsigned int cat = 0; if (!findCategory(category, &cat)) return e_invalidArg; unsigned int i, entries = numEntries(cat); for (i = 0; i < entries; ++i) { if (dti.dta[cat].d[i].listViewPos == listViewPos) { *foundComment = dti.dta[cat].d[i].comment; if (dti.dta[cat].d[i].binary) return e_binEntry; return e_normalEntry; } } BUG(); return e_generic; } PwMerror PwMDoc::getCommentByLvp_long(const QString &category, int listViewPos, string *foundComment) { PWM_ASSERT(foundComment); unsigned int cat = 0; if (!findCategory(category, &cat)) return e_invalidArg; unsigned int i, entries = numEntries(cat); for (i = 0; i < entries; ++i) { if (dti.dta[cat].d[i].listViewPos == listViewPos) { if (dti.dta[cat].d[i].binary) return e_binEntry; PwMCategoryItem* catItem = getCategoryEntry(cat); QString retval; QString tempval = QString (dti.dta[cat].d[i].desc.c_str()); if ( !tempval.isEmpty() ) { retval += "<b>" +QString ( catItem->desc_text.c_str() )+ ":</b> "+ tempval+"<br>" ; } tempval = QString (dti.dta[cat].d[i].name.c_str()); if ( !tempval.isEmpty() ) { retval += "<b>" +QString ( catItem->name_text.c_str() ) + ":</b> "+ tempval+"<br>" ; } tempval = QString (dti.dta[cat].d[i].pw.c_str()); if ( !tempval.isEmpty() ) { if ( dti.dta[cat].d[i].lockStat ) retval += "<b>" +QString ( catItem->pw_text.c_str() )+ ": " + i18n("LOCKED") +"</b><br>" ; else retval += "<b>" +QString ( catItem->pw_text.c_str() )+ ":</b> " + tempval+"<br>" ; } tempval = QString (dti.dta[cat].d[i].url.c_str()); if ( !tempval.isEmpty() ) { retval += "<b>" +i18n("URL:")+ "</b> " + tempval+"<br>" ; } tempval = QString (dti.dta[cat].d[i].launcher.c_str()); if ( !tempval.isEmpty() ) { retval += "<b>" +i18n("Launcher:")+ "</b> " + tempval+"<br>" ; } tempval = QString (dti.dta[cat].d[i].comment.c_str()); if ( !tempval.isEmpty() ) { tempval.replace(QRegExp ( "\n" ), "<br>" ); retval += "<b>" +i18n("Comment:")+ "</b><br>" + tempval+"<br>" ; } string ret ( retval.latin1() ); // *foundComment = dti.dta[cat].d[i].comment; *foundComment = ret; return e_normalEntry; } } BUG(); return e_generic; } bool PwMDoc::compressDta(string *d, char algo) { PWM_ASSERT(d); switch (algo) { case PWM_COMPRESS_GZIP: { CompressGzip comp; return comp.compress(d); } #ifndef PWM_EMBEDDED case PWM_COMPRESS_BZIP2: { CompressBzip2 comp; return comp.compress(d); } #endif case PWM_COMPRESS_NONE: { return true; } default: { BUG(); } } return false; } bool PwMDoc::decompressDta(string *d, char algo) { PWM_ASSERT(d); switch (algo) { case PWM_COMPRESS_GZIP: { CompressGzip comp; return comp.decompress(d); } #ifndef PWM_EMBEDDED case PWM_COMPRESS_BZIP2: { CompressBzip2 comp; return comp.decompress(d); } #endif case PWM_COMPRESS_NONE: { return true; } } return false; } PwMerror PwMDoc::encrypt(string *d, const QString *pw, QFile *f, char algo, char hashalgo //US BUG: pass _hashalgo because we need it in hashPassphrase ) { PWM_ASSERT(d); PWM_ASSERT(pw); PWM_ASSERT(f); size_t encSize; byte *encrypted = 0; switch (algo) { case PWM_CRYPT_BLOWFISH: { Blowfish::padNull(d); encSize = d->length(); encrypted = new byte[encSize]; Blowfish bf; if (bf.bf_setkey((byte *) pw->latin1(), pw->length())) { delete [] encrypted; return e_weakPw; } bf.bf_encrypt((byte *) encrypted, (byte *) d->c_str(), encSize); break; } case PWM_CRYPT_AES128: /*... fall through */ case PWM_CRYPT_AES192: case PWM_CRYPT_AES256: case PWM_CRYPT_3DES: case PWM_CRYPT_TWOFISH: case PWM_CRYPT_TWOFISH128: { if (!LibGCryptIf::available()) return e_cryptNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *plain = new unsigned char[d->length() + 1024]; memcpy(plain, d->c_str(), d->length()); err = gc.encrypt(&encrypted, &encSize, plain, d->length(), reinterpret_cast<const unsigned char *>(pw->latin1()), pw->length(), algo, hashalgo //US BUG: pass _hashalgo because we need it in hashPassphrase ); delete [] plain; if (err != e_success) return e_cryptNotImpl; break; } default: { delete_ifnot_null_array(encrypted); return e_cryptNotImpl; } } // write encrypted data to file if (f->writeBlock(reinterpret_cast<const char *>(encrypted), static_cast<Q_ULONG>(encSize)) != static_cast<Q_LONG>(encSize)) { delete_ifnot_null_array(encrypted); return e_writeFile; } delete_ifnot_null_array(encrypted); return e_success; } PwMerror PwMDoc::decrypt(string *d, unsigned int pos, const QString *pw, char algo, char hashalgo, //US BUG: pass _hashalgo because we need it in hashPassphrase QFile *f) { PWM_ASSERT(d); PWM_ASSERT(pw); PWM_ASSERT(f); - unsigned int cryptLen = f->size() - pos; + size_t cryptLen = f->size() - pos; byte *encrypted = new byte[cryptLen]; byte *decrypted = new byte[cryptLen]; f->at(pos); #ifndef PWM_EMBEDDED if (f->readBlock(reinterpret_cast<char *>(encrypted), static_cast<Q_ULONG>(cryptLen)) != static_cast<Q_LONG>(cryptLen)) { delete [] encrypted; delete [] decrypted; return e_readFile; } #else if (f->readBlock((char *)(encrypted), (unsigned long)(cryptLen)) != (long)(cryptLen)) { delete [] encrypted; delete [] decrypted; return e_readFile; } #endif switch (algo) { case PWM_CRYPT_BLOWFISH: { Blowfish bf; bf.bf_setkey((byte *) pw->latin1(), pw->length()); bf.bf_decrypt(decrypted, encrypted, cryptLen); break; } case PWM_CRYPT_AES128: /*... fall through */ case PWM_CRYPT_AES192: case PWM_CRYPT_AES256: case PWM_CRYPT_3DES: case PWM_CRYPT_TWOFISH: case PWM_CRYPT_TWOFISH128: { if (!LibGCryptIf::available()) return e_cryptNotImpl; LibGCryptIf gc; PwMerror err; - err = gc.decrypt(&decrypted, + err = gc.decrypt((unsigned char **)&decrypted, &cryptLen, - encrypted, + (unsigned char*)encrypted, cryptLen, reinterpret_cast<const unsigned char *>(pw->latin1()), pw->length(), algo, hashalgo //US BUG: pass _hashalgo because we need it in hashPassphrase ); if (err != e_success) { delete [] encrypted; delete [] decrypted; return e_cryptNotImpl; } break; } default: { delete [] encrypted; delete [] decrypted; return e_cryptNotImpl; } } delete [] encrypted; #ifndef PWM_EMBEDDED d->assign(reinterpret_cast<const char *>(decrypted), static_cast<string::size_type>(cryptLen)); #else d->assign((const char *)(decrypted), (string::size_type)(cryptLen)); #endif delete [] decrypted; if (algo == PWM_CRYPT_BLOWFISH) { if (!Blowfish::unpadNull(d)) { BUG(); return e_readFile; } } return e_success; } PwMerror PwMDoc::checkDataHash(char dataHashType, const string *dataHash, const string *dataStream) { PWM_ASSERT(dataHash); PWM_ASSERT(dataStream); switch(dataHashType) { case PWM_HASH_SHA1: { Sha1 hash; hash.sha1_write((byte*)dataStream->c_str(), dataStream->length()); string ret = hash.sha1_read(); if (ret != *dataHash) return e_fileCorrupt; break; } case PWM_HASH_SHA256: /*... fall through */ case PWM_HASH_SHA384: case PWM_HASH_SHA512: case PWM_HASH_MD5: case PWM_HASH_RMD160: case PWM_HASH_TIGER: { if (!LibGCryptIf::available()) return e_hashNotImpl; LibGCryptIf gc; PwMerror err; unsigned char *buf; size_t hashLen; err = gc.hash(&buf, &hashLen, reinterpret_cast<const unsigned char *>(dataStream->c_str()), dataStream->length(), dataHashType); if (err != e_success) return e_hashNotImpl; string calcHash(reinterpret_cast<const char *>(buf), static_cast<string::size_type>(hashLen)); delete [] buf; if (calcHash != *dataHash) return e_fileCorrupt; break; } default: return e_hashNotImpl; } return e_success; } bool PwMDoc::lockAt(unsigned int category, unsigned int index, bool lock) { if (index >= numEntries(category)) { BUG(); return false; } if (lock == dti.dta[category].d[index].lockStat) return true; if (!lock && currentPw != "") { // "unlocking" and "password is already set" if (!getDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW)) { // unlocking without pw not allowed QString pw; pw = requestMpw(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); if (pw != "") { if (pw != currentPw) { wrongMpwMsgBox(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); return false; } else { timer()->start(DocTimer::id_mpwTimer); } } else { return false; } } else { timer()->start(DocTimer::id_mpwTimer); } } dti.dta[category].d[index].lockStat = lock; dti.dta[category].d[index].rev++; // increment revision counter. emitDataChanged(this); if (!lock) timer()->start(DocTimer::id_autoLockTimer); return true; } bool PwMDoc::lockAt(const QString &category,unsigned int index, bool lock) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return false; } return lockAt(cat, index, lock); } bool PwMDoc::lockAll(bool lock) { if (!lock && isDeepLocked()) { PwMerror ret; ret = deepLock(false); if (ret != e_success) return false; return true; } if (isDocEmpty()) { return true; } if (!lock && currentPw != "") { // unlocking and password is already set if (!getDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW)) { // unlocking without pw not allowed QString pw; pw = requestMpw(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); if (pw != "") { if (pw != currentPw) { wrongMpwMsgBox(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); return false; } else { timer()->start(DocTimer::id_mpwTimer); } } else { return false; } } else { timer()->start(DocTimer::id_mpwTimer); } } vector<PwMCategoryItem>::iterator catBegin = dti.dta.begin(), catEnd = dti.dta.end(), catI = catBegin; vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; while (catI != catEnd) { entrBegin = catI->d.begin(); entrEnd = catI->d.end(); entrI = entrBegin; while (entrI != entrEnd) { entrI->lockStat = lock; entrI->rev++; // increment revision counter. ++entrI; } ++catI; } emitDataChanged(this); if (lock) timer()->stop(DocTimer::id_autoLockTimer); else timer()->start(DocTimer::id_autoLockTimer); return true; } bool PwMDoc::isLocked(const QString &category, unsigned int index) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return false; } return isLocked(cat, index); } bool PwMDoc::unlockAll_tempoary(bool revert) { static vector< vector<bool> > *oldLockStates = 0; static bool wasDeepLocked; if (revert) { // revert the unlocking if (oldLockStates) { /* we actually _have_ unlocked something, because * we have allocated space for the oldLockStates. * So, go on and revert them! */ if (wasDeepLocked) { PwMerror ret = deepLock(true); if (ret == e_success) { /* deep-lock succeed. We are save. * (but if it failed, just go on * lock them normally) */ delete_and_null(oldLockStates); timer()->start(DocTimer::id_autoLockTimer); printDebug("tempoary unlocking of dta " "reverted by deep-locking."); return true; } printDebug("deep-lock failed while reverting! " "Falling back to normal-lock."); } if (unlikely(!wasDeepLocked && numCategories() != oldLockStates->size())) { /* DOH! We have modified "dta" while * it was unlocked tempoary. DON'T DO THIS! */ BUG(); delete_and_null(oldLockStates); timer()->start(DocTimer::id_autoLockTimer); return false; } vector<PwMCategoryItem>::iterator catBegin = dti.dta.begin(), catEnd = dti.dta.end(), catI = catBegin; vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; vector< vector<bool> >::iterator oldCatStatI = oldLockStates->begin(); vector<bool>::iterator oldEntrStatBegin, oldEntrStatEnd, oldEntrStatI; while (catI != catEnd) { entrBegin = catI->d.begin(); entrEnd = catI->d.end(); entrI = entrBegin; if (likely(!wasDeepLocked)) { oldEntrStatBegin = oldCatStatI->begin(); oldEntrStatEnd = oldCatStatI->end(); oldEntrStatI = oldEntrStatBegin; if (unlikely(catI->d.size() != oldCatStatI->size())) { /* DOH! We have modified "dta" while * it was unlocked tempoary. DON'T DO THIS! */ BUG(); delete_and_null(oldLockStates); timer()->start(DocTimer::id_autoLockTimer); return false; } } while (entrI != entrEnd) { if (wasDeepLocked) { /* this is an error-fallback if * deeplock didn't succeed */ entrI->lockStat = true; } else { entrI->lockStat = *oldEntrStatI; } ++entrI; if (likely(!wasDeepLocked)) ++oldEntrStatI; } ++catI; if (likely(!wasDeepLocked)) ++oldCatStatI; } delete_and_null(oldLockStates); if (unlikely(wasDeepLocked)) { /* error fallback... */ unsetDocStatFlag(DOC_STAT_DEEPLOCKED); emitDataChanged(this); printDebug("WARNING: unlockAll_tempoary(true) " "deeplock fallback!"); } printDebug("tempoary unlocking of dta reverted."); } else { printDebug("unlockAll_tempoary(true): nothing to do."); } timer()->start(DocTimer::id_autoLockTimer); } else { // unlock all data tempoary if (unlikely(oldLockStates != 0)) { /* DOH! We have already unlocked the data tempoarly. * No need to do it twice. ;) */ BUG(); return false; } wasDeepLocked = false; bool mustUnlock = false; if (isDeepLocked()) { PwMerror ret; while (1) { ret = deepLock(false); if (ret == e_success) { break; } else if (ret == e_wrongPw) { wrongMpwMsgBox(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); } else { printDebug("deep-unlocking failed while " "tempoary unlocking!"); return false; } } wasDeepLocked = true; mustUnlock = true; } else { // first check if it's needed to unlock some entries vector<PwMCategoryItem>::iterator catBegin = dti.dta.begin(), catEnd = dti.dta.end(), catI = catBegin; vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; while (catI != catEnd) { entrBegin = catI->d.begin(); entrEnd = catI->d.end(); entrI = entrBegin; while (entrI != entrEnd) { if (entrI->lockStat == true) { mustUnlock = true; break; } ++entrI; } if (mustUnlock) break; ++catI; } } if (!mustUnlock) { // nothing to do. timer()->stop(DocTimer::id_autoLockTimer); printDebug("unlockAll_tempoary(): nothing to do."); return true; } else if (!wasDeepLocked) { if (!getDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW) && currentPw != "") { /* we can't unlock without mpw, so * we need to ask for it. */ QString pw; while (1) { pw = requestMpw(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); if (pw == "") { return false; } else if (pw == currentPw) { break; } wrongMpwMsgBox(getDocStatFlag(DOC_STAT_USE_CHIPCARD)); } } } timer()->stop(DocTimer::id_autoLockTimer); oldLockStates = new vector< vector<bool> >; vector<bool> tmp_vec; vector<PwMCategoryItem>::iterator catBegin = dti.dta.begin(), catEnd = dti.dta.end(), catI = catBegin; vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; while (catI != catEnd) { entrBegin = catI->d.begin(); entrEnd = catI->d.end(); entrI = entrBegin; while (entrI != entrEnd) { if (!wasDeepLocked) { tmp_vec.push_back(entrI->lockStat); } entrI->lockStat = false; ++entrI; } if (!wasDeepLocked) { oldLockStates->push_back(tmp_vec); tmp_vec.clear(); } ++catI; } printDebug("tempoary unlocked dta."); } return true; } PwMerror PwMDoc::deepLock(bool lock, bool saveToFile) { PwMerror ret; /* NOTE: saveDoc() depends on this function to return * e_success if saveToFile == false */ if (lock) { if (isDeepLocked()) return e_lock; if (saveToFile) { if (isDocEmpty()) return e_docIsEmpty; ret = saveDoc(conf()->confGlobCompression()); if (ret == e_filename) { /* the doc wasn't saved to a file * by the user, yet. */ cantDeeplock_notSavedMsgBox(); return e_docNotSaved; } else if (ret != e_success) { return e_lock; } } timer()->stop(DocTimer::id_autoLockTimer); clearDoc(); PwMDataItem d; d.desc = IS_DEEPLOCKED_SHORTMSG.latin1(); d.comment = IS_DEEPLOCKED_MSG.latin1(); d.listViewPos = 0; addEntry(DEFAULT_CATEGORY, &d, true); lockAt(DEFAULT_CATEGORY, 0, true); unsetDocStatFlag(DOC_STAT_DISK_DIRTY); setDocStatFlag(DOC_STAT_DEEPLOCKED); } else { if (!isDeepLocked()) return e_lock; ret = openDoc(&filename, (conf()->confGlobUnlockOnOpen()) ? 0 : 1); if (ret == e_wrongPw) { return e_wrongPw; } else if (ret != e_success) { printDebug(string("PwMDoc::deepLock(false): ERR! openDoc() == ") + tostr(static_cast<int>(ret))); return e_lock; } unsetDocStatFlag(DOC_STAT_DEEPLOCKED); timer()->start(DocTimer::id_autoLockTimer); } emitDataChanged(this); return e_success; } void PwMDoc::_deepUnlock() { deepLock(false); } void PwMDoc::clearDoc() { dti.clear(); PwMCategoryItem d; //US ENH: to initialize all members with meaningfull data. d.clear(); d.name = DEFAULT_CATEGORY.latin1(); dti.dta.push_back(d); currentPw = ""; unsetDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW); } void PwMDoc::changeCurrentPw() { if (currentPw == "") return; // doc hasn't been saved. No mpw available. bool useChipcard = getDocStatFlag(DOC_STAT_USE_CHIPCARD); QString pw = requestMpwChange(¤tPw, &useChipcard); if (pw == "") return; if (useChipcard) setDocStatFlag(DOC_STAT_USE_CHIPCARD); else unsetDocStatFlag(DOC_STAT_USE_CHIPCARD); setCurrentPw(pw); } void PwMDoc::setListViewPos(const QString &category, unsigned int index, int pos) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return; } setListViewPos(cat, index, pos); } void PwMDoc::setListViewPos(unsigned int category, unsigned int index, int pos) { dti.dta[category].d[index].listViewPos = pos; /* FIXME workaround: don't flag dirty, because this function sometimes * get's called when it shouldn't. It's because PwMView assumes * the user resorted the UI on behalf of signal layoutChanged(). * This is somewhat broken and incorrect, but I've no other * solution for now. */ // setDocStatFlag(DOC_STAT_DISK_DIRTY); } int PwMDoc::getListViewPos(const QString &category, unsigned int index) { unsigned int cat = 0; if (!findCategory(category, &cat)) { BUG(); return -1; } return dti.dta[cat].d[index].listViewPos; } void PwMDoc::findEntry(unsigned int category, PwMDataItem find, unsigned int searchIn, vector<unsigned int> *foundPositions, bool breakAfterFound, bool caseSensitive, bool exactWordMatch, bool sortByLvp) { PWM_ASSERT(foundPositions); PWM_ASSERT(searchIn); foundPositions->clear(); unsigned int i, entries = numEntries(category); for (i = 0; i < entries; ++i) { if (searchIn & SEARCH_IN_DESC) { if (!compareString(find.desc, dti.dta[category].d[i].desc, caseSensitive, exactWordMatch)) { continue; } } if (searchIn & SEARCH_IN_NAME) { if (!compareString(find.name, dti.dta[category].d[i].name, caseSensitive, exactWordMatch)) { continue; } } if (searchIn & SEARCH_IN_PW) { bool wasLocked = isLocked(category, i); getDataChangedLock(); lockAt(category, i, false); if (!compareString(find.pw, dti.dta[category].d[i].pw, caseSensitive, exactWordMatch)) { lockAt(category, i, wasLocked); putDataChangedLock(); continue; } lockAt(category, i, wasLocked); putDataChangedLock(); } if (searchIn & SEARCH_IN_COMMENT) { if (!compareString(find.comment, dti.dta[category].d[i].comment, caseSensitive, exactWordMatch)) { continue; } } if (searchIn & SEARCH_IN_URL) { if (!compareString(find.url, dti.dta[category].d[i].url, caseSensitive, exactWordMatch)) { continue; } } if (searchIn & SEARCH_IN_LAUNCHER) { if (!compareString(find.launcher, dti.dta[category].d[i].launcher, caseSensitive, exactWordMatch)) { continue; } } // all selected "searchIn" matched. foundPositions->push_back(i); if (breakAfterFound) break; } if (sortByLvp && foundPositions->size() > 1) { vector< pair<unsigned int /* foundPosition (real doc pos) */, unsigned int /* lvp-pos */> > tmp_vec; unsigned int i, items = foundPositions->size(); pair<unsigned int, unsigned int> tmp_pair; for (i = 0; i < items; ++i) { tmp_pair.first = (*foundPositions)[i]; tmp_pair.second = dti.dta[category].d[(*foundPositions)[i]].listViewPos; tmp_vec.push_back(tmp_pair); } sort(tmp_vec.begin(), tmp_vec.end(), dta_lvp_greater()); foundPositions->clear(); for (i = 0; i < items; ++i) { foundPositions->push_back(tmp_vec[i].first); } } } void PwMDoc::findEntry(const QString &category, PwMDataItem find, unsigned int searchIn, vector<unsigned int> *foundPositions, bool breakAfterFound, bool caseSensitive, bool exactWordMatch, bool sortByLvp) { PWM_ASSERT(foundPositions); unsigned int cat = 0; if (!findCategory(category, &cat)) { foundPositions->clear(); return; } findEntry(cat, find, searchIn, foundPositions, breakAfterFound, caseSensitive, exactWordMatch, sortByLvp); } bool PwMDoc::compareString(const string &s1, const string &s2, bool caseSensitive, bool exactWordMatch) { QString _s1(s1.c_str()); QString _s2(s2.c_str()); if (!caseSensitive) { _s1 = _s1.lower(); _s2 = _s2.lower(); } if (exactWordMatch ? (_s1 == _s2) : (_s2.find(_s1) != -1)) return true; return false; } bool PwMDoc::findCategory(const QString &name, unsigned int *index) { vector<PwMCategoryItem>::iterator i = dti.dta.begin(), end = dti.dta.end(); while (i != end) { if ((*i).name == name.latin1()) { if (index) { *index = i - dti.dta.begin(); } return true; } ++i; } return false; } bool PwMDoc::renameCategory(const QString &category, const QString &newName) { unsigned int cat = 0; if (!findCategory(category, &cat)) return false; return renameCategory(cat, newName); } bool PwMDoc::renameCategory(unsigned int category, const QString &newName, bool dontFlagDirty) { if (category > numCategories() - 1) return false; dti.dta[category].name = newName.latin1(); if (!dontFlagDirty) flagDirty(); return true; } bool PwMDoc::delCategory(const QString &category) { unsigned int cat = 0; if (!findCategory(category, &cat)) return false; return delCategory(cat); } bool PwMDoc::delCategory(unsigned int category, bool dontFlagDirty) { if (category > numCategories() - 1) return false; // We don't delete it, if it is the last existing // category! Instead we rename it to "Default". if (numCategories() > 1) { dti.dta.erase(dti.dta.begin() + category); } else { renameCategory(category, DEFAULT_CATEGORY, dontFlagDirty); return true; } if (!dontFlagDirty) flagDirty(); return true; } void PwMDoc::delAllEmptyCat(bool dontFlagDirty) { vector<PwMCategoryItem>::iterator begin = dti.dta.begin(), end = dti.dta.end(), i = begin; while (i != end) { if (i->d.empty()) { delCategory(begin - i, dontFlagDirty); } ++i; } } void PwMDoc::getCategoryList(vector<string> *list) { PWM_ASSERT(list); list->clear(); vector<PwMCategoryItem>::iterator i = dti.dta.begin(), end = dti.dta.end(); while (i != end) { list->push_back(i->name); ++i; } } void PwMDoc::getCategoryList(QStringList *list) { PWM_ASSERT(list); list->clear(); vector<PwMCategoryItem>::iterator i = dti.dta.begin(), end = dti.dta.end(); while (i != end) { #ifndef PWM_EMBEDDED list->push_back(i->name.c_str()); #else list->append(i->name.c_str()); #endif ++i; } } void PwMDoc::getEntryList(const QString &category, QStringList *list) { PWM_ASSERT(list); unsigned int cat = 0; if (!findCategory(category, &cat)) { list->clear(); return; } getEntryList(cat, list); } void PwMDoc::getEntryList(const QString &category, vector<string> *list) { PWM_ASSERT(list); unsigned int cat = 0; if (!findCategory(category, &cat)) { list->clear(); return; } getEntryList(cat, list); } void PwMDoc::getEntryList(unsigned int category, vector<string> *list) { PWM_ASSERT(list); list->clear(); vector<PwMDataItem>::iterator begin = dti.dta[category].d.begin(), end = dti.dta[category].d.end(), i = begin; while (i != end) { list->push_back(i->desc); ++i; } } void PwMDoc::getEntryList(unsigned int category, QStringList *list) { PWM_ASSERT(list); list->clear(); vector<PwMDataItem>::iterator begin = dti.dta[category].d.begin(), end = dti.dta[category].d.end(), i = begin; while (i != end) { #ifndef PWM_EMBEDDED list->push_back(i->desc.c_str()); #else list->append(i->desc.c_str()); #endif ++i; } } bool PwMDoc::execLauncher(const QString &category, unsigned int entryIndex) { unsigned int cat = 0; if (!findCategory(category, &cat)) return false; return execLauncher(cat, entryIndex); } bool PwMDoc::execLauncher(unsigned int category, unsigned int entryIndex) { #ifndef _WIN32_ if (geteuid() == 0) { rootAlertMsgBox(); return false; } #endif QString command(dti.dta[category].d[entryIndex].launcher.c_str()); bool wasLocked = isLocked(category, entryIndex); if (command.find("$p") != -1) { /* the user requested the password to be included * into the command. We have to ask for the password, * if it's locked. We do that by unlocking the entry */ if (!lockAt(category, entryIndex, false)) return false; } #ifndef PWM_EMBEDDED command.replace("$d", dti.dta[category].d[entryIndex].desc.c_str()); command.replace("$n", dti.dta[category].d[entryIndex].name.c_str()); command.replace("$p", dti.dta[category].d[entryIndex].pw.c_str()); command.replace("$u", dti.dta[category].d[entryIndex].url.c_str()); command.replace("$c", dti.dta[category].d[entryIndex].comment.c_str()); #else command.replace(QRegExp("$d"), dti.dta[category].d[entryIndex].desc.c_str()); command.replace(QRegExp("$n"), dti.dta[category].d[entryIndex].name.c_str()); command.replace(QRegExp("$p"), dti.dta[category].d[entryIndex].pw.c_str()); command.replace(QRegExp("$u"), dti.dta[category].d[entryIndex].url.c_str()); command.replace(QRegExp("$c"), dti.dta[category].d[entryIndex].comment.c_str()); #endif command.append(" &"); QString customXterm(conf()->confGlobXtermCommand()); if (!customXterm.isEmpty()) command = customXterm + " " + command; system(command.latin1()); lockAt(category, entryIndex, wasLocked); return true; } bool PwMDoc::goToURL(const QString &category, unsigned int entryIndex) { unsigned int cat = 0; if (!findCategory(category, &cat)) return false; return goToURL(cat, entryIndex); } bool PwMDoc::goToURL(unsigned int category, unsigned int entryIndex) { #ifndef _WIN32_ if (geteuid() == 0) { rootAlertMsgBox(); return false; } #endif QString url(dti.dta[category].d[entryIndex].url.c_str()); if (url.isEmpty()) return false; QString customBrowser(conf()->confGlobBrowserCommand()); if (!customBrowser.isEmpty()) { browserProc.clearArguments(); browserProc << customBrowser << url; if (browserProc.start(KProcess::DontCare)) return true; } browserProc.clearArguments(); browserProc << "konqueror" << url; if (browserProc.start(KProcess::DontCare)) return true; browserProc.clearArguments(); browserProc << "mozilla" << url; if (browserProc.start(KProcess::DontCare)) return true; browserProc.clearArguments(); browserProc << "opera" << url; if (browserProc.start(KProcess::DontCare)) return true; return false; } PwMerror PwMDoc::exportToText(const QString *file) { PWM_ASSERT(file); if (QFile::exists(*file)) { if (!QFile::remove(*file)) return e_accessFile; } QFile f(*file); - if (!f.open(IO_ReadWrite)) + if (!f.open(QIODevice::ReadWrite)) return e_openFile; if (!unlockAll_tempoary()) { f.close(); return e_lock; } // write header string header = i18n("Password table generated by\nPwM v").latin1(); header += PACKAGE_VER; header += i18n("\non ").latin1(); QDate currDate = QDate::currentDate(); QTime currTime = QTime::currentTime(); #ifndef PWM_EMBEDDED header += currDate.toString("ddd MMMM d ").latin1(); header += currTime.toString("hh:mm:ss ").latin1(); #else QString dfs = KGlobal::locale()->dateFormatShort(); bool ampm = KGlobal::locale()->use12Clock(); KGlobal::locale()->setDateFormatShort("%A %B %d"); KGlobal::locale()->setHore24Format(true); header += KGlobal::locale()->formatDate(currDate, true, KLocale::Userdefined).latin1(); header += KGlobal::locale()->formatTime(currTime, true).latin1(); KGlobal::locale()->setDateFormatShort(dfs); KGlobal::locale()->setHore24Format(!ampm); #endif header += tostr(currDate.year()); header += "\n==============================\n\n"; #ifndef PWM_EMBEDDED if (f.writeBlock(header.c_str(), header.length()) != (Q_LONG)header.length()) { unlockAll_tempoary(true); f.close(); return e_writeFile; } #else if (f.writeBlock(header.c_str(), header.length()) != (long)header.length()) { unlockAll_tempoary(true); f.close(); return e_writeFile; } #endif unsigned int i, numCat = numCategories(); unsigned int j, numEnt; string exp; for (i = 0; i < numCat; ++i) { numEnt = numEntries(i); exp = "\n== Category: "; exp += dti.dta[i].name; exp += " ==\n"; #ifndef PWM_EMBEDDED if (f.writeBlock(exp.c_str(), exp.length()) != (Q_LONG)exp.length()) { unlockAll_tempoary(true); f.close(); return e_writeFile; } #else if (f.writeBlock(exp.c_str(), exp.length()) != (long)exp.length()) { unlockAll_tempoary(true); f.close(); return e_writeFile; } #endif for (j = 0; j < numEnt; ++j) { exp = "\n-- "; exp += dti.dta[i].d[j].desc; exp += " --\n"; exp += i18n("Username: ").latin1(); exp += dti.dta[i].d[j].name; exp += "\n"; exp += i18n("Password: ").latin1(); exp += dti.dta[i].d[j].pw; exp += "\n"; exp += i18n("Comment: ").latin1(); exp += dti.dta[i].d[j].comment; exp += "\n"; exp += i18n("URL: ").latin1(); exp += dti.dta[i].d[j].url; exp += "\n"; exp += i18n("Launcher: ").latin1(); exp += dti.dta[i].d[j].launcher; exp += "\n"; #ifndef PWM_EMBEDDED if (f.writeBlock(exp.c_str(), exp.length()) != (Q_LONG)exp.length()) { unlockAll_tempoary(true); f.close(); return e_writeFile; } #else if (f.writeBlock(exp.c_str(), exp.length()) != (long)exp.length()) { unlockAll_tempoary(true); f.close(); return e_writeFile; } #endif } } unlockAll_tempoary(true); f.close(); return e_success; } PwMerror PwMDoc::importFromText(const QString *file, int format) { PWM_ASSERT(file); if (format == 0) return importText_PwM(file); else if (format == -1) { // probe for all formats if (importText_PwM(file) == e_success) return e_success; dti.clear(); emitDataChanged(this); // add next format here... return e_fileFormat; } return e_invalidArg; } PwMerror PwMDoc::importText_PwM(const QString *file) { #ifndef PWM_EMBEDDED PWM_ASSERT(file); FILE *f; int tmp; ssize_t ret; string curCat; unsigned int entriesRead = 0; PwMDataItem currItem; f = fopen(file->latin1(), "r"); if (!f) return e_openFile; size_t ch_tmp_size = 1024; char *ch_tmp = (char*)malloc(ch_tmp_size); if (!ch_tmp) { fclose(f); return e_outOfMem; } // - check header if (getline(&ch_tmp, &ch_tmp_size, f) == -1) // skip first line. goto formatError; // check version-string and return version in "ch_tmp". if (fscanf(f, "PwM v%s", ch_tmp) != 1) { // header not recognized as PwM generated header goto formatError; } // set filepointer behind version-string-line previously checked if (getline(&ch_tmp, &ch_tmp_size, f) == -1) goto formatError; // skip next line containing the build-date if (getline(&ch_tmp, &ch_tmp_size, f) == -1) goto formatError; // read header termination line if (getline(&ch_tmp, &ch_tmp_size, f) == -1) goto formatError; if (strcmp(ch_tmp, "==============================\n")) goto formatError; // - read entries do { // find beginning of next category do { tmp = fgetc(f); } while (tmp == '\n' && tmp != EOF); if (tmp == EOF) break; // decrement filepos by one fseek(f, -1, SEEK_CUR); // read cat-name if (getline(&ch_tmp, &ch_tmp_size, f) == -1) goto formatError; // check cat-name format if (memcmp(ch_tmp, "== Category: ", 13) != 0) goto formatError; if (memcmp(ch_tmp + (strlen(ch_tmp) - 1 - 3), " ==", 3) != 0) goto formatError; // copy cat-name curCat.assign(ch_tmp + 13, strlen(ch_tmp) - 1 - 16); do { // find beginning of next entry do { tmp = fgetc(f); } while (tmp == '\n' && tmp != EOF && tmp != '='); if (tmp == EOF) break; if (tmp == '=') { fseek(f, -1, SEEK_CUR); break; } // decrement filepos by one fseek(f, -1, SEEK_CUR); // read desc-line if (getline(&ch_tmp, &ch_tmp_size, f) == -1) goto formatError; // check desc-line format if (memcmp(ch_tmp, "-- ", 3) != 0) goto formatError; if (memcmp(ch_tmp + (strlen(ch_tmp) - 1 - 3), " --", 3) != 0) goto formatError; // add desc-line currItem.desc.assign(ch_tmp + 3, strlen(ch_tmp) - 1 - 6); // read username-line if ((ret = getline(&ch_tmp, &ch_tmp_size, f)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.name)) goto formatError; // read pw-line if ((ret = getline(&ch_tmp, &ch_tmp_size, f)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.pw)) goto formatError; // read comment-line if ((ret = getline(&ch_tmp, &ch_tmp_size, f)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.comment)) goto formatError; // read URL-line if ((ret = getline(&ch_tmp, &ch_tmp_size, f)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.url)) goto formatError; // read launcher-line if ((ret = getline(&ch_tmp, &ch_tmp_size, f)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.launcher)) goto formatError; currItem.lockStat = true; currItem.listViewPos = -1; addEntry(curCat.c_str(), &currItem, true); ++entriesRead; } while (1); } while (1); if (!entriesRead) goto formatError; free(ch_tmp); fclose(f); flagDirty(); return e_success; formatError: free(ch_tmp); fclose(f); return e_fileFormat; #else PWM_ASSERT(file); QFile f(file->latin1()); int tmp; ssize_t ret; string curCat; unsigned int entriesRead = 0; PwMDataItem currItem; - bool res = f.open(IO_ReadOnly); + bool res = f.open(QIODevice::ReadOnly); if (res == false) return e_openFile; unsigned int ch_tmp_size = 1024; char *ch_tmp = (char*)malloc(ch_tmp_size); if (!ch_tmp) { f.close(); return e_outOfMem; } // - check header if (f.readLine(ch_tmp, ch_tmp_size) == -1) // skip first line. goto formatError; //US read fileversion first, then check if ok. if (f.readLine(ch_tmp, ch_tmp_size) == -1) goto formatError; // check version-string and return version in "ch_tmp". //US if (fscanf(f, "PwM v%s", ch_tmp) != 1) { //US // header not recognized as PwM generated header //US goto formatError; //US } //US set filepointer behind version-string-line previously checked //US if (f.readLine(ch_tmp, ch_tmp_size) == -1) //US goto formatError; // skip next line containing the build-date if (f.readLine(ch_tmp, ch_tmp_size) == -1) goto formatError; // read header termination line if (f.readLine(ch_tmp, ch_tmp_size) == -1) goto formatError; if (strcmp(ch_tmp, "==============================\n")) goto formatError; // - read entries do { // find beginning of next category do { tmp = f.getch(); } while (tmp == '\n' && tmp != EOF); if (tmp == EOF) break; // decrement filepos by one f.at(f.at()-1); // read cat-name if (f.readLine(ch_tmp, ch_tmp_size) == -1) goto formatError; // check cat-name format if (memcmp(ch_tmp, "== Category: ", 13) != 0) goto formatError; if (memcmp(ch_tmp + (strlen(ch_tmp) - 1 - 3), " ==", 3) != 0) goto formatError; // copy cat-name curCat.assign(ch_tmp + 13, strlen(ch_tmp) - 1 - 16); do { // find beginning of next entry do { tmp = f.getch(); } while (tmp == '\n' && tmp != EOF && tmp != '='); if (tmp == EOF) break; if (tmp == '=') { f.at(f.at()-1); break; } // decrement filepos by one f.at(f.at()-1); // read desc-line if (f.readLine(ch_tmp, ch_tmp_size) == -1) goto formatError; // check desc-line format if (memcmp(ch_tmp, "-- ", 3) != 0) goto formatError; if (memcmp(ch_tmp + (strlen(ch_tmp) - 1 - 3), " --", 3) != 0) goto formatError; // add desc-line currItem.desc.assign(ch_tmp + 3, strlen(ch_tmp) - 1 - 6); // read username-line if ((ret = f.readLine(ch_tmp, ch_tmp_size)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.name)) goto formatError; // read pw-line if ((ret = f.readLine(ch_tmp, ch_tmp_size)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.pw)) goto formatError; // read comment-line if ((ret = f.readLine(ch_tmp, ch_tmp_size)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.comment)) goto formatError; // read URL-line if ((ret = f.readLine(ch_tmp, ch_tmp_size)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.url)) goto formatError; // read launcher-line if ((ret = f.readLine(ch_tmp, ch_tmp_size)) == -1) goto formatError; if (!textExtractEntry_PwM(ch_tmp, ret, &currItem.launcher)) goto formatError; currItem.lockStat = true; currItem.listViewPos = -1; addEntry(curCat.c_str(), &currItem, true); ++entriesRead; } while (1); } while (1); if (!entriesRead) goto formatError; free(ch_tmp); f.close(); flagDirty(); return e_success; formatError: free(ch_tmp); f.close(); return e_fileFormat; #endif } bool PwMDoc::textExtractEntry_PwM(const char *in, ssize_t in_size, string *out) { PWM_ASSERT(in && out); ssize_t i = 0, len = in_size - 1; while (i < len) { if (in[i] == ':') break; ++i; } i += 2; *out = ""; out->append(in + i, in_size - i - 1); return true; } PwMerror PwMDoc::exportToGpasman(const QString *file) { PWM_ASSERT(file); GpasmanFile gp; int ret; if (!unlockAll_tempoary()) return e_lock; QString gpmPassword; while (1) { gpmPassword = requestNewMpw(0); if (gpmPassword == "") { unlockAll_tempoary(true); return e_noPw; } if (gpmPassword.length() < 4) { gpmPwLenErrMsgBox(); } else { break; } } ret = gp.save_init(file->latin1(), gpmPassword.latin1()); if (ret != 1) { unlockAll_tempoary(true); return e_accessFile; } char *entry[4]; unsigned int numCat = numCategories(), i; unsigned int numEntr, j; int descLen, nameLen, pwLen, commentLen; for (i = 0; i < numCat; ++i) { numEntr = numEntries(i); for (j = 0; j < numEntr; ++j) { descLen = dti.dta[i].d[j].desc.length(); nameLen = dti.dta[i].d[j].name.length(); pwLen = dti.dta[i].d[j].pw.length(); commentLen = dti.dta[i].d[j].comment.length(); entry[0] = new char[descLen + 1]; entry[1] = new char[nameLen + 1]; entry[2] = new char[pwLen + 1]; entry[3] = new char[commentLen + 1]; strcpy(entry[0], descLen == 0 ? " " : dti.dta[i].d[j].desc.c_str()); strcpy(entry[1], nameLen == 0 ? " " : dti.dta[i].d[j].name.c_str()); strcpy(entry[2], pwLen == 0 ? " " : dti.dta[i].d[j].pw.c_str()); strcpy(entry[3], commentLen == 0 ? " " : dti.dta[i].d[j].comment.c_str()); entry[0][descLen == 0 ? descLen + 1 : descLen] = '\0'; entry[1][nameLen == 0 ? nameLen + 1 : nameLen] = '\0'; entry[2][pwLen == 0 ? pwLen + 1 : pwLen] = '\0'; entry[3][commentLen == 0 ? commentLen + 1 : commentLen] = '\0'; ret = gp.save_entry(entry); if (ret == -1){ delete [] entry[0]; delete [] entry[1]; delete [] entry[2]; delete [] entry[3]; gp.save_finalize(); unlockAll_tempoary(true); return e_writeFile; } delete [] entry[0]; delete [] entry[1]; delete [] entry[2]; delete [] entry[3]; } } unlockAll_tempoary(true); if (gp.save_finalize() == -1) return e_writeFile; return e_success; } PwMerror PwMDoc::importFromGpasman(const QString *file) { PWM_ASSERT(file); QString pw = requestMpw(false); if (pw == "") return e_noPw; GpasmanFile gp; int ret, i; PwMerror ret2; char *entry[4]; PwMDataItem tmpData; ret = gp.load_init(file->latin1(), pw.latin1()); if (ret != 1) return e_accessFile; do { ret = gp.load_entry(entry); if(ret != 1) break; tmpData.desc = entry[0]; tmpData.name = entry[1]; tmpData.pw = entry[2]; tmpData.comment = entry[3]; tmpData.lockStat = true; tmpData.listViewPos = -1; ret2 = addEntry(DEFAULT_CATEGORY, &tmpData, true); for (i = 0; i < 4; ++i) free(entry[i]); if (ret2 == e_maxAllowedEntr) { gp.load_finalize(); return e_maxAllowedEntr; } } while (1); gp.load_finalize(); if (isDocEmpty()) return e_wrongPw; // we assume this. flagDirty(); return e_success; } //US: we use the stl sort algorythm to sort all elements in the order //of its listViewPos (in the order 1,2,3,5,...,x,-1, -1, -1 struct PwMDataItemListViewPosSort { bool operator()(PwMDataItem* rpStart, PwMDataItem* rpEnd) { //qDebug("pwMDoc::PwMDataItemListViewPosSort()"); if ((rpEnd)->listViewPos < 0) return false; else return (rpStart)->listViewPos < (rpEnd)->listViewPos; } }; void PwMDoc::ensureLvp() { if (isDocEmpty()) return; //US ENH BUG: when using syncronizing, this way of sorting //is not sufficient, because there might be empty spaces // at the beginning. But the old algorythm only can add elements //to the end.The result are crashes because of list overflows //we need something to fill all gaps. vector<PwMDataItem*> sorted; vector< PwMDataItem*>::iterator sortedBegin, sortedEnd, sortedI; vector<PwMCategoryItem>::iterator catBegin = dti.dta.begin(), catEnd = dti.dta.end(), catI = catBegin; vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; int lvpTop, tmpLvp; //qDebug("collect:"); while (catI != catEnd) { lvpTop = -1; sorted.clear(); entrBegin = catI->d.begin(); entrEnd = catI->d.end(); entrI = entrBegin; //US: we use the stl sort algorythm to sort all elements in the order //of its listViewPos (in the order 1,2,2,3,5,...,x,-1, -1, -1 while (entrI != entrEnd) { //qDebug("found: %s, pos=%i", (*entrI).desc.c_str(), (*entrI).listViewPos); sorted.push_back((PwMDataItem*)&(*entrI)); ++entrI; } sortedBegin = sorted.begin(); sortedEnd = sorted.end(); sort(sortedBegin, sortedEnd, PwMDataItemListViewPosSort()); // qDebug("resort:"); //now we have all sorted in a collection //Now start with the sorted and reset listviewpos. sortedBegin = sorted.begin(); sortedEnd = sorted.end(); sortedI = sortedBegin; while (sortedI != sortedEnd) { // qDebug("reset defined: %s, from pos=%i to pos=%i", (*sortedI)->desc.c_str(), (*sortedI)->listViewPos, lvpTop+1); (*sortedI)->listViewPos = ++lvpTop; ++sortedI; } /*/debug entrBegin = catI->d.begin(); entrEnd = catI->d.end(); entrI = entrBegin; while (entrI != entrEnd) { qDebug("check: %s, pos=%i", (*entrI).desc.c_str(), (*entrI).listViewPos); ++entrI; } */ ++catI; } } QString PwMDoc::getTitle() { /* NOTE: We have to ensure, that the returned title * is unique and not reused somewhere else while * this document is valid (open). */ QString title(getFilename()); //US ENH: The whole filename on PDAs is too long. So use only the last characters if (QApplication::desktop()->width() < 640) { if (title.length() > 30) title = "..." + title.right(30); } if (title.isEmpty()) { if (unnamedNum == 0) { unnamedNum = PwMDocList::getNewUnnamedNumber(); PWM_ASSERT(unnamedNum != 0); } title = DEFAULT_TITLE; title += " "; title += tostr(unnamedNum).c_str(); } return title; } bool PwMDoc::tryDelete() { if (deleted) return true; int ret; if (isDirty()) { ret = dirtyAskSave(getTitle()); if (ret == 0) { // save to disk if (!saveDocUi(this)) goto out_ignore; } else if (ret == 1) { // don't save and delete goto out_accept; } else { // cancel operation goto out_ignore; } } out_accept: deleted = true; delete this; return true; out_ignore: return false; } #ifdef PWM_EMBEDDED //US ENH: this is the magic function that syncronizes the this doc with the remote doc //US it could have been defined as static, but I did not want to. PwMerror PwMDoc::syncronize(KSyncManager* manager, PwMDoc* syncLocal , PwMDoc* syncRemote, int mode ) { int addedPasswordsLocal = 0; int addedPasswordsRemote = 0; int deletedPasswordsRemote = 0; int deletedPasswordsLocal = 0; int changedLocal = 0; int changedRemote = 0; PwMSyncItem* syncItemLocal; PwMSyncItem* syncItemRemote; QString mCurrentSyncName = manager->getCurrentSyncName(); QString mCurrentSyncDevice = manager->getCurrentSyncDevice(); bool mSyncLauncher = true; bool fullDateRange = false; int take; // local->resetTempSyncStat(); QDateTime mLastSync = QDateTime::currentDateTime(); QDateTime modifiedSync = mLastSync; unsigned int index; //Step 1. Find syncinfo in Local file and create if not existent. bool found = syncLocal->findSyncData(mCurrentSyncDevice, &index); if (found == false) { PwMSyncItem newSyncItemLocal; newSyncItemLocal.syncName = mCurrentSyncDevice.latin1(); newSyncItemLocal.lastSyncDate = mLastSync; syncLocal->addSyncDataEntry(&newSyncItemLocal, true); found = syncLocal->findSyncData(mCurrentSyncDevice, &index); if (found == false) { qDebug("PwMDoc::syncronize : newly created local sync data could not be found"); return e_syncError; } } syncItemLocal = syncLocal->getSyncDataEntry(index); qDebug("Last Sync Local %s ", syncItemLocal->lastSyncDate.toString().latin1()); //Step 2. Find syncinfo in remote file and create if not existent. found = syncRemote->findSyncData(mCurrentSyncName, &index); if (found == false) { qDebug("FULLDATE 1"); fullDateRange = true; PwMSyncItem newSyncItemRemote; newSyncItemRemote.syncName = mCurrentSyncName.latin1(); newSyncItemRemote.lastSyncDate = mLastSync; syncRemote->addSyncDataEntry(&newSyncItemRemote, true); found = syncRemote->findSyncData(mCurrentSyncName, &index); if (found == false) { qDebug("PwMDoc::syncronize : newly created remote sync data could not be found"); return e_syncError; } } syncItemRemote = syncRemote->getSyncDataEntry(index); qDebug("Last Sync Remote %s ", syncItemRemote->lastSyncDate.toString().latin1()); //and remove the found entry here. We will reenter it later again. //US syncRemote->delSyncDataEntry(index, true); if ( syncItemLocal->lastSyncDate == mLastSync ) { qDebug("FULLDATE 2"); fullDateRange = true; } if ( ! fullDateRange ) { if ( syncItemLocal->lastSyncDate != syncItemRemote->lastSyncDate ) { fullDateRange = true; qDebug("FULLDATE 3 %s %s", syncItemLocal->lastSyncDate.toString().latin1() , syncItemRemote->lastSyncDate.toString().latin1() ); } } // fullDateRange = true; // debug only! if ( fullDateRange ) mLastSync = QDateTime::currentDateTime().addDays( -100*365); else mLastSync = syncItemLocal->lastSyncDate; qDebug("*************************** "); qDebug("mLastSync %s ",mLastSync.toString().latin1() ); QStringList er = syncRemote->getIDEntryList(); PwMDataItem* inRemote ;//= er.first(); PwMDataItem* inLocal; unsigned int catLocal, indexLocal; unsigned int catRemote, indexRemote; QString uid; manager->showProgressBar(0, i18n("Syncing - close to abort!"), er.count()); int modulo = (er.count()/10)+1; unsigned int incCounter = 0; while ( incCounter < er.count()) { if (manager->isProgressBarCanceled()) return e_syncError; if ( incCounter % modulo == 0 ) manager->showProgressBar(incCounter); uid = er[ incCounter ]; qDebug("sync uid %s from remote file", uid.latin1()); qApp->processEvents(); inLocal = syncLocal->findEntryByID( uid, &catLocal, &indexLocal ); inRemote = syncRemote->findEntryByID( uid, &catRemote, &indexRemote ); PWM_ASSERT(inRemote); if ( inLocal != 0 ) { // maybe conflict - same uid in both files if ( (take = takePwMDataItem( inLocal, inRemote, mLastSync, mode, fullDateRange) ) ) { qDebug("take %d %s ", take, inLocal->desc.c_str()); if ( take == 3 ) return e_syncError; if ( take == 1 ) {// take local inRemote->syncItem(*inLocal, mSyncLauncher); ++changedRemote; } else { // take == 2 take remote inLocal->syncItem(*inRemote, mSyncLauncher); ++changedLocal; } } } else { // no conflict if ( inRemote->meta.update > mLastSync || mode == 5 ) { inRemote->meta.update = modifiedSync; //first check if we have a matching category in the local file const string* remotecat = syncRemote->getCategory(catRemote); syncLocal->addEntry(remotecat->c_str(), inRemote, true, false); ++addedPasswordsLocal; } else { // pending checkExternSyncAddressee(addresseeRSyncSharp, inR); syncRemote->delEntry(catRemote, indexRemote, true); ++deletedPasswordsRemote; } } ++incCounter; } er.clear(); QStringList el = syncLocal->getIDEntryList(); modulo = (el.count()/10)+1; manager->showProgressBar(0, i18n("Add / remove addressees"), el.count()); incCounter = 0; while ( incCounter < el.count()) { qApp->processEvents(); if (manager->isProgressBarCanceled()) return e_syncError; if ( incCounter % modulo == 0 ) manager->showProgressBar(incCounter); uid = el[ incCounter ]; qDebug("sync uid %s from local file", uid.latin1()); inLocal = syncLocal->findEntryByID( uid, &catLocal, &indexLocal ); inRemote = syncRemote->findEntryByID( uid, &catRemote, &indexRemote ); PWM_ASSERT(inLocal); if ( inRemote == 0 ) { if ( inLocal->meta.update < mLastSync && mode != 4 ) { // pending checkExternSyncAddressee(addresseeLSyncSharp, inL); syncLocal->delEntry(catLocal, indexLocal, true); ++deletedPasswordsLocal; } else { if ( ! manager->mWriteBackExistingOnly ) { ++addedPasswordsRemote; inLocal->meta.update = modifiedSync; //first check if we have a matching category in the remote file const string* localcat = syncLocal->getCategory(catLocal); PwMDataItem newEntry; newEntry = *inLocal; inRemote = &newEntry; //USsyncRemote->insertAddressee( inRemote, false ); syncRemote->addEntry(localcat->c_str(), inRemote, true, false); } } } ++incCounter; } el.clear(); manager->hideProgressBar(); // Now write the info back into the sync data space of the files mLastSync = QDateTime::currentDateTime().addSecs( 1 ); // get rid of micro seconds QTime t = mLastSync.time(); mLastSync.setTime( QTime (t.hour (), t.minute (), t.second () ) ); syncItemLocal->lastSyncDate = mLastSync; syncItemRemote->lastSyncDate = mLastSync; QString mes; mes .sprintf( i18n("Synchronization summary:\n\n %d items added to local\n %d items added to remote\n %d items updated on local\n %d items updated on remote\n %d items deleted on local\n %d items deleted on remote\n"),addedPasswordsLocal, addedPasswordsRemote, changedLocal, changedRemote, deletedPasswordsLocal, deletedPasswordsRemote ); if ( manager->mShowSyncSummary ) { KMessageBox::information(0, mes, i18n("PWM/Pi Synchronization") ); } qDebug( mes ); return e_success; } int PwMDoc::takePwMDataItem( PwMDataItem* local, PwMDataItem* remote, QDateTime lastSync, int mode , bool full ) { // 0 equal // 1 take local // 2 take remote // 3 cancel QDateTime localMod = local->meta.update; QDateTime remoteMod = remote->meta.update; if ( localMod == remoteMod ) return 0; qDebug(" %d %d conflict on %s %s ", mode, full, local->desc.c_str(), remote->desc.c_str() ); //qDebug("%s %d %s %d", local->lastModified().toString().latin1() , localMod, remote->lastModified().toString().latin1(), remoteMod); //qDebug("%d %d %d %d ", local->lastModified().time().second(), local->lastModified().time().msec(), remote->lastModified().time().second(), remote->lastModified().time().msec() ); //full = true; //debug only if ( full ) { bool equ = ( (*local) == (*remote) ); if ( equ ) { //qDebug("equal "); if ( mode < SYNC_PREF_FORCE_LOCAL ) return 0; }//else //debug only //qDebug("not equal %s %s ", local->desc.c_str(), remote->desc.c_str()); } int result; bool localIsNew; //qDebug("%s -- %s mLastCalendarSync %s lastsync %s --- local %s remote %s ",local->summary().latin1(), remote->summary().latin1(),mLastCalendarSync.toString().latin1() ,lastSync.toString().latin1() , local->lastModified().toString().latin1() , remote->lastModified().toString().latin1() ); if ( full && mode < SYNC_PREF_NEWEST ) mode = SYNC_PREF_ASK; switch( mode ) { case SYNC_PREF_LOCAL: if ( lastSync > remoteMod ) return 1; if ( lastSync > localMod ) return 2; return 1; break; case SYNC_PREF_REMOTE: if ( lastSync > remoteMod ) return 1; if ( lastSync > localMod ) return 2; return 2; break; case SYNC_PREF_NEWEST: if ( localMod > remoteMod ) return 1; else return 2; break; case SYNC_PREF_ASK: //qDebug("lsy %s --- lo %s --- re %s ", lastSync.toString().latin1(), localMod.toString().latin1(), remoteMod.toString().latin1() ); if ( lastSync > remoteMod ) return 1; if ( lastSync > localMod ) return 2; localIsNew = localMod >= remoteMod; //qDebug("conflict! ************************************** "); { PwMDataItemChooser acd ( *local,*remote, localIsNew , 0/*this*/ ); result = acd.executeD(localIsNew); return result; } break; case SYNC_PREF_FORCE_LOCAL: return 1; break; case SYNC_PREF_FORCE_REMOTE: return 2; break; default: // SYNC_PREF_TAKE_BOTH not implemented break; } return 0; } void PwMDoc::removeSyncInfo( QString syncProfile) { bool res, found; unsigned int count, i; if ( syncProfile.isEmpty() ) { count = numSyncDataEntries(); for (i = count; count > 0; count-- ) { res = delSyncDataEntry(i-1, false); if (res == false) { qDebug("PwMDoc::removeSyncInfo: could not remove syncprofile"); } } } else { found = findSyncData(syncProfile, &count); if (found == true) { res = delSyncDataEntry(count, false); if (res == false) { qDebug("PwMDoc::removeSyncInfo: could not remove %s", syncProfile.latin1()); } } } } //this are the overwritten callbackmethods from the syncinterface bool PwMDoc::sync(KSyncManager* manager, QString filename, int mode, QString resource) { QString mCurrentSyncDevice = manager->getCurrentSyncDevice(); //1) unlock local file first if necessary (ask for password) if (this->isDeepLocked()) { PwMerror ret = this->deepLock(false); if (ret != e_success) return false; } //2) construct and open a new doc on the stack(automatic cleanup of remote file). PwMDoc syncTarget(this, "synctarget"); PwMDoc* pSyncTarget = &syncTarget; PwMerror err = pSyncTarget->openDoc(&filename, 1 /*== open with all entries locked*/); if (err == e_alreadyOpen) { PwMDocList::listItem li; if (getOpenDocList()->find(filename.latin1(), &li)) pSyncTarget = li.doc; else { qDebug("PwmDoc::sync: sync failed. Error %i while opening file %s",err, filename.latin1()); return false; } } else if (err != e_success) { qDebug("PwmDoc::sync: sync failed. Error %i while opening file %s",err, filename.latin1()); return false; } qDebug("PWM file loaded %s,sync mode %d",filename.latin1(), mode ); //3) unlock remote file first if necessary (ask for password) if (pSyncTarget->isDeepLocked()) { PwMerror ret = pSyncTarget->deepLock(false); if (ret != e_success) return false; } err = syncronize(manager, this, pSyncTarget, mode ); if (err == e_success) { if ( manager->mWriteBackFile ) { qDebug("Saving remote PWManager file"); err = pSyncTarget->saveDoc(conf()->confGlobCompression()); if (err != e_success) { qDebug("PwmDoc::sync: Sync failed. Error %i while storing file %s",err, filename.latin1()); return false; } } flagDirty(); return true; } else { return false; } } #endif bool PwMDoc::findSyncData(const QString &syncname, unsigned int *index) { vector<PwMSyncItem>::iterator i = dti.syncDta.begin(), end = dti.syncDta.end(); while (i != end) { if ((*i).syncName == syncname.latin1()) { if (index) { *index = i - dti.syncDta.begin(); } return true; } ++i; } return false; }; /** add new syncdataentry */ PwMerror PwMDoc::addSyncDataEntry(PwMSyncItem *d, bool dontFlagDirty) { PWM_ASSERT(d); if (isDeepLocked()) { PwMerror ret; ret = deepLock(false); if (ret != e_success) return e_lock; } unsigned int index; const QString tmp = d->syncName.c_str(); bool exists = findSyncData(d->syncName.c_str(), &index); if (exists == true) { // DOH! We found this entry. return e_entryExists; } dti.syncDta.push_back(*d); if (!dontFlagDirty) flagDirty(); return e_success; } /** delete syncdata entry */ bool PwMDoc::delSyncDataEntry(unsigned int index, bool dontFlagDirty) { if (isDeepLocked()) return false; if (index > dti.syncDta.size() - 1) return false; // delete entry dti.syncDta.erase(dti.syncDta.begin() + index); if (!dontFlagDirty) flagDirty(); return true; } PwMDataItem* PwMDoc::findEntryByID(const QString &uid, unsigned int *category, unsigned int *index) { vector<PwMCategoryItem>::iterator catcounter = dti.dta.begin(), catend = dti.dta.end(); vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; while (catcounter != catend) { entrBegin = catcounter->d.begin(); entrEnd = catcounter->d.end(); entrI = entrBegin; while (entrI != entrEnd) { if ((*entrI).meta.uniqueid == uid.latin1()) { if (category) *category = catcounter - dti.dta.begin(); if (index) *index = entrI - entrBegin; return &(*entrI); } ++entrI; } ++catcounter; } return 0; } QStringList PwMDoc::getIDEntryList() { QStringList results; vector<PwMCategoryItem>::iterator catcounter = dti.dta.begin(), catend = dti.dta.end(); vector<PwMDataItem>::iterator entrBegin, entrEnd, entrI; while (catcounter != catend) { entrBegin = catcounter->d.begin(); entrEnd = catcounter->d.end(); entrI = entrBegin; while (entrI != entrEnd) { results.append( (*entrI).meta.uniqueid.c_str() ); ++entrI; } ++catcounter; } return results; } -#ifndef PWM_EMBEDDED -#include "pwmdoc.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwmdoc.cpp" #endif diff --git a/pwmanager/pwmanager/pwmdoc.h b/pwmanager/pwmanager/pwmdoc.h index 144831f..07c97a9 100644 --- a/pwmanager/pwmanager/pwmdoc.h +++ b/pwmanager/pwmanager/pwmdoc.h @@ -1,742 +1,742 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __PWMDOC_H #define __PWMDOC_H #ifdef _WIN32_ #define ssize_t unsigned int #endif #define PWM_FILE_VER (static_cast<char>(0x05)) #define PWM_HASH_SHA1 (static_cast<char>(0x01)) #define PWM_HASH_SHA256 (static_cast<char>(0x02)) #define PWM_HASH_SHA384 (static_cast<char>(0x03)) #define PWM_HASH_SHA512 (static_cast<char>(0x04)) #define PWM_HASH_MD5 (static_cast<char>(0x05)) #define PWM_HASH_RMD160 (static_cast<char>(0x06)) #define PWM_HASH_TIGER (static_cast<char>(0x07)) #define PWM_CRYPT_BLOWFISH (static_cast<char>(0x01)) #define PWM_CRYPT_AES128 (static_cast<char>(0x02)) #define PWM_CRYPT_AES192 (static_cast<char>(0x03)) #define PWM_CRYPT_AES256 (static_cast<char>(0x04)) #define PWM_CRYPT_3DES (static_cast<char>(0x05)) #define PWM_CRYPT_TWOFISH (static_cast<char>(0x06)) #define PWM_CRYPT_TWOFISH128 (static_cast<char>(0x07)) #define PWM_COMPRESS_NONE (static_cast<char>(0x00)) #define PWM_COMPRESS_GZIP (static_cast<char>(0x01)) #define PWM_COMPRESS_BZIP2 (static_cast<char>(0x02)) #define DEFAULT_MAX_ENTRIES (~(static_cast<unsigned int>(0))) #define FILE_ID_HEADER "PWM_PASSWORD_FILE" #include "pwmexception.h" #include "pwmdocui.h" #include <qobject.h> #include <qtimer.h> #include <qdatetime.h> #include <kprocess.h> #ifndef PWM_EMBEDDED #include "configuration.h" #else #include <kapplication.h> #include <ksyncmanager.h> #endif #include <string> #include <vector> #include <utility> using std::vector; using std::string; using std::pair; /* used in findEntry() function */ #define SEARCH_IN_DESC (1) #define SEARCH_IN_NAME (1 << 1) #define SEARCH_IN_PW (1 << 2) #define SEARCH_IN_COMMENT (1 << 3) #define SEARCH_IN_URL (1 << 4) #define SEARCH_IN_LAUNCHER (1 << 5) #define SEARCH_IN_ALL (SEARCH_IN_DESC | SEARCH_IN_NAME | \ SEARCH_IN_PW | SEARCH_IN_COMMENT | \ SEARCH_IN_URL | SEARCH_IN_LAUNCHER) /** document deeplocked. Data is out for lunch to disk */ #define DOC_STAT_DEEPLOCKED (1) /** encrypted document on disk is dirty. data has to go to disk. */ #define DOC_STAT_DISK_DIRTY (1 << 1) /** we are using a chipcard to encrypt the data */ #define DOC_STAT_USE_CHIPCARD (1 << 2) /** use "currentPw" to unlock. (This flag is set/unset by a timer) */ #define DOC_STAT_UNLOCK_WITHOUT_PW (1 << 3) class PwMDoc; class PwMView; class QFile; /* meta data for a PwMDataItem */ struct PwMMetaData { PwMMetaData() : updateInt (0) { } /** creation date of the PwMDataItem to which * this meta data belongs. */ QDateTime create; /** becomes valid on this date */ QDateTime valid; /** expire date */ QDateTime expire; /** update date (last updated at this date) */ QDateTime update; /** update interval (in minutes). Time since the * last update to remind the user to update the item. * 0 disables. */ unsigned long updateInt; //US ENH: enhancements of the filestructure /* each entry gets a unique id assigned */ string uniqueid; void clear() { create = QDateTime(); expire = QDateTime(); update = QDateTime(); updateInt = 0; uniqueid = KApplication::randomString(8).latin1(); } inline bool isValid() const { if (valid.isNull()) return true; return (valid < QDateTime::currentDateTime()); } inline bool isExpired() const { if (expire.isNull()) return false; return (expire < QDateTime::currentDateTime()); } inline bool isUpdateIntOver() const { if (updateInt == 0 || update.isNull()) return false; QDateTime d(update); return (d.addSecs(updateInt * 60) < QDateTime::currentDateTime()); } }; struct PwMDataItem { PwMDataItem() : lockStat (true) , listViewPos (-1) , binary (false) , rev (0) { } /** password description */ string desc; /** user-name */ string name; /** the password itself */ string pw; /** some comment */ string comment; /** an URL string */ string url; /** launcher. Can be executed as a system() command */ string launcher; /** locking status. If locked (true), pw is not emitted through getEntry() */ bool lockStat; /** position of this item in main "list-view" * If -1, the position is not yet specified and should be appended to the list */ int listViewPos; /** does this entry contain binary data? */ bool binary; /** meta data for this data item. */ PwMMetaData meta; /** data revision counter. This counter can be used * to easily, efficiently determine if this data item * has changed since some time. * This counter is incremented on every update. */ unsigned int rev; void clear(bool clearMeta = true) { /* NOTE: Don't use .clear() here to be * backward compatible with gcc-2 (Debian Woody) */ desc = ""; name = ""; pw = ""; comment = ""; url = ""; launcher = ""; lockStat = true; listViewPos = -1; binary = false; if (clearMeta) meta.clear(); } //US ENH: we need this operator to compare two items if we have no unique ids //available. Generaly this happens before the first sync - bool PwMDataItem::operator==( const PwMDataItem &a ) const + bool operator==( const PwMDataItem &a ) const { //qDebug("oper==%s", a.desc.c_str()); if ( desc != a.desc ) return false; if ( name != a.name ) return false; if ( pw != a.pw ) return false; if ( comment != a.comment ) return false; if ( url != a.url ) return false; if ( launcher != a.launcher ) return false; //all other field will not be checked. return true; } //US ENH: this sync method actually copies all values from the parameter like the =operator //does with two exceptions: listViewPos will not be changed, and the launcher only if required. - bool PwMDataItem::syncItem(const PwMDataItem &a, bool syncLauncher=true ) + bool syncItem(const PwMDataItem &a, bool syncLauncher=true ) { desc = a.desc; name = a.name; pw = a.pw; comment = a.comment; url = a.url; if (syncLauncher == true) launcher = a.launcher; meta = a.meta; binary = a.binary; lockStat = a.lockStat; rev = a.rev; return true; } }; struct PwMCategoryItem { /** all PwMDataItems (all passwords) within this category */ vector<PwMDataItem> d; /** category name/description */ string name; //US ENH: enhancements of the filestructure /* each category stores the text for description,name and password */ string desc_text; string name_text; string pw_text; void clear() { d.clear(); name = ""; desc_text = "Description"; name_text = "Username"; pw_text = "Password"; } }; struct PwMSyncItem { string syncName; QDateTime lastSyncDate; void clear() { lastSyncDate = QDateTime(); syncName = ""; } }; struct PwMItem { vector<PwMCategoryItem> dta; vector<PwMSyncItem> syncDta; void clear() { dta.clear(); syncDta.clear(); } }; /** "Function Object" for sort()ing PwMDataItem::listViewPos */ class dta_lvp_greater { public: bool operator() (const pair<unsigned int, unsigned int> &d1, const pair<unsigned int, unsigned int> &d2) { return d1.second > d2.second; } }; /** list of PwMDoc documents and it's IDs */ class PwMDocList { public: struct listItem { /** document filename (known as ID, here) */ string docId; /** pointer to the document class */ PwMDoc *doc; }; PwMDocList() {} /** add a new item to the list */ void add(PwMDoc *doc, const string &id); /** changes the contents of an existing item */ void edit(PwMDoc *doc, const string &newId); /** remove the given item */ void del(PwMDoc *doc); /** get the item at index */ listItem getAt(int index) { return docList[index]; } /** find an entry with this id */ bool find(const string &id, listItem *ret = 0); /** returns a copy of the list */ const vector<listItem>* getList() const { return &docList; } /** returns a new unique number to extend the name of * an unnamed document. */ static unsigned int getNewUnnamedNumber() { return unnamedDocCnt++; } protected: /* Hm, I think we shouldn't really use a "list" here, should we? * So I decided to actually use a vector. */ vector<listItem> docList; /** This value is used to get a new number for yet unnamed * documents. It is incremented on every request. So it's * theoretically possible to overflow it, but... :) */ static unsigned int unnamedDocCnt; }; /** implements timers for the document */ class DocTimer : public QObject { Q_OBJECT public: enum TimerIDs { id_mpwTimer, id_autoLockTimer, id_metaCheckTimer }; public: DocTimer(PwMDoc *_doc); ~DocTimer(); /** start the timer */ void start(TimerIDs timer); /** stop the timer */ void stop(TimerIDs timer); /** get the lock for a timer. * This lock is a recursive lock. When a lock is * held, the timer will be stopped and timeout is * guaranteed to not happen */ void getLock(TimerIDs timer); /** put a recursive timer lock */ void putLock(TimerIDs timer); protected slots: /** timeout slot for the mpw timer */ void mpwTimeout(); /** timeout slot for the autoLock timer */ void autoLockTimeout(); /** timeout slot for the metaCheck timer */ void metaCheckTimeout(); protected: /** pointer to the document associated with this timer. */ PwMDoc *doc; /** timer object for mpw timer */ QTimer *mpwTimer; /** timer object for the autoLock timer */ QTimer *autoLockTimer; /** timer object for the metaCheck timer */ QTimer *metaCheckTimer; /** lock counter for the mpw timer */ unsigned int mpwLock; /** lock counter for the autoLock timer */ unsigned int autoLockLock; /** lock counter for the metaCheck timer */ unsigned int metaCheckLock; }; /** Document class for PwM */ //US ENH: derived from KSyncInterfaces, to get called by PwM when a sync is required. // But PwMDoc is handling the sync by itself. class PwMDoc : public PwMDocUi, public KSyncInterface { Q_OBJECT friend class DocTimer; public: /** construtor */ PwMDoc(QObject* parent = 0, const char *name = 0); /** destructor */ ~PwMDoc(); /** returns a pointer to a list of all open documents */ static PwMDocList* getOpenDocList() { return &openDocList; } /** flag document dirty. dta changed */ void flagDirty() { setDocStatFlag(DOC_STAT_DISK_DIRTY); emitDataChanged(this); } /** modified? */ bool isDirty() { return getDocStatFlag(DOC_STAT_DISK_DIRTY); } /** save document to disk */ PwMerror saveDoc(char compress, const QString *file = 0); /** read document from file. * "openLocked is must be set to either of these values: * 0 == open with all entries unlocked * 1 == open with all entries locked * 2 == open deep-locked */ PwMerror openDoc(const QString *file, int openLocked); /** export document to ascii-textfile */ PwMerror exportToText(const QString *file); /** export document to gpasman / kpasman file */ PwMerror exportToGpasman(const QString *file); /** import document from ascii-textfile */ PwMerror importFromText(const QString *file, int format = -1); /** import document from gpasman / kpasman file */ PwMerror importFromGpasman(const QString *file); /** add new entry */ PwMerror addEntry(const QString &category, PwMDataItem *d, bool dontFlagDirty = false, bool updateMeta = true); /** add new category. This function doesn't flag the document dirty! */ PwMerror addCategory(const QString &category, unsigned int *categoryIndex, bool checkIfExist = true); /** rename an existing category */ bool renameCategory(const QString &category, const QString &newName); /** rename an existing category */ bool renameCategory(unsigned int category, const QString &newName, bool dontFlagDirty = false); /** delete an existing category */ bool delCategory(const QString &category); /** delete an existing category */ bool delCategory(unsigned int category, bool dontFlagDirty = false); /** returns a list of all category-names */ void getCategoryList(vector<string> *list); /** returns a list of all category-names */ void getCategoryList(QStringList *list); /** returns a list of all entry-descs in the given category */ void getEntryList(const QString &category, QStringList *list); /** returns a list of all entry-descs in the given category */ void getEntryList(const QString &category, vector<string> *list); /** returns a list of all entry-descs in the given category */ void getEntryList(unsigned int category, vector<string> *list); /** returns a list of all entry-descs in the given category */ void getEntryList(unsigned int category, QStringList *list); /** delete entry */ bool delEntry(const QString &category, unsigned int index, bool dontFlagDirty = false); /** delete entry */ bool delEntry(unsigned int category, unsigned int index, bool dontFlagDirty = false); /** edit entry */ bool editEntry(const QString &oldCategory, const QString &newCategory, unsigned int index, PwMDataItem *d, bool updateMeta = true); /** edit entry */ bool editEntry(unsigned int oldCategory, const QString &newCategory, unsigned int index, PwMDataItem *d, bool updateMeta = true); /** finds the category with the "name" and return it's index */ bool findCategory(const QString &name, unsigned int *index); /** search for an entry "find" and check while searching only for * the data-fields specified by "searchIn". To set the "searchIn" * value, we may use one or more of the SEARCH_IN_* defines at * the top of this header-file. It returns the positions of all * matched entries in "foundPositions". If "breakAfterFound" is true, * the function terminates after the first occurence of the entry * and doesn't go on searching. So foundPositions->size() is never * > 1 if breakAfterFound is true. */ void findEntry(unsigned int category, PwMDataItem find, unsigned int searchIn, vector<unsigned int> *foundPositions, bool breakAfterFound = false, bool caseSensitive = true, bool exactWordMatch = true, bool sortByLvp = false); /** see the above funtion. This function allows to set the category by name. */ void findEntry(const QString &category, PwMDataItem find, unsigned int searchIn, vector<unsigned int> *foundPositions, bool breakAfterFound = false, bool caseSensitive = true, bool exactWordMatch = true, bool sortByLvp = false); /** returns number of entries */ unsigned int numEntries(const QString &category); unsigned int numEntries(unsigned int category) { return dti.dta[category].d.size(); } /** returns number of categories */ unsigned int numCategories() { return dti.dta.size(); } /** returns the name of the category at "index" */ const string* getCategory(unsigned int index) { return (&(dti.dta[index].name)); } /** returns the data of item at "index". * It unlocks the entry if it's locked and unlockIfLocked is true. * If the entry is locked, but unlockIfLocked is false, it'll not return * the pw. */ bool getEntry(const QString &category, unsigned int index, PwMDataItem *d, bool unlockIfLocked = false); bool getEntry(unsigned int category, unsigned int index, PwMDataItem *d, bool unlockIfLocked = false); /** returns the comment-string by looking at the category * and the listViewPos */ PwMerror getCommentByLvp(const QString &category, int listViewPos, string *foundComment); PwMerror getCommentByLvp_long(const QString &category, int listViewPos, string *foundComment); /** checks if a password is already available. (currentPw) */ bool isPwAvailable() { return (currentPw != ""); } /** un/lock entry at "index". If needed, ask for password. */ bool lockAt(const QString &category, unsigned int index, bool lock = true); bool lockAt(unsigned int category, unsigned int index, bool lock = true); /** returns the lock-status at "index" */ bool isLocked(const QString &category, unsigned int index); bool isLocked(unsigned int category, unsigned int index) { return dti.dta[category].d[index].lockStat; } /** returns the deeplock status */ bool isDeepLocked() { return getDocStatFlag(DOC_STAT_DEEPLOCKED); } /** (un)lock all entries */ bool lockAll(bool lock); /** unlocks all entries tempoarly. * 1st NOTE: Be very careful with this function! :) * 2nd NOTE: After you have called unlockAll_Tempoary(); , * please DON'T forget to call unlockAll_Tempoary(true); * _before_ the user (or someone else) is able to change * the document! * 3rd NOTE: Please DON'T change "dta" while the data is tempoary * unlocked! This will cause corruption. */ bool unlockAll_tempoary(bool revert = false); /** deep-(un)locks the document. * deep-locking writes all data to the file, deletes all data * in memory, but doesn't close the document. * deep-locking is only available, if the user previously saved * the doc to a file (with a password). * If "saveToFile" is false, it does NOT write the data to the file! */ PwMerror deepLock(bool lock = true, bool saveToFile = true); /** is unlockable without pw? */ bool unlockWoPw() { return getDocStatFlag(DOC_STAT_UNLOCK_WITHOUT_PW); } /** get the "currentPassword" */ const QString& getCurrentPw() { return currentPw; } /** open a window and request the user to change the mpw */ void changeCurrentPw(); /** set the "listViewPos" variable of "dta" */ void setListViewPos(const QString &category, unsigned int index, int pos); /** set the "listViewPos" variable of "dta" */ void setListViewPos(unsigned int category, unsigned int index, int pos); /** get the "listViewPos" variable of "dta" */ int getListViewPos(const QString &category, unsigned int index); /** set the maximum number of entries allowed */ void setMaxNumEntries(unsigned int num = DEFAULT_MAX_ENTRIES) { maxEntries = num; } /** get the maximum number of entries allowed */ unsigned int getMaxNumEntries() { return maxEntries; } /** ensure all listViewPos of all dta items are set. (are ! -1). * If there are some undefined entries, add them to the end of * the listViewPos(itions). */ void ensureLvp(); /** execute the "launcher" of this entry */ bool execLauncher(const QString &category, unsigned int entryIndex); /** see above */ bool execLauncher(unsigned int category, unsigned int entryIndex); /** open a browser with the URL-section of the given entry */ bool goToURL(const QString &category, unsigned int entryIndex); /** see above */ bool goToURL(unsigned int category, unsigned int entryIndex); /** returns true if there is no entry present in the document. * Note: The "default" Category is present everytime, so * it's checked for it's entries. */ bool isDocEmpty() { if (numCategories() > 1) return false; if (numEntries(0)) return false; return true; } /** returns the filename of this doc */ const QString& getFilename() { return filename; } /** returns the title of the doc */ QString getTitle(); /** sets the list-view-pointer hold in the doc */ void setListViewPointer(PwMView *_listView) { listView = _listView; } /** returns the list-view-pointer */ PwMView * getListViewPointer() { return listView; } /** try to delete the doc. The user may be asked to save * the data. The user may cancel the whole operation. * false is returned, then. */ bool tryDelete(); /** is the doc deleted? (with tryDelete() ) */ bool isDeleted() { return deleted; } /** returns the document timer object */ DocTimer * timer() { return _timer; } /** get a lock on the dataChanged signal. * If someone is holding a lock, the signal is not emitted. */ void getDataChangedLock() { ++dataChangedLock; } /** put the dataChanged lock */ void putDataChangedLock() { --dataChangedLock; } /** returns the revision count of the item at cat/index */ unsigned int getEntryRevCnt(unsigned int category, unsigned int index) { return dti.dta[category].d[index].rev; } /** returns a const pointer to the entries meta */ const PwMMetaData * getEntryMeta(unsigned int category, unsigned int index) { return &(dti.dta[category].d[index].meta); } /** is the entry at "category" "index" a binary entry? */ bool isBinEntry(unsigned int category, unsigned int index) { return dti.dta[category].d[index].binary; } public slots: /** wrapper for PwMTray */ void _deepUnlock(); signals: /** the data of the document has changed and must be updated * in all views. * NOTE: use emitDataChanged(PwMDoc *document) to emit this signal! */ void dataChanged(PwMDoc *document); /** the document class is going to close. This signal may be * used to nofify all views, that the user closed the document, * so the views can go down, too. */ void docClosed(PwMDoc *document); /** somebody just opened the document */ void docOpened(PwMDoc *document); /** this document object just got created */ void docCreated(PwMDoc *document); public: /** emit the dataChanged signal after checking for a lock */ void emitDataChanged(PwMDoc *document) { if (!dataChangedLock) emit dataChanged(document); } protected: /** current file for this doc */ QString filename; //US ENH: we need a place where we keep the syncentries. So I invented // struct PwMItem, that has a vector of PwMCategoryItem and vector of PwMSyncItem /** holds all data */ PwMItem dti; /** maximum number of entries */ unsigned int maxEntries; /** currently used password to encrypt data */ QString currentPw; /** current global document status flags */ unsigned int curDocStat; /** browser process for goToURL() */ KProcess browserProc; /** pointer to the list-view, using this document. * As there can only be one list-view per doc, we * don't need a list here. */ PwMView *listView; /** unnamedNum is used to store the "unnamed counter" * for this document, while it's unnamed. If it's 0, * we have to get a new unique one. */ unsigned int unnamedNum; /** is this doc going to be deleted (executing in destructor context) */ bool deleted; /** document timer */ DocTimer *_timer; /** lock counter for the "dataChanged" signal */ unsigned int dataChangedLock; /** list of all open documents */ static PwMDocList openDocList; protected: /** serialize "dta" and return it in "d". */ bool serializeDta(string *d); /** de-serialize "d" and overwrite "dta" */ bool deSerializeDta(const string *d, bool entriesLocked); /** write header to file */ PwMerror writeFileHeader(char keyHash, char dataHash, char crypt, char compress, QString *pw, QFile *f); /** write data-hash to file */ PwMerror writeDataHash(char dataHash, string *d, QFile *f); /** check header. Read header info and verify key-hash and filever. * returns length of header in "headerLength" */ PwMerror checkHeader(char *cryptAlgo, QString *pw, char *compress, unsigned int *headerLength, char *dataHashType, string *dataHash, QFile *f); /** check the data-hash */ PwMerror checkDataHash(char dataHashType, const string *dataHash, const string *dataStream); /** encrypt data "d" and write to "filename" */ PwMerror encrypt(string *d, const QString *pw, QFile *f, char algo, char _hashalgo //US BUG: pass _hashalgo because we need it in hashPassphrase diff --git a/pwmanager/pwmanager/pwmdocui.cpp b/pwmanager/pwmanager/pwmdocui.cpp index a9916c2..ea96509 100644 --- a/pwmanager/pwmanager/pwmdocui.cpp +++ b/pwmanager/pwmanager/pwmdocui.cpp @@ -1,470 +1,470 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmdocui.h" #include "setmasterpwwndimpl.h" #include "getmasterpwwndimpl.h" #include "pwmexception.h" #include "getkeycardwnd.h" #include "pwm.h" #include "globalstuff.h" #include "spinforsignal.h" #include <qlineedit.h> #include <qtabwidget.h> #include <kmessagebox.h> #include <kfiledialog.h> #ifndef PWM_EMBEDDED #include <kwin.h> #else #include <qdir.h> #include "pwmprefs.h" #endif #ifdef CONFIG_KEYCARD # include "pwmkeycard.h" #endif PwMDocUi::PwMDocUi(QObject *parent, const char *name) : QObject(parent, name) { currentView = 0; keyCard = 0; } PwMDocUi::~PwMDocUi() { } QString PwMDocUi::requestMpw(bool chipcard) { QString pw; if (chipcard) { #ifdef CONFIG_KEYCARD PWM_ASSERT(keyCard); uint32_t id; string ret; SpinForSignal *spinner = keyCard->getSpinner(); connect(keyCard, SIGNAL(keyAvailable(uint32_t, const string &)), spinner, SLOT(u32_str_slot(uint32_t, const string &))); keyCard->getKey(); spinner->spin(&id, &ret); disconnect(keyCard, SIGNAL(keyAvailable(uint32_t, const string &)), spinner, SLOT(u32_str_slot(uint32_t, const string &))); if (ret == "") return ""; pw = ret.c_str(); #else // CONFIG_KEYCARD no_keycard_support_msg_box(currentView); #endif // CONFIG_KEYCARD } else { #ifndef PWM_EMBEDDED GetMasterPwWndImpl pwWnd; KWin::setState(pwWnd.winId(), NET::StaysOnTop); #else GetMasterPwWndImpl pwWnd; #endif if (pwWnd.exec() != 1) return ""; pw = pwWnd.pwLineEdit->text(); } return pw; } QString PwMDocUi::requestNewMpw(bool *chipcard) { QString pw; SetMasterPwWndImpl pwWnd(currentView); pwWnd.setPwMKeyCard(keyCard); if (!chipcard) { #ifndef PWM_EMBEDDED pwWnd.mainTab->removePage(pwWnd.mainTab->page(1)); #else pwWnd.mainTab->removePage(pwWnd.tab_2); #endif } if (pwWnd.exec() != 1) return ""; pw = pwWnd.getPw(chipcard).c_str(); return pw; } QString PwMDocUi::requestMpwChange(const QString *currentPw, bool *chipcard) { QString pw(requestMpw(*chipcard)); if (pw == "") return ""; if (pw != *currentPw) { wrongMpwMsgBox(*chipcard); return ""; } pw = requestNewMpw(chipcard); if (pw == "") return ""; return pw; } void PwMDocUi::wrongMpwMsgBox(bool chipcard, QString prefix, QString postfix) { QString msg; if (prefix != "") { msg += prefix; msg += "\n"; } if (chipcard) { msg += i18n("Wrong key-card!\n" "Please try again with the\n" "correct key-card."); } else { msg += i18n("Wrong master-password!\n" "Please try again."); } if (postfix != "") { msg += "\n"; msg += postfix; } KMessageBox::error(currentView, msg, (chipcard) ? (i18n("wrong chipcard")) : (i18n("password error"))); } void PwMDocUi::noMpwMsgBox(bool chipcard, QString prefix, QString postfix) { QString msg; if (prefix != "") { msg += prefix; msg += "\n"; } if (chipcard) { msg += i18n("No key-card found!\n" "Please insert the\n" "correct key-card."); } else { msg += i18n("No master-password given!"); } if (postfix != "") { msg += "\n"; msg += postfix; } KMessageBox::error(currentView, msg, (chipcard) ? (i18n("no chipcard")) : (i18n("password error"))); } void PwMDocUi::rootAlertMsgBox() { KMessageBox::error(currentView, i18n("This feature is not available,n" "if you execute PwM with \"root\" \n" "UID 0 privileges, for security reasons!"), i18n("not allowed as root!")); } void PwMDocUi::cantDeeplock_notSavedMsgBox() { KMessageBox::error(currentView, i18n("Can't deep-lock, because the document\n" "hasn't been saved, yet. Please save\n" "to a file and try again."), i18n("not saved, yet")); } void PwMDocUi::gpmPwLenErrMsgBox() { KMessageBox::error(currentView, i18n("GPasman does not support passwords\n" "shorter than 4 characters! Please try\n" "again with a longer password."), i18n("Password too short")); } int PwMDocUi::dirtyAskSave(const QString &docTitle) { int ret; #ifndef PWM_EMBEDDED ret = KMessageBox::questionYesNoCancel(currentView, i18n("The list\n\"") + docTitle + i18n ("\" has been modified.\n" "Do you want to save it?"), i18n("Save?")); if (ret == KMessageBox::Yes) { return 0; } else if (ret == KMessageBox::No) { return 1; } #else QString doc = docTitle; if ( doc.length() > 33 ) doc = "..." + doc.right(30); ret = KMessageBox::warningYesNoCancel(currentView, i18n("The list\n \"") + doc + i18n ("\"\nhas been modified.\n" "Do you want to save it?"), i18n("Save?")); if (ret == KMessageBox::Yes) { return 0; } else if (ret == KMessageBox::No) { return 1; } #endif // cancel return -1; } bool PwMDocUi::saveDocUi(PwMDoc *doc) { PWM_ASSERT(doc); doc->timer()->getLock(DocTimer::id_autoLockTimer); if (doc->isDocEmpty()) { KMessageBox::information(currentView, i18n ("Sorry, there's nothing to save.\n" "Please first add some passwords."), i18n("nothing to do")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return true; } PwMerror ret = doc->saveDoc(conf()->confGlobCompression()); if (ret == e_filename) { doc->timer()->putLock(DocTimer::id_autoLockTimer); return saveAsDocUi(doc); } else if (ret == e_weakPw) { KMessageBox::error(currentView, i18n("Error: This is a weak password.\n" "Please select another password."), i18n("weak password")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return false; } else if (ret == e_fileBackup) { KMessageBox::error(currentView, i18n("Error: Couldn't make backup-file!"), i18n("backup failed")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return false; } else if (ret == e_noPw || ret == e_wrongPw || ret == e_openFile) { doc->timer()->putLock(DocTimer::id_autoLockTimer); return false; } else if (ret != e_success) { KMessageBox::error(currentView, i18n("Error: Couldn't write to file.\n" "Please check if you have permission to\n" "write to the file in that directory."), i18n("error while writing")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return false; } doc->timer()->putLock(DocTimer::id_autoLockTimer); return true; } bool PwMDocUi::saveAsDocUi(PwMDoc *doc) { PWM_ASSERT(doc); doc->timer()->getLock(DocTimer::id_autoLockTimer); if (doc->isDocEmpty()) { KMessageBox::information(currentView, i18n ("Sorry, there's nothing to save.\n" "Please first add some passwords."), i18n("nothing to do")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return true; } #ifndef PWM_EMBEDDED QString fn(KFileDialog::getSaveFileName(QString::null, i18n("*.pwm|PwManager Password file"), currentView)); #else QString fn = locateLocal( "data", KGlobal::getAppName() + "/*.pwm" ); fn = KFileDialog::getSaveFileName(fn, i18n("password filename(*.pwm)"), currentView); #endif if (fn == "") { doc->timer()->putLock(DocTimer::id_autoLockTimer); return false; } if (fn.right(4) != ".pwm") fn += ".pwm"; PwMerror ret = doc->saveDoc(conf()->confGlobCompression(), &fn); if (ret == e_noPw || ret == e_wrongPw || ret == e_openFile) { doc->timer()->putLock(DocTimer::id_autoLockTimer); return false; } else if (ret != e_success) { KMessageBox::error(currentView, i18n("Error: Couldn't write to file.\n" "Please check if you have permission to\n" "write to the file in that directory."), i18n("error while writing")); doc->timer()->putLock(DocTimer::id_autoLockTimer); return false; } doc->timer()->putLock(DocTimer::id_autoLockTimer); return true; } bool PwMDocUi::openDocUi(PwMDoc *doc, QString filename, bool openDeepLocked) { if (filename.isEmpty()) { #ifndef PWM_EMBEDDED filename = KFileDialog::getOpenFileName(QString::null, i18n("*.pwm|PwManager Password file\n" "*|All files"), getCurrentView()); #else filename = locateLocal( "data", KGlobal::getAppName() + "/*.pwm"); filename = KFileDialog::getOpenFileName(filename, i18n("password filename(*.pwm)"), getCurrentView()); #endif } if (filename.isEmpty()) goto cancelOpen; PwMerror ret; while (true) { int lockStat = -1; if (openDeepLocked) { lockStat = 2; } else { if (conf()->confGlobUnlockOnOpen()) { lockStat = 0; } else { lockStat = 1; } } ret = doc->openDoc(&filename, lockStat); //qDebug("pwmdocui::OpenDocui %i", ret); if (ret != e_success) { if (ret == e_readFile || ret == e_openFile) { KMessageBox::error(getCurrentView(), i18n("Could not read file!") + "\n" + filename, i18n("File error")); goto cancelOpen; } if (ret == e_alreadyOpen) { KMessageBox::error(getCurrentView(), i18n("This file is already open."), i18n("Already open")); goto cancelOpen; } if (ret == e_fileVer) { KMessageBox::error(getCurrentView(), i18n ("File-version is not supported!\n" "Did you create this file with an\nolder or newer version of PwM?"), i18n ("Incompatible version")); goto cancelOpen; } if (ret == e_wrongPw) { continue; } if (ret == e_noPw) { goto cancelOpen; } if (ret == e_fileFormat) { KMessageBox::error(getCurrentView(), i18n ("Sorry, this file has not been recognized\n" "as a PwM Password file.\n" "Probably you have selected the wrong file."), i18n ("No PwM password-file")); goto cancelOpen; } if (ret == e_fileCorrupt) { KMessageBox::error(getCurrentView(), i18n ("File corrupt!\n" "Maybe the media, you stored this file on,\n" "had bad sectors?"), i18n ("Checksum error")); goto cancelOpen; } } break; } return true; cancelOpen: return false; } QString PwMDocUi::string_defaultCategory() { return i18n("Default"); } QString PwMDocUi::string_locked() { return i18n("<LOCKED>"); } QString PwMDocUi::string_deepLockedShort() { return i18n("DEEP-LOCKED"); } QString PwMDocUi::string_deepLockedLong() { return i18n("This file is DEEP-LOCKED!\n" "That means all data has been encrypted\n" "and written out to the file. If you want\n" "to see the entries, please UNLOCK the file.\n" "While unlocking, you will be prompted for the\n" "master-password or the key-card."); } QString PwMDocUi::string_defaultTitle() { return i18n("Untitled"); } -#ifndef PWM_EMBEDDED -#include "pwmdocui.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwmdocui.cpp" #endif diff --git a/pwmanager/pwmanager/pwminit.cpp b/pwmanager/pwmanager/pwminit.cpp index d59d4d8..15e21ee 100644 --- a/pwmanager/pwmanager/pwminit.cpp +++ b/pwmanager/pwmanager/pwminit.cpp @@ -1,661 +1,662 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwminit.h" #include "randomizer.h" #include <qdir.h> +//Added by qt3to4: +#include <Q3ValueList> #ifndef PWM_EMBEDDED #include "selftest.h" #include "configuration.h" #else #include "pwmprefs.h" #endif #include "pwm.h" #include "pwmexception.h" #include "pwmtray.h" #include "pwmdoc.h" #ifdef CONFIG_KWALLETIF # include "kwalletemu.h" #endif // CONFIG_KWALLETIF #ifdef CONFIG_KEYCARD # include "pwmkeycard.h" #endif // CONFIG_KEYCARD #include <qmessagebox.h> #include <kmessagebox.h> #ifndef PWM_EMBEDDED #include <kcmdlineargs.h> #include <kwin.h> #include <dcopclient.h> #endif #include <kapplication.h> #include <kiconloader.h> #include <signal.h> static PwMInit *sig_init_pointer; #ifdef _WIN32_ static void sig_handler(int signum) #else static NOREGPARM void sig_handler(int signum) #endif { switch (signum) { case SIGINT: case SIGTERM: sig_init_pointer->shutdownApp(20 + signum); break; default: printDebug(string("unhandled signal ") + tostr(signum)); } } PwMInit::PwMInit(PwMApplication *_app) : runStatus (unknown) , _curWidget (0) , _dcopClient (0) , _kwalletEmu (0) , _keycard (0) , _tray (0) { sig_init_pointer = this; app = _app; } PwMInit::~PwMInit() { //qDebug("PwMInit::~PwMInit() "); #ifndef PWM_EMBEDDED SelfTest::cancel(); // close all open mainwnds - QValueList<PwM *>::iterator i = _mainWndList.begin(), + Q3ValueList<PwM *>::iterator i = _mainWndList.begin(), end = _mainWndList.end(); #else // close all open mainwnds - QValueList<PwM *>::Iterator i = _mainWndList.begin(), + Q3ValueList<PwM *>::Iterator i = _mainWndList.begin(), end = _mainWndList.end(); #endif while (i != end) { disconnect(*i, SIGNAL(closed(PwM *)), this, SLOT(mainWndClosed(PwM *))); delete *i; ++i; } _mainWndList.clear(); // close all remaining open documents PwMDocList *_dl = PwMDoc::getOpenDocList(); vector<PwMDocList::listItem> dl = *(_dl->getList()); vector<PwMDocList::listItem>::iterator i2 = dl.begin(), end2 = dl.end(); while (i2 != end2) { delete (*i2).doc; ++i2; } #ifdef CONFIG_KWALLETIF delete_ifnot_null(_kwalletEmu); #endif // CONFIG_KWALLETIF #ifdef CONFIG_KEYCARD delete_ifnot_null(_keycard); #endif // CONFIG_KEYCARD delete_ifnot_null(_tray); Randomizer::cleanup(); #ifndef PWM_EMBEDDED Configuration::cleanup(); #endif } void PwMInit::initializeApp() { //qDebug("PwMInit::initializeApp() "); PWM_ASSERT(runStatus == unknown); runStatus = init; initPosixSignalHandler(); Randomizer::init(); #ifndef PWM_EMBEDDED Configuration::init(); #endif initDCOP(); initKWalletEmu(); initKeycard(); initTray(); handleCmdLineArgs(); bool openDeeplocked = false; if (conf()->confGlobAutostartDeepLocked() || savedCmd.open_deeplocked) openDeeplocked = true; if ( false ){ // LR is not working //if (conf()->confWndAutoMinimizeOnStart() || // savedCmd.minToTray) { PwMDoc *newDoc = createDoc(); //qDebug(" createDoc()"); if (!newDoc->openDocUi(newDoc, conf()->confGlobAutoStart(), openDeeplocked)) { delete newDoc; } //US ENH for embedded devices: in the case of failure, open a document the default way createMainWnd(conf()->confGlobAutoStart(), openDeeplocked, true, 0, savedCmd.minimized); // } } else { createMainWnd(conf()->confGlobAutoStart(), openDeeplocked, true, 0, savedCmd.minimized); } runStatus = running; } void PwMInit::shutdownApp(int exitStatus) { PwM * iii;; while ( _mainWndList.count() ) { iii = _mainWndList.first(); disconnect(iii, SIGNAL(closed(PwM *)), this, SLOT(mainWndClosed(PwM *))); mainWndClosed((iii)); } printDebug(string("PwMInit::shutdownApp(") + tostr(exitStatus) + ") called."); PWM_ASSERT((runStatus == running) || (runStatus == init)); runStatus = shutdown; QApplication::exit(exitStatus); /* The destructor of PwMInit is called when control * leaves main() */ } void PwMInit::initPosixSignalHandler() { signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); } void PwMInit::initDCOP() { #ifndef PWM_EMBEDDED _dcopClient = app->dcopClient(); _dcopClient->setNotifications(true); #endif } void PwMInit::initKWalletEmu(bool forceDisable, bool forceReload) { #ifdef CONFIG_KWALLETIF if (!conf()->confGlobKwalletEmu() || forceDisable) { delete_ifnot_null(_kwalletEmu); return; } try { if (_kwalletEmu && forceReload) delete_and_null(_kwalletEmu); if (!_kwalletEmu) _kwalletEmu = new KWalletEmu(this); } catch (PwMException e) { string errMsg("initializing KWallet emulation failed. ID: "); errMsg += tostr(static_cast<int>(e.getId())); errMsg += " err-message: "; errMsg += e.getMessage(); printWarn(errMsg); return; } #else // CONFIG_KWALLETIF PARAM_UNUSED(forceDisable); PARAM_UNUSED(forceReload); #endif // CONFIG_KWALLETIF } void PwMInit::initKeycard() { #ifdef CONFIG_KEYCARD PWM_ASSERT(!_keycard); _keycard = new PwMKeyCard(this); #endif // CONFIG_KEYCARD } void PwMInit::initTray() { #ifdef PWM_EMBEDDED //US ENH : embedded version does not support a tray return; #endif if (!conf()->confGlobTray()) { if (!_tray) return; _tray->hide(); delete_and_null(_tray); return; } if (_tray) return; _tray = new PwMTray(this); connect(_tray, SIGNAL(quitSelected()), this, SLOT(removeTrayAndQuit())); connect(_tray, SIGNAL(closed(PwMTray *)), this, SLOT(trayIconClosed(PwMTray *))); KIconLoader icons; #ifndef PWM_EMBEDDED _tray->setPixmap(icons.loadIcon(PACKAGE_NAME, KIcon::Small)); #endif _tray->show(); // connect the signals of all open documents. const vector<PwMDocList::listItem> *dl = PwMDoc::getOpenDocList()->getList(); vector<PwMDocList::listItem>::const_iterator i = dl->begin(), end = dl->end(); while (i != end) { _tray->connectDocToTray((*i).doc); ++i; } } void PwMInit::removeTrayAndQuit() { PWM_ASSERT(_tray); // _tray is deleted in ~PwMInit shutdownApp(0); } PwM * PwMInit::createMainWnd(const QString &loadFile, bool loadFileDeepLocked, bool virginity, PwMDoc *doc, bool minimized) { PwM *newWnd; if (!doc) doc = createDoc(); newWnd = new PwM(this, doc, virginity); #ifndef PWM_EMBEDDED _mainWndList.push_back(newWnd); #else _mainWndList.append(newWnd); #endif connect(newWnd, SIGNAL(closed(PwM *)), this, SLOT(mainWndClosed(PwM *))); connect(newWnd, SIGNAL(gotFocus(PwM *)), this, SLOT(setCurWidget(PwM *))); connect(newWnd, SIGNAL(lostFocus(PwM *)), this, SLOT(resetCurWidget())); //US ENH #ifndef PWM_EMBEDDED if (minimized) newWnd->showMinimized(); else newWnd->show(); #else //PWM_EMBEDDED #ifndef DESKTOP_VERSION app->showMainWidget( newWnd ); #else //DESKTOP_VERSION newWnd->resize (640, 480 ); newWnd->show(); #endif //DESKTOP_VERSION #endif //PWM_EMBEDDED if (loadFile != QString::null && loadFile != "") { newWnd->openDoc(loadFile, loadFileDeepLocked); } return newWnd; } PwMDoc * PwMInit::createDoc() { PwMDoc *doc = new PwMDoc(this); #ifdef CONFIG_KEYCARD doc->setPwMKeyCard(keycard()); #endif #ifdef CONFIG_KWALLETIF if (kwalletEmu()) kwalletEmu()->connectDocSignals(doc); #endif if (_tray) _tray->connectDocToTray(doc); return doc; } void PwMInit::mainWndClosed(PwM *wnd) { bool doMinimizeToTray = false; bool doDeleteDoc = false; #ifndef PWM_EMBEDDED dcopClient()->suspend(); dcopClient()->setAcceptCalls(false); #endif again: if (wnd->isForceMinimizeToTray()) { if (unlikely(!_tray)) { /* This should not happen! If we set forceMinimizeToTray , * we must be sure that _tray exists. */ BUG(); wnd->setForceMinimizeToTray(false); goto again; } doMinimizeToTray = true; } else { // Ask to minimize to tray. If not, delete doc. if (_tray && runStatus != shutdown && !wnd->isForceQuit() && !wnd->curDoc()->isDeleted()) { if (conf()->confWndClose()) doDeleteDoc = true; else doMinimizeToTray = true; } else { doDeleteDoc = true; } } if (doMinimizeToTray) { //qDebug("doMinimizeToTray "); PWM_ASSERT(_tray); int mmlock = conf()->confGlobMinimizeLock(); switch (mmlock) { case 0: // don't lock anything break; case 1: // normal lock wnd->curDoc()->lockAll(true); break; case 2: // deep-lock wnd->curDoc()->deepLock(); break; default: WARN(); } } else if (doDeleteDoc) { //qDebug("doDeleteDoc "); if (!wnd->curDoc()->tryDelete()) { /* We failed deleting the doc, * so open a new window with it, again. */ createMainWnd(QString::null, false, false, wnd->curDoc()); } } #ifndef PWM_EMBEDDED // find the closed window in the "mainWndList" and delete it. - QValueList<PwM *>::iterator i = _mainWndList.begin(), + Q3ValueList<PwM *>::iterator i = _mainWndList.begin(), end = _mainWndList.end(); #else // find the closed window in the "mainWndList" and delete it. - QValueList<PwM *>::Iterator i = _mainWndList.begin(), + Q3ValueList<PwM *>::Iterator i = _mainWndList.begin(), end = _mainWndList.end(); #endif while (i != end) { //qDebug("iii %x end %x wnd %x", (*i), (*end), wnd); if (*i == wnd) { #ifndef PWM_EMBEDDED _mainWndList.erase(i); #else _mainWndList.remove(i); #endif if ( app->mainWidget() == wnd ) { if ( _mainWndList.count() ) { #ifndef DESKTOP_VERSION app->showMainWidget(_mainWndList.first() ); #endif //DESKTOP_VERSION } } delete wnd; goto out_success; } ++i; } BUG(); out_success: #ifndef PWM_EMBEDDED if (!_mainWndList.size()) #else if (!_mainWndList.count()) #endif { /* If there's no main window and no tray icon * left, we have no user interface, so we can * shut down the application. */ if (!_tray) { #ifndef PWM_EMBEDDED dcopClient()->setAcceptCalls(true); dcopClient()->resume(); #endif shutdownApp(0); return; } /* There is no widget left, so set * _curWidget to 0 */ resetCurWidget(); } #ifndef PWM_EMBEDDED dcopClient()->setAcceptCalls(true); dcopClient()->resume(); #endif } void PwMInit::trayIconClosed(PwMTray *tray) { if (runStatus != running) return; PARAM_UNUSED(tray); PWM_ASSERT(tray == _tray); /* If there's no main wnd left we have to * shutdown the app (same as in mainWndClosed()) */ #ifndef PWM_EMBEDDED if (!_mainWndList.size()) shutdownApp(0); #else if (!_mainWndList.count()) shutdownApp(0); #endif } void PwMInit::handleCmdLineArgs(bool initial) { #ifndef PWM_EMBEDDED KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); PWM_ASSERT(args); int i, numArgs = args->count(); const char *curArg; // read all cmdline options savedCmd.open_deeplocked = args->isSet("open-deeplocked"); savedCmd.minimized = args->isSet("minimized"); savedCmd.minToTray = args->isSet("mintray"); savedCmd.skipSelfTest = args->isSet("skip-self-test"); if (savedCmd.minimized && savedCmd.minToTray) { printInfo(i18n("Commandline option \"--minimized\" and " "\"--mintray\" selected. These are incompatible. " "\"--mintray\" will be selected.").latin1()); } /* Iterate through all non-option arguments. * Every non-option arg is a filename to open. */ for (i = 0; i < numArgs; ++i) { curArg = args->arg(i); PWM_ASSERT(curArg); if (savedCmd.minToTray) { PwMDoc *newDoc = createDoc(); if (!newDoc->openDocUi(newDoc, curArg, savedCmd.open_deeplocked)) { delete newDoc; } } else { PwM *newInstance = createMainWnd(QString::null, false, true, 0, savedCmd.minimized); PwMDoc *newDoc = newInstance->openDoc(curArg, savedCmd.open_deeplocked); if (!newDoc) { newInstance->setForceQuit(true); delete_and_null(newInstance); } } } if (savedCmd.minToTray) { minimizeAllMainWnd(true); } else if (savedCmd.minimized) { minimizeAllMainWnd(false); } if (!savedCmd.skipSelfTest && initial) { SelfTest::schedule(); } args->clear(); #endif } void PwMInit::minimizeAllMainWnd(bool toTray) { #ifndef PWM_EMBEDDED if (!_mainWndList.size()) return; #else if (!_mainWndList.count()) return; #endif - const QValueList<PwM *> *ml = mainWndList(); + const Q3ValueList<PwM *> *ml = mainWndList(); #ifndef PWM_EMBEDDED - QValueList<PwM *>::const_iterator it = ml->begin(), + Q3ValueList<PwM *>::const_iterator it = ml->begin(), end = ml->end(); #else - QValueList<PwM *>::ConstIterator it = ml->begin(), + Q3ValueList<PwM *>::ConstIterator it = ml->begin(), end = ml->end(); #endif PwM *wnd; if (toTray && _tray) { /* minimize to tray. * close all mainWnd. */ while (it != end) { wnd = *it; wnd->setForceMinimizeToTray(true); wnd->close_slot(); ++it; } } else { // normal minimize while (it != end) { wnd = *it; wnd->hide(); wnd->showMinimized(); ++it; } } } #ifdef PWM_EMBEDDED #ifndef DESKTOP_VERSION PwMApplication::PwMApplication(int & argc, char ** argv) : QPEApplication( argc, argv ) , init (0) { this->setKeepRunning (); } PwMApplication::~PwMApplication() { delete_ifnot_null(init); } #else //DESKTOP_VERSION PwMApplication::PwMApplication(int & argc, char ** argv) : QApplication( argc, argv ) , init (0) { - setStyle( new QPlatinumStyle ()); QString hdir = QDir::homeDirPath(); // there is a bug when creating dirs for WIN 98 // it is difficult to fix, because we have no WIN 98 runnung // such that we try it to create the dirs at startup here if ( hdir == "C:\\" ) { // win 98 or ME QDir app_dir; if ( !app_dir.exists("C:\\kdepim") ) app_dir.mkdir ("C:\\kdepim"); if ( !app_dir.exists("C:\\kdepim\\apps") ) app_dir.mkdir ("C:\\kdepim\\apps"); if ( !app_dir.exists("C:\\kdepim\\config") ) app_dir.mkdir ("C:\\kdepim\\config"); if ( !app_dir.exists("C:\\kdepim\\apps\\pwmanager") ) app_dir.mkdir ("C:\\kdepim\\apps\\pwmanager"); } } PwMApplication::~PwMApplication() { delete_ifnot_null(init); } #endif //DESKTOP_VERSION #endif //PWM_EMBEDDED -#ifndef PWM_EMBEDDED -#include "pwminit.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwminit.cpp" #endif diff --git a/pwmanager/pwmanager/pwminit.h b/pwmanager/pwmanager/pwminit.h index bf72093..32d1b4f 100644 --- a/pwmanager/pwmanager/pwminit.h +++ b/pwmanager/pwmanager/pwminit.h @@ -1,222 +1,221 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __PWMINIT_H #define __PWMINIT_H -#include <qvaluelist.h> +#include <q3valuelist.h> #include <qobject.h> #ifndef PWM_EMBEDDED #include <kuniqueapplication.h> #else //PWM_EMBEDDED #ifndef DESKTOP_VERSION #include <qpe/qpeapplication.h> #else //DESKTOP_VERSION #include <qapplication.h> -#include <qplatinumstyle.h> #endif //DESKTOP_VERSION #include <kapplication.h> #endif //PWM_EMBEDDED #include "globalstuff.h" class DCOPClient; class KWalletEmu; class PwMKeyCard; class KApplication; class QWidget; class PwM; class PwMTray; class PwMDoc; class PwMInit; /** main application class */ #ifndef PWM_EMBEDDED -//MOC_SKIP_BEGIN +#ifndef Q_MOC_RUN class PwMApplication : public KUniqueApplication { public: PwMApplication(bool allowStyles=true, bool GUIenabled=true, bool configUnique=false) : KUniqueApplication(allowStyles, GUIenabled, configUnique) , init (0) { } ~PwMApplication() { delete_ifnot_null(init); } int newInstance(); protected: PwMInit *init; }; -//MOC_SKIP_END +#endif #else //PWM_EMBEDDED #ifndef DESKTOP_VERSION class PwMApplication : public QPEApplication { public: PwMApplication(int & argc, char ** argv); ~PwMApplication(); int newInstance(); protected: PwMInit *init; }; #else //DESKTOP_VERSION class PwMApplication : public QApplication { public: PwMApplication(int & argc, char ** argv); ~PwMApplication(); int newInstance(); protected: PwMInit *init; }; #endif #endif /** PwManager initialisation class. * This class sets up a new instance of PwManager and finally * starts the user interface. */ class PwMInit : public QObject { Q_OBJECT friend class PwMApplication; protected: enum RunStatus { unknown, init, running, shutdown, }; /* saved command line options. */ class savedCmd_t { public: bool open_deeplocked; bool minimized; bool minToTray; bool skipSelfTest; // initial open paths are not saved here. }; public: PwMInit(PwMApplication *_app); ~PwMInit(); /** Initialize the application. */ void initializeApp(); /** shutdown PwManager */ void shutdownApp(int exitStatus); /** returns a pointer to the current widget */ QWidget * curWidget() { return _curWidget; } /** returns a pointer to the dcop client */ DCOPClient * dcopClient() { return _dcopClient; } /** returns a pointer to the KWallet emulation */ KWalletEmu * kwalletEmu() { return _kwalletEmu; } /** returns a pointer to the keycard interface */ PwMKeyCard * keycard() { return _keycard; } /** returns a pointer to the tray icon */ PwMTray * tray() { return _tray; } /** returns a list of all open main windows */ - const QValueList<PwM *> * mainWndList() + const Q3ValueList<PwM *> * mainWndList() { return &_mainWndList; } /** create a new document */ PwMDoc * createDoc(); /** create a new PwM main window */ PwM * createMainWnd(const QString &loadFile = QString::null, bool loadFileDeepLocked = false, bool virginity = true, PwMDoc *doc = 0, bool minimized = false); /** (re)initialize the KWallet emulation */ void initKWalletEmu(bool forceDisable = false, bool forceReload = false); /** (re)initialize the tray icon */ void initTray(); protected: /** initialize the DCOP connection */ void initDCOP(); /** initialize the keycard interface */ void initKeycard(); /** initialize posix signal handling */ void initPosixSignalHandler(); /** handle the commandline args */ void handleCmdLineArgs(bool initial = true); /** minimize all open mainWnds to tray (or if * no tray is present, minimize them the normal way) */ void minimizeAllMainWnd(bool toTray); protected slots: /** a main window got closed */ void mainWndClosed(PwM *wnd); /** the tray icon got closed */ void trayIconClosed(PwMTray *tray); /** sets _curWidget on behalf of a PwM signal */ void setCurWidget(PwM *w) { _curWidget = reinterpret_cast<QWidget *>(w); } /** resets _curWidget to nothing */ void resetCurWidget() { _curWidget = 0; } /** remove the tray and quit the app */ void removeTrayAndQuit(); protected: /** run-status of the app */ RunStatus runStatus; /** PwMApplication pointer */ PwMApplication *app; /** pointer to the current widget the user is dealing with */ QWidget *_curWidget; /** pointer to the dcop client */ DCOPClient *_dcopClient; /** pointer to the KWallet emulation */ KWalletEmu *_kwalletEmu; /** pointer to the keycard interface */ PwMKeyCard *_keycard; /** pointer to the tray icon */ PwMTray *_tray; /** list of all open main windows */ - QValueList<PwM *> _mainWndList; + Q3ValueList<PwM *> _mainWndList; /** saved command line options. */ savedCmd_t savedCmd; }; #endif // __PWMINIT_H diff --git a/pwmanager/pwmanager/pwmprefs.h b/pwmanager/pwmanager/pwmprefs.h index 1f6a35c..42f7c2e 100644 --- a/pwmanager/pwmanager/pwmprefs.h +++ b/pwmanager/pwmanager/pwmprefs.h @@ -1,166 +1,168 @@ /* This file is part of PwManager/Pi Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #ifndef PWMPREFS_H #define PWMPREFS_H #include <qstringlist.h> #include <qsize.h> +//Added by qt3to4: +#include <Q3ValueList> #include <kpimprefs.h> class KConfig; #define conf() PWMPrefs::instance() #define CONF_DEFAULT_PWTIMEOUT 10/* 10 sec */ #define CONF_DEFAULT_LOCKTIMEOUT 0/* 0 == disable */ #define CONF_DEFAULT_TRAY false #define CONF_DEFAULT_UNLOCKONOPEN true #define CONF_DEFAULT_MAINVIEWSTYLE 1/* Category List Left */ #define CONF_DEFAULT_COMPRESSION 0x01/* gzip */ #define CONF_DEFAULT_CRYPTALGO (0x01 - 1)/* blowfish */ #define CONF_DEFAULT_HASHALGO (0x01 - 1)/* sha1 */ #define CONF_DEFAULT_AUTOMINIMIZE false #define CONF_DEFAULT_BROWSERCOMMAND "" #define CONF_DEFAULT_XTERMCOMMAND "konsole -e" #define CONF_DEFAULT_FILEPERMISSIONS 0600 #define CONF_DEFAULT_MAKEFILEBACKUP false #define CONF_DEFAULT_AUTOSTART_DEEPL true #define CONF_DEFAULT_AUTODEEPLOCK true #define CONF_DEFAULT_KWALLETEMU false #define CONF_DEFAULT_MINIMIZELOCK 2/* deep-lock */ #define CONF_DEFAULT_NEWENTRLOCKSTAT false/* new entries unlocked */ #define CONF_DEFAULT_WNDCLOSE true/* don't minimize to tray */ class PWMPrefs : public KPimPrefs { public: virtual ~PWMPrefs(); static PWMPrefs *instance(); public: /* functions for reading the configuration settings */ /* GLOBAL */ QString confGlobAutoStart(); QString confGlobBrowserCommand(); QString confGlobXtermCommand(); QFont confGlobEntryFont(); QFont confGlobViewFont(); int confGlobPwTimeout(); int confGlobLockTimeout(); int confGlobCompression(); int confGlobCryptAlgo(); int confGlobHashAlgo(); int confGlobFilePermissions(); int confGlobMinimizeLock(); bool confGlobUnlockOnOpen(); bool confGlobTray(); bool confGlobMakeFileBackup(); bool confGlobAutostartDeepLocked(); bool confGlobAutoDeepLock(); bool confGlobKwalletEmu(); bool confGlobNewEntrLockStat(); /* WND */ QSize confWndMainWndSize(); int confWndMainViewStyle(); bool confWndAutoMinimizeOnStart(); bool confWndClose(); public: /* functions for writing the configuration settings */ /* GLOBAL */ void confGlobAutoStart(const QString &e); void confGlobBrowserCommand(const QString &e); void confGlobXtermCommand(const QString &e); void confGlobEntryFont(const QFont &e); void confGlobViewFont(const QFont &e); void confGlobPwTimeout(int e); void confGlobLockTimeout(int e); void confGlobCompression(int e); void confGlobCryptAlgo(int e); void confGlobHashAlgo(int e); void confGlobFilePermissions(int e); void confGlobMinimizeLock(int e); void confGlobUnlockOnOpen(bool e); void confGlobTray(bool e); void confGlobMakeFileBackup(bool e); void confGlobAutostartDeepLocked(bool e); void confGlobAutoDeepLock(bool e); void confGlobKwalletEmu(bool e); void confGlobNewEntrLockStat(bool e); /* WND */ void confWndMainWndSize(const QSize &e); void confWndMainViewStyle(int e); void confWndAutoMinimizeOnStart(bool e); void confWndClose(bool e); QString mAutoStart; QString mBrowserCommand; QString mXTermCommand; QFont mEntryFont; QFont mViewFont; int mPwTimeout; int mLockTimeout; int mCompression; int mCryptAlgo; int mHashAlgo; int mFilePermissions; int mMinimizeLock; bool mUnlockOnOpen; bool mTray; bool mMakeFileBackup; bool mAutostartDeeplocked; bool mAutoDeeplock; bool mKWalletEmu; bool mNewEntrLockStat; QSize mMainWndSize; int mMainViewStyle; bool mAutoMinimizeOnStart; bool mClose; //US ENH - QValueList<int> mCommentSplitter; - QValueList<int> mCategorySplitter; + Q3ValueList<int> mCommentSplitter; + Q3ValueList<int> mCategorySplitter; // US introduce a nonconst way to return the config object. KConfig* getConfig(); private: PWMPrefs(); static PWMPrefs *sInstance; }; #endif diff --git a/pwmanager/pwmanager/pwmtray.cpp b/pwmanager/pwmanager/pwmtray.cpp index fe074ca..478116f 100644 --- a/pwmanager/pwmanager/pwmtray.cpp +++ b/pwmanager/pwmanager/pwmtray.cpp @@ -1,486 +1,489 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * Original implementation of the tray-tree * * (c) by Matt Scifo <mscifo@o1.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmtray.h" #include "pwmexception.h" #include "pwm.h" #include "pwmdoc.h" #include "pwminit.h" #ifndef PWM_EMBEDDED #include "configuration.h" #else #include "pwmprefs.h" #endif #include <klocale.h> +//Added by qt3to4: +#include <Q3ValueList> +#include <QMouseEvent> void ActiveTreeItem::execIt() { #ifndef PWM_EMBEDDED unsigned int entr = static_cast<unsigned int>(entry); unsigned int cat = static_cast<unsigned int>(category); #else unsigned int entr = (unsigned int)(entry); unsigned int cat = (unsigned int)(category); #endif switch (task) { case pwToClipboard: { PwMDataItem d; doc->getDataChangedLock(); bool wasLocked = doc->isLocked(cat, entr); doc->getEntry(cat, entr, &d, true); if (wasLocked) doc->lockAt(cat, entr, true); doc->putDataChangedLock(); PwM::copyToClipboard(d.pw.c_str()); break; } case nameToClipboard: { PwMDataItem d; doc->getEntry(cat, entr, &d); PwM::copyToClipboard(d.name.c_str()); break; } case descToClipboard: { PwMDataItem d; doc->getEntry(cat, entr, &d); PwM::copyToClipboard(d.desc.c_str()); break; } case urlToClipboard: { PwMDataItem d; doc->getEntry(cat, entr, &d); PwM::copyToClipboard(d.url.c_str()); break; } case launcherToClipboard: { PwMDataItem d; doc->getEntry(cat, entr, &d); PwM::copyToClipboard(d.launcher.c_str()); break; } case commentToClipboard: { PwMDataItem d; doc->getEntry(cat, entr, &d); PwM::copyToClipboard(d.comment.c_str()); break; } case execLauncher: { doc->execLauncher(cat, entr); break; } case goToURL: { doc->goToURL(cat, entr); break; } case openMainWnd: { // search if there is already an open window. - const QValueList<PwM *> *wl = tray->init->mainWndList(); + const Q3ValueList<PwM *> *wl = tray->init->mainWndList(); #ifndef PWM_EMBEDDED - QValueList<PwM *>::const_iterator i = wl->begin(), + Q3ValueList<PwM *>::const_iterator i = wl->begin(), end = wl->end(); #else - QValueList<PwM *>::ConstIterator i = wl->begin(), + Q3ValueList<PwM *>::ConstIterator i = wl->begin(), end = wl->end(); #endif PwM *wnd; while (i != end) { wnd = *i; if (wnd->curDoc() == doc) { // now bring this window to the foreground. if (!wnd->hasFocus()) { wnd->hide(); wnd->showNormal(); wnd->setFocus(); } return; } ++i; } // there is no open window, so open a new one. tray->init->createMainWnd(QString::null, false, false, doc); break; } case closeDoc: { doc->tryDelete(); break; } case lock: { doc->lockAll(true); break; } case deepLock: { doc->deepLock(); break; } case unlock: { doc->lockAll(false); break; } default: { BUG(); } } } #ifndef PWM_EMBEDDED PwMTray::PwMTray(PwMInit *_init, QWidget * parent, const char *name) : KSystemTray(parent, name) #else PwMTray::PwMTray(PwMInit *_init, QWidget * parent, const char *name) : QWidget(parent, name) #endif { init = _init; buildMain(); } PwMTray::~PwMTray() { emit closed(this); } //US ENH for embedded tray class KPopupMenu* PwMTray::contextMenu() { if (m_ctxMenu == 0) { m_ctxMenu = new KPopupMenu(); } return m_ctxMenu; } void PwMTray::buildMain() { KPopupMenu *ctxMenu = contextMenu(); ctxMenu->insertSeparator(); ctxMenu->insertItem(i18n("&New main window..."), this, SLOT(newMainWnd())); ctxMenu->insertItem(i18n("&Open file..."), this, SLOT(openDoc())); ctxMenu->insertSeparator(); ctxMenu->insertItem(i18n("&Remove from tray"), this, SLOT(undock())); } void PwMTray::insertActiveTreeItem(KPopupMenu *insertIn, const QString &text, ActiveTreeItem::Task task, PwMDoc *doc, int docCategory, int docEntry, - QValueList<int> *activeItemsList) + Q3ValueList<int> *activeItemsList) { ActiveTreeItem *activeItem; int id; activeItem = new ActiveTreeItem(text, insertIn->font(), task, doc, docCategory, docEntry, this); id = insertIn->insertItem(activeItem); insertIn->connectItem(id, activeItem, SLOT(execIt())); #ifndef PWM_EMBEDDED activeItemsList->push_back(id); #else activeItemsList->append(id); #endif } void PwMTray::rebuildTree(KPopupMenu *popup, PwMDoc *doc, - QValueList<int> *activeItems) + Q3ValueList<int> *activeItems) { PWM_ASSERT(doc); PWM_ASSERT(popup); activeItems->clear(); popup->clear(); #ifndef PWM_EMBEDDED popup->insertTitle(i18n("Categories:")); #endif vector<string> catList; vector<string> entrList; doc->getCategoryList(&catList); KPopupMenu *newCatMenu; KPopupMenu *newEntrMenu; int i, size = catList.size(); int j, entries; for (i = 0; i < size; ++i) { newCatMenu = new KPopupMenu(popup); popup->insertItem(catList[i].c_str(), newCatMenu); doc->getEntryList(i, &entrList); entries = entrList.size(); for (j = 0; j < entries; ++j) { newEntrMenu = new KPopupMenu(newCatMenu); newCatMenu->insertItem(entrList[j].c_str(), newEntrMenu); if (doc->isBinEntry(i, j)) { /* This is a binary entry. Don't insert the usual * menu items. */ #ifndef PWM_EMBEDDED newEntrMenu->insertTitle(i18n("This is a binary entry.\n" "It is not a normal password-entry, as it contains " "binary data, which PwManager can't display here.")); #endif continue; } insertActiveTreeItem(newEntrMenu, i18n("copy password to clipboard"), ActiveTreeItem::pwToClipboard, doc, i, j, activeItems); insertActiveTreeItem(newEntrMenu, i18n("copy username to clipboard"), ActiveTreeItem::nameToClipboard, doc, i, j, activeItems); insertActiveTreeItem(newEntrMenu, i18n("copy description to clipboard"), ActiveTreeItem::descToClipboard, doc, i, j, activeItems); insertActiveTreeItem(newEntrMenu, i18n("copy url to clipboard"), ActiveTreeItem::urlToClipboard, doc, i, j, activeItems); insertActiveTreeItem(newEntrMenu, i18n("copy launcher to clipboard"), ActiveTreeItem::launcherToClipboard, doc, i, j, activeItems); insertActiveTreeItem(newEntrMenu, i18n("copy comment to clipboard"), ActiveTreeItem::commentToClipboard, doc, i, j, activeItems); newEntrMenu->insertSeparator(); insertActiveTreeItem(newEntrMenu, i18n("Execute \"Launcher\""), ActiveTreeItem::execLauncher, doc, i, j, activeItems); insertActiveTreeItem(newEntrMenu, i18n("Go to \"URL\""), ActiveTreeItem::goToURL, doc, i, j, activeItems); } } insertMainWndCtrl(popup, doc); } void PwMTray::insertMainWndCtrl(KPopupMenu *menu, PwMDoc *doc) { ActiveTreeItem *activeItem; int id; #ifndef PWM_EMBEDDED menu->insertTitle(i18n("Manager:")); #endif activeItem = new ActiveTreeItem(i18n("&Open main manager window ..."), menu->font(), ActiveTreeItem::openMainWnd, doc, 0, 0, this); id = menu->insertItem(activeItem); menu->connectItem(id, activeItem, SLOT(execIt())); activeItem = new ActiveTreeItem(i18n("&Close this document ..."), menu->font(), ActiveTreeItem::closeDoc, doc, 0, 0, this); id = menu->insertItem(activeItem); menu->connectItem(id, activeItem, SLOT(execIt())); menu->insertSeparator(); activeItem = new ActiveTreeItem(i18n("&Lock all entries"), menu->font(), ActiveTreeItem::lock, doc, 0, 0, this); id = menu->insertItem(activeItem); menu->connectItem(id, activeItem, SLOT(execIt())); activeItem = new ActiveTreeItem(i18n("&Deep-lock all entries"), menu->font(), ActiveTreeItem::deepLock, doc, 0, 0, this); id = menu->insertItem(activeItem); menu->connectItem(id, activeItem, SLOT(execIt())); activeItem = new ActiveTreeItem(i18n("&Unlock all entries"), menu->font(), ActiveTreeItem::unlock, doc, 0, 0, this); id = menu->insertItem(activeItem); menu->connectItem(id, activeItem, SLOT(execIt())); } void PwMTray::updateTree(PwMDoc *document) { PWM_ASSERT(document); KPopupMenu *treeEntry; int treeItemNum = -1; int id = findTreeEntry(document, &treeEntry, &treeItemNum); if (id == -1) { // tree-entry doesn't exist, yet. id = insertTreeEntry(document, &treeEntry); } if (treeItemNum != -1) { // delete all *old* active items KPopupMenu *ctxMenu = contextMenu(); - QValueList<int> *oldItems = &tree[treeItemNum].activeItems; + Q3ValueList<int> *oldItems = &tree[treeItemNum].activeItems; #ifndef PWM_EMBEDDED - QValueList<int>::iterator i = oldItems->begin(); + Q3ValueList<int>::iterator i = oldItems->begin(); #else - QValueList<int>::Iterator i = oldItems->begin(); + Q3ValueList<int>::Iterator i = oldItems->begin(); #endif while (i != oldItems->end()) { ctxMenu->removeItem(*i); ++i; } oldItems->clear(); ctxMenu->changeItem(id, document->getTitle()); } treeItem newTreeItem; if (document->isDeepLocked()) { treeEntry->clear(); #ifndef PWM_EMBEDDED treeEntry->insertTitle(i18n("Categories:")); #endif QString msg(IS_DEEPLOCKED_SHORTMSG); msg += " "; msg += i18n("(Click here to unlock)"); treeEntry->insertItem(msg, document, SLOT(_deepUnlock())); insertMainWndCtrl(treeEntry, document); } else { rebuildTree(treeEntry, document, &newTreeItem.activeItems); } newTreeItem.menuId = id; newTreeItem.doc = document; newTreeItem.menu = treeEntry; if (treeItemNum == -1) { #ifndef PWM_EMBEDDED tree.push_back(newTreeItem); #else tree.append(newTreeItem); #endif } else { tree[treeItemNum] = newTreeItem; } } void PwMTray::closeTreeEntry(PwMDoc *document) { KPopupMenu *menu; int treeItem; int id = findTreeEntry(document, &menu, &treeItem); if (id != -1) { removeTreeEntry(id, treeItem, &menu); } } int PwMTray::findTreeEntry(PwMDoc *doc, KPopupMenu **menu, int *treeItem) { PWM_ASSERT(doc); #ifndef PWM_EMBEDDED int i, count = tree.size(); #else int i, count = tree.count(); #endif for (i = 0; i < count; ++i) { if (tree[i].doc == doc) { if (menu) *menu = tree[i].menu; if (treeItem) *treeItem = i; return tree[i].menuId; } } if (menu) *menu = 0; if (treeItem) *treeItem = -1; return -1; } int PwMTray::insertTreeEntry(PwMDoc *doc, KPopupMenu **popup) { PWM_ASSERT(doc); PWM_ASSERT(popup); KPopupMenu *ctxMenu = contextMenu(); *popup = new KPopupMenu(ctxMenu); return ctxMenu->insertItem(doc->getTitle(), *popup, -1, 1); } void PwMTray::removeTreeEntry(int menuId, int treeItem, KPopupMenu **menu) { PWM_ASSERT(menu); KPopupMenu *ctxMenu = contextMenu(); ctxMenu->removeItem(menuId); delete_and_null(*menu); #ifndef PWM_EMBEDDED tree.erase(tree.at(treeItem)); #else tree.remove(tree.at(treeItem)); #endif } void PwMTray::mouseReleaseEvent(QMouseEvent *e) { QWidget *curWnd = init->curWidget(); KPopupMenu *ctxMenu = contextMenu(); // give focus to init->curWidget() if (curWnd && !curWnd->hasFocus()) { curWnd->hide(); curWnd->showNormal(); curWnd->setFocus(); } // popup the context menu ctxMenu->popup(e->globalPos()); emit clickedIcon(this); } void PwMTray::connectDocToTray(PwMDoc *doc) { connect(doc, SIGNAL(dataChanged(PwMDoc *)), this, SLOT(updateTree(PwMDoc *))); connect(doc, SIGNAL(docClosed(PwMDoc *)), this, SLOT(closeTreeEntry(PwMDoc *))); // fake a dataChanged signal for this doc to update the tray tree. updateTree(doc); } void PwMTray::openDoc() { // open the document in a new window. PwM *newInstance = init->createMainWnd(); PwMDoc *newDoc = newInstance->openDoc(""); if (!newDoc) { newInstance->setForceQuit(true); delete_and_null(newInstance); } } void PwMTray::newMainWnd() { init->createMainWnd(); } void PwMTray::undock() { conf()->confGlobTray(false); init->initTray(); // Attention! "this" is already deleted here! } -#ifndef PWM_EMBEDDED -#include "pwmtray.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwmtray.cpp" #endif diff --git a/pwmanager/pwmanager/pwmtray.h b/pwmanager/pwmanager/pwmtray.h index ffb625e..b1145e0 100644 --- a/pwmanager/pwmanager/pwmtray.h +++ b/pwmanager/pwmanager/pwmtray.h @@ -1,292 +1,294 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __PWMTRAY_H #define __PWMTRAY_H #ifndef PWM_EMBEDDED #include <ksystemtray.h> #endif #include <kpopupmenu.h> #include <qpainter.h> -#include <qvaluelist.h> +#include <q3valuelist.h> +//Added by qt3to4: +#include <QMouseEvent> +#include <QMenuItem> //#include "pwmexception.h" class PwMInit; class PwMDoc; class PwMTray; /* wrapper to workaround MOC problems */ -class __ActiveTreeItem : public QCustomMenuItem - , public QObject +class __ActiveTreeItem : public QMenuItem { public: __ActiveTreeItem() {} }; /** implements the "active" part of the tree */ class ActiveTreeItem : public __ActiveTreeItem { Q_OBJECT public: enum Task { pwToClipboard, nameToClipboard, descToClipboard, urlToClipboard, launcherToClipboard, commentToClipboard, execLauncher, goToURL, openMainWnd, closeDoc, lock, deepLock, unlock }; public: ActiveTreeItem(const QString &_text, const QFont &_font, Task _task, PwMDoc * _doc, int _category, int _entry, PwMTray *_tray) : text (_text) , font (_font) , task (_task) , doc (_doc) , category (_category) , entry (_entry) , tray (_tray) { } /* ~ActiveTreeItem() { cout << "deleted \"" << text << "\"" << endl; } */ void paint(QPainter *p, const QColorGroup & /*cg*/, bool /*act*/, bool /*enabled*/, int x, int y, int w, int h) { p->setFont(font); - p->drawText(x, y, w, h, AlignLeft | AlignVCenter | - DontClip | ShowPrefix, text); + p->drawText(x, y, w, h, Qt::AlignLeft | Qt::AlignVCenter | + Qt::DontClip | Qt::ShowPrefix, text); } QSize sizeHint() { - return QFontMetrics(font).size(AlignLeft | AlignVCenter | - ShowPrefix | DontClip, text); + return QFontMetrics(font).size(Qt::AlignLeft | Qt::AlignVCenter | + Qt::ShowPrefix | Qt::DontClip, text); } bool fullSpan() const { return false; } bool isSeparator() const { return false; } void setFont(const QFont &f) { font = f; } public slots: /** this is the executive part, that is triggered, when the user clicks it */ void execIt(); protected: QString text; QFont font; Task task; PwMDoc *doc; int category; int entry; PwMTray *tray; }; /** tray icon implementation */ #ifndef PWM_EMBEDDED -//MOC_SKIP_BEGIN +#ifndef Q_MOC_RUN class PwMTray : public KSystemTray { Q_OBJECT friend class ActiveTreeItem; struct treeItem { int menuId; PwMDoc *doc; KPopupMenu *menu; - QValueList<int> activeItems; // ids of all active items + Q3ValueList<int> activeItems; // ids of all active items }; public: PwMTray(PwMInit *_init, QWidget* parent = 0, const char* name = 0); ~PwMTray(); /** connect all signals for this document to the tray */ void connectDocToTray(PwMDoc *doc); public slots: /** for update-notification from all open documents */ void updateTree(PwMDoc *document); /** when a document has been closed, call this func * to delete its tray-entry */ void closeTreeEntry(PwMDoc *document); protected slots: /** open a new document */ void openDoc(); /** open a new mainwnd */ void newMainWnd(); /** undock this tray icon */ void undock(); signals: /** this icon got deleted */ void closed(PwMTray *); /** the user clicked on the tray icon */ void clickedIcon(PwMTray *); protected: /** holds a list of all open files, its documents and * its menuIDs */ - QValueList<struct treeItem> tree; + Q3ValueList<struct treeItem> tree; /** pointer to init */ PwMInit *init; protected: /** search if an entry with for the given document * exists and resturn its ID and a pointer to the main * KPopupMenu. If no item is found, * it returns -1 as ID and a NULL-pointer. */ int findTreeEntry(PwMDoc *doc, KPopupMenu **menu, int *treeItem); /** build the main menu-items */ void buildMain(); /** rebuilds the tree for the given KPopupMenu entry */ void rebuildTree(KPopupMenu *popup, PwMDoc *doc, - QValueList<int> *activeItems); + Q3ValueList<int> *activeItems); /** insert a new tree-entry for the given doc and returns the ID.*/ int insertTreeEntry(PwMDoc *doc, KPopupMenu **popup); /** removes a tree entry */ void removeTreeEntry(int menuId, int treeItem, KPopupMenu **menu); /** inserts a new active-tree-item into the given tree entry */ void insertActiveTreeItem(KPopupMenu *insertIn, const QString &text, ActiveTreeItem::Task task, PwMDoc *doc, int docCategory, int docEntry, - QValueList<int> *activeItemsList); + Q3ValueList<int> *activeItemsList); /** mouse event on icon */ void mouseReleaseEvent(QMouseEvent *e); /** inserts the items for the main window control * into the popup menu. */ void insertMainWndCtrl(KPopupMenu *menu, PwMDoc *doc); }; -//MOC_SKIP_END +#endif #else class PwMTray : public QWidget { Q_OBJECT friend class ActiveTreeItem; struct treeItem { int menuId; PwMDoc *doc; KPopupMenu *menu; - QValueList<int> activeItems; // ids of all active items + Q3ValueList<int> activeItems; // ids of all active items }; public: PwMTray(PwMInit *_init, QWidget* parent = 0, const char* name = 0); ~PwMTray(); //US ENH needed for embedde version. KPopupMenu* contextMenu(); KPopupMenu* m_ctxMenu; /** connect all signals for this document to the tray */ void connectDocToTray(PwMDoc *doc); public slots: /** for update-notification from all open documents */ void updateTree(PwMDoc *document); /** when a document has been closed, call this func * to delete its tray-entry */ void closeTreeEntry(PwMDoc *document); protected slots: /** open a new document */ void openDoc(); /** open a new mainwnd */ void newMainWnd(); /** undock this tray icon */ void undock(); signals: /** this icon got deleted */ void closed(PwMTray *); /** the user clicked on the tray icon */ void clickedIcon(PwMTray *); protected: /** holds a list of all open files, its documents and * its menuIDs */ - QValueList<struct treeItem> tree; + Q3ValueList<struct treeItem> tree; /** pointer to init */ PwMInit *init; protected: /** search if an entry with for the given document * exists and resturn its ID and a pointer to the main * KPopupMenu. If no item is found, * it returns -1 as ID and a NULL-pointer. */ int findTreeEntry(PwMDoc *doc, KPopupMenu **menu, int *treeItem); /** build the main menu-items */ void buildMain(); /** rebuilds the tree for the given KPopupMenu entry */ void rebuildTree(KPopupMenu *popup, PwMDoc *doc, - QValueList<int> *activeItems); + Q3ValueList<int> *activeItems); /** insert a new tree-entry for the given doc and returns the ID.*/ int insertTreeEntry(PwMDoc *doc, KPopupMenu **popup); /** removes a tree entry */ void removeTreeEntry(int menuId, int treeItem, KPopupMenu **menu); /** inserts a new active-tree-item into the given tree entry */ void insertActiveTreeItem(KPopupMenu *insertIn, const QString &text, ActiveTreeItem::Task task, PwMDoc *doc, int docCategory, int docEntry, - QValueList<int> *activeItemsList); + Q3ValueList<int> *activeItemsList); /** mouse event on icon */ void mouseReleaseEvent(QMouseEvent *e); /** inserts the items for the main window control * into the popup menu. */ void insertMainWndCtrl(KPopupMenu *menu, PwMDoc *doc); }; #endif #endif diff --git a/pwmanager/pwmanager/pwmview.cpp b/pwmanager/pwmanager/pwmview.cpp index 2533487..68500d0 100644 --- a/pwmanager/pwmanager/pwmview.cpp +++ b/pwmanager/pwmanager/pwmview.cpp @@ -1,623 +1,631 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmview.h" #include "pwmexception.h" #include "globalstuff.h" #include "pwm.h" #include "rencatwnd.h" #ifndef PWM_EMBEDDED #include "configuration.h" #else #include "pwmprefs.h" #endif #include "commentbox.h" #include <kmessagebox.h> #include <klocale.h> #include <qlineedit.h> #include <qpoint.h> #include <qapplication.h> +#include <QDesktopWidget> #include <qlayout.h> +//Added by qt3to4: +#include <Q3HBoxLayout> +#include <QKeyEvent> +#include <QLabel> +#include <QResizeEvent> +#include <Q3PopupMenu> +#include <Q3VBoxLayout> //US ENH: wouldn't it be a good idea if we could use this consts everywhere else. //US ENH: for examle in listviewpwm.cpp //US ENH: Because of that I transfer them into the headerfile. /* #define COLUMN_DESC 0 #define COLUMN_NAME 1 #define COLUMN_PW 2 #define COLUMN_URL 3 #define COLUMN_LAUNCHER 4 */ PwMView::PwMView(PwM *_mainClass, QWidget *parent, PwMDoc *_doc, const char *name) : PwMViewStyle(parent, name) { PWM_ASSERT(_mainClass); PWM_ASSERT(parent); PWM_ASSERT(_doc); setView(this); doc = _doc; doc->setListViewPointer(this); mainClass = _mainClass; resize(_mainClass->size()); initStyle(conf()->confWndMainViewStyle()); initCtxMenu(); doc->setCurrentView(this); connect(doc, SIGNAL(dataChanged(PwMDoc *)), this, SLOT(updateView())); connect(this, SIGNAL(editPW()), mainClass, SLOT(editPwd_slot())); connect(this, SIGNAL(insertPW()), mainClass, SLOT(addPwd_slot())); connect(this, SIGNAL(deletePW()), mainClass, SLOT(deletePwd_slot())); } PwMView::~PwMView() { } void PwMView::initCtxMenu() { - ctxMenu = new QPopupMenu(this); + ctxMenu = new Q3PopupMenu(this); ctxMenu->insertItem(i18n("&Add password"), mainClass, SLOT(addPwd_slot())); ctxMenu->insertSeparator(); ctxMenu->insertItem(i18n("&Edit"), mainClass, SLOT(editPwd_slot())); ctxMenu->insertItem(i18n("&Delete"), mainClass, SLOT(deletePwd_slot())); ctxMenu->insertSeparator(); ctxMenu->insertItem(i18n("copy password to clipboard"), this, SLOT(copyPwToClip())); ctxMenu->insertItem(i18n("copy username to clipboard"), this, SLOT(copyNameToClip())); ctxMenu->insertItem(i18n("copy description to clipboard"), this, SLOT(copyDescToClip())); ctxMenu->insertItem(i18n("copy url to clipboard"), this, SLOT(copyUrlToClip())); ctxMenu->insertItem(i18n("copy launcher to clipboard"), this, SLOT(copyLauncherToClip())); ctxMenu->insertItem(i18n("copy comment to clipboard"), this, SLOT(copyCommentToClip())); ctxMenu->insertSeparator(); ctxMenu->insertItem(i18n("Execute \"Launcher\""), mainClass, SLOT(execLauncher_slot())); ctxMenu->insertItem(i18n("Go to \"URL\""), mainClass, SLOT(goToURL_slot())); } void PwMView::resizeEvent(QResizeEvent *) { resizeView(size()); } -void PwMView::refreshCommentTextEdit(QListViewItem *curItem) +void PwMView::refreshCommentTextEdit(Q3ListViewItem *curItem) { PWM_ASSERT(commentBox); if (!curItem) return; string comment; PwMerror ret; ret = document()->getCommentByLvp_long(getCurrentCategory(), lv->childCount() - lv->itemIndex(curItem) - 1, &comment); if (ret == e_binEntry) { commentBox->setContent(i18n("This is a binary entry.\n" "It is not a normal password-entry, as it contains " "binary data, which PwManager can't display here.")); } else if (ret == e_normalEntry) { commentBox->setContent(comment.c_str()); } else { BUG(); return; } lv->ensureItemVisible(curItem); } void PwMView::keyReleaseEvent(QKeyEvent * /*e*/) { refreshCommentTextEdit(lv->currentItem()); } bool PwMView::getCurEntryIndex(unsigned int *index) { - QListViewItem *current = lv->currentItem(); + Q3ListViewItem *current = lv->currentItem(); if (!current) return false; return getDocEntryIndex(index, current); } bool PwMView::getDocEntryIndex(unsigned int *index, - const QListViewItem *item) + const Q3ListViewItem *item) { vector<unsigned int> foundPositions; PwMDataItem curItem; curItem.desc = item->text(COLUMN_DESC).latin1(); curItem.name = item->text(COLUMN_NAME).latin1(); document()->getCommentByLvp(getCurrentCategory(), lv->childCount() - lv->itemIndex(item) - 1, &curItem.comment); curItem.url = item->text(COLUMN_URL).latin1(); curItem.launcher = item->text(COLUMN_LAUNCHER).latin1(); document()->findEntry(getCurrentCategory(), curItem, SEARCH_IN_DESC | SEARCH_IN_NAME | SEARCH_IN_COMMENT | SEARCH_IN_URL | SEARCH_IN_LAUNCHER, &foundPositions, true); if (foundPositions.size()) { *index = foundPositions[0]; return true; } return false; } -void PwMView::handleToggle(QListViewItem *item) +void PwMView::handleToggle(Q3ListViewItem *item) { PWM_ASSERT(doc); if (!item) return; - QCheckListItem *clItem = (QCheckListItem *)item; + Q3CheckListItem *clItem = (Q3CheckListItem *)item; QString curCat(getCurrentCategory()); // find document position of this entry. unsigned int curEntryDocIndex; if (!getDocEntryIndex(&curEntryDocIndex, item)) return; // hack to refresh the comment, if only one item is present if (lv->childCount() == 1) refreshCommentTextEdit(lv->currentItem()); if (doc->isLocked(curCat, curEntryDocIndex) != clItem->isOn()) return; // this is just a click somewhere on the entry if (doc->isDeepLocked()) { PwMerror ret; ret = doc->deepLock(false); if (ret != e_success) clItem->setOn(false); return; } doc->lockAt(curCat, curEntryDocIndex, !clItem->isOn()); } -void PwMView::handleRightClick(QListViewItem *item, const QPoint &point, int) +void PwMView::handleRightClick(Q3ListViewItem *item, const QPoint &point, int) { if (!item) return; ctxMenu->move(point); /* don't use ctxMenu->exec() here, as it generates race conditions * with the card interface code. Believe it or not. :) */ ctxMenu->show(); } void PwMView::updateCategories() { //qDebug("PwMView::updateCategories() "); QString oldSel(getCurrentCategory()); delAllCategories(); QStringList catList; document()->getCategoryList(&catList); catList.sort(); #ifndef PWM_EMBEDDED QStringList::iterator i = catList.begin(), end = catList.end(); #else QStringList::Iterator i = catList.begin(), end = catList.end(); #endif while (i != end) { addCategory(*i); ++i; } selectCategory(oldSel); } void PwMView::shiftToView() { int cX = lv->contentsX(); int cY = lv->contentsY(); commentBox->clear(); unsigned int catDocIndex; if (unlikely( !(document()->findCategory(getCurrentCategory(), &catDocIndex)))) { BUG(); } // ensure all listViewPos are set doc->ensureLvp(); // clear all tmp-data vectors unsigned int i, entries = doc->numEntries(catDocIndex); if (entries) { mainClass->setVirgin(false); } vector<PwMDataItem> tmpSorted; PwMDataItem currItem; currItem.clear(); tmpSorted.insert(tmpSorted.begin(), entries, currItem); // Sort items and store them in tempoary tmpSorted. for (i = 0; i < entries; ++i) { doc->getEntry(catDocIndex, i, &currItem); //qDebug("PwMView::shiftToView: %s, %i", currItem.desc.c_str(), currItem.listViewPos); tmpSorted[currItem.listViewPos] = currItem; } // shift tempoary data to ListView. tmpDisableSort(); lv->clear(); //US ENH: adjust the headers of the table according the category texts { PwMCategoryItem* catItem = doc->getCategoryEntry(catDocIndex); // qDebug("PwMView::ShiftToView CAT: %i, %s", catDocIndex, catItem->name.c_str()); lv->setColumnText(COLUMN_DESC, catItem->desc_text.c_str()); lv->setColumnText(COLUMN_NAME, catItem->name_text.c_str()); lv->setColumnText(COLUMN_PW, catItem->pw_text.c_str()); } - QCheckListItem *newItem; + Q3CheckListItem *newItem; vector<PwMDataItem>::iterator it = tmpSorted.begin(), end = tmpSorted.end(); while (it != end) { newItem = new ListViewItemPwM(lv); newItem->setText(COLUMN_DESC, (*it).desc.c_str()); if ((*it).binary) { newItem->setText(COLUMN_NAME, ""); newItem->setText(COLUMN_PW, i18n("<BINARY ENTRY>")); newItem->setText(COLUMN_URL, ""); newItem->setText(COLUMN_LAUNCHER, (*it).launcher.c_str()); } else { newItem->setText(COLUMN_NAME, (*it).name.c_str()); if ((*it).lockStat) { newItem->setText(COLUMN_PW, QString((*it).pw.c_str()) + " " + i18n("To unlock click the icon on the left.")); } else { newItem->setText(COLUMN_PW, (*it).pw.c_str()); } newItem->setText(COLUMN_URL, (*it).url.c_str()); newItem->setText(COLUMN_LAUNCHER, (*it).launcher.c_str()); } newItem->setOn(!((*it).lockStat)); lv->insertItem(newItem); ++it; } tmpReEnableSort(); if (cY || cX) lv->setContentsPos(cX, cY); } void PwMView::reorgLp() { if (!lv->childCount()) return; PWM_ASSERT(doc); PWM_ASSERT(!doc->isDocEmpty()); - QListViewItem *currItem; + Q3ListViewItem *currItem; vector<unsigned int> foundPos; /* This searchIn _should_ be: * const unsigned int searchIn = SEARCH_IN_DESC; * But we want backward compatibility (see comment in PwMDoc::addEntry()). * So we need to search again, if we don't find the entry. (see below) */ const unsigned int searchIn = SEARCH_IN_DESC | SEARCH_IN_NAME | SEARCH_IN_URL | SEARCH_IN_LAUNCHER; QString curCat(getCurrentCategory()); PwMDataItem findThis; unsigned int i, cnt = lv->childCount(); for (i = 0; i < cnt; ++i) { currItem = lv->itemAtIndex(i); findThis.desc = currItem->text(COLUMN_DESC).latin1(); findThis.name = currItem->text(COLUMN_NAME).latin1(); findThis.url = currItem->text(COLUMN_URL).latin1(); findThis.launcher = currItem->text(COLUMN_LAUNCHER).latin1(); doc->findEntry(curCat, findThis, searchIn, &foundPos, true); if (!foundPos.size()) { /* Did not find the entry. We seem to have a binary * entry here (pray for it!). So search again with * the "correct" searchIn flags. */ const unsigned int searchIn2 = SEARCH_IN_DESC; doc->findEntry(curCat, findThis, searchIn2, &foundPos, true); if (unlikely(!foundPos.size())) { BUG(); continue; } /* We assert that it's a binary entry, now. * No chance to efficiently verify it here. */ } doc->setListViewPos(curCat, foundPos[0], cnt - i - 1); } } void PwMView::selAt(int index) { - QListViewItem *item = lv->itemAtIndex(index); + Q3ListViewItem *item = lv->itemAtIndex(index); if (!item) return; lv->setCurrentItem(item); lv->ensureItemVisible(item); } void PwMView::renCatButton_slot() { if (doc->isDeepLocked()) return; RenCatWnd wnd(this); if (wnd.exec() == 1) { QString newName(wnd.getNewName()); if (newName == "") return; document()->renameCategory(getCurrentCategory(), newName); } } void PwMView::delCatButton_slot() { if (doc->isDeepLocked()) return; if (numCategories() <= 1) { mainClass->showStatMsg(i18n("Can't remove the last category.")); return; } if (KMessageBox::questionYesNo(this, i18n("Do you really want to\n" "delete the selected\n" "category? All password-\n" "entries will be lost in\n" "this category!\n"), i18n("Delete category?")) == KMessageBox::No) { return; } document()->delCategory(getCurrentCategory()); } void PwMView::copyPwToClip() { if (doc->isDeepLocked()) return; unsigned int curIndex = 0; if (!getCurEntryIndex(&curIndex)) return; PwMDataItem d; document()->getDataChangedLock(); document()->getEntry(getCurrentCategory(), curIndex, &d, true); document()->putDataChangedLock(); PwM::copyToClipboard(d.pw.c_str()); } void PwMView::copyNameToClip() { if (doc->isDeepLocked()) return; unsigned int curIndex = 0; if (!getCurEntryIndex(&curIndex)) return; PwMDataItem d; document()->getEntry(getCurrentCategory(), curIndex, &d); PwM::copyToClipboard(d.name.c_str()); } void PwMView::copyDescToClip() { if (doc->isDeepLocked()) return; unsigned int curIndex = 0; if (!getCurEntryIndex(&curIndex)) return; PwMDataItem d; document()->getEntry(getCurrentCategory(), curIndex, &d); PwM::copyToClipboard(d.desc.c_str()); } void PwMView::copyUrlToClip() { if (doc->isDeepLocked()) return; unsigned int curIndex = 0; if (!getCurEntryIndex(&curIndex)) return; PwMDataItem d; document()->getEntry(getCurrentCategory(), curIndex, &d); PwM::copyToClipboard(d.url.c_str()); } void PwMView::copyLauncherToClip() { if (doc->isDeepLocked()) return; unsigned int curIndex = 0; if (!getCurEntryIndex(&curIndex)) return; PwMDataItem d; document()->getEntry(getCurrentCategory(), curIndex, &d); PwM::copyToClipboard(d.launcher.c_str()); } void PwMView::copyCommentToClip() { if (doc->isDeepLocked()) return; unsigned int curIndex = 0; if (!getCurEntryIndex(&curIndex)) return; PwMDataItem d; document()->getEntry(getCurrentCategory(), curIndex, &d); PwM::copyToClipboard(d.comment.c_str()); } /************************************************************************ * * * ************************************************************************/ PwMDataItemView::PwMDataItemView( QWidget *parent, const char *name ) - : QTextBrowser( parent, name ) + : Q3TextBrowser( parent, name ) { //US setWrapPolicy( QTextEdit::AtWordBoundary ); setLinkUnderline( false ); // setVScrollBarMode( QScrollView::AlwaysOff ); //setHScrollBarMode( QScrollView::AlwaysOff ); //US QStyleSheet *sheet = styleSheet(); //US QStyleSheetItem *link = sheet->item( "a" ); //US link->setColor( KGlobalSettings::linkColor() ); } void PwMDataItemView::setPwMDataItem( const PwMDataItem& a ) { mItem = a; // clear view setText( QString::null ); QString dynamicPart; QString format = "<tr><td align=\"right\"><b>%1</b></td>" "<td align=\"left\">%2</td></tr>"; dynamicPart += format .arg( i18n("LastUpdate") ) .arg( mItem.meta.update.toString().latin1() ); dynamicPart += format .arg( i18n("Description") ) .arg( mItem.desc.c_str() ); dynamicPart += format .arg( i18n("Name") ) .arg( mItem.name.c_str() ); dynamicPart += format .arg( i18n("Password") ) .arg( mItem.pw.c_str() ); QString comment(mItem.pw.c_str()); dynamicPart += format .arg( i18n("Comment") ) .arg( comment.replace( QRegExp("\n"), "<br>" ) ); dynamicPart += format .arg( i18n("URL") ) .arg( mItem.url.c_str() ); dynamicPart += format .arg( i18n("Launcher") ) .arg( mItem.launcher.c_str() ); QString mText = "<table><td colspan=\"2\"> </td>"; mText += dynamicPart; mText += "</table>"; // at last display it... setText( mText ); } PwMDataItem PwMDataItemView::pwmdataitem() const { return mItem; } /************************************************************************ * * * ************************************************************************/ PwMDataItemChooser::PwMDataItemChooser( PwMDataItem loc, PwMDataItem rem, bool takeloc, QWidget *parent, const char *name ) : KDialogBase(parent, name, true , i18n("Conflict! Please choose Entry!"),Ok|User1|Close,Close, false) { findButton( Close )->setText( i18n("Cancel Sync")); findButton( Ok )->setText( i18n("Remote")); findButton( User1 )->setText( i18n("Local")); QWidget* topframe = new QWidget( this ); setMainWidget( topframe ); - QBoxLayout* bl; + Q3BoxLayout* bl; if ( QApplication::desktop()->width() < 640 ) { - bl = new QVBoxLayout( topframe ); + bl = new Q3VBoxLayout( topframe ); } else { - bl = new QHBoxLayout( topframe ); + bl = new Q3HBoxLayout( topframe ); } - QVBox* subframe = new QVBox( topframe ); + Q3VBox* subframe = new Q3VBox( topframe ); bl->addWidget(subframe ); QLabel* lab = new QLabel( i18n("Local Entry"), subframe ); if ( takeloc ) - lab->setBackgroundColor(Qt::green.light() ); + lab->setBackgroundColor(QColor(Qt::green).light() ); PwMDataItemView * av = new PwMDataItemView( subframe ); av->setPwMDataItem( loc ); - subframe = new QVBox( topframe ); + subframe = new Q3VBox( topframe ); bl->addWidget(subframe ); lab = new QLabel( i18n("Remote Entry"), subframe ); if ( !takeloc ) - lab->setBackgroundColor(Qt::green.light() ); + lab->setBackgroundColor(QColor(Qt::green).light() ); av = new PwMDataItemView( subframe ); av->setPwMDataItem( rem ); QObject::connect(findButton( Ok ),SIGNAL(clicked()),this, SLOT(slot_remote())); QObject::connect(this,SIGNAL(user1Clicked()),this, SLOT(slot_local())); #ifndef DESKTOP_VERSION showMaximized(); #else resize ( 640, 400 ); #endif } int PwMDataItemChooser::executeD( bool local ) { mSyncResult = 3; if ( local ) findButton( User1 )->setFocus(); else findButton( Ok )->setFocus(); exec(); return mSyncResult; } void PwMDataItemChooser::slot_remote() { mSyncResult = 2; accept(); } void PwMDataItemChooser::slot_local() { mSyncResult = 1; accept(); } -#ifndef PWM_EMBEDDED -#include "pwmview.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwmview.cpp" #endif diff --git a/pwmanager/pwmanager/pwmview.h b/pwmanager/pwmanager/pwmview.h index e42b17a..8f60063 100644 --- a/pwmanager/pwmanager/pwmview.h +++ b/pwmanager/pwmanager/pwmview.h @@ -1,197 +1,201 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef PWMVIEW_H #define PWMVIEW_H //US ENH: wouldn't it be a good idea if we could use this consts everywhere else. //US ENH: for examle in listviewpwm.cpp //US ENH: Because of that I transfer them into the headerfile. #define COLUMN_DESC 0 #define COLUMN_NAME 1 #define COLUMN_PW 2 #define COLUMN_URL 3 #define COLUMN_LAUNCHER 4 #include "listviewpwm.h" #include "pwmdoc.h" #include "pwmviewstyle.h" #include <kconfig.h> #include <klocale.h> #include <kdialogbase.h> #include <qevent.h> #include <qfont.h> #include <qobject.h> -#include <qtextbrowser.h> +#include <q3textbrowser.h> +//Added by qt3to4: +#include <QResizeEvent> +#include <QKeyEvent> +#include <Q3PopupMenu> #include <vector> #include <string> using std::string; using std::vector; class PwM; class ConfFile; class PwMStatusBar; /** View class for PwM */ class PwMView : public PwMViewStyle { Q_OBJECT friend class PwMViewStyle; public: /** construtor */ PwMView(PwM *_mainClass, QWidget* parent, PwMDoc *_doc, const char *name = 0); /** destructor */ ~PwMView(); /** returns pointer to the document */ PwMDoc* document() { return doc; } /** returns the index of the currently selected entry. * (index as represented in PwMDoc !) */ bool getCurEntryIndex(unsigned int *index); /** returns the position of the given item in the document * Note: This func only serches in the current category. */ bool getDocEntryIndex(unsigned int *index, - const QListViewItem *item); + const Q3ListViewItem *item); public slots: /** update the view (call if dirty) */ void updateView() { updateCategories(); shiftToView(); } /** (re)sort all items and (re)shift them to listView. */ void shiftToView(); /** handle clicking on an item */ - void handleToggle(QListViewItem *item); + void handleToggle(Q3ListViewItem *item); /** handle right-clicking on an item */ - void handleRightClick(QListViewItem *item, const QPoint &point, int); + void handleRightClick(Q3ListViewItem *item, const QPoint &point, int); /** selects the item at "index" */ void selAt(int index); /** rename category button pressed */ void renCatButton_slot(); /** delete category button pressed */ void delCatButton_slot(); protected: /** right-click context-menu */ - QPopupMenu *ctxMenu; + Q3PopupMenu *ctxMenu; protected: /** update the categories from document */ void updateCategories(); /** widget resize event */ void resizeEvent(QResizeEvent *); /** initialize context-menu */ void initCtxMenu(); /** tempoarly disable auto-sorting and user-sorting */ void tmpDisableSort() { lv->setSorting(-1); } /** re-enable tempoarly disabled sorting */ void tmpReEnableSort() { lv->setSorting(lv->columns() + 1, true/*lv->sortOrder() == Qt::Ascending*/); } /** The user pressed and released a key. */ void keyReleaseEvent(QKeyEvent *e); protected slots: /** changes the comment text-edit, because a new item has been selected */ - void refreshCommentTextEdit(QListViewItem *curItem); + void refreshCommentTextEdit(Q3ListViewItem *curItem); /** copy pw to clipboard */ void copyPwToClip(); /** copy name to clipboard */ void copyNameToClip(); /** copy desc to clipboard */ void copyDescToClip(); /** copy url to clipboard */ void copyUrlToClip(); /** copy launcher to clipboard */ void copyLauncherToClip(); /** copy comment to clipboard */ void copyCommentToClip(); /** reorganize the "listViewPos" positions in the document * (for the current category only!) */ void reorgLp(); private: /** document */ PwMDoc *doc; /** pointer to the main class "PwM" */ PwM *mainClass; }; //US ENH basic widget to view an password entry. We need it for the sync stuff. //But might be oif interest for other functionalities as well. -class PwMDataItemView : public QTextBrowser +class PwMDataItemView : public Q3TextBrowser { public: PwMDataItemView( QWidget *parent = 0, const char *name = 0 ); /** Sets the PwMDataItem object. It is displayed immediately. @param a The PwMDataItem object. */ void setPwMDataItem( const PwMDataItem& a ); /** Returns the current PwMDataItem object. */ PwMDataItem pwmdataitem() const; private: PwMDataItem mItem; }; //US ENH we need this chooser when syncing results in a conflict class PwMDataItemChooser : public KDialogBase { Q_OBJECT public: PwMDataItemChooser( PwMDataItem loc, PwMDataItem rem, bool takeloc, QWidget *parent = 0, const char *name = 0 ); int executeD( bool local ); private: int mSyncResult; private slots: void slot_remote(); void slot_local(); }; #endif diff --git a/pwmanager/pwmanager/pwmviewstyle.cpp b/pwmanager/pwmanager/pwmviewstyle.cpp index ee35472..b6d930f 100644 --- a/pwmanager/pwmanager/pwmviewstyle.cpp +++ b/pwmanager/pwmanager/pwmviewstyle.cpp @@ -1,254 +1,254 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmviewstyle.h" #include "pwmexception.h" #include "pwmviewstyle_0.h" #include "pwmviewstyle_1.h" #include "listviewpwm.h" #include "pwmview.h" #include "commentbox.h" #ifndef PWM_EMBEDDED #include "configuration.h" #else #include "pwmprefs.h" #endif PwMViewStyle::PwMViewStyle(QWidget *parent, const char *name) : QWidget(parent, name) { curStyle = style_notset; s0 = 0; s1 = 0; } PwMViewStyle::~PwMViewStyle() { //US ENH : store the size of the listviewcolumns switch (curStyle) { case style_0: s0->saveSettings(PWMPrefs::instance()); break; case style_1: s1->saveSettings(PWMPrefs::instance()); break; default: BUG(); } PWMPrefs::instance()->writeConfig(); delete_ifnot_null(s0); delete_ifnot_null(s1); } -void PwMViewStyle::editPassWord( QListViewItem * i ) +void PwMViewStyle::editPassWord( Q3ListViewItem * i ) { if ( !i ) return; emit editPW(); } void PwMViewStyle::initStyle(style_t style) { printDebug(string("initializing style ") + tostr(style)); bool wasMaximized = v->isMaximized(); if (v->isVisible()) v->hide(); switch (style) { case style_0: delete_ifnot_null(s0); delete_ifnot_null(s1); s0 = new PwMViewStyle_0(v); lv = s0->getLv(); commentBox = s0->getCommentBox(); break; case style_1: delete_ifnot_null(s0); delete_ifnot_null(s1); s1 = new PwMViewStyle_1(v); lv = s1->getLv(); commentBox = s1->getCommentBox(); break; default: BUG(); return; } curStyle = style; - connect(lv, SIGNAL(pressed(QListViewItem *)), - v, SLOT(handleToggle(QListViewItem *))); - connect(lv, SIGNAL(rightButtonClicked(QListViewItem *, const QPoint &, int)), - v, SLOT(handleRightClick(QListViewItem *, const QPoint &, int))); - connect(lv, SIGNAL(clicked(QListViewItem *)), - v, SLOT(refreshCommentTextEdit(QListViewItem *))); - connect(lv, SIGNAL(returnPressed(QListViewItem *)), - this, SLOT(editPassWord(QListViewItem *))); - connect(lv, SIGNAL(doubleClicked(QListViewItem *)), - this, SLOT(editPassWord(QListViewItem *))); + connect(lv, SIGNAL(pressed(Q3ListViewItem *)), + v, SLOT(handleToggle(Q3ListViewItem *))); + connect(lv, SIGNAL(rightButtonClicked(Q3ListViewItem *, const QPoint &, int)), + v, SLOT(handleRightClick(Q3ListViewItem *, const QPoint &, int))); + connect(lv, SIGNAL(clicked(Q3ListViewItem *)), + v, SLOT(refreshCommentTextEdit(Q3ListViewItem *))); + connect(lv, SIGNAL(returnPressed(Q3ListViewItem *)), + this, SLOT(editPassWord(Q3ListViewItem *))); + connect(lv, SIGNAL(doubleClicked(Q3ListViewItem *)), + this, SLOT(editPassWord(Q3ListViewItem *))); connect(lv, SIGNAL(insertPW()), this, SIGNAL( insertPW() )); connect(lv, SIGNAL(deletePW()), this, SIGNAL( deletePW() )); lv->addColumn(i18n("Description"), 180); lv->addColumn(i18n("Username"), 150); lv->addColumn(i18n("Password"), 150); lv->addColumn(i18n("URL"), 180); lv->addColumn(i18n("Launcher"), 120); v->tmpReEnableSort(); //US ENH : load the size of the listviewcolumns switch (curStyle) { case style_0: s0->restoreSettings(PWMPrefs::instance()); break; case style_1: s1->restoreSettings(PWMPrefs::instance()); break; default: BUG(); } resizeView(v->size()); v->updateView(); if (wasMaximized) { v->showMaximized(); } else { v->show(); } connect(lv, SIGNAL(layoutChanged()), v, SLOT(reorgLp())); } void PwMViewStyle::resizeView(const QSize &size) { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->resize(size); return; case style_1: PWM_ASSERT(s1); s1->resize(size); return; default: BUG(); } } QString PwMViewStyle::getCurrentCategory() { switch (curStyle) { case style_0: PWM_ASSERT(s0); return s0->getCurrentCategory(); case style_1: PWM_ASSERT(s1); return s1->getCurrentCategory(); default: BUG(); } return ""; } void PwMViewStyle::addCategory(const QString &cat) { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->addCategory(cat); return; case style_1: PWM_ASSERT(s1); s1->addCategory(cat); return; default: BUG(); } } void PwMViewStyle::delCategory(const QString &cat) { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->delCategory(cat); return; case style_1: PWM_ASSERT(s1); s1->delCategory(cat); return; default: BUG(); } } void PwMViewStyle::delAllCategories() { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->delAllCategories(); return; case style_1: PWM_ASSERT(s1); s1->delAllCategories(); return; default: BUG(); } } void PwMViewStyle::selectCategory(const QString &cat) { switch (curStyle) { case style_0: PWM_ASSERT(s0); s0->selectCategory(cat); return; case style_1: PWM_ASSERT(s1); s1->selectCategory(cat); return; default: BUG(); } } int PwMViewStyle::numCategories() { switch (curStyle) { case style_0: PWM_ASSERT(s0); return s0->numCategories(); case style_1: PWM_ASSERT(s1); return s1->numCategories(); default: BUG(); } return 0; } -#ifndef PWM_EMBEDDED -#include "pwmviewstyle.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwmviewstyle.cpp" #endif diff --git a/pwmanager/pwmanager/pwmviewstyle.h b/pwmanager/pwmanager/pwmviewstyle.h index 6c2d81c..a7dccbe 100644 --- a/pwmanager/pwmanager/pwmviewstyle.h +++ b/pwmanager/pwmanager/pwmviewstyle.h @@ -1,115 +1,115 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef PWMVIEWSTYLE_H #define PWMVIEWSTYLE_H #include <qwidget.h> #include <qsplitter.h> -#include <qhbox.h> -#include <qvbox.h> +#include <q3hbox.h> +#include <q3vbox.h> #include <qpushbutton.h> -#include <qpopupmenu.h> +#include <q3popupmenu.h> #ifndef PWM_EMBEDDED -#include <qtextedit.h> +#include <q3textedit.h> #else -#include <qmultilineedit.h> +#include <q3multilineedit.h> #endif #include <qlabel.h> -#include <qlistbox.h> +#include <q3listbox.h> #include <qcombobox.h> #include <qsize.h> class ListViewPwM; class PwMViewStyle_0; class PwMViewStyle_1; class PwMView; -class QListViewItem; +class Q3ListViewItem; class CommentBox; class PwMViewStyle : public QWidget { Q_OBJECT public: enum style_t { style_notset = -1, style_0 = 0, style_1 = 1 }; public: PwMViewStyle(QWidget *parent = 0, const char *name = 0); ~PwMViewStyle(); /** initialize a new style */ void initStyle(style_t style); void initStyle(int style) { initStyle(static_cast<style_t>(style)); } /** returns the currently used style */ style_t getCurStyle() { return curStyle; } void setView(PwMView *view) { v = view; } /** returns the currently selected category */ QString getCurrentCategory(); protected: /** add Category to the view */ void addCategory(const QString &cat); /** delete Category from view */ void delCategory(const QString &cat); /** delete all categories from view */ void delAllCategories(); /** select the specified category */ void selectCategory(const QString &cat); /** returns the number of categories in this view. * This value dosn't say anything about the number of * categories in the document. */ int numCategories(); /** resize the view */ void resizeView(const QSize &size); ListViewPwM *lv; CommentBox *commentBox; protected slots: - void editPassWord( QListViewItem * ); + void editPassWord( Q3ListViewItem * ); private: /** which style has the view? * KListBox on the left, * or QComboBox on the top? */ style_t curStyle; PwMViewStyle_0 *s0; PwMViewStyle_1 *s1; PwMView *v; signals: void editPW(); void insertPW(); void deletePW(); }; #endif diff --git a/pwmanager/pwmanager/pwmviewstyle_0.cpp b/pwmanager/pwmanager/pwmviewstyle_0.cpp index 1d88a34..3d1f41f 100644 --- a/pwmanager/pwmanager/pwmviewstyle_0.cpp +++ b/pwmanager/pwmanager/pwmviewstyle_0.cpp @@ -1,144 +1,147 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmviewstyle_0.h" #include "pwmview.h" #include "listviewpwm.h" #include "commentbox.h" #include <klocale.h> #include <kglobal.h> #include <kiconloader.h> #include "pwmprefs.h" +//Added by qt3to4: +#include <QLabel> +#include <Q3ValueList> PwMViewStyle_0::PwMViewStyle_0(PwMView *view) : QObject() { - vbox1 = new QVBox(view); + vbox1 = new Q3VBox(view); vbox1->setSpacing(0); - hbox1 = new QHBox(vbox1); + hbox1 = new Q3HBox(vbox1); hbox1->setSpacing(0); categoriesTitle = new QLabel(hbox1); categoriesTitle->setText(i18n("Category:")); categoriesCombo = new QComboBox(hbox1); categoriesCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding,QSizePolicy::Preferred )); renCatButton = new QPushButton( hbox1); renCatButton->setPixmap (KGlobal::iconLoader()->loadIcon("edit", KIcon::Small) ); int maxsi = renCatButton->sizeHint().height()+4; renCatButton->setMinimumSize( maxsi, maxsi ); delCatButton = new QPushButton( hbox1); delCatButton->setPixmap (KGlobal::iconLoader()->loadIcon("editdelete", KIcon::Small) ); maxsi = delCatButton->sizeHint().height()+4; delCatButton->setMinimumSize( maxsi, maxsi ); - delCatButton->setFocusPolicy( QWidget::NoFocus ); - renCatButton->setFocusPolicy( QWidget::NoFocus ); + delCatButton->setFocusPolicy( Qt::NoFocus ); + renCatButton->setFocusPolicy( Qt::NoFocus ); #ifndef PWM_EMBEDDED splitter1 = new QSplitter(vbox1); splitter1->setOrientation(Qt::Vertical); #else splitter1 = new KDGanttMinimizeSplitter( Qt::Vertical, vbox1); splitter1->setMinimizeDirection ( KDGanttMinimizeSplitter::Down ); //US topLayout->addWidget(mMiniSplitter ); #endif lv = new ListViewPwM(splitter1); commentBox = new CommentBox(splitter1); // set sizes and styles commentBox->resize(commentBox->size().width(), 60); categoriesTitle->setAlignment(Qt::AlignVCenter | Qt::AlignRight); // connections connect(categoriesCombo, SIGNAL(activated(int)), view, SLOT(shiftToView())); connect(renCatButton, SIGNAL(clicked()), view, SLOT(renCatButton_slot())); connect(delCatButton, SIGNAL(clicked()), view, SLOT(delCatButton_slot())); connect(lv, SIGNAL(toggleOverview()), this, SLOT(toggleSplitter())); } PwMViewStyle_0::~PwMViewStyle_0() { delete vbox1; } void PwMViewStyle_0::toggleSplitter() { - QValueList<int> si = splitter1->sizes(); + Q3ValueList<int> si = splitter1->sizes(); splitter1->toggle(); - QValueList<int> si2 = splitter1->sizes(); + Q3ValueList<int> si2 = splitter1->sizes(); //qDebug("PwMViewStyle_0::toggleSplitter() %d %d %d %d", si[0],si[1],si2[0],si2[1] ); if ( si[0] == si2[0] && si[1] == si2[1] && si2[1] == 1 ) { int diff = si[0]/2; if ( diff > 200 ) diff = 200; si[0] -= diff; si[1] += diff; splitter1->toggle(); splitter1->setSizes( si ); } } void PwMViewStyle_0::delCategory(const QString &cat) { PWM_ASSERT(categoriesCombo); int i, count = categoriesCombo->count(); for (i = 0; i < count; ++i) { if (categoriesCombo->text(i) == cat) { categoriesCombo->removeItem(i); return; } } BUG(); } void PwMViewStyle_0::selectCategory(const QString &cat) { PWM_ASSERT(categoriesCombo); int i, count = categoriesCombo->count(); for (i = 0; i < count; ++i) { if (categoriesCombo->text(i) == cat) { categoriesCombo->setCurrentItem(i); return; } } // fall back to 0 categoriesCombo->setCurrentItem(0); } //US ENH: I need a place to load the view dependend settings. Eg. splittersize void PwMViewStyle_0::restoreSettings(PWMPrefs* prefs) { //load and store the size of the listviewcolumns lv->restoreLayout(prefs->getConfig(), "listview"); splitter1->setSizes( prefs->mCommentSplitter ); commentBox->setFont( prefs->mViewFont ); } //US ENH: I need a place to load the view dependend settings. Eg. splittersize void PwMViewStyle_0::saveSettings(PWMPrefs* prefs) { //store the size of the listviewcolumns lv->saveLayout(prefs->getConfig(), "listview"); prefs->mCommentSplitter = splitter1->sizes(); } diff --git a/pwmanager/pwmanager/pwmviewstyle_0.h b/pwmanager/pwmanager/pwmviewstyle_0.h index 6d3c1d1..f144eec 100644 --- a/pwmanager/pwmanager/pwmviewstyle_0.h +++ b/pwmanager/pwmanager/pwmviewstyle_0.h @@ -1,107 +1,107 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef PWMVIEWSTYLE_0_H #define PWMVIEWSTYLE_0_H -#include <qhbox.h> -#include <qvbox.h> +#include <q3hbox.h> +#include <q3vbox.h> #include <qpushbutton.h> #ifndef PWM_EMBEDDED -#include <qtextedit.h> +#include <q3textedit.h> #include <qsplitter.h> #else -#include <qmultilineedit.h> +#include <q3multilineedit.h> #include <KDGanttMinimizeSplitter.h> #endif #include <qlabel.h> #include <qcombobox.h> class PwMView; class ListViewPwM; class CommentBox; class PWMPrefs; class PwMViewStyle_0 : public QObject { Q_OBJECT public: PwMViewStyle_0(PwMView *view); ~PwMViewStyle_0(); ListViewPwM * getLv() { return lv; } CommentBox * getCommentBox() { return commentBox; } /** returns the currently selected category */ QString getCurrentCategory() { return categoriesCombo->currentText(); } /** add Category to the view */ void addCategory(const QString &cat) { categoriesCombo->insertItem(cat); } /** delete Category from view */ void delCategory(const QString &cat); /** delete all categories from view */ void delAllCategories() { categoriesCombo->clear(); } /** select the specified category */ void selectCategory(const QString &cat); /** returns the number of categories in this view. * This value dosn't say anything about the number of * categories in the document. */ int numCategories() { return categoriesCombo->count(); } /** resize the view */ void resize(const QSize &size) { vbox1->resize(size); } //US ENH: I need a place to load the view dependend settings. Eg. splittersize void restoreSettings(PWMPrefs* prefs); void saveSettings(PWMPrefs* prefs); public slots: void toggleSplitter(); protected: /** main list view */ ListViewPwM *lv; /** categories combo-box */ QComboBox *categoriesCombo; /** title string for the categories combo or list box */ QLabel *categoriesTitle; /** hbox1 for widget style */ - QHBox *hbox1; + Q3HBox *hbox1; /** vbox1 for widget style */ - QVBox *vbox1; + Q3VBox *vbox1; /** splitter for commentTextEdit */ #ifndef PWM_EMBEDDED QSplitter *splitter1; #else KDGanttMinimizeSplitter * splitter1; #endif /** push button to change the category name */ QPushButton *renCatButton; /** push button to delete the category */ QPushButton *delCatButton; /** comment box */ CommentBox *commentBox; }; #endif diff --git a/pwmanager/pwmanager/pwmviewstyle_1.cpp b/pwmanager/pwmanager/pwmviewstyle_1.cpp index e335a3f..83eed97 100644 --- a/pwmanager/pwmanager/pwmviewstyle_1.cpp +++ b/pwmanager/pwmanager/pwmviewstyle_1.cpp @@ -1,192 +1,198 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "pwmviewstyle_1.h" #include "pwmview.h" #include "listviewpwm.h" #include "commentbox.h" #include <klocale.h> #include "pwmprefs.h" #ifndef DESKTOP_VERSION #include <qpe/qpeapplication.h> #else #include <qapplication.h> +#include <QDesktopWidget> +//Added by qt3to4: +#include <QLabel> +#include <Q3ValueList> +#include <Q3Frame> +#include <Q3PopupMenu> #endif #define INITIAL_CATEGORIES_WIDTH 100 PwMViewStyle_1::PwMViewStyle_1(PwMView *view) : QObject() { #ifndef PWM_EMBEDDED splitter = new QSplitter(view); #else if ( QApplication::desktop()->width() > 240 ) { splitter = new KDGanttMinimizeSplitter( Qt::Horizontal, view); splitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Left ); // topLayout = new QHBoxLayout( this ); // mMiniSplitter = new KDGanttMinimizeSplitter( Qt::Horizontal, this); // mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Right ); } else { splitter = new KDGanttMinimizeSplitter( Qt::Vertical, view); splitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Up ); // topLayout = new QHBoxLayout( this ); // mMiniSplitter = new KDGanttMinimizeSplitter( Qt::Vertical, this); // mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Down ); } //US topLayout->addWidget(mMiniSplitter ); #endif - vbox1 = new QVBox(splitter); + vbox1 = new Q3VBox(splitter); categoriesTitle = new QLabel(vbox1); - categoriesList = new QListBox(vbox1); + categoriesList = new Q3ListBox(vbox1); #ifndef PWM_EMBEDDED splitter2 = new QSplitter(splitter); splitter2->setOrientation(Qt::Vertical); #else splitter2 = new KDGanttMinimizeSplitter( Qt::Vertical, splitter); splitter2->setMinimizeDirection ( KDGanttMinimizeSplitter::Down ); //US topLayout->addWidget(mMiniSplitter ); #endif lv = new ListViewPwM(splitter2); commentBox = new CommentBox(splitter2); // set sizes and styles //US commentBox->resize(commentBox->size().width(), 60); - QValueList<int> sizes; + Q3ValueList<int> sizes; #ifndef PWM_EMBEDDED sizes.push_back(INITIAL_CATEGORIES_WIDTH); sizes.push_back(view->height() - INITIAL_CATEGORIES_WIDTH); #else sizes.append(INITIAL_CATEGORIES_WIDTH); sizes.append(view->height() - INITIAL_CATEGORIES_WIDTH); #endif //US splitter->setSizes(sizes); categoriesTitle->setAlignment(Qt::AlignHCenter); #ifndef PWM_EMBEDDED - categoriesTitle->setFrameShape(QFrame::MenuBarPanel); + categoriesTitle->setFrameShape(Q3Frame::MenuBarPanel); #else //categoriesTitle->setFrameShape(QFrame::StyledPanel); #endif categoriesTitle->setText(i18n("Category:")); - catCtxMenu = new QPopupMenu(view); + catCtxMenu = new Q3PopupMenu(view); catCtxMenu->insertItem(i18n("&Rename"), view, SLOT(renCatButton_slot())); catCtxMenu->insertItem(i18n("&Delete"), view, SLOT(delCatButton_slot())); #ifndef DESKTOP_VERSION QPEApplication::setStylusOperation( categoriesList->viewport(), QPEApplication::RightOnHold ); #endif // connections connect(categoriesList, SIGNAL(highlighted(int)), view, SLOT(shiftToView())); connect(categoriesList, - SIGNAL(rightButtonClicked(QListBoxItem *, const QPoint &)), + SIGNAL(rightButtonClicked(Q3ListBoxItem *, const QPoint &)), this, - SLOT(catRightClick(QListBoxItem *, const QPoint &))); + SLOT(catRightClick(Q3ListBoxItem *, const QPoint &))); connect(lv, SIGNAL(toggleOverview()), this, SLOT(toggleSplitter())); } PwMViewStyle_1::~PwMViewStyle_1() { delete catCtxMenu; delete splitter; } void PwMViewStyle_1::toggleSplitter() { - QValueList<int> si = splitter2->sizes(); + Q3ValueList<int> si = splitter2->sizes(); splitter2->toggle(); - QValueList<int> si2 = splitter2->sizes(); + Q3ValueList<int> si2 = splitter2->sizes(); //qDebug("PwMViewStyle_1::toggleSplitter() %d %d %d %d", si[0],si[1],si2[0],si2[1] ); if ( si[0] == si2[0] && si[1] == si2[1] && si2[1] == 1 ) { int diff = si[0]/2; if ( diff > 200 ) diff = 200; si[0] -= diff; si[1] += diff; splitter2->toggle(); splitter2->setSizes( si ); } } -void PwMViewStyle_1::catRightClick(QListBoxItem *item, const QPoint &point) +void PwMViewStyle_1::catRightClick(Q3ListBoxItem *item, const QPoint &point) { if (!item) return; catCtxMenu->move(point); catCtxMenu->show(); } void PwMViewStyle_1::delCategory(const QString &cat) { PWM_ASSERT(categoriesList); int i, count = categoriesList->count(); for (i = 0; i < count; ++i) { if (categoriesList->text(i) == cat) { categoriesList->removeItem(i); return; } } BUG(); } void PwMViewStyle_1::selectCategory(const QString &cat) { PWM_ASSERT(categoriesList); int i, count = categoriesList->count(); for (i = 0; i < count; ++i) { if (categoriesList->text(i) == cat) { categoriesList->setCurrentItem(i); return; } } // fall back to 0 categoriesList->setCurrentItem(0); } //US ENH: I need a place to load the view dependend settings. Eg. splittersize void PwMViewStyle_1::restoreSettings(PWMPrefs* prefs) { //load and store the size of the listviewcolumns lv->restoreLayout(prefs->getConfig(), "listview"); splitter->setSizes( prefs->mCategorySplitter ); splitter2->setSizes( prefs->mCommentSplitter ); commentBox->setFont( prefs->mViewFont ); } //US ENH: I need a place to load the view dependend settings. Eg. splittersize void PwMViewStyle_1::saveSettings(PWMPrefs* prefs) { //store the size of the listviewcolumns lv->saveLayout(prefs->getConfig(), "listview"); prefs->mCategorySplitter = splitter->sizes(); prefs->mCommentSplitter = splitter2->sizes(); } -#ifndef PWM_EMBEDDED -#include "pwmviewstyle_1.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_pwmviewstyle_1.cpp" #endif diff --git a/pwmanager/pwmanager/pwmviewstyle_1.h b/pwmanager/pwmanager/pwmviewstyle_1.h index 4f7a256..66cba03 100644 --- a/pwmanager/pwmanager/pwmviewstyle_1.h +++ b/pwmanager/pwmanager/pwmviewstyle_1.h @@ -1,114 +1,114 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef PWMVIEWSTYLE_1_H #define PWMVIEWSTYLE_1_H -#include <qvbox.h> +#include <q3vbox.h> #ifndef PWM_EMBEDDED -#include <qtextedit.h> +#include <q3textedit.h> #include <qsplitter.h> #else -#include <qmultilineedit.h> +#include <q3multilineedit.h> #include <KDGanttMinimizeSplitter.h> #endif #include <qlabel.h> -#include <qlistbox.h> -#include <qpopupmenu.h> +#include <q3listbox.h> +#include <q3popupmenu.h> class PwMView; class ListViewPwM; class CommentBox; class PWMPrefs; class PwMViewStyle_1 : public QObject { Q_OBJECT public: PwMViewStyle_1(PwMView *view); ~PwMViewStyle_1(); ListViewPwM * getLv() { return lv; } CommentBox * getCommentBox() { return commentBox; } /** returns the currently selected category */ QString getCurrentCategory() { return categoriesList->currentText(); } /** add Category to the view */ void addCategory(const QString &cat) { categoriesList->insertItem(cat); } /** delete Category from view */ void delCategory(const QString &cat); /** delete all categories from view */ void delAllCategories() { categoriesList->clear(); } /** select the specified category */ void selectCategory(const QString &cat); /** returns the number of categories in this view. * This value dosn't say anything about the number of * categories in the document. */ int numCategories() { return categoriesList->count(); } /** resize the view */ void resize(const QSize &size) { splitter->resize(size); } //US ENH: I need a place to load the view dependend settings. Eg. splittersize void restoreSettings(PWMPrefs* prefs); void saveSettings(PWMPrefs* prefs); public slots: void toggleSplitter(); protected slots: /** user clicked right button in category list */ - void catRightClick(QListBoxItem *item, const QPoint &point); + void catRightClick(Q3ListBoxItem *item, const QPoint &point); protected: /** main list view */ ListViewPwM *lv; #ifndef PWM_EMBEDDED /** main splitter widget */ QSplitter *splitter; /** commentTextEdit splitter */ QSplitter *splitter2; #else /** main splitter widget */ KDGanttMinimizeSplitter *splitter; /** commentTextEdit splitter */ KDGanttMinimizeSplitter *splitter2; #endif /** categories list-box */ - QListBox *categoriesList; + Q3ListBox *categoriesList; /** title string for the categories combo or list box */ QLabel *categoriesTitle; /** hbox1 for widget style */ - QVBox *vbox1; + Q3VBox *vbox1; /** text-edit to display the comment */ CommentBox *commentBox; /** category list context menu */ - QPopupMenu *catCtxMenu; + Q3PopupMenu *catCtxMenu; }; #endif diff --git a/pwmanager/pwmanager/randomizer.cpp b/pwmanager/pwmanager/randomizer.cpp index da4df78..24f9926 100644 --- a/pwmanager/pwmanager/randomizer.cpp +++ b/pwmanager/pwmanager/randomizer.cpp @@ -1,225 +1,225 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "randomizer.h" #include "pwmexception.h" #include <qfile.h> #include <kapplication.h> #include <stdlib.h> #include <time.h> #ifdef PWM_EMBEDDED #ifndef Q_LONG #define Q_LONG long #endif #endif //PWM_EMBEDDED #ifdef _WIN32_ int rand_r( uint * seed ) { srand(*seed); return rand(); } #endif Randomizer * Randomizer::rndObj (0); Randomizer::Randomizer() { rndDev = new QFile; seed = time(0); #if 1 // set to 0 to test rand_r() fallback // probe for /dev/urandom rndDev->setName("/dev/urandom"); if (rndDev->exists() && - rndDev->open(IO_ReadOnly)) { + rndDev->open(QIODevice::ReadOnly)) { printDebug("Randomizer: using /dev/urandom"); return; } // probe for /dev/random rndDev->setName("/dev/random"); if (rndDev->exists() && - rndDev->open(IO_ReadOnly)) { + rndDev->open(QIODevice::ReadOnly)) { printDebug("Randomizer: using /dev/random"); return; } // probe for EGD char *fn = getenv("RANDFILE"); if (fn) { rndDev->setName(fn); if (rndDev->exists() && - rndDev->open(IO_ReadOnly)) { + rndDev->open(QIODevice::ReadOnly)) { printDebug(string("Randomizer: using $RANDFILE \"") + fn + "\" (aka EGD)"); return; } } #endif /* no secure randomizer found. * Fall back to stdlib randomizer. */ delete_and_null(rndDev); printWarn("neither /dev/*random nor EGD found! " "Falling back to insecure rand_r()!"); } Randomizer::~Randomizer() { #ifndef PWM_EMBEDDED while (mutex.locked()) { /* wait for the mutex to unlock. * Don't block the GUI here, so processEvents() */ kapp->processEvents(); } #endif if (rndDev) { rndDev->close(); delete rndDev; } } char Randomizer::genRndChar() { char ret; #ifndef PWM_EMBEDDED mutex.lock(); #endif if (rndDev) { /* we have a file which provides random data. * Simply read it. */ ret = rndDev->getch(); } else { /* fall back to rand_r() */ ret = rand_r(&seed) % 0xFF; } #ifndef PWM_EMBEDDED mutex->unlock(); #endif return ret; } int Randomizer::genRndInt() { int ret; #ifndef PWM_EMBEDDED mutex->lock(); #endif if (rndDev) { if (sizeof(int) == 4) { (reinterpret_cast<char *>(&ret))[0] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[1] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[2] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[3] = rndDev->getch(); } else if (sizeof(int) == 8) { (reinterpret_cast<char *>(&ret))[0] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[1] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[2] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[3] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[4] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[5] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[6] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[7] = rndDev->getch(); } else { printWarn(string(__FILE__) + ":" + tostr(__LINE__) + ": sizeof(int) != 4 && sizeof(int) != 8"); ret = rand_r(&seed); } } else { ret = rand_r(&seed); } #ifndef PWM_EMBEDDED mutex->unlock(); #endif return ret; } unsigned int Randomizer::genRndUInt() { unsigned int ret; #ifndef PWM_EMBEDDED mutex->lock(); #endif if (rndDev) { if (sizeof(unsigned int) == 4) { (reinterpret_cast<char *>(&ret))[0] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[1] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[2] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[3] = rndDev->getch(); } else if (sizeof(unsigned int) == 8) { (reinterpret_cast<char *>(&ret))[0] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[1] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[2] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[3] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[4] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[5] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[6] = rndDev->getch(); (reinterpret_cast<char *>(&ret))[7] = rndDev->getch(); } else { printWarn(string(__FILE__) + ":" + tostr(__LINE__) + ": sizeof(unsigned int) != 4 && sizeof(unsigned int) != 8"); ret = rand_r(&seed); } } else { ret = rand_r(&seed); } #ifndef PWM_EMBEDDED mutex->unlock(); #endif return ret; } void Randomizer::genRndBuf(unsigned char *buf, size_t len) { #ifndef PWM_EMBEDDED mutex->lock(); #endif if (rndDev) { Q_LONG n; n = rndDev->readBlock(reinterpret_cast<char *>(buf), len); WARN_ON(n != static_cast<Q_LONG>(len)); } else { size_t i; for (i = 0; i < len; ++i) buf[i] = rand_r(&seed) % 0xFF; } #ifndef PWM_EMBEDDED mutex->unlock(); #endif } string Randomizer::genRndBuf(size_t len) { string ret; unsigned char *buf; buf = new unsigned char[len]; genRndBuf(buf, len); ret.assign(reinterpret_cast<const char *>(buf), len); return ret; } diff --git a/pwmanager/pwmanager/rencatwnd.cpp b/pwmanager/pwmanager/rencatwnd.cpp index 3c4de27..3ca758c 100644 --- a/pwmanager/pwmanager/rencatwnd.cpp +++ b/pwmanager/pwmanager/rencatwnd.cpp @@ -1,70 +1,73 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "rencatwnd.h" #include <klocale.h> +//Added by qt3to4: +#include <QResizeEvent> +#include <QLabel> RenCatWnd::RenCatWnd(QWidget *parent, - const char *name, bool modal, WFlags f) + const char *name, bool modal, Qt::WFlags f) : QDialog(parent, name, true, f) { - vbox1 = new QVBox(this); + vbox1 = new Q3VBox(this); label = new QLabel(vbox1); newName = new QLineEdit(vbox1); - hbox1 = new QHBox(vbox1); + hbox1 = new Q3HBox(vbox1); okButton = new QPushButton(i18n("&Ok"), hbox1); cancelButton = new QPushButton(i18n("&Cancel"), hbox1); vbox1->setSpacing(10); vbox1->setMargin(10); hbox1->setSpacing(10); resize(220, 100); setCaption(i18n("Rename category")); label->setText(i18n("New category name:")); connect(okButton, SIGNAL(clicked()), this, SLOT(okButton_slot())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancelButton_slot())); } RenCatWnd::~RenCatWnd() { } void RenCatWnd::resizeEvent(QResizeEvent *) { vbox1->resize(size()); } void RenCatWnd::okButton_slot() { done(1); } void RenCatWnd::cancelButton_slot() { done(2); } -#ifndef PWM_EMBEDDED -#include "rencatwnd.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_rencatwnd.cpp" #endif diff --git a/pwmanager/pwmanager/rencatwnd.h b/pwmanager/pwmanager/rencatwnd.h index 37b6725..1773136 100644 --- a/pwmanager/pwmanager/rencatwnd.h +++ b/pwmanager/pwmanager/rencatwnd.h @@ -1,60 +1,62 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef RENCATWND_H #define RENCATWND_H -#include <qvbox.h> -#include <qhbox.h> +#include <q3vbox.h> +#include <q3hbox.h> #include <qdialog.h> #include <qlabel.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qevent.h> +//Added by qt3to4: +#include <QResizeEvent> /** rename category window */ class RenCatWnd : public QDialog { Q_OBJECT public: RenCatWnd(QWidget *parent = 0, const char *name = 0, - bool modal = FALSE, WFlags f = 0); + bool modal = FALSE, Qt::WFlags f = 0); ~RenCatWnd(); QString getNewName() { return newName->text(); } protected slots: void okButton_slot(); void cancelButton_slot(); protected: - QVBox *vbox1; - QHBox *hbox1; + Q3VBox *vbox1; + Q3HBox *hbox1; QLabel *label; QLineEdit *newName; QPushButton *okButton; QPushButton *cancelButton; protected: void resizeEvent(QResizeEvent *); }; #endif diff --git a/pwmanager/pwmanager/serializer.cpp b/pwmanager/pwmanager/serializer.cpp index 507fa30..6c6512e 100644 --- a/pwmanager/pwmanager/serializer.cpp +++ b/pwmanager/pwmanager/serializer.cpp @@ -1,739 +1,741 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "serializer.h" #include "pwmexception.h" #ifdef PWM_EMBEDDED #include <kglobal.h> #include <klocale.h> +//Added by qt3to4: +#include <Q3CString> #endif /* enable/disable serializer debugging (0/1) */ #define SERIALIZER_DEBUG 0 /* use the old xml tags for writing (0/1) */ #define USE_OLD_TAGS 0 /* write a CDATA section (0/1) */ #define WRITE_CDATA_SEC 0 #define META_CREATE_DATE "c" #define META_VALID_DATE "v" #define META_EXPIRE_DATE "e" #define META_UPDATE_DATE "u" #define META_UPDATE_INT "i" //US ENH : uniqueid and sync information #define META_UNIQUEID "n" #define SYNC_ROOT "s" #define SYNC_TARGET_PREFIX "t" #define SYNC_TARGET_NAME "n" /* This is compatibility stuff. * The names of the entries have changed and here are the * new and old ones */ #define ROOT_MAGIC_OLD "PwM-xml-dat" #define VER_STR_OLD "ver" #define COMPAT_VER_OLD "0x02" #define CAT_ROOT_OLD "categories" #define CAT_PREFIX_OLD "cat_" #define CAT_NAME_OLD "name" //US ENH : optional text for categories #define CAT_TEXT_OLD "text" #define ENTRY_PREFIX_OLD "entry_" #define ENTRY_DESC_OLD "desc" #define ENTRY_NAME_OLD "name" #define ENTRY_PW_OLD "pw" #define ENTRY_COMMENT_OLD "comment" #define ENTRY_URL_OLD "url" #define ENTRY_LAUNCHER_OLD "launcher" #define ENTRY_LVP_OLD "listViewPos" #define ENTRY_BIN_OLD "b" #define ENTRY_META_OLD "m" #define ROOT_MAGIC_NEW "P" #define VER_STR_NEW "v" #define COMPAT_VER_NEW "2" #define CAT_ROOT_NEW "c" #define CAT_PREFIX_NEW "c" #define CAT_NAME_NEW "n" //US ENH : optional text for categories #define CAT_TEXT_NEW "t" #define ENTRY_PREFIX_NEW "e" #define ENTRY_DESC_NEW "d" #define ENTRY_NAME_NEW "n" #define ENTRY_PW_NEW "p" #define ENTRY_COMMENT_NEW "c" #define ENTRY_URL_NEW "u" #define ENTRY_LAUNCHER_NEW "l" #define ENTRY_LVP_NEW "v" #define ENTRY_BIN_NEW ENTRY_BIN_OLD #define ENTRY_META_NEW ENTRY_META_OLD #if USE_OLD_TAGS != 0 # define ROOT_MAGIC_WR ROOT_MAGIC_OLD # define VER_STR_WR VER_STR_OLD # define COMPAT_VER_WR COMPAT_VER_OLD # define CAT_ROOT_WR CAT_ROOT_OLD # define CAT_PREFIX_WR CAT_PREFIX_OLD # define CAT_NAME_WR CAT_NAME_OLD //US ENH : optional text for categories # define CAT_TEXT_WR CAT_TEXT_OLD # define ENTRY_PREFIX_WR ENTRY_PREFIX_OLD # define ENTRY_DESC_WR ENTRY_DESC_OLD # define ENTRY_NAME_WR ENTRY_NAME_OLD # define ENTRY_PW_WR ENTRY_PW_OLD # define ENTRY_COMMENT_WR ENTRY_COMMENT_OLD # define ENTRY_URL_WR ENTRY_URL_OLD # define ENTRY_LAUNCHER_WR ENTRY_LAUNCHER_OLD # define ENTRY_LVP_WR ENTRY_LVP_OLD # define ENTRY_BIN_WR ENTRY_BIN_OLD # define ENTRY_META_WR ENTRY_META_OLD #else # define ROOT_MAGIC_WR ROOT_MAGIC_NEW # define VER_STR_WR VER_STR_NEW # define COMPAT_VER_WR COMPAT_VER_NEW # define CAT_ROOT_WR CAT_ROOT_NEW # define CAT_PREFIX_WR CAT_PREFIX_NEW # define CAT_NAME_WR CAT_NAME_NEW //US ENH : optional text for categories # define CAT_TEXT_WR CAT_TEXT_NEW # define ENTRY_PREFIX_WR ENTRY_PREFIX_NEW # define ENTRY_DESC_WR ENTRY_DESC_NEW # define ENTRY_NAME_WR ENTRY_NAME_NEW # define ENTRY_PW_WR ENTRY_PW_NEW # define ENTRY_COMMENT_WR ENTRY_COMMENT_NEW # define ENTRY_URL_WR ENTRY_URL_NEW # define ENTRY_LAUNCHER_WR ENTRY_LAUNCHER_NEW # define ENTRY_LVP_WR ENTRY_LVP_NEW # define ENTRY_BIN_WR ENTRY_BIN_NEW # define ENTRY_META_WR ENTRY_META_NEW #endif Serializer::Serializer() { defaultLockStat = true; //US BUG: I needed to specify a document name. Otherwise impl will not be created for serializing #ifndef PWM_EMBEDDED domDoc = new QDomDocument; #else domDoc = new QDomDocument("mydoc"); #endif } -Serializer::Serializer(const QCString &buffer) +Serializer::Serializer(const Q3CString &buffer) { defaultLockStat = true; //US BUG: I needed to specify a document name. Otherwise impl will not be created for serializing #ifndef PWM_EMBEDDED domDoc = new QDomDocument; #else domDoc = new QDomDocument("mydoc"); #endif if (!parseXml(buffer)) { delete domDoc; #ifndef PWM_EMBEDDED throw PwMException(PwMException::EX_PARSE); #else qDebug("Serializer::Serializer : Parse Exception "); #endif } } Serializer::~Serializer() { delete_ifnot_null(domDoc); } void Serializer::clear() { delete_ifnot_null(domDoc); domDoc = new QDomDocument; } -bool Serializer::parseXml(const QCString &buffer) +bool Serializer::parseXml(const Q3CString &buffer) { //abort(); //qDebug("parse %s ", buffer.data()); PWM_ASSERT(domDoc); #ifndef PWM_EMBEDDED if (!domDoc->setContent(buffer, true)) return false; #else #ifdef DESKTOP_VERSION if (!domDoc->setContent(buffer, true)) #else if (!domDoc->setContent(buffer)) #endif return false; #endif if (!checkValid()) return false; return true; } -QCString Serializer::getXml() +Q3CString Serializer::getXml() { PWM_ASSERT(domDoc); #ifndef PWM_EMBEDDED #if defined(PWM_DEBUG) && SERIALIZER_DEBUG != 0 - QCString tmp(domDoc->toCString(8)); + Q3CString tmp(domDoc->toCString(8)); printDebug("<BEGIN Serializer::getXml() dump>\n"); cout << tmp << endl; printDebug("<END Serializer::getXml() dump>"); #endif // DEBUG - QCString ret(domDoc->toCString(0)); + Q3CString ret(domDoc->toCString(0)); ret.replace('\n', ""); return ret; #else #if defined(PWM_DEBUG) && SERIALIZER_DEBUG != 0 - QCString tmp(" " + domDoc->toCString()); + Q3CString tmp(" " + domDoc->toCString()); printDebug("<BEGIN Serializer::getXml() dump>\n"); qDebug(tmp); cout << tmp << endl; printDebug("<END Serializer::getXml() dump>"); #endif // DEBUG - QCString ret(domDoc->toCString()); - ret.replace(QRegExp("\n"), ""); + Q3CString ret(domDoc->toByteArray()); + ret.replace("\n", ""); return ret; #endif } bool Serializer::serialize(PwMItem &dta) { PWM_ASSERT(domDoc); QDomElement root(genNewRoot()); QDomElement catNode(domDoc->createElement(CAT_ROOT_WR)); QDomElement syncNode(domDoc->createElement(SYNC_ROOT)); if (!addSyncData(&syncNode, dta.syncDta)) return false; root.appendChild(syncNode); if (!addCategories(&catNode, dta.dta)) return false; root.appendChild(catNode); return true; } bool Serializer::deSerialize(PwMItem *dta) { PWM_ASSERT(domDoc); PWM_ASSERT(dta); QDomElement root(domDoc->documentElement()); QDomNode n; dta->clear(); for (n = root.firstChild(); !n.isNull(); n = n.nextSibling()) { // find <categories> ... </categories> // <c> ... </c> if (n.nodeName() == CAT_ROOT_NEW || n.nodeName() == CAT_ROOT_OLD) { if (!readCategories(n, &(dta->dta))) { return false; } continue; } else if (n.nodeName() == SYNC_ROOT) { if (!readSyncData(n, &(dta->syncDta))) { return false; } continue; } /* NOTE: We can stop processing here, as we * don't have more nodes in root, yet. */ return false; } return true; } bool Serializer::readCategories(const QDomNode &n, vector<PwMCategoryItem> *dta) { QDomNodeList nl(n.childNodes()); QDomNode cur; QString name; QString text; unsigned int numCat = nl.count(), i; PwMCategoryItem curCat; vector<PwMDataItem> curEntr; if (!numCat) { printDebug("Serializer::readCategories(): empty"); return false; } for (i = 0; i < numCat; ++i) { cur = nl.item(i); if (cur.nodeName().left(1) == CAT_PREFIX_NEW || cur.nodeName().left(4) == CAT_PREFIX_OLD) { name = cur.toElement().attribute(CAT_NAME_NEW); if (name == QString::null) name = cur.toElement().attribute(CAT_NAME_OLD); PWM_ASSERT(name != QString::null); PWM_ASSERT(name != ""); curCat.clear(); curCat.name = name.latin1(); //US ENH: new version might include text for description, name and pw text = cur.toElement().attribute(CAT_TEXT_NEW); if (text == QString::null) text = cur.toElement().attribute(CAT_TEXT_OLD); if (text != QString::null) { QStringList textlist = QStringList::split(";", text, true); unsigned int num = textlist.count(); if (num > 0) curCat.desc_text = textlist[0].latin1(); if (num > 1) curCat.name_text = textlist[1].latin1(); if (num > 2) curCat.pw_text = textlist[2].latin1(); } if (!readEntries(cur, &curEntr)) { dta->clear(); return false; } curCat.d = curEntr; dta->push_back(curCat); } else { printDebug("Serializer::readCategories(): uh? not a category?"); } } return true; } bool Serializer::readEntries(const QDomNode &n, vector<PwMDataItem> *dta) { QDomNodeList nl(n.childNodes()); QDomNode cur; unsigned int numEntr = nl.count(), i; PwMDataItem curEntr; //US BUG: to initialize all values of curEntr with meaningfulldata, // we call clear on it. Reason: Information in the file we will read might be incomplete. // e.g. the metadata is missing. curEntr.clear(true); dta->clear(); for (i = 0; i < numEntr; ++i) { cur = nl.item(i); if (cur.nodeName().left(1) == ENTRY_PREFIX_NEW || cur.nodeName().left(6) == ENTRY_PREFIX_OLD) { if (!extractEntry(cur, &curEntr)) { return false; } dta->push_back(curEntr); } else { printDebug("Serializer::readEntries(): hm? not an entry?"); } } return true; } bool Serializer::extractEntry(const QDomNode &n, PwMDataItem *dta) { QDomNodeList nl(n.childNodes()); QDomNode cur, cdata; unsigned int cnt = nl.count(), i; QString name, text; if (!cnt) { printDebug("Serializer::extractEntry(): empty"); return false; } dta->clear(); for (i = 0; i < cnt; ++i) { cur = nl.item(i); name = cur.nodeName(); cdata = cur.firstChild(); if (unlikely(cdata.isCDATASection())) { text = cdata.toCDATASection().data(); } else if (likely(cur.isElement())) { text = cur.toElement().text(); } else { printDebug("Serializer::extractEntry(): neither CDATA nor element."); return false; } if (text == " ") text = ""; // for backward compatibility. //qDebug("entry %s ",unescapeEntryData(text).latin1()); if (name == ENTRY_DESC_NEW || name == ENTRY_DESC_OLD) { dta->desc = unescapeEntryData(text).latin1(); } else if (name == ENTRY_NAME_NEW || name == ENTRY_NAME_OLD) { dta->name = unescapeEntryData(text).latin1(); } else if (name == ENTRY_PW_NEW || name == ENTRY_PW_OLD) { dta->pw = unescapeEntryData(text).latin1(); } else if (name == ENTRY_COMMENT_NEW || name == ENTRY_COMMENT_OLD) { dta->comment = unescapeEntryData(text).latin1(); } else if (name == ENTRY_URL_NEW || name == ENTRY_URL_OLD) { dta->url = unescapeEntryData(text).latin1(); } else if (name == ENTRY_LAUNCHER_NEW || name == ENTRY_LAUNCHER_OLD) { dta->launcher = unescapeEntryData(text).latin1(); } else if (name == ENTRY_LVP_NEW || name == ENTRY_LVP_OLD) { dta->listViewPos = strtol(text.latin1(), 0, 10); } else if (name == ENTRY_BIN_NEW) { // ENTRY_BIN_NEW == ENTRY_BIN_OLD if (text == "0") { dta->binary = false; } else { dta->binary = true; } } else if (name == ENTRY_META_NEW) { // ENTRY_META_NEW == ENTRY_META_OLD if (!extractMeta(cur, &dta->meta)) return false; } else { printDebug(string("Serializer::extractEntry(): invalid: ") + name.latin1()); } } dta->lockStat = defaultLockStat; return true; } bool Serializer::extractMeta(const QDomNode &n, PwMMetaData *dta) { QDomNode cur(n.firstChild()); QString name, val; while (!cur.isNull()) { name = cur.nodeName(); val = cur.toElement().text(); if (val == "") { cur = cur.nextSibling(); continue; } //US BUG: The transformation of an empty date into an ISO date and back is different on different systems/compilers. //because of that it is possible that here some values are not set, which means they are null. //US ENH: at the same moment we need backwardcompatibility. So older versions might have stored invalid dates. QDateTime dtval; //dtval should be invalid by definition. if ((name == META_CREATE_DATE) || (name == META_VALID_DATE) || (name == META_EXPIRE_DATE) || (name == META_UPDATE_DATE)) { //qDebug("Serializer::extractMeta:: val:%s, empty:%i, length:%i",val.utf8(), val.isEmpty(), val.length()); #ifndef PWM_EMBEDDED dtval = QDateTime::fromString(val, Qt::ISODate); #else bool ok; dtval = KGlobal::locale()->readDateTime(val, KLocale::ISODate, &ok); if (ok == false) qDebug("Serializer::extractMeta invalid date or time !!!!!!!!!!!!!"); #endif //if the parsed data is wrong, dtval should be invalid at this time. } if (name == META_CREATE_DATE) { dta->create = dtval; } else if (name == META_VALID_DATE) { dta->valid = dtval; } else if (name == META_EXPIRE_DATE) { dta->expire = dtval; } else if (name == META_UPDATE_DATE) { dta->update = dtval; } else if (name == META_UPDATE_INT) { dta->updateInt = strtoul(val.latin1(), 0, 10); } else if (name == META_UNIQUEID) { dta->uniqueid = unescapeEntryData(val).latin1(); } else { printDebug(string("extractMeta(): invalid: ") + name.latin1()); } cur = cur.nextSibling(); } return true; } bool Serializer::checkValid() { PWM_ASSERT(domDoc); QDomElement root(domDoc->documentElement()); if (root.nodeName() != ROOT_MAGIC_NEW && root.nodeName() != ROOT_MAGIC_OLD) { printDebug("Serializer: wrong magic"); return false; } if (root.attribute(VER_STR_NEW) != COMPAT_VER_NEW && root.attribute(VER_STR_OLD) != COMPAT_VER_OLD) { printDebug("Serializer: wrong version"); return false; } return true; } QDomElement Serializer::genNewRoot() { PWM_ASSERT(domDoc); QDomElement root(domDoc->createElement(ROOT_MAGIC_WR)); root.setAttribute(VER_STR_WR, COMPAT_VER_WR); domDoc->appendChild(root); return root; } bool Serializer::addCategories(QDomElement *e, const vector<PwMCategoryItem> &dta) { unsigned int numCat = dta.size(), i; QString curId, curName; QDomElement curCat; for (i = 0; i < numCat; ++i) { curId = CAT_PREFIX_WR; curId += tostr(i).c_str(); curName = dta[i].name.c_str(); curCat = domDoc->createElement(curId); curCat.setAttribute(CAT_NAME_WR, curName); //US ENH: new version includes text for description, name and pw QStringList curTextList; curTextList << dta[i].desc_text.c_str(); curTextList << dta[i].name_text.c_str(); curTextList << dta[i].pw_text.c_str(); QString text = curTextList.join(";"); curCat.setAttribute(CAT_TEXT_WR, text); if (!addEntries(&curCat, dta[i].d)) { return false; } e->appendChild(curCat); } return true; } bool Serializer::addEntries(QDomElement *e, const vector<PwMDataItem> &dta) { unsigned int numEntr = dta.size(), i; QString curId; QDomElement curEntr; for (i = 0; i < numEntr; ++i) { curId = ENTRY_PREFIX_WR; curId += tostr(i).c_str(); curEntr = domDoc->createElement(curId); if (!writeEntry(&curEntr, dta[i])) { return false; } e->appendChild(curEntr); } return true; } bool Serializer::writeEntry(QDomElement *e, const PwMDataItem &_dta) { #if WRITE_CDATA_SEC != 0 # define new_text(x) domDoc->createCDATASection(x) QDomCDATASection curText; #else # define new_text(x) domDoc->createTextNode(x) QDomText curText; #endif QDomText plainText; QDomElement tag; // begin -- This is for compatibility with the old serializer PwMDataItem dta = _dta; if (!dta.desc.size()) dta.desc = " "; if (!dta.name.size()) dta.name = " "; if (!dta.pw.size()) dta.pw = " "; if (!dta.comment.size()) dta.comment = " "; if (!dta.url.size()) dta.url = " "; if (!dta.launcher.size()) dta.launcher = " "; // end -- This is for compatibility with the old serializer tag = domDoc->createElement(ENTRY_DESC_WR); curText = new_text(escapeEntryData(dta.desc.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_NAME_WR); curText = new_text(escapeEntryData(dta.name.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_PW_WR); curText = new_text(escapeEntryData(dta.pw.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_COMMENT_WR); curText = new_text(escapeEntryData(dta.comment.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_URL_WR); curText = new_text(escapeEntryData(dta.url.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_LAUNCHER_WR); curText = new_text(escapeEntryData(dta.launcher.c_str())); tag.appendChild(curText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_LVP_WR); plainText = domDoc->createTextNode(tostr(dta.listViewPos).c_str()); tag.appendChild(plainText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_BIN_WR); if (dta.binary) plainText = domDoc->createTextNode("1"); else plainText = domDoc->createTextNode("0"); tag.appendChild(plainText); e->appendChild(tag); tag = domDoc->createElement(ENTRY_META_WR); if (!writeMeta(&tag, dta.meta)) return false; e->appendChild(tag); #undef new_text return true; } bool Serializer::writeMeta(QDomElement *e, const PwMMetaData &dta) { QDomText text; QDomElement tag; //US BUG!!!: The transformation of an empty date into an ISO date is different on different systems/compilers. //So do not transform an empty value at all. if (dta.create.isValid()) { tag = domDoc->createElement(META_CREATE_DATE); #ifndef PWM_EMBEDDED text = domDoc->createTextNode(dta.create.toString(Qt::ISODate)); #else text = domDoc->createTextNode(KGlobal::locale()->formatDateTime(dta.create, KLocale::ISODate)); #endif tag.appendChild(text); e->appendChild(tag); } //US BUG!!!: The transformation of an empty date into an ISO date is different on different systems/compilers. //So do not transform an empty value at all. if (dta.valid.isValid()) { tag = domDoc->createElement(META_VALID_DATE); #ifndef PWM_EMBEDDED text = domDoc->createTextNode(dta.valid.toString(Qt::ISODate)); #else text = domDoc->createTextNode(KGlobal::locale()->formatDateTime(dta.valid, KLocale::ISODate)); #endif tag.appendChild(text); e->appendChild(tag); } //US BUG!!!: The transformation of an empty date into an ISO date is different on different systems/compilers. //So do not transform an empty value at all. if (dta.expire.isValid()) { tag = domDoc->createElement(META_EXPIRE_DATE); #ifndef PWM_EMBEDDED text = domDoc->createTextNode(dta.expire.toString(Qt::ISODate)); #else text = domDoc->createTextNode(KGlobal::locale()->formatDateTime(dta.expire, KLocale::ISODate)); #endif tag.appendChild(text); e->appendChild(tag); } //US BUG!!!: The transformation of an empty date into an ISO date is different on different systems/compilers. //So do not transform an empty value at all. if (dta.update.isValid()) { tag = domDoc->createElement(META_UPDATE_DATE); #ifndef PWM_EMBEDDED text = domDoc->createTextNode(dta.update.toString(Qt::ISODate)); #else text = domDoc->createTextNode(KGlobal::locale()->formatDateTime(dta.update, KLocale::ISODate)); #endif tag.appendChild(text); e->appendChild(tag); } tag = domDoc->createElement(META_UPDATE_INT); text = domDoc->createTextNode(tostr(dta.updateInt).c_str()); tag.appendChild(text); e->appendChild(tag); tag = domDoc->createElement(META_UNIQUEID); text = domDoc->createTextNode(escapeEntryData(dta.uniqueid.c_str())); tag.appendChild(text); e->appendChild(tag); #undef new_text return true; } QString Serializer::escapeEntryData(QString dta) { #ifndef PWM_EMBEDDED dta.replace('\n', "$>--endl--<$"); dta.replace("]]>", "||>"); #else dta.replace(QRegExp("\n"), "$>--endl--<$"); dta.replace(QRegExp("]]>"), "||>"); #endif diff --git a/pwmanager/pwmanager/serializer.h b/pwmanager/pwmanager/serializer.h index df50e42..e085ade 100644 --- a/pwmanager/pwmanager/serializer.h +++ b/pwmanager/pwmanager/serializer.h @@ -1,115 +1,115 @@ /*************************************************************************** * * * copyright (C) 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef __SERIALIZER_H #define __SERIALIZER_H #include "pwmdoc.h" -#include <qcstring.h> +#include <q3cstring.h> #include <qdom.h> #include <vector> using std::vector; /** This serializes its input data into * the PwManager-XML-datastream, that becomes * encrypted and maybe compressed */ class Serializer { public: /** construct an empty serializer document */ Serializer(); /** construct a serializer document and parse "buffer" */ - Serializer(const QCString &buffer); + Serializer(const Q3CString &buffer); /** destructor */ virtual ~Serializer(); /** clears all data */ void clear(); /** parse the given data buffer */ - bool parseXml(const QCString &buffer); + bool parseXml(const Q3CString &buffer); /** returns the current XML data */ - QCString getXml(); + Q3CString getXml(); /** serialize "dta" and store it as XML data */ //US ENH: we need to serialize and deserialize not only categories, but also synctargets bool serialize(PwMItem &dta); /** deserialize the (parsed) XML data and store it in "dta" */ bool deSerialize(PwMItem *dta); /** sets the initial default lockStat we should assign */ void setDefaultLockStat(bool stat) { defaultLockStat = stat; } protected: /** main data holder */ QDomDocument *domDoc; /** default lockStat to assign */ bool defaultLockStat; protected: /** check if this is valid PwManager XML data */ bool checkValid(); /** read the categories in the node "n" */ bool readCategories(const QDomNode &n, vector<PwMCategoryItem> *dta); /** read the entries in the node "n" */ bool readEntries(const QDomNode &n, vector<PwMDataItem> *dta); /** extract the data out of the given item at "n" */ bool extractEntry(const QDomNode &n, PwMDataItem *dta); /** extract the meta-data */ bool extractMeta(const QDomNode &n, PwMMetaData *dta); /** generates a new root node and sets all initial parameters */ QDomElement genNewRoot(); /** add new categories to the XML data stream in e */ bool addCategories(QDomElement *e, const vector<PwMCategoryItem> &dta); /** add the given new entries to the XML data stream in e */ bool addEntries(QDomElement *e, const vector<PwMDataItem> &dta); /** do serialize and write the given entry to the XML stream */ bool writeEntry(QDomElement *e, const PwMDataItem &_dta); /** write the entry meta data to the xml stream */ bool writeMeta(QDomElement *e, const PwMMetaData &dta); /** escape illegal characters out of the given entry data string */ QString escapeEntryData(QString dta); /** un-escape illegal characters out of the given entry data string */ QString unescapeEntryData(QString dta); //US ENH: the following methods are getting used to write/read sync entries /** read the syncentries in the node "n" */ bool readSyncData(const QDomNode &n, vector<PwMSyncItem> *dta); /** add new syncentries to the XML data stream in e */ bool addSyncData(QDomElement *e, const vector<PwMSyncItem> &dta); }; #endif // __SERIALIZER_H diff --git a/pwmanager/pwmanager/setmasterpwwnd_emb.cpp b/pwmanager/pwmanager/setmasterpwwnd_emb.cpp index e6471e6..c5fd4e4 100644 --- a/pwmanager/pwmanager/setmasterpwwnd_emb.cpp +++ b/pwmanager/pwmanager/setmasterpwwnd_emb.cpp @@ -1,163 +1,166 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #include "setmasterpwwnd_emb.h" #include <qpushbutton.h> #include <qtabwidget.h> #include <qwidget.h> #include <qlabel.h> #include <qlineedit.h> #include <qlayout.h> +//Added by qt3to4: +#include <Q3VBoxLayout> +#include <Q3GridLayout> #include <klocale.h> /*US #include <qvariant.h> #include <qpushbutton.h> #include <qtabwidget.h> #include <qwidget.h> #include <qlabel.h> #include <qlineedit.h> #include <qlayout.h> #include <qtooltip.h> #include <qwhatsthis.h> */ /* * Constructs a setMasterPwWnd as a child of 'parent', with the * name 'name' * */ setMasterPwWnd::setMasterPwWnd( QWidget* parent, const char* name ) : KDialogBase( KDialogBase::Plain, i18n( "Set master-password" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, parent, name, true ) { QWidget *page = plainPage(); - QVBoxLayout *pageLayout = new QVBoxLayout( page ); + Q3VBoxLayout *pageLayout = new Q3VBoxLayout( page ); mainTab = new QTabWidget( page ); pageLayout->addWidget( mainTab ); if ( !name ) setName( "setMasterPwWnd" ); //////////////////////////////////////////////////////////////////// // This is the Password tab1 tab = new QWidget( mainTab ); - QGridLayout *layout = new QGridLayout( tab, 5, 1 ); + Q3GridLayout *layout = new Q3GridLayout( tab, 5, 1 ); layout->setMargin( KDialogBase::marginHint() ); layout->setSpacing( KDialogBase::spacingHint() ); QLabel* label = new QLabel( i18n( "Using a normal password-string to encrypt the data." ), tab ); - label->setAlignment( int( QLabel::WordBreak | QLabel::AlignCenter ) ); + label->setAlignment( int( Qt::WordBreak | Qt::AlignCenter ) ); layout->addWidget(label, 0, 0); pwEdit_1 = new QLineEdit( tab, "pwEdit_1" ); pwEdit_1->setEchoMode( QLineEdit::Password ); label = new QLabel( pwEdit_1, i18n( "Please enter the new master-password:" ), tab ); layout->addWidget(label, 1, 0); layout->addWidget(pwEdit_1, 2, 0); pwEdit_2 = new QLineEdit( tab, "pwEdit_2" ); pwEdit_2->setEchoMode( QLineEdit::Password ); label = new QLabel( pwEdit_2, i18n( "Please enter the password again:" ), tab ); layout->addWidget(label, 3, 0); layout->addWidget(pwEdit_2, 4, 0); mainTab->insertTab( tab, i18n("Normal password") ); //////////////////////////////////////////////////////////////////// // This is the Password tab2 tab_2 = new QWidget( mainTab ); - layout = new QGridLayout( tab_2, 5, 1 ); + layout = new Q3GridLayout( tab_2, 5, 1 ); layout->setMargin( KDialogBase::marginHint() ); layout->setSpacing( KDialogBase::spacingHint() ); label = new QLabel( i18n( "Using a PwM key-card to encrypt the data." ), tab_2 ); - label->setAlignment( int( QLabel::WordBreak | QLabel::AlignCenter ) ); + label->setAlignment( int( Qt::WordBreak | Qt::AlignCenter ) ); layout->addWidget(label, 0, 0); label = new QLabel( i18n( "selected card:" ), tab_2 ); - label->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); + label->setAlignment( int( Qt::AlignVCenter | Qt::AlignRight ) ); layout->addWidget(label, 1, 0); selCardButton = new QPushButton( i18n( "&Select the currently inserted card as key-card" ), tab_2 ); layout->addWidget(selCardButton, 2, 0); genCardButton = new QPushButton( i18n( "&generate new key-card") , tab_2 ); layout->addWidget(genCardButton, 3, 0); curCardIdLabel = new QLabel( QString("") , tab_2 ); layout->addWidget(curCardIdLabel, 4, 0); mainTab->insertTab( tab_2, i18n("Key-card (chipcard)" ) ); // resize( QSize(411, 313).expandedTo(minimumSizeHint()) ); // signals and slots connections // connect( okButton, SIGNAL( clicked() ), this, SLOT( okButton_slot() ) ); // connect( cancelButton, SIGNAL( clicked() ), this, SLOT( cancelButton_slot() ) ); connect( genCardButton, SIGNAL( clicked() ), this, SLOT( genCardButton_slot() ) ); connect( selCardButton, SIGNAL( clicked() ), this, SLOT( selCardButton_slot() ) ); } /* * Destroys the object and frees any allocated resources */ setMasterPwWnd::~setMasterPwWnd() { // no need to delete child widgets, Qt does it all for us } void setMasterPwWnd::okButton_slot() { qWarning( "setMasterPwWnd::okButton_slot(): Not implemented yet" ); } void setMasterPwWnd::cancelButton_slot() { qWarning( "setMasterPwWnd::cancelButton_slot(): Not implemented yet" ); } void setMasterPwWnd::genCardButton_slot() { qWarning( "setMasterPwWnd::genCardButton_slot(): Not implemented yet" ); } void setMasterPwWnd::selCardButton_slot() { qWarning( "setMasterPwWnd::selCardButton_slot(): Not implemented yet" ); } diff --git a/pwmanager/pwmanager/setmasterpwwnd_emb.h b/pwmanager/pwmanager/setmasterpwwnd_emb.h index c8ddec6..a070fea 100644 --- a/pwmanager/pwmanager/setmasterpwwnd_emb.h +++ b/pwmanager/pwmanager/setmasterpwwnd_emb.h @@ -1,62 +1,64 @@ /* This file is part of PwManager/Platform independent. Copyright (c) 2004 Ulf Schenk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. $Id$ */ #ifndef SETMASTERPWWND_EMB_H #define SETMASTERPWWND_EMB_H #include <kdialogbase.h> +//Added by qt3to4: +#include <QLabel> class QLineEdit; class QPushButton; class QLabel; class QTabWidget; class QWidget; class setMasterPwWnd : public KDialogBase { Q_OBJECT public: setMasterPwWnd( QWidget* parent = 0, const char* name = 0 ); ~setMasterPwWnd(); QTabWidget* mainTab; QWidget* tab; QWidget* tab_2; QLineEdit* pwEdit_1; QLineEdit* pwEdit_2; QPushButton* selCardButton; QPushButton* genCardButton; QLabel* curCardIdLabel; public slots: virtual void okButton_slot(); virtual void cancelButton_slot(); virtual void genCardButton_slot(); virtual void selCardButton_slot(); }; #endif // SETMASTERPWWND_H diff --git a/pwmanager/pwmanager/setmasterpwwndimpl.cpp b/pwmanager/pwmanager/setmasterpwwndimpl.cpp index 3482643..7041d2e 100644 --- a/pwmanager/pwmanager/setmasterpwwndimpl.cpp +++ b/pwmanager/pwmanager/setmasterpwwndimpl.cpp @@ -1,193 +1,193 @@ /*************************************************************************** * * * copyright (C) 2003, 2004 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "setmasterpwwndimpl.h" #include "pwm.h" #include "globalstuff.h" #include <kmessagebox.h> #include <qlineedit.h> #include <qlabel.h> #include <qtabwidget.h> #include <stdio.h> #ifdef CONFIG_KEYCARD # include "pwmkeycard.h" #endif #define STRING_CARD_NONE (SetMasterPwWndImpl::string_cardNone()) SetMasterPwWndImpl::SetMasterPwWndImpl(QWidget * parent, const char *name) : setMasterPwWnd(parent, name) { #ifdef CONFIG_KEYCARD curCardIdLabel->setText(STRING_CARD_NONE); #else // CONFIG_KEYCARD #ifndef PWM_EMBEDDED mainTab->removePage(mainTab->page(1)); #else mainTab->removePage(tab_2); #endif #endif // CONFIG_KEYCARD keyCard = 0; } SetMasterPwWndImpl::~SetMasterPwWndImpl() { } void SetMasterPwWndImpl::okButton_slot() { #ifndef PWM_EMBEDDED int index = mainTab->currentPageIndex(); if (index == 0) { // normal password if (pwEdit_1->text() != pwEdit_2->text()) { KMessageBox::error(this, i18n ("The two passwords you have entered don't match.\n" "Please try entering them again."), i18n("Different passwords")); return; } if (pwEdit_1->text() == "") { KMessageBox::error(this, i18n("No password entered. " "Please type in a password, that " "you want to use for the encryption."), i18n("no password")); return; } } else { // key-card if (curCardIdLabel->text() == STRING_CARD_NONE) { KMessageBox::error(this, i18n("You didn't select a card as " "PwM-key-card."), i18n("no card")); return; } } done(1); #endif } void SetMasterPwWndImpl::cancelButton_slot() { #ifndef PWM_EMBEDDED done(2); #endif } void SetMasterPwWndImpl::slotOk() { int index = mainTab->currentPageIndex(); if (index == 0) { // normal password if (pwEdit_1->text() != pwEdit_2->text()) { KMessageBox::error(this, i18n ("The two passwords you have entered\ndon't match.\n" "Please try entering them again."), i18n("Different passwords")); return; } if (pwEdit_1->text() == "") { KMessageBox::error(this, i18n("No password entered.\n" "Please type in a password,\nthat " "you want to use for\nthe encryption."), i18n("no password")); return; } } else { // key-card if (curCardIdLabel->text() == STRING_CARD_NONE) { KMessageBox::error(this, i18n("You didn't select a card as\n" "PwM-key-card."), i18n("no card")); return; } } setMasterPwWnd::slotOk(); } void SetMasterPwWndImpl::genCardButton_slot() { #ifdef CONFIG_KEYCARD PWM_ASSERT(keyCard); keyCard->genNewCard(); #endif // CONFIG_KEYCARD } void SetMasterPwWndImpl::selCardButton_slot() { #ifdef CONFIG_KEYCARD PWM_ASSERT(keyCard); connect(keyCard, SIGNAL(keyAvailable(uint32_t, const string &)), this, SLOT(keyAvailable_slot(uint32_t, const string &))); keyCard->getKey(); #endif // CONFIG_KEYCARD } void SetMasterPwWndImpl::keyAvailable_slot(uint32_t cardId, const string &key) { if (key == "") return; curCardKey = key; char id_buf[(sizeof(cardId) * 2) + 2 /* "0x" */ + 1 /* NULL */]; memcpy(id_buf, "0x", 2); sprintf(id_buf + 2, "%X", cardId); curCardIdLabel->setText(id_buf); } string SetMasterPwWndImpl::getPw(bool *useCard) { int index = mainTab->currentPageIndex(); if (index == 0) { // normal password if (useCard) *useCard = false; PWM_ASSERT(pwEdit_1->text() == pwEdit_2->text()); return pwEdit_1->text().latin1(); } else { #ifdef CONFIG_KEYCARD // key-card if (useCard) *useCard = true; PWM_ASSERT(curCardKey != ""); PWM_ASSERT(curCardIdLabel->text() != STRING_CARD_NONE); return curCardKey; #endif // CONFIG_KEYCARD } return ""; } -#ifndef PWM_EMBEDDED -#include "setmasterpwwndimpl.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_setmasterpwwndimpl.cpp" #endif diff --git a/pwmanager/pwmanager/waitwnd.cpp b/pwmanager/pwmanager/waitwnd.cpp index a3f25cc..d4676a9 100644 --- a/pwmanager/pwmanager/waitwnd.cpp +++ b/pwmanager/pwmanager/waitwnd.cpp @@ -1,94 +1,98 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #include "waitwnd.h" #include "globalstuff.h" #include "pwmexception.h" #include <qmessagebox.h> +//Added by qt3to4: +#include <QResizeEvent> +#include <QCloseEvent> +#include <QLabel> #include <klocale.h> WaitWnd::WaitWnd(QString caption, QString _staticText, bool showCancelButton, bool showGenericText, QWidget *parent, - const char *name, bool modal, WFlags f) + const char *name, bool modal, Qt::WFlags f) : QDialog(parent, name, modal, f) { canClose = false; - vbox1 = new QVBox(this); + vbox1 = new Q3VBox(this); staticText = new QLabel(vbox1); if (showGenericText) { genericText = new QLabel(vbox1); genericText->setAlignment(Qt::AlignHCenter | Qt::WordBreak); } else { genericText = 0; } if (showCancelButton) { cancelButton = new QPushButton(vbox1); connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel_slot())); cancelButton->setText(i18n("&Cancel")); } else { cancelButton = 0; } vbox1->setSpacing(10); vbox1->setMargin(10); resize(300, 150); setCaption(caption); staticText->setText(_staticText); staticText->setAlignment(Qt::AlignHCenter | Qt::WordBreak); } WaitWnd::~WaitWnd() { } void WaitWnd::resizeEvent(QResizeEvent *) { vbox1->resize(size()); } void WaitWnd::closeEvent(QCloseEvent *e) { if (canClose) { emit goingToClose(); e->accept(); } else { e->ignore(); } } void WaitWnd::cancel_slot() { canClose = true; close(); } void WaitWnd::updateGenericText(const QString &text) { if (genericText) genericText->setText(text); } -#ifndef PWM_EMBEDDED -#include "waitwnd.moc" +#ifndef PWM_EMBEDDED_ +#include "moc_waitwnd.cpp" #endif diff --git a/pwmanager/pwmanager/waitwnd.h b/pwmanager/pwmanager/waitwnd.h index ae86c8b..6a619b9 100644 --- a/pwmanager/pwmanager/waitwnd.h +++ b/pwmanager/pwmanager/waitwnd.h @@ -1,61 +1,64 @@ /*************************************************************************** * * * copyright (C) 2003 by Michael Buesch * * email: mbuesch@freenet.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 * * as published by the Free Software Foundation. * * * ***************************************************************************/ /*************************************************************************** * copyright (C) 2004 by Ulf Schenk * This file is originaly based on version 1.0.1 of pwmanager * and was modified to run on embedded devices that run microkde * * $Id$ **************************************************************************/ #ifndef WAITWND_H #define WAITWND_H -#include <qvbox.h> +#include <q3vbox.h> #include <qdialog.h> #include <qlabel.h> #include <qpushbutton.h> #include <qevent.h> +//Added by qt3to4: +#include <QResizeEvent> +#include <QCloseEvent> /** window to ask the user to wait */ class WaitWnd : public QDialog { Q_OBJECT public: WaitWnd(QString caption, QString _staticText, bool showCancelButton, bool showGenericText, QWidget *parent = 0, const char *name = 0, - bool modal = FALSE, WFlags f = 0); + bool modal = FALSE, Qt::WFlags f = 0); ~WaitWnd(); void updateGenericText(const QString &text); signals: void goingToClose(); protected slots: void cancel_slot(); protected: - QVBox *vbox1; + Q3VBox *vbox1; QLabel *staticText; QLabel *genericText; QPushButton *cancelButton; /** can we safely close the widget? */ bool canClose; protected: void resizeEvent(QResizeEvent *); void closeEvent(QCloseEvent *e); }; #endif |