diff --git a/certmanager/Makefile.am b/certmanager/Makefile.am index e8b8b1ba9a..f86b7bc7bc 100644 --- a/certmanager/Makefile.am +++ b/certmanager/Makefile.am @@ -1,32 +1,32 @@ SUBDIRS = lib conf kwatchgnupg . KDE_CXXFLAGS = -DLIBKLEOPATRA_NO_COMPAT INCLUDES = -I$(srcdir)/lib -I$(top_srcdir)/libkdenetwork $(GPGME_CFLAGS) $(all_includes) bin_PROGRAMS = kleopatra kleopatra_SOURCES = \ customactions.cpp \ aboutdata.cpp \ main.cpp certmanager.cpp \ hierarchyanalyser.cpp \ certificatewizard.ui certificatewizardimpl.cpp \ certificateinfowidget.ui certificateinfowidgetimpl.cpp \ crlview.cpp storedtransferjob.cpp certlistview.cpp METASOURCES = AUTO kleopatra_LDFLAGS = $(all_libraries) $(KDE_RPATH) kleopatra_LDADD = conf/libconf.la lib/libkleopatra.la $(LIB_KUTILS) $(LIB_KABC) rcdir = $(kde_datadir)/kleopatra rc_DATA = kleopatraui.rc xdg_apps_DATA = kleopatra_import.desktop messages: rc.cpp $(EXTRACTRC) conf/*.ui >> rc.cpp $(XGETTEXT) conf/*.cpp *.cpp *.h -o $(podir)/kleopatra.pot -include $(top_srcdir)/doc/api/Doxyfile.am +include $(top_srcdir)/admin/Doxyfile.am diff --git a/certmanager/aboutdata.cpp b/certmanager/aboutdata.cpp index a1b0a398e4..fb5813ec44 100644 --- a/certmanager/aboutdata.cpp +++ b/certmanager/aboutdata.cpp @@ -1,93 +1,93 @@ /* aboutdata.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "aboutdata.h" #include static const char kleopatra_version[] = "0.40"; static const char description[] = I18N_NOOP("KDE Key Manager"); struct about_data { const char * name; const char * desc; const char * email; const char * web; }; static const about_data authors[] = { { "Marc Mutz", I18N_NOOP("Current Maintainer"), "mutz@kde.org", 0 }, { "Steffen Hansen", I18N_NOOP("Former Maintainer"), "hansen@kde.org", 0 }, { "Kalle Dalheimer", I18N_NOOP("Original Author"), "kalle@kde.org", 0 }, { "Jesper Petersen", I18N_NOOP("Original Author"), "blackie@kde.org", 0 }, }; static const about_data credits[] = { { "David Faure", I18N_NOOP("Backend configuration framework, KIO integration"), "faure@kde.org", 0 }, { "Michel Boyer de la Giroday", I18N_NOOP("Key-state dependant colors and fonts in the key list"), "michel@klaralvdalens-datakonsult.se", 0 }, { "Daniel Molkentin", I18N_NOOP("Certificate Wizard KIOSK integration, infrastructure"), "molkentin@kde.org", 0 }, { "Ralf Nolden", I18N_NOOP("Support for obsolete EMAIL RDN in Certificate Wizard"), "nolden@kde.org", 0 }, { "Karl-Heinz Zimmer", I18N_NOOP("DN display ordering support, infrastructure"), "khz@kde.org", 0 }, }; AboutData::AboutData() : KAboutData( "kleopatra", I18N_NOOP("Kleopatra"), kleopatra_version, description, License_GPL, "(c) 2002 Steffen Hansen, Jesper Pedersen,\n" "Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB\n\n" "(c) 2004 Marc Mutz, Klar\xC3\xA4lvdalens Datakonsult AB" ) { using ::authors; using ::credits; for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i ) addAuthor( authors[i].name, authors[i].desc, authors[i].email, authors[i].web ); for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i ) addCredit( credits[i].name, credits[i].desc, credits[i].email, credits[i].web ); } diff --git a/certmanager/aboutdata.h b/certmanager/aboutdata.h index d8742d705e..29e516f5c1 100644 --- a/certmanager/aboutdata.h +++ b/certmanager/aboutdata.h @@ -1,43 +1,43 @@ /* aboutdata.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __ABOUTDATA_H__ #define __ABOUTDATA_H__ #include class AboutData : public KAboutData { public: AboutData(); }; #endif // __ABOUTDATA_H__ diff --git a/certmanager/certificateinfowidgetimpl.cpp b/certmanager/certificateinfowidgetimpl.cpp index 589a5f2135..082c035ba2 100644 --- a/certmanager/certificateinfowidgetimpl.cpp +++ b/certmanager/certificateinfowidgetimpl.cpp @@ -1,438 +1,438 @@ /* certificateinfowidgetimpl.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "certificateinfowidgetimpl.h" // libkleopatra #include #include #include #include // gpgme++ #include // KDE #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include // other #include #include CertificateInfoWidgetImpl::CertificateInfoWidgetImpl( const GpgME::Key & key, bool external, QWidget * parent, const char * name ) : CertificateInfoWidget( parent, name ), mExternal( external ), mFoundIssuer( true ), mHaveKeyLocally( false ) { importButton->setEnabled( false ); listView->setColumnWidthMode( 1, QListView::Maximum ); QFontMetrics fm = fontMetrics(); listView->setColumnWidth( 1, fm.width( i18n("Information") ) * 5 ); listView->header()->setClickEnabled( false ); listView->setSorting( -1 ); connect( listView, SIGNAL( selectionChanged( QListViewItem* ) ), this, SLOT( slotShowInfo( QListViewItem* ) ) ); pathView->setColumnWidthMode( 0, QListView::Maximum ); pathView->header()->hide(); connect( pathView, SIGNAL( doubleClicked( QListViewItem* ) ), this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) ); connect( pathView, SIGNAL( returnPressed( QListViewItem* ) ), this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) ); connect( importButton, SIGNAL( clicked() ), this, SLOT( slotImportCertificate() ) ); dumpView->setFont( KGlobalSettings::fixedFont() ); if ( !key.isNull() ) setKey( key ); } static QString time_t2string( time_t t ) { QDateTime dt; dt.setTime_t( t ); return dt.toString(); } void CertificateInfoWidgetImpl::setKey( const GpgME::Key & key ) { mChain.clear(); mFoundIssuer = true; mHaveKeyLocally = false; listView->clear(); pathView->clear(); importButton->setEnabled( false ); if ( key.isNull() ) return; mChain.push_front( key ); startKeyExistanceCheck(); // starts a local keylisting to enable the // importButton if needed QListViewItem * item = 0; item = new QListViewItem( listView, item, i18n("Valid"), QString("From %1 to %2") .arg( time_t2string( key.subkey(0).creationTime() ), time_t2string( key.subkey(0).expirationTime() ) ) ); item = new QListViewItem( listView, item, i18n("Can be used for signing"), key.canSign() ? i18n("Yes") : i18n("No") ); item = new QListViewItem( listView, item, i18n("Can be used for encryption"), key.canEncrypt() ? i18n("Yes") : i18n("No") ); item = new QListViewItem( listView, item, i18n("Can be used for certification"), key.canCertify() ? i18n("Yes") : i18n("No") ); item = new QListViewItem( listView, item, i18n("Can be used for authentication"), key.canAuthenticate() ? i18n("Yes") : i18n("No" ) ); item = new QListViewItem( listView, item, i18n("Fingerprint"), key.primaryFingerprint() ); item = new QListViewItem( listView, item, i18n("Issuer"), Kleo::DN( key.issuerName() ).prettyDN() ); item = new QListViewItem( listView, item, i18n("Serial Number"), key.issuerSerial() ); const Kleo::DN dn = key.userID(0).id(); // FIXME: use the attributeLabelMap from certificatewizardimpl.cpp: static QMap dnComponentNames; if ( dnComponentNames.isEmpty() ) { dnComponentNames["C"] = i18n("Country"); dnComponentNames["OU"] = i18n("Organizational Unit"); dnComponentNames["O"] = i18n("Organization"); dnComponentNames["L"] = i18n("Location"); dnComponentNames["CN"] = i18n("Common Name"); dnComponentNames["EMAIL"] = i18n("Email"); } for ( Kleo::DN::const_iterator dnit = dn.begin() ; dnit != dn.end() ; ++dnit ) { QString displayName = (*dnit).name(); if( dnComponentNames.contains(displayName) ) displayName = dnComponentNames[displayName]; item = new QListViewItem( listView, item, displayName, (*dnit).value() ); } const std::vector uids = key.userIDs(); if ( !uids.empty() ) { item = new QListViewItem( listView, item, i18n("Subject"), Kleo::DN( uids.front().id() ).prettyDN() ); for ( std::vector::const_iterator it = uids.begin() + 1 ; it != uids.end() ; ++it ) { if ( !(*it).id() ) continue; const QString email = QString::fromUtf8( (*it).id() ).stripWhiteSpace(); if ( email.isEmpty() ) continue; if ( email.startsWith( "<" ) ) item = new QListViewItem( listView, item, i18n("Email"), email.mid( 1, email.length()-2 ) ); else item = new QListViewItem( listView, item, i18n("A.k.a."), email ); } } updateChainView(); startCertificateChainListing(); startCertificateDump(); } static void showChainListError( QWidget * parent, const GpgME::Error & err, const char * subject ) { assert( err ); const QString msg = i18n("

An error occurred while fetching " "the certificate %1 from the backend:

" "

%2

") .arg( subject ? QString::fromUtf8( subject ) : QString::null, QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n("Certificate Listing Failed" ) ); } void CertificateInfoWidgetImpl::startCertificateChainListing() { kdDebug() << "CertificateInfoWidgetImpl::startCertificateChainListing()" << endl; if ( mChain.empty() ) { // we need a seed... kdWarning() << "CertificateInfoWidgetImpl::startCertificateChainListing(): mChain is empty!" << endl; return; } const char * chainID = mChain.front().chainID(); if ( !chainID || !*chainID ) { // cert not found: kdDebug() << "CertificateInfoWidgetImpl::startCertificateChainListing(): empty chain ID - root not found" << endl; return; } const char * fpr = mChain.front().primaryFingerprint(); if ( qstricmp( fpr, chainID ) == 0 ) { kdDebug() << "CertificateInfoWidgetImpl::startCertificateChainListing(): chain_id equals fingerprint -> found root" << endl; return; } if ( mChain.size() > 100 ) { // safe guard against certificate loops (paranoia factor 8 out of 10)... kdWarning() << "CertificateInfoWidgetImpl::startCertificateChainListing(): maximum chain length of 100 exceeded!" << endl; return; } if ( !mFoundIssuer ) { // key listing failed. Don't end up in endless loop kdDebug() << "CertificateInfoWidgetImpl::startCertificateChainListing(): issuer not found - giving up" << endl; return; } mFoundIssuer = false; // gpgsm / dirmngr / LDAP / whoever doesn't support looking up // external keys by fingerprint. Furthermore, since we actually got // a chain-id set on the key, we know that we have the issuer's cert // in the local keyring, so just use local keylisting. Kleo::KeyListJob * job = Kleo::CryptoBackendFactory::instance()->smime()->keyListJob( false ); assert( job ); connect( job, SIGNAL(result(const GpgME::KeyListResult&)), SLOT(slotCertificateChainListingResult(const GpgME::KeyListResult&)) ); connect( job, SIGNAL(nextKey(const GpgME::Key&)), SLOT(slotNextKey(const GpgME::Key&)) ); kdDebug() << "Going to fetch" << endl << " issuer : \"" << mChain.front().issuerName() << "\"" << endl << " chain id: " << mChain.front().chainID() << endl << "for" << endl << " subject : \"" << mChain.front().userID(0).id() << "\"" << endl << " subj.fpr: " << mChain.front().primaryFingerprint() << endl; const GpgME::Error err = job->start( mChain.front().chainID() ); if ( err ) showChainListError( this, err, mChain.front().issuerName() ); else (void)new Kleo::ProgressDialog( job, i18n("Fetching Certificate Chain"), this ); } void CertificateInfoWidgetImpl::startCertificateDump() { KProcess* proc = new KProcess( this ); (*proc) << "gpgsm"; // must be in the PATH (*proc) << "--dump-keys"; (*proc) << mChain.front().primaryFingerprint(); QObject::connect( proc, SIGNAL( receivedStdout(KProcess *, char *, int) ), this, SLOT( slotCollectStdout(KProcess *, char *, int) ) ); QObject::connect( proc, SIGNAL( receivedStderr(KProcess *, char *, int) ), this, SLOT( slotCollectStderr(KProcess *, char *, int) ) ); QObject::connect( proc, SIGNAL( processExited(KProcess*) ), this, SLOT( slotDumpProcessExited(KProcess*) ) ); if ( !proc->start( KProcess::NotifyOnExit, (KProcess::Communication)(KProcess::Stdout | KProcess::Stderr) ) ) { QString wmsg = i18n("Failed to execute gpgsm:\n%1").arg( i18n( "program not found" ) ); dumpView->setText( wmsg ); } } void CertificateInfoWidgetImpl::slotCollectStdout(KProcess *, char *buffer, int buflen) { mDumpOutput += QCString(buffer, buflen+1); // like KProcIO does } void CertificateInfoWidgetImpl::slotCollectStderr(KProcess *, char *buffer, int buflen) { mDumpError += QCString(buffer, buflen+1); // like KProcIO does } void CertificateInfoWidgetImpl::slotDumpProcessExited(KProcess* proc) { int rc = ( proc->normalExit() ) ? proc->exitStatus() : -1 ; if ( rc == 0 ) { dumpView->setText( QString::fromUtf8( mDumpOutput ) ); } else { if ( !mDumpError.isEmpty() ) { dumpView->setText( QString::fromUtf8( mDumpError ) ); } else { QString wmsg = i18n("Failed to execute gpgsm:\n%1"); if ( rc == -1 ) wmsg = wmsg.arg( i18n( "program cannot be executed" ) ); else wmsg = wmsg.arg( strerror(rc) ); dumpView->setText( wmsg ); } } proc->deleteLater(); } void CertificateInfoWidgetImpl::slotNextKey( const GpgME::Key & key ) { kdDebug() << "CertificateInfoWidgetImpl::slotNextKey( \"" << key.userID(0).id() << "\" )" << endl; if ( key.isNull() ) return; mFoundIssuer = true; mChain.push_front( key ); updateChainView(); // FIXME: cancel the keylisting. We're only interested in _one_ key. } void CertificateInfoWidgetImpl::updateChainView() { pathView->clear(); if ( mChain.empty() ) return; QListViewItem * item = 0; QValueList::const_iterator it = mChain.begin(); // root item: if ( (*it).chainID() && qstrcmp( (*it).chainID(), (*it).primaryFingerprint() ) == 0 ) item = new QListViewItem( pathView, Kleo::DN( (*it++).userID(0).id() ).prettyDN() ); else { item = new QListViewItem( pathView, i18n("Issuer certificate not found ( %1)") .arg( Kleo::DN( (*it).issuerName() ).prettyDN() ) ); item->setOpen( true ); // Qt bug: doesn't open after setEnabled( false ) :/ item->setEnabled( false ); } item->setOpen( true ); // subsequent items: while ( it != mChain.end() ) { item = new QListViewItem( item, Kleo::DN( (*it++).userID(0).id() ).prettyDN() ); item->setOpen( true ); } } void CertificateInfoWidgetImpl::slotCertificateChainListingResult( const GpgME::KeyListResult & res ) { if ( res.error() ) return showChainListError( this, res.error(), mChain.front().issuerName() ); else startCertificateChainListing(); } void CertificateInfoWidgetImpl::slotShowInfo( QListViewItem * item ) { textView->setText( item->text(1) ); } void CertificateInfoWidgetImpl::slotShowCertPathDetails( QListViewItem * item ) { if ( !item ) return; // find the key corresponding to "item". This hack would not be // necessary if pathView was a Kleo::KeyListView, but it's // Qt-Designer-generated and I don't feel like creating a custom // widget spec for Kleo::KeyListView. unsigned int totalCount = 0; int itemIndex = -1; for ( const QListViewItem * i = pathView->firstChild() ; i ; i = i->firstChild() ) { if ( i == item ) itemIndex = totalCount; ++totalCount; } assert( totalCount == mChain.size() || totalCount == mChain.size() + 1 ); // skip pseudo root item with "not found message": if ( totalCount == mChain.size() + 1 ) --itemIndex; assert( itemIndex >= 0 ); KDialogBase * dialog = new KDialogBase( this, "dialog", false, i18n("Additional Information for Key"), KDialogBase::Close, KDialogBase::Close ); CertificateInfoWidgetImpl * top = new CertificateInfoWidgetImpl( mChain[itemIndex], mExternal, dialog ); dialog->setMainWidget( top ); // proxy the signal to our receiver: connect( top, SIGNAL(requestCertificateDownload(const QString&, const QString&)), SIGNAL(requestCertificateDownload(const QString&, const QString&)) ); dialog->show(); } void CertificateInfoWidgetImpl::slotImportCertificate() { if ( mChain.empty() || mChain.back().isNull() ) return; const Kleo::DN dn = mChain.back().userID( 0 ).id(); emit requestCertificateDownload( mChain.back().primaryFingerprint(), dn.prettyDN() ); importButton->setEnabled( false ); } void CertificateInfoWidgetImpl::startKeyExistanceCheck() { if ( !mExternal ) // we already have it if it's from a local keylisting :) return; if ( mChain.empty() || mChain.back().isNull() ) // need a key to look for return; const QString fingerprint = mChain.back().primaryFingerprint(); if ( fingerprint.isEmpty() ) // empty pattern means list all keys. We don't want that return; // start _local_ keylistjob (no progressdialog needed here): Kleo::KeyListJob * job = Kleo::CryptoBackendFactory::instance()->smime()->keyListJob( false ); assert( job ); connect( job, SIGNAL(nextKey(const GpgME::Key&)), SLOT(slotKeyExistanceCheckNextCandidate(const GpgME::Key&)) ); connect( job, SIGNAL(result(const GpgME::KeyListResult&)), SLOT(slotKeyExistanceCheckFinished()) ); // nor to check for errors: job->start( fingerprint ); } void CertificateInfoWidgetImpl::slotKeyExistanceCheckNextCandidate( const GpgME::Key & key ) { if ( key.isNull() || mChain.empty() || !key.primaryFingerprint() ) return; if ( qstrcmp( key.primaryFingerprint(), mChain.back().primaryFingerprint() ) == 0 ) mHaveKeyLocally = true; } void CertificateInfoWidgetImpl::slotKeyExistanceCheckFinished() { importButton->setEnabled( !mHaveKeyLocally ); } #include "certificateinfowidgetimpl.moc" diff --git a/certmanager/certificateinfowidgetimpl.h b/certmanager/certificateinfowidgetimpl.h index 19eefff0ac..961d67c39f 100644 --- a/certmanager/certificateinfowidgetimpl.h +++ b/certmanager/certificateinfowidgetimpl.h @@ -1,87 +1,87 @@ /* certificateinfowidgetimpl.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef CERTIFICATEINFOWIDGETIMPL_H #define CERTIFICATEINFOWIDGETIMPL_H #include "certificateinfowidget.h" #include #include class KProcess; class QListViewItem; namespace GpgME { class KeyListResult; } class CertificateInfoWidgetImpl : public CertificateInfoWidget { Q_OBJECT public: CertificateInfoWidgetImpl( const GpgME::Key & key, bool external, QWidget * parent=0, const char * name=0); void setKey( const GpgME::Key & key ); signals: void requestCertificateDownload( const QString & fingerprint, const QString& displayName ); private slots: void slotShowInfo( QListViewItem* ); void slotShowCertPathDetails( QListViewItem* ); void slotImportCertificate(); void slotCertificateChainListingResult( const GpgME::KeyListResult & res ); void slotNextKey( const GpgME::Key & key ); void slotKeyExistanceCheckNextCandidate( const GpgME::Key & key ); void slotKeyExistanceCheckFinished(); void slotCollectStdout(KProcess *, char *, int); void slotCollectStderr(KProcess *, char *, int); void slotDumpProcessExited(KProcess*); private: void startCertificateChainListing(); void startCertificateDump(); void startKeyExistanceCheck(); void updateChainView(); private: QCString mDumpOutput; QCString mDumpError; QValueList mChain; bool mExternal; bool mFoundIssuer; bool mHaveKeyLocally; }; #endif // CERTIFICATEINFOWIDGETIMPL_H diff --git a/certmanager/certificatewizardimpl.cpp b/certmanager/certificatewizardimpl.cpp index 3f294294e3..8c2d6a8ac8 100644 --- a/certmanager/certificatewizardimpl.cpp +++ b/certmanager/certificatewizardimpl.cpp @@ -1,512 +1,515 @@ /* certificatewizardimpl.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "certificatewizardimpl.h" #include "storedtransferjob.h" // libkleopatra #include #include #include #include #include // gpgme++ #include // KDE #include #include #include #include #include #include #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include #include #include +#include static const unsigned int keyLengths[] = { 1024, 1532, 2048, 3072, 4096 }; static const unsigned int numKeyLengths = sizeof keyLengths / sizeof *keyLengths; static QString attributeLabel( const QString & attr, bool required ) { if ( attr.isEmpty() ) return QString::null; const QString label = Kleo::DNAttributeMapper::instance()->name2label( attr ); if ( !label.isEmpty() ) if ( required ) return i18n("Format string for the labels in the \"Your Personal Data\" page - required field", "*%1 (%2):").arg( label, attr ); else return i18n("Format string for the labels in the \"Your Personal Data\" page", "%1 (%2):").arg( label, attr ); else if ( required ) return '*' + attr + ':'; else return attr + ':'; } static QString attributeFromKey( QString key ) { return key.remove( '!' ); } static bool availForMod( const QLineEdit * le ) { return le && le->isEnabled(); } /* * Constructs a CertificateWizardImpl which is a child of 'parent', with the * name 'name' and widget flags set to 'f' * * The wizard will by default be modeless, unless you set 'modal' to * TRUE to construct a modal wizard. */ CertificateWizardImpl::CertificateWizardImpl( QWidget* parent, const char* name, bool modal, WFlags fl ) : CertificateWizard( parent, name, modal, fl ) { // don't allow to go to last page until a key has been generated setNextEnabled( generatePage, false ); // setNextEnabled( personalDataPage, false ); // ## disable again once we have a criteria when to enable again createPersonalDataPage(); // Allow to select remote URLs storeUR->setMode( KFile::File ); storeUR->setFilter( "application/pkcs10" ); connect( storeUR, SIGNAL( urlSelected( const QString& ) ), this, SLOT( slotURLSelected( const QString& ) ) ); const KConfigGroup config( KGlobal::config(), "CertificateCreationWizard" ); caEmailED->setText( config.readEntry( "CAEmailAddress" ) ); connect( this, SIGNAL( helpClicked() ), this, SLOT( slotHelpClicked() ) ); connect( insertAddressButton, SIGNAL( clicked() ), this, SLOT( slotSetValuesFromWhoAmI() ) ); for ( unsigned int i = 0 ; i < numKeyLengths ; ++i ) keyLengthCB->insertItem( i18n("%n bit", "%n bits", keyLengths[i] ) ); } static bool requirementsAreMet( const CertificateWizardImpl::AttrPairList & list ) { for ( CertificateWizardImpl::AttrPairList::const_iterator it = list.begin() ; it != list.end() ; ++it ) { const QLineEdit * le = (*it).second; if ( !le ) continue; const QString key = (*it).first; #ifndef NDEBUG kdbgstream s = kdDebug(); #else kndbgstream s = kdDebug(); #endif s << "requirementsAreMet(): checking \"" << key << "\" against \"" << le->text() << "\": "; if ( key.endsWith("!") && le->text().stripWhiteSpace().isEmpty() ) { s << "required field is empty!" << endl; return false; } s << "ok" << endl; } return true; } /* This slot is called when the user changes the text. */ void CertificateWizardImpl::slotEnablePersonalDataPageExit() { setNextEnabled( personalDataPage, requirementsAreMet( _attrPairList ) ); } /* * Destroys the object and frees any allocated resources */ CertificateWizardImpl::~CertificateWizardImpl() { // no need to delete child widgets, Qt does it all for us } static const char * oidForAttributeName( const QString & attr ) { QCString attrUtf8 = attr.utf8(); for ( unsigned int i = 0 ; i < numOidMaps ; ++i ) if ( qstricmp( attrUtf8, oidmap[i].name ) == 0 ) return oidmap[i].oid; return 0; } /* * protected slot */ void CertificateWizardImpl::slotGenerateCertificate() { // Ask gpgme to generate a key and return it QString certParms; certParms += "\n"; certParms += "Key-Type: RSA\n"; certParms += QString( "Key-Length: %1\n" ).arg( keyLengths[keyLengthCB->currentItem()] ); certParms += "Key-Usage: "; if ( signOnlyCB->isChecked() ) certParms += "Sign"; else if ( encryptOnlyCB->isChecked() ) certParms += "Encrypt"; else certParms += "Sign, Encrypt"; certParms += "\n"; certParms += "name-dn: "; QString email; QStringList rdns; for( AttrPairList::const_iterator it = _attrPairList.begin(); it != _attrPairList.end(); ++it ) { const QString attr = attributeFromKey( (*it).first.upper() ); const QLineEdit * le = (*it).second; if ( !le ) continue; const QString value = le->text().stripWhiteSpace(); if ( value.isEmpty() ) continue; if ( attr == "EMAIL" ) { // EMAIL is special, since it shouldn't be part of the DN, // except for non-RFC-conformant CAs that require it to be // there. email = value; if ( !brokenCA->isChecked() ) continue; } if ( const char * oid = oidForAttributeName( attr ) ) { // we need to translate the attribute name for the backend: rdns.push_back( QString::fromUtf8( oid ) + '=' + value ); } else { rdns.push_back( attr + '=' + value ); } } certParms += rdns.join(","); if( !email.isEmpty() ) certParms += "\nname-email: " + email; certParms += "\n\n"; kdDebug() << certParms << endl; Kleo::KeyGenerationJob * job = Kleo::CryptoBackendFactory::instance()->smime()->keyGenerationJob(); assert( job ); connect( job, SIGNAL(result(const GpgME::KeyGenerationResult&,const QByteArray&)), SLOT(slotResult(const GpgME::KeyGenerationResult&,const QByteArray&)) ); certificateTE->setText( certParms ); const GpgME::Error err = job->start( certParms ); if ( err ) KMessageBox::error( this, i18n( "Could not start certificate generation: %1" ) .arg( QString::fromLocal8Bit( err.asString() ) ), i18n( "Certificate Manager Error" ) ); else { generatePB->setEnabled( false ); setBackEnabled( generatePage, false ); (void)new Kleo::ProgressDialog( job, i18n("Generating key"), this ); } } void CertificateWizardImpl::slotResult( const GpgME::KeyGenerationResult & res, const QByteArray & keyData ) { //kdDebug() << "keyData.size(): " << keyData.size() << endl; _keyData = keyData; if ( res.error().isCanceled() || res.error() ) { setNextEnabled( generatePage, false ); setBackEnabled( generatePage, true ); setFinishEnabled( finishPage, false ); generatePB->setEnabled( true ); if ( !res.error().isCanceled() ) KMessageBox::error( this, i18n( "Could not generate certificate: %1" ) .arg( QString::fromLatin1( res.error().asString() ) ), i18n( "Certificate Manager Error" ) ); } else { // next will stay enabled until the user clicks Generate // Certificate again setNextEnabled( generatePage, true ); setFinishEnabled( finishPage, true ); } } void CertificateWizardImpl::slotHelpClicked() { kapp->invokeHelp( "newcert" ); } void CertificateWizardImpl::slotSetValuesFromWhoAmI() { const KABC::Addressee a = KABC::StdAddressBook::self( true )->whoAmI(); if ( a.isEmpty() ) return; const KABC::Address adr = a.address(KABC::Address::Work); for ( AttrPairList::const_iterator it = _attrPairList.begin() ; it != _attrPairList.end() ; ++it ) { QLineEdit * le = (*it).second; if ( !availForMod( le ) ) continue; const QString attr = attributeFromKey( (*it).first.upper() ); if ( attr == "CN" ) le->setText( a.formattedName() ); else if ( attr == "EMAIL" ) le->setText( a.preferredEmail() ); else if ( attr == "O" ) le->setText( a.organization() ); else if ( attr == "OU" ) le->setText( a.custom( "KADDRESSBOOK", "X-Department" ) ); else if ( attr == "L" ) le->setText( adr.locality() ); else if ( attr == "SP" ) le->setText( adr.region() ); else if ( attr == "PC" ) le->setText( adr.postalCode() ); else if ( attr == "SN" ) le->setText( a.familyName() ); else if ( attr == "GN" ) le->setText( a.givenName() ); else if ( attr == "T" ) le->setText( a.title() ); else if ( attr == "BC" ) le->setText( a.role() ); // correct mapping? } } void CertificateWizardImpl::createPersonalDataPage() { QGridLayout* grid = new QGridLayout( edContainer, 2, 1, KDialog::marginHint(), KDialog::spacingHint() ); KConfigGroup config( KGlobal::config(), "CertificateCreationWizard" ); QStringList attrOrder = config.readListEntry( "DNAttributeOrder" ); if ( attrOrder.empty() ) attrOrder << "CN!" << "L" << "OU" << "O!" << "C!" << "EMAIL!"; int row = 0; for ( QStringList::const_iterator it = attrOrder.begin() ; it != attrOrder.end() ; ++it, ++row ) { const QString key = (*it).stripWhiteSpace().upper(); const QString attr = attributeFromKey( key ); if ( attr.isEmpty() ) { --row; continue; } const QString preset = config.readEntry( attr ); const QString label = config.readEntry( attr + "_label", attributeLabel( attr, key.endsWith("!") ) ); QLineEdit * le = new QLineEdit( edContainer ); grid->addWidget( le, row, 1 ); grid->addWidget( new QLabel( le, label.isEmpty() ? attr : label, edContainer ), row, 0 ); le->setText( preset ); if ( config.entryIsImmutable( attr ) ) le->setEnabled( false ); _attrPairList.append(qMakePair(key, le)); connect( le, SIGNAL(textChanged(const QString&)), SLOT(slotEnablePersonalDataPageExit()) ); } // enable button only if administrator wants to allow it if (KABC::StdAddressBook::self( true )->whoAmI().isEmpty() || !config.readBoolEntry("ShowSetWhoAmI", true)) insertAddressButton->setEnabled( false ); slotEnablePersonalDataPageExit(); } bool CertificateWizardImpl::sendToCA() const { return sendToCARB->isChecked(); } QString CertificateWizardImpl::caEMailAddress() const { return caEmailED->text().stripWhiteSpace(); } void CertificateWizardImpl::slotURLSelected( const QString& _url ) { KURL url = KURL::fromPathOrURL( _url.stripWhiteSpace() ); #if ! KDE_IS_VERSION(3,2,90) // The application/pkcs10 mimetype didn't have a native extension, // so the filedialog didn't have the checkbox for auto-adding it. QString fileName = url.fileName(); int pos = fileName.findRev( '.' ); if ( pos < 0 ) // no extension url.setFileName( fileName + ".p10" ); #endif storeUR->setURL( url.prettyURL() ); } KURL CertificateWizardImpl::saveFileUrl() const { return KURL::fromPathOrURL( storeUR->url().stripWhiteSpace() ); } void CertificateWizardImpl::showPage( QWidget * page ) { CertificateWizard::showPage( page ); if ( page == generatePage ) { // Initial settings for the generation page: focus the correct lineedit // and disable the other one if ( storeInFileRB->isChecked() ) { storeUR->setEnabled( true ); caEmailED->setEnabled( false ); storeUR->setFocus(); } else { storeUR->setEnabled( false ); caEmailED->setEnabled( true ); caEmailED->setFocus(); } } } static const char* const dcopObjectId = "KMailIface"; /** Send the new certificate by mail using KMail */ void CertificateWizardImpl::sendCertificate( const QString& email, const QByteArray& certificateData ) { QString error; QCString dcopService; int result = KDCOPServiceStarter::self()-> findServiceFor( "DCOP/Mailer", QString::null, QString::null, &error, &dcopService ); if ( result != 0 ) { kdDebug() << "Couldn't connect to KMail\n"; KMessageBox::error( this, i18n( "DCOP Communication Error, unable to send certificate using KMail.\n%1" ).arg( error ) ); return; } QCString dummy; // OK, so kmail (or kontact) is running. Now ensure the object we want is available. - // This is kind of a limitation of findServiceFor, which should do this by itself, - // for that it needs to know the dcop object ID -> requires kdelibs API change. - if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dcopService, dummy ) ) { - KDCOPServiceStarter::self()->startServiceFor( "DCOP/Mailer", QString::null, - QString::null, &error, &dcopService ); - assert( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dcopService, dummy ) ); + // [that's not the case when kontact was already running, but kmail not loaded into it... in theory.] + if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ) { + DCOPRef ref( dcopService, dcopService ); // talk to the KUniqueApplication or its kontact wrapper + DCOPReply reply = ref.call( "load()" ); + if ( reply.isValid() && (bool)reply ) { + Q_ASSERT( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ); + } else + kdWarning() << "Error loading " << dcopService << endl; } DCOPClient* dcopClient = kapp->dcopClient(); QByteArray data; QDataStream arg( data, IO_WriteOnly ); arg << email; arg << certificateData; if( !dcopClient->send( dcopService, dcopObjectId, "sendCertificate(QString,QByteArray)", data ) ) { KMessageBox::error( this, i18n( "DCOP Communication Error, unable to send certificate using KMail." ) ); return; } // All good, close dialog CertificateWizard::accept(); } // Called when pressing Finish // We want to do the emailing/uploading first, before closing the dialog, // in case of errors during the upload. void CertificateWizardImpl::accept() { if( sendToCA() ) { // Ask KMail to send this key to the CA. sendCertificate( caEMailAddress(), _keyData ); } else { // Save in file/URL KURL url = saveFileUrl(); bool overwrite = false; if ( KIO::NetAccess::exists( url, false /*dest*/, this ) ) { if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel( this, i18n( "A file named \"%1\" already exists. " "Are you sure you want to overwrite it?" ).arg( url.prettyURL() ), i18n( "Overwrite File?" ), i18n( "&Overwrite" ) ) ) return; overwrite = true; } KIO::Job* uploadJob = KIOext::put( _keyData, url, -1, overwrite, false /*resume*/ ); uploadJob->setWindow( this ); connect( uploadJob, SIGNAL( result( KIO::Job* ) ), this, SLOT( slotUploadResult( KIO::Job* ) ) ); // Can't press finish again during the upload setFinishEnabled( finishPage, false ); } } /** This slot is invoked by the KIO job used in newCertificate to save/upload the certificate, when finished (success or error). */ void CertificateWizardImpl::slotUploadResult( KIO::Job* job ) { if ( job->error() ) { job->showErrorDialog(); setFinishEnabled( finishPage, true ); } else { // All good, close dialog CertificateWizard::accept(); } } #include "certificatewizardimpl.moc" diff --git a/certmanager/certificatewizardimpl.h b/certmanager/certificatewizardimpl.h index 52b8c5fce4..d275cbc721 100644 --- a/certmanager/certificatewizardimpl.h +++ b/certmanager/certificatewizardimpl.h @@ -1,88 +1,88 @@ /* certificatewizardimpl.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef CERTIFICATEWIZARDIMPL_H #define CERTIFICATEWIZARDIMPL_H #include "certificatewizard.h" #include #include #include #include namespace GpgME { class KeyGenerationResult; } namespace KIO { class Job; } class CertificateWizardImpl : public CertificateWizard { Q_OBJECT public: CertificateWizardImpl( QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0 ); ~CertificateWizardImpl(); bool sendToCA() const; QString caEMailAddress() const; KURL saveFileUrl() const; typedef QPair StringLEPair; typedef QValueVector< StringLEPair > AttrPairList; public: virtual void showPage( QWidget * page ); virtual void accept(); private slots: void slotGenerateCertificate(); void slotResult( const GpgME::KeyGenerationResult & res, const QByteArray & keyData ); void slotSetValuesFromWhoAmI(); void slotEnablePersonalDataPageExit(); void slotURLSelected( const QString& ); void slotHelpClicked(); void slotUploadResult( KIO::Job* ); private: void createPersonalDataPage(); void sendCertificate( const QString& email, const QByteArray& certificateData ); private: AttrPairList _attrPairList; QByteArray _keyData; }; #endif // CERTIFICATEWIZARDIMPL_H diff --git a/certmanager/certmanager.cpp b/certmanager/certmanager.cpp index 8bca1f17f8..a94b47e127 100644 --- a/certmanager/certmanager.cpp +++ b/certmanager/certmanager.cpp @@ -1,1370 +1,1382 @@ /* certmanager.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "certmanager.h" #include "certlistview.h" #include "certificatewizardimpl.h" #include "certificateinfowidgetimpl.h" #include "crlview.h" #include "customactions.h" #include "hierarchyanalyser.h" #include "storedtransferjob.h" #include "conf/configuredialog.h" // libkleopatra #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // GPGME++ #include #include #include // KDE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Qt #include #include // other #include #include #include -static const bool startWithHierarchicalKeyListing = false; - namespace { class KDE_EXPORT DisplayStrategy : public Kleo::KeyListView::DisplayStrategy{ public: ~DisplayStrategy() {} virtual QFont keyFont( const GpgME::Key& key, const QFont& font ) const { const Kleo::KeyFilter* filter = Kleo::KeyFilterManager::instance()->filterMatching( key ); return filter ? filter->font( font ) : font; } virtual QColor keyForeground( const GpgME::Key& key, const QColor& c ) const { const Kleo::KeyFilter* filter = Kleo::KeyFilterManager::instance()->filterMatching( key ); if ( filter && filter->fgColor().isValid() ) return filter->fgColor(); return c; } virtual QColor keyBackground( const GpgME::Key& key, const QColor& c ) const { const Kleo::KeyFilter* filter = Kleo::KeyFilterManager::instance()->filterMatching( key ); if ( filter && filter->bgColor().isValid() ) return filter->bgColor(); return c; } }; class KDE_EXPORT ColumnStrategy : public Kleo::KeyListView::ColumnStrategy { public: ~ColumnStrategy() {} QString title( int col ) const; QString text( const GpgME::Key & key, int col ) const; int width( int col, const QFontMetrics & fm ) const; }; QString ColumnStrategy::title( int col ) const { switch ( col ) { case 0: return i18n("Subject"); case 1: return i18n("Issuer"); case 2: return i18n("Serial"); default: return QString::null; } } QString ColumnStrategy::text( const GpgME::Key & key, int col ) const { switch ( col ) { case 0: return Kleo::DN( key.userID(0).id() ).prettyDN(); case 1: return Kleo::DN( key.issuerName() ).prettyDN(); case 2: return key.issuerSerial() ? QString::fromUtf8( key.issuerSerial() ) : QString::null ; default: return QString::null; } } int ColumnStrategy::width( int col, const QFontMetrics & fm ) const { int factor = -1; switch ( col ) { case 0: factor = 6; break; case 1: factor = 4; break; default: return -1; } return fm.width( title( col ) ) * factor; } } // anon namespace CertManager::CertManager( bool remote, const QString& query, const QString & import, QWidget* parent, const char* name, WFlags f ) : KMainWindow( parent, name, f|WDestructiveClose ), mCrlView( 0 ), mDirmngrProc( 0 ), mHierarchyAnalyser( 0 ), mLineEditAction( 0 ), mComboAction( 0 ), mFindAction( 0 ), mImportCertFromFileAction( 0 ), mImportCRLFromFileAction( 0 ), mNextFindRemote( false ), mRemote( remote ), mDirMngrFound( false ) { createStatusBar(); createActions(); createGUI(); setAutoSaveSettings(); // Main Window -------------------------------------------------- mKeyListView = new CertKeyListView( new ColumnStrategy(), new DisplayStrategy(), this, "mKeyListView" ); - mKeyListView->setHierarchical( startWithHierarchicalKeyListing ); - mKeyListView->setRootIsDecorated( startWithHierarchicalKeyListing ); mKeyListView->setSelectionMode( QListView::Extended ); setCentralWidget( mKeyListView ); connect( mKeyListView, SIGNAL(doubleClicked(Kleo::KeyListViewItem*,const QPoint&,int)), SLOT(slotViewDetails(Kleo::KeyListViewItem*)) ); connect( mKeyListView, SIGNAL(returnPressed(Kleo::KeyListViewItem*)), SLOT(slotViewDetails(Kleo::KeyListViewItem*)) ); connect( mKeyListView, SIGNAL(selectionChanged()), SLOT(slotSelectionChanged()) ); connect( mKeyListView, SIGNAL(contextMenu(Kleo::KeyListViewItem*, const QPoint&)), SLOT(slotContextMenu(Kleo::KeyListViewItem*, const QPoint&)) ); connect( mKeyListView, SIGNAL(dropped(const KURL::List&) ), SLOT( slotDropped(const KURL::List&) ) ); mLineEditAction->setText(query); if ( !mRemote || !query.isEmpty() ) slotSearch(); if ( !import.isEmpty() ) slotImportCertFromFile( KURL( import ) ); + readConfig(); updateStatusBarLabels(); slotSelectionChanged(); // initial state for selection-dependent actions } CertManager::~CertManager() { + writeConfig(); delete mDirmngrProc; mDirmngrProc = 0; delete mHierarchyAnalyser; mHierarchyAnalyser = 0; } +void CertManager::readConfig() { + KConfig config( "kleopatrarc" ); + config.setGroup( "Display Options" ); + slotToggleHierarchicalView( config.readBoolEntry( "hierarchicalView", false ) ); +} + +void CertManager::writeConfig() { + KConfig config( "kleopatrarc" ); + config.setGroup( "Display Options" ); + config.writeEntry( "hierarchicalView", mKeyListView->hierarchical() ); +} + void CertManager::createStatusBar() { KStatusBar * bar = statusBar(); mProgressBar = new Kleo::ProgressBar( bar, "mProgressBar" ); mProgressBar->reset(); mProgressBar->setFixedSize( QSize( 100, mProgressBar->height() * 3 / 5 ) ); bar->addWidget( mProgressBar, 0, true ); mStatusLabel = new QLabel( bar, "mStatusLabel" ); bar->addWidget( mStatusLabel, 1, false ); } static inline void connectEnableOperationSignal( QObject * s, QObject * d ) { QObject::connect( s, SIGNAL(enableOperations(bool)), d, SLOT(setEnabled(bool)) ); } void CertManager::createActions() { KAction * action = 0; (void)KStdAction::quit( this, SLOT(close()), actionCollection() ); action = KStdAction::redisplay( this, SLOT(slotRedisplay()), actionCollection() ); // work around the fact that the stdaction has no shortcut KShortcut reloadShortcut = KStdAccel::shortcut(KStdAccel::Reload); reloadShortcut.append(KKey(CTRL + Key_R)); action->setShortcut( reloadShortcut ); connectEnableOperationSignal( this, action ); action = new KAction( i18n("Stop Operation"), "stop", Key_Escape, this, SIGNAL(stopOperations()), actionCollection(), "view_stop_operations" ); action->setEnabled( false ); (void) new KAction( i18n("New Key Pair..."), "filenew", 0, this, SLOT(newCertificate()), actionCollection(), "file_new_certificate" ); connect( new KToggleAction( i18n("Hierarchical Key List"), 0, actionCollection(), "view_hierarchical" ), SIGNAL(toggled(bool)), SLOT(slotToggleHierarchicalView(bool)) ); action = new KAction( i18n("Expand All"), 0, CTRL+Key_Period, this, SLOT(slotExpandAll()), actionCollection(), "view_expandall" ); - action->setEnabled( startWithHierarchicalKeyListing ); action = new KAction( i18n("Collapse All"), 0, CTRL+Key_Comma, this, SLOT(slotCollapseAll()), actionCollection(), "view_collapseall" ); - action->setEnabled( startWithHierarchicalKeyListing ); (void) new KAction( i18n("Refresh CRLs"), 0, 0, this, SLOT(slotRefreshKeys()), actionCollection(), "certificates_refresh_clr" ); #ifdef NOT_IMPLEMENTED_ANYWAY mRevokeCertificateAction = new KAction( i18n("Revoke"), 0, this, SLOT(revokeCertificate()), actionCollection(), "edit_revoke_certificate" ); connectEnableOperationSignal( this, mRevokeCertificateAction ); mExtendCertificateAction = new KAction( i18n("Extend"), 0, this, SLOT(extendCertificate()), actionCollection(), "edit_extend_certificate" ); connectEnableOperationSignal( this, mExtendCertificateAction ); #endif mDeleteCertificateAction = new KAction( i18n("Delete"), "editdelete", Key_Delete, this, SLOT(slotDeleteCertificate()), actionCollection(), "edit_delete_certificate" ); connectEnableOperationSignal( this, mDeleteCertificateAction ); mValidateCertificateAction = new KAction( i18n("Validate"), "reload", SHIFT + Key_F5, this, SLOT(slotValidate()), actionCollection(), "certificates_validate" ); connectEnableOperationSignal( this, mValidateCertificateAction ); mImportCertFromFileAction = new KAction( i18n("Import Certificates..."), 0, this, SLOT(slotImportCertFromFile()), actionCollection(), "file_import_certificates" ); connectEnableOperationSignal( this, mImportCertFromFileAction ); mImportCRLFromFileAction = new KAction( i18n("Import CRLs..."), 0, this, SLOT(importCRLFromFile()), actionCollection(), "file_import_crls" ); connectEnableOperationSignal( this, mImportCRLFromFileAction ); mExportCertificateAction = new KAction( i18n("Export Certificates..."), "export", 0, this, SLOT(slotExportCertificate()), actionCollection(), "file_export_certificate" ); mExportSecretKeyAction = new KAction( i18n("Export Secret Key..."), "export", 0, this, SLOT(slotExportSecretKey()), actionCollection(), "file_export_secret_keys" ); connectEnableOperationSignal( this, mExportSecretKeyAction ); mViewCertDetailsAction = new KAction( i18n("Certificate Details..."), 0, 0, this, SLOT(slotViewDetails()), actionCollection(), "view_certificate_details" ); mDownloadCertificateAction = new KAction( i18n( "Download"), 0, 0, this, SLOT(slotDownloadCertificate()), actionCollection(), "download_certificate" ); const QString dirmngr = KStandardDirs::findExe( "gpgsm" ); mDirMngrFound = !dirmngr.isEmpty(); action = new KAction( i18n("Dump CRL Cache..."), 0, this, SLOT(slotViewCRLs()), actionCollection(), "crl_dump_crl_cache" ); action->setEnabled( mDirMngrFound ); // we also need dirmngr for this action = new KAction( i18n("Clear CRL Cache..."), 0, this, SLOT(slotClearCRLs()), actionCollection(), "crl_clear_crl_cache" ); action->setEnabled( mDirMngrFound ); // we also need dirmngr for this action = new KAction( i18n("GnuPG Log Viewer..."), "pgp-keys", 0, this, SLOT(slotStartWatchGnuPG()), actionCollection(), "tools_start_kwatchgnupg"); // disable action if no kwatchgnupg binary is around if (KStandardDirs::findExe("kwatchgnupg").isEmpty()) action->setEnabled(false); (void)new LabelAction( i18n("Search:"), actionCollection(), "label_action" ); mLineEditAction = new LineEditAction( QString::null, actionCollection(), this, SLOT(slotSearch()), "query_lineedit_action"); QStringList lst; lst << i18n("In Local Certificates") << i18n("In External Certificates"); mComboAction = new ComboAction( lst, actionCollection(), this, SLOT( slotToggleRemote(int) ), "location_combo_action"); mFindAction = new KAction( i18n("Find"), "find", 0, this, SLOT(slotSearch()), actionCollection(), "find" ); KStdAction::keyBindings( this, SLOT(slotEditKeybindings()), actionCollection() ); KStdAction::preferences( this, SLOT(slotShowConfigurationDialog()), actionCollection() ); new KAction( i18n( "Configure &GpgME Backend" ), 0, 0, this, SLOT(slotConfigureGpgME()), actionCollection(), "configure_gpgme" ); createStandardStatusBarAction(); updateImportActions( true ); } void CertManager::updateImportActions( bool enable ) { mImportCRLFromFileAction->setEnabled( mDirMngrFound && enable ); mImportCertFromFileAction->setEnabled( enable ); } void CertManager::slotEditKeybindings() { KKeyDialog::configure( actionCollection(), true ); } void CertManager::slotShowConfigurationDialog() { ConfigureDialog dlg( this ); connect( &dlg, SIGNAL( configCommitted() ), SLOT( slotRepaint() ) ); dlg.exec(); } void CertManager::slotConfigureGpgME() { Kleo::CryptoConfig* config = Kleo::CryptoBackendFactory::instance()->config(); if ( config ) { Kleo::CryptoConfigDialog dlg( config ); int result = dlg.exec(); // Forget all data parsed from gpgconf, so that we show updated information // when reopening the configuration dialog. config->clear(); if ( result == QDialog::Accepted ) { // Tell other apps (e.g. kmail) that the gpgconf data might have changed kapp->dcopClient()->emitDCOPSignal( "KPIM::CryptoConfig", "changed()", QByteArray() ); } } } void CertManager::slotRepaint() { mKeyListView->repaintContents(); } void CertManager::slotToggleRemote( int idx ) { mNextFindRemote = idx != 0; } void CertManager::slotToggleHierarchicalView( bool hier ) { mKeyListView->setHierarchical( hier ); mKeyListView->setRootIsDecorated( hier ); if ( KAction * act = action("view_expandall") ) act->setEnabled( hier ); if ( KAction * act = action("view_collapseall" ) ) act->setEnabled( hier ); + if ( KToggleAction * act = + static_cast( action("view_hierarchical") ) ) + act->setChecked( hier ); + if ( hier && !mCurrentQuery.isEmpty() ) startRedisplay( false ); } void CertManager::slotExpandAll() { for ( QListViewItemIterator it( mKeyListView ) ; it.current() ; ++it ) it.current()->setOpen( true ); } void CertManager::slotCollapseAll() { for ( QListViewItemIterator it( mKeyListView ) ; it.current() ; ++it ) it.current()->setOpen( false ); } void CertManager::connectJobToStatusBarProgress( Kleo::Job * job, const QString & initialText ) { assert( mProgressBar ); if ( !job ) return; if ( !initialText.isEmpty() ) statusBar()->message( initialText ); connect( job, SIGNAL(progress(const QString&,int,int)), mProgressBar, SLOT(slotProgress(const QString&,int,int)) ); connect( job, SIGNAL(done()), mProgressBar, SLOT(reset()) ); connect( this, SIGNAL(stopOperations()), job, SLOT(slotCancel()) ); action("view_stop_operations")->setEnabled( true ); emit enableOperations( false ); } void CertManager::disconnectJobFromStatusBarProgress( const GpgME::Error & err ) { updateStatusBarLabels(); const QString msg = err.isCanceled() ? i18n("Canceled.") : err ? i18n("Failed.") : i18n("Done.") ; statusBar()->message( msg, 4000 ); action("view_stop_operations")->setEnabled( false ); emit enableOperations( true ); slotSelectionChanged(); } void CertManager::updateStatusBarLabels() { mKeyListView->flushKeys(); int total = 0; for ( QListViewItemIterator it( mKeyListView ) ; it.current() ; ++it ) ++total; mStatusLabel->setText( i18n( "%n Key.","%n Keys.", total ) ); } // // // Key Listing: // // static std::set extractKeyFingerprints( const QPtrList & items ) { std::set result; for ( QPtrListIterator it( items ) ; it.current() ; ++it ) if ( const char * fpr = it.current()->key().primaryFingerprint() ) result.insert( fpr ); return result; } static QStringList stringlistFromSet( const std::set & set ) { // ARGH. This is madness. Shitty Qt containers don't support QStringList( patterns.begin(), patterns.end() ) :/ QStringList sl; for ( std::set::const_iterator it = set.begin() ; it != set.end() ; ++it ) // let's make extra sure, maybe someone tries to make Qt not support std::string->QString conversion sl.push_back( QString::fromLatin1( it->c_str() ) ); return sl; } void CertManager::slotRefreshKeys() { const QStringList keys = stringlistFromSet( extractKeyFingerprints( mKeyListView->selectedItems() ) ); Kleo::RefreshKeysJob * job = Kleo::CryptoBackendFactory::instance()->smime()->refreshKeysJob(); assert( job ); connect( job, SIGNAL(result(const GpgME::Error&)), this, SLOT(slotRefreshKeysResult(const GpgME::Error&)) ); connectJobToStatusBarProgress( job, i18n("Refreshing keys...") ); if ( const GpgME::Error err = job->start( keys ) ) slotRefreshKeysResult( err ); } void CertManager::slotRefreshKeysResult( const GpgME::Error & err ) { disconnectJobFromStatusBarProgress( err ); if ( err.isCanceled() ) return; if ( err ) KMessageBox::error( this, i18n("An error occurred while trying to refresh " "keys:\n%1").arg( QString::fromLocal8Bit( err.asString() ) ), i18n("Refreshing Keys Failed") ); } static void showKeyListError( QWidget * parent, const GpgME::Error & err ) { assert( err ); const QString msg = i18n( "

An error occurred while fetching " "the certificates from the backend:

" "

%1

" ) .arg( QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n( "Certificate Listing Failed" ) ); } void CertManager::slotSearch() { mPreviouslySelectedFingerprints.clear(); // Clear display mKeyListView->clear(); mCurrentQuery = mLineEditAction->text(); startKeyListing( false, false, mCurrentQuery ); } void CertManager::startRedisplay( bool validate ) { mPreviouslySelectedFingerprints = extractKeyFingerprints( mKeyListView->selectedItems() ); if ( mPreviouslySelectedFingerprints.empty() ) startKeyListing( validate, true, mCurrentQuery ); else startKeyListing( validate, true, mPreviouslySelectedFingerprints ); } void CertManager::startKeyListing( bool validating, bool refresh, const std::set & patterns ) { startKeyListing( validating, refresh, stringlistFromSet( patterns ) ); } void CertManager::startKeyListing( bool validating, bool refresh, const QStringList & patterns ) { mRemote = mNextFindRemote; mLineEditAction->setEnabled( false ); mComboAction->setEnabled( false ); mFindAction->setEnabled( false ); Kleo::KeyListJob * job = 0; if ( !validating && !refresh && mKeyListView->hierarchical() && !patterns.empty() ) job = new Kleo::HierarchicalKeyListJob( Kleo::CryptoBackendFactory::instance()->smime(), mRemote, false, validating ); else job = Kleo::CryptoBackendFactory::instance()->smime()->keyListJob( mRemote, false, validating ); assert( job ); connect( job, SIGNAL(nextKey(const GpgME::Key&)), mKeyListView, refresh ? SLOT(slotRefreshKey(const GpgME::Key&)) : SLOT(slotAddKey(const GpgME::Key&)) ); connect( job, SIGNAL(result(const GpgME::KeyListResult&)), this, SLOT(slotKeyListResult(const GpgME::KeyListResult&)) ); connectJobToStatusBarProgress( job, i18n("Fetching keys...") ); const GpgME::Error err = job->start( patterns ) ; if ( err ) { showKeyListError( this, err ); return; } mProgressBar->setProgress( 0, 0 ); // enable busy indicator } static void selectKeys( Kleo::KeyListView * lv, const std::set & fprs ) { if ( !lv || fprs.empty() ) return; for ( QListViewItemIterator it( lv ) ; it.current() ; ++it ) if ( Kleo::KeyListViewItem * item = Kleo::lvi_cast( it.current() ) ) { const char * fpr = item->key().primaryFingerprint(); item->setSelected( fpr && fprs.find( fpr ) != fprs.end() ); } } void CertManager::slotKeyListResult( const GpgME::KeyListResult & res ) { if ( res.error() ) showKeyListError( this, res.error() ); else if ( res.isTruncated() ) KMessageBox::information( this, i18n("The query result has been truncated.\n" "Either the local or a remote limit on " "the maximum number of returned hits has " "been exceeded.\n" "You can try to increase the local limit " "in the configuration dialog, but if one " "of the configured servers is the limiting " "factor, you have to refine your search.") ); mLineEditAction->setEnabled( true ); mComboAction->setEnabled( true ); mFindAction->setEnabled( true ); mLineEditAction->focusAll(); disconnectJobFromStatusBarProgress( res.error() ); selectKeys( mKeyListView, mPreviouslySelectedFingerprints ); } void CertManager::slotContextMenu(Kleo::KeyListViewItem* item, const QPoint& point) { if ( !item ) return; if ( QPopupMenu * popup = static_cast(factory()->container("listview_popup",this)) ) popup->exec( point ); } /** This slot is invoked when the user selects "New certificate" */ void CertManager::newCertificate() { CertificateWizardImpl wizard( this ); wizard.exec(); } /** This slot is invoked when the user selects revoke certificate. The slot will revoke the selected certificates */ void CertManager::revokeCertificate() { qDebug("Not Yet Implemented"); } /** This slot is invoked when the user selects extend certificate. It will send an extension request for the selected certificates */ void CertManager::extendCertificate() { qDebug("Not Yet Implemented"); } // // // Downloading / Importing Certificates // // /** This slot is invoked when the user selects Certificates/Import/From File. */ void CertManager::slotImportCertFromFile() { const QString filter = "application/x-x509-ca-cert application/x-pkcs12 application/pkcs7-mime"; //const QString filter = QString("*.pem *.der *.p7c *.p12|") + i18n("Certificates (*.pem *.der *.p7c *.p12)"); slotImportCertFromFile( KFileDialog::getOpenURL( QString::null, filter, this, i18n( "Select Certificate File" ) ) ); } void CertManager::slotImportCertFromFile( const KURL & certURL ) { if ( !certURL.isValid() ) // empty or malformed return; mPreviouslySelectedFingerprints.clear(); // Prevent two simultaneous imports updateImportActions( false ); // Download the cert KIOext::StoredTransferJob* importJob = KIOext::storedGet( certURL ); importJob->setWindow( this ); connect( importJob, SIGNAL(result(KIO::Job*)), SLOT(slotImportResult(KIO::Job*)) ); } void CertManager::slotImportResult( KIO::Job* job ) { if ( job->error() ) { job->showErrorDialog(); } else { KIOext::StoredTransferJob* trJob = static_cast( job ); startCertificateImport( trJob->data(), trJob->url().fileName() ); } updateImportActions( true ); } static void showCertificateDownloadError( QWidget * parent, const GpgME::Error & err, const QString& certDisplayName ) { assert( err ); const QString msg = i18n( "

An error occurred while trying " "to download the certificate %1:

" "

%2

" ) .arg( certDisplayName ) .arg( QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n( "Certificate Download Failed" ) ); } void CertManager::slotDownloadCertificate() { mPreviouslySelectedFingerprints.clear(); QPtrList items = mKeyListView->selectedItems(); for ( QPtrListIterator it( items ) ; it.current() ; ++it ) if ( !it.current()->key().isNull() ) if ( const char * fpr = it.current()->key().primaryFingerprint() ) slotStartCertificateDownload( fpr, it.current()->text(0) ); } // Called from slotDownloadCertificate and from the certificate-details widget void CertManager::slotStartCertificateDownload( const QString& fingerprint, const QString& displayName ) { if ( fingerprint.isEmpty() ) return; Kleo::DownloadJob * job = Kleo::CryptoBackendFactory::instance()->smime()->downloadJob( false /* no armor */ ); assert( job ); connect( job, SIGNAL(result(const GpgME::Error&,const QByteArray&)), SLOT(slotCertificateDownloadResult(const GpgME::Error&,const QByteArray&)) ); connectJobToStatusBarProgress( job, i18n("Fetching certificate from server...") ); const GpgME::Error err = job->start( fingerprint ); if ( err ) showCertificateDownloadError( this, err, displayName ); else { mProgressBar->setProgress( 0, 0 ); mJobsDisplayNameMap.insert( job, displayName ); } } QString CertManager::displayNameForJob( const Kleo::Job *job ) { JobsDisplayNameMap::iterator it = mJobsDisplayNameMap.find( job ); QString displayName; if ( it != mJobsDisplayNameMap.end() ) { displayName = *it; mJobsDisplayNameMap.remove( it ); } else { kdWarning() << "Job not found in map: " << job << endl; } return displayName; } // Don't call directly! void CertManager::slotCertificateDownloadResult( const GpgME::Error & err, const QByteArray & keyData ) { QString displayName = displayNameForJob( static_cast( sender() ) ); if ( err ) showCertificateDownloadError( this, err, displayName ); else startCertificateImport( keyData, displayName ); disconnectJobFromStatusBarProgress( err ); } static void showCertificateImportError( QWidget * parent, const GpgME::Error & err, const QString& certDisplayName ) { assert( err ); const QString msg = i18n( "

An error occurred while trying " "to import the certificate %1:

" "

%2

" ) .arg( certDisplayName ) .arg( QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n( "Certificate Import Failed" ) ); } void CertManager::startCertificateImport( const QByteArray & keyData, const QString& certDisplayName ) { Kleo::ImportJob * job = Kleo::CryptoBackendFactory::instance()->smime()->importJob(); assert( job ); connect( job, SIGNAL(result(const GpgME::ImportResult&)), SLOT(slotCertificateImportResult(const GpgME::ImportResult&)) ); connectJobToStatusBarProgress( job, i18n("Importing certificates...") ); kdDebug() << "Importing certificate. keyData size:" << keyData.size() << endl; const GpgME::Error err = job->start( keyData ); if ( err ) showCertificateImportError( this, err, certDisplayName ); else { mProgressBar->setProgress( 0, 0 ); mJobsDisplayNameMap.insert( job, certDisplayName ); } } void CertManager::slotCertificateImportResult( const GpgME::ImportResult & res ) { QString displayName = displayNameForJob( static_cast( sender() ) ); if ( res.error().isCanceled() ) { // do nothing } else if ( res.error() ) { showCertificateImportError( this, res.error(), displayName ); } else { const QString normalLine = i18n("%1%2"); const QString boldLine = i18n("%1%2"); QStringList lines; lines.push_back( normalLine.arg( i18n("Total number processed:"), QString::number( res.numConsidered() ) ) ); lines.push_back( normalLine.arg( i18n("Imported:"), QString::number( res.numImported() ) ) ); if ( res.newSignatures() ) lines.push_back( normalLine.arg( i18n("New signatures:"), QString::number( res.newSignatures() ) ) ); if ( res.newUserIDs() ) lines.push_back( normalLine.arg( i18n("New user IDs:"), QString::number( res.newUserIDs() ) ) ); if ( res.numKeysWithoutUserID() ) lines.push_back( normalLine.arg( i18n("Keys without user IDs:"), QString::number( res.numKeysWithoutUserID() ) ) ); if ( res.newSubkeys() ) lines.push_back( normalLine.arg( i18n("New subkeys:"), QString::number( res.newSubkeys() ) ) ); if ( res.newRevocations() ) lines.push_back( boldLine.arg( i18n("Newly revoked:"), QString::number( res.newRevocations() ) ) ); if ( res.notImported() ) lines.push_back( boldLine.arg( i18n("Not imported:"), QString::number( res.notImported() ) ) ); if ( res.numUnchanged() ) lines.push_back( normalLine.arg( i18n("Unchanged:"), QString::number( res.numUnchanged() ) ) ); if ( res.numSecretKeysConsidered() ) lines.push_back( normalLine.arg( i18n("Secret keys processed:"), QString::number( res.numSecretKeysConsidered() ) ) ); if ( res.numSecretKeysImported() ) lines.push_back( normalLine.arg( i18n("Secret keys imported:"), QString::number( res.numSecretKeysImported() ) ) ); if ( res.numSecretKeysConsidered() - res.numSecretKeysImported() - res.numSecretKeysUnchanged() > 0 ) lines.push_back( boldLine.arg( i18n("Secret keys not imported:"), QString::number( res.numSecretKeysConsidered() - res.numSecretKeysImported() - res.numSecretKeysUnchanged() ) ) ); if ( res.numSecretKeysUnchanged() ) lines.push_back( normalLine.arg( i18n("Secret keys unchanged:"), QString::number( res.numSecretKeysUnchanged() ) ) ); KMessageBox::information( this, i18n( "

Detailed results of importing %1:

" "%2
" ) .arg( displayName ).arg( lines.join( QString::null ) ), i18n( "Certificate Import Result" ) ); disconnectJobFromStatusBarProgress( res.error() ); // save the fingerprints of imported certs for later selection: const std::vector imports = res.imports(); for ( std::vector::const_iterator it = imports.begin() ; it != imports.end() ; ++it ) mPreviouslySelectedFingerprints.insert( it->fingerprint() ); } importNextURLOrRedisplay(); } /** This slot is called when the dirmngr process that imports a certificate file exists. */ void CertManager::slotDirmngrExited() { if ( !mDirmngrProc->normalExit() ) KMessageBox::error( this, i18n( "The GpgSM process that tried to import the CRL file ended prematurely because of an unexpected error." ), i18n( "Certificate Manager Error" ) ); else if ( mDirmngrProc->exitStatus() ) KMessageBox::error( this, i18n( "An error occurred when trying to import the CRL file. The output from GpgSM was:\n%1").arg( mErrorbuffer ), i18n( "Certificate Manager Error" ) ); else KMessageBox::information( this, i18n( "CRL file imported successfully." ), i18n( "Certificate Manager Information" ) ); delete mDirmngrProc; mDirmngrProc = 0; if ( !mImportCRLTempFile.isEmpty() ) QFile::remove( mImportCRLTempFile ); updateImportActions( true ); } /** This slot will import CRLs from a file. */ void CertManager::importCRLFromFile() { QString filter = QString("*.crl *.arl *-crl.der *-arl.der|") + i18n("Certificate Revocation List (*.crl *.arl *-crl.der *-arl.der)"); KURL url = KFileDialog::getOpenURL( QString::null, filter, this, i18n( "Select CRL File" ) ); if ( url.isValid() ) { updateImportActions( false ); if ( url.isLocalFile() ) { startImportCRL( url.path(), false ); updateImportActions( true ); } else { KTempFile tempFile; KURL destURL; destURL.setPath( tempFile.name() ); KIO::Job* copyJob = KIO::file_copy( url, destURL, 0600, true, false ); copyJob->setWindow( this ); connect( copyJob, SIGNAL( result( KIO::Job * ) ), SLOT( slotImportCRLJobFinished( KIO::Job * ) ) ); } } } void CertManager::slotImportCRLJobFinished( KIO::Job *job ) { KIO::FileCopyJob* fcjob = static_cast( job ); QString tempFilePath = fcjob->destURL().path(); if ( job->error() ) { job->showErrorDialog(); QFile::remove( tempFilePath ); // unlink tempfile updateImportActions( true ); return; } startImportCRL( tempFilePath, true ); } bool CertManager::connectAndStartDirmngr( const char * slot, const char * processname ) { assert( slot ); assert( processname ); assert( mDirmngrProc ); mErrorbuffer = QString::null; connect( mDirmngrProc, SIGNAL(processExited(KProcess*)), slot ); connect( mDirmngrProc, SIGNAL(receivedStderr(KProcess*,char*,int) ), this, SLOT(slotStderr(KProcess*,char*,int)) ); if( !mDirmngrProc->start( KProcess::NotifyOnExit, KProcess::Stderr ) ) { delete mDirmngrProc; mDirmngrProc = 0; KMessageBox::error( this, i18n( "Unable to start %1 process. Please check your installation." ).arg( processname ), i18n( "Certificate Manager Error" ) ); return false; } return true; } void CertManager::startImportCRL( const QString& filename, bool isTempFile ) { assert( !mDirmngrProc ); mImportCRLTempFile = isTempFile ? filename : QString::null; mDirmngrProc = new KProcess(); *mDirmngrProc << "gpgsm" << "--call-dirmngr" << "loadcrl" << filename; if ( !connectAndStartDirmngr( SLOT(slotDirmngrExited()), "gpgsm" ) ) { updateImportActions( true ); if ( isTempFile ) QFile::remove( mImportCRLTempFile ); // unlink tempfile } } void CertManager::startClearCRLs() { assert( !mDirmngrProc ); mDirmngrProc = new KProcess(); *mDirmngrProc << "dirmngr" << "--flush"; //*mDirmngrProc << "gpgsm" << "--call-dimngr" << "flush"; // use this once it's implemented! connectAndStartDirmngr( SLOT(slotClearCRLsResult()), "dirmngr" ); } void CertManager::slotStderr( KProcess*, char* buf, int len ) { mErrorbuffer += QString::fromLocal8Bit( buf, len ); } /** This slot will import CRLs from an LDAP server. */ void CertManager::importCRLFromLDAP() { qDebug("Not Yet Implemented"); } void CertManager::slotViewCRLs() { if ( !mCrlView ) mCrlView = new CRLView( this ); mCrlView->show(); mCrlView->slotUpdateView(); } void CertManager::slotClearCRLs() { startClearCRLs(); } void CertManager::slotClearCRLsResult() { assert( mDirmngrProc ); if ( !mDirmngrProc->normalExit() ) KMessageBox::error( this, i18n( "The DirMngr process that tried to clear the CRL cache ended prematurely because of an unexpected error." ), i18n( "Certificate Manager Error" ) ); else if ( mDirmngrProc->exitStatus() ) KMessageBox::error( this, i18n( "An error occurred when trying to clear the CRL cache. The output from DirMngr was:\n%1").arg( mErrorbuffer ), i18n( "Certificate Manager Error" ) ); else KMessageBox::information( this, i18n( "CRL cache cleared successfully." ), i18n( "Certificate Manager Information" ) ); delete mDirmngrProc; mDirmngrProc = 0; } static void showDeleteError( QWidget * parent, const GpgME::Error & err ) { assert( err ); const QString msg = i18n("

An error occurred while trying to delete " "the certificates:

" "

%1

") .arg( QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n("Certificate Deletion Failed") ); } static bool ByFingerprint( const GpgME::Key & left, const GpgME::Key & right ) { return qstricmp( left.primaryFingerprint(), right.primaryFingerprint() ) < 0 ; } static bool WithRespectToFingerprints( const GpgME::Key & left, const GpgME::Key & right ) { return qstricmp( left.primaryFingerprint(), right.primaryFingerprint() ) == 0; } void CertManager::slotDeleteCertificate() { mItemsToDelete = mKeyListView->selectedItems(); if ( mItemsToDelete.isEmpty() ) return; std::vector keys; keys.reserve( mItemsToDelete.count() ); QStringList keyDisplayNames; for ( QPtrListIterator it( mItemsToDelete ) ; it.current() ; ++it ) if ( !it.current()->key().isNull() ) { keys.push_back( it.current()->key() ); keyDisplayNames.push_back( it.current()->text( 0 ) ); } if ( keys.empty() ) return; if ( !mHierarchyAnalyser ) { mHierarchyAnalyser = new HierarchyAnalyser( this, "mHierarchyAnalyser" ); Kleo::KeyListJob * job = Kleo::CryptoBackendFactory::instance()->smime()->keyListJob(); assert( job ); connect( job, SIGNAL(nextKey(const GpgME::Key&)), mHierarchyAnalyser, SLOT(slotNextKey(const GpgME::Key&)) ); connect( job, SIGNAL(result(const GpgME::KeyListResult&)), this, SLOT(slotDeleteCertificate()) ); connectJobToStatusBarProgress( job, i18n("Checking key dependencies...") ); if ( const GpgME::Error error = job->start( QStringList() ) ) { showKeyListError( this, error ); delete mHierarchyAnalyser; mHierarchyAnalyser = 0; } return; } else disconnectJobFromStatusBarProgress( 0 ); std::vector keysToDelete = keys; for ( std::vector::const_iterator it = keys.begin() ; it != keys.end() ; ++it ) if ( !it->isNull() ) { const std::vector subjects = mHierarchyAnalyser->subjectsForIssuerRecursive( it->primaryFingerprint() ); keysToDelete.insert( keysToDelete.end(), subjects.begin(), subjects.end() ); } std::sort( keysToDelete.begin(), keysToDelete.end(), ByFingerprint ); keysToDelete.erase( std::unique( keysToDelete.begin(), keysToDelete.end(), WithRespectToFingerprints ), keysToDelete.end() ); delete mHierarchyAnalyser; mHierarchyAnalyser = 0; if ( keysToDelete.size() > keys.size() ) if ( KMessageBox::warningContinueCancel( this, i18n("Some or all of the selected " "certificates are issuers (CA certificates) " "for other, non-selected certificates.\n" "Deleting a CA certificate will also delete " "all certificates issued by it."), i18n("Deleting CA Certificates") ) != KMessageBox::Continue ) return; const QString msg = keysToDelete.size() > keys.size() ? i18n("Do you really want to delete this certificate and the %1 certificates it certified?", "Do you really want to delete these %n certificates and the %1 certificates they certified?", keys.size() ).arg( keysToDelete.size() - keys.size() ) : i18n("Do you really want to delete this certificate?", "Do you really want to delete these %n certificates?", keys.size() ) ; if ( KMessageBox::warningContinueCancelList( this, msg, keyDisplayNames, i18n( "Delete Certificates" ), KGuiItem( i18n( "Delete" ), "editdelete" ), "ConfirmDeleteCert", KMessageBox::Dangerous ) != KMessageBox::Continue ) return; if ( Kleo::DeleteJob * job = Kleo::CryptoBackendFactory::instance()->smime()->deleteJob() ) job->slotCancel(); else { QString str = keys.size() == 1 ? i18n("

An error occurred while trying to delete " "the certificate:

" "

%1

" ) : i18n( "

An error occurred while trying to delete " "the certificates:

" "

%1

" ); KMessageBox::error( this, str.arg( i18n("Operation not supported by the backend.") ), i18n("Certificate Deletion Failed") ); } mItemsToDelete.clear(); // re-create according to the real selection for ( std::vector::const_iterator it = keysToDelete.begin() ; it != keysToDelete.end() ; ++it ) if ( Kleo::KeyListViewItem * item = mKeyListView->itemByFingerprint( it->primaryFingerprint() ) ) mItemsToDelete.append( item ); Kleo::MultiDeleteJob * job = new Kleo::MultiDeleteJob( Kleo::CryptoBackendFactory::instance()->smime() ); assert( job ); connect( job, SIGNAL(result(const GpgME::Error&,const GpgME::Key&)), SLOT(slotDeleteResult(const GpgME::Error&,const GpgME::Key&)) ); connectJobToStatusBarProgress( job, i18n("Deleting keys...") ); const GpgME::Error err = job->start( keys, true ); if ( err ) showDeleteError( this, err ); else mProgressBar->setProgress( 0, 0 ); } void CertManager::slotDeleteResult( const GpgME::Error & err, const GpgME::Key & ) { if ( err ) showDeleteError( this, err ); else { const int infinity = 100; // infinite loop guard... mItemsToDelete.setAutoDelete( true ); for ( int i = 0 ; i < infinity ; ++i ) { QPtrListIterator it( mItemsToDelete ); while ( Kleo::KeyListViewItem * cur = it.current() ) { ++it; if ( cur->childCount() == 0 ) { mItemsToDelete.remove( cur ); } } if ( mItemsToDelete.isEmpty() ) break; } mItemsToDelete.setAutoDelete( false ); Q_ASSERT( mItemsToDelete.isEmpty() ); mItemsToDelete.clear(); } disconnectJobFromStatusBarProgress( err ); } void CertManager::slotViewDetails( Kleo::KeyListViewItem * item ) { if ( !item || item->key().isNull() ) return; // KDialogBase * dialog = new KDialogBase( this, "dialog", false, i18n("Additional Information for Key"), KDialogBase::Close, KDialogBase::Close ); CertificateInfoWidgetImpl * top = new CertificateInfoWidgetImpl( item->key(), isRemote(), dialog ); dialog->setMainWidget( top ); // connect( top, SIGNAL(requestCertificateDownload(const QString&, const QString&)), SLOT(slotStartCertificateDownload(const QString&, const QString&)) ); dialog->show(); } void CertManager::slotViewDetails() { QPtrList items = mKeyListView->selectedItems(); if ( items.isEmpty() ) return; // selectedItem() doesn't work in Extended mode. // But we only want to show the details of one item... slotViewDetails( items.first() ); } void CertManager::slotSelectionChanged() { mKeyListView->flushKeys(); bool b = mKeyListView->hasSelection(); mExportCertificateAction->setEnabled( b ); mViewCertDetailsAction->setEnabled( b ); mDeleteCertificateAction->setEnabled( b ); #ifdef NOT_IMPLEMENTED_ANYWAY mRevokeCertificateAction->setEnabled( b ); mExtendCertificateAction->setEnabled( b ); #endif mDownloadCertificateAction->setEnabled( b && mRemote ); mValidateCertificateAction->setEnabled( !mRemote ); } void CertManager::slotExportCertificate() { QPtrList items = mKeyListView->selectedItems(); if ( items.isEmpty() ) return; QStringList fingerprints; for ( QPtrListIterator it( items ) ; it.current() ; ++it ) if ( !it.current()->key().isNull() ) if ( const char * fpr = it.current()->key().primaryFingerprint() ) fingerprints.push_back( fpr ); startCertificateExport( fingerprints ); } static void showCertificateExportError( QWidget * parent, const GpgME::Error & err ) { assert( err ); const QString msg = i18n("

An error occurred while trying to export " "the certificate:

" "

%1

") .arg( QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n("Certificate Export Failed") ); } void CertManager::startCertificateExport( const QStringList & fingerprints ) { if ( fingerprints.empty() ) return; // we need to use PEM (ascii armoured) format, since DER (binary) // can't transport more than one certificate *sigh* this is madness :/ Kleo::ExportJob * job = Kleo::CryptoBackendFactory::instance()->smime()->publicKeyExportJob( true ); assert( job ); connect( job, SIGNAL(result(const GpgME::Error&,const QByteArray&)), SLOT(slotCertificateExportResult(const GpgME::Error&,const QByteArray&)) ); connectJobToStatusBarProgress( job, i18n("Exporting certificate...") ); const GpgME::Error err = job->start( fingerprints ); if ( err ) showCertificateExportError( this, err ); else mProgressBar->setProgress( 0, 0 ); } // return true if we should proceed, false if we should abort static bool checkOverwrite( const KURL& url, bool& overwrite, QWidget* w ) { if ( KIO::NetAccess::exists( url, false /*dest*/, w ) ) { if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel( w, i18n( "A file named \"%1\" already exists. " "Are you sure you want to overwrite it?" ).arg( url.prettyURL() ), i18n( "Overwrite File?" ), i18n( "&Overwrite" ) ) ) return false; overwrite = true; } return true; } void CertManager::slotCertificateExportResult( const GpgME::Error & err, const QByteArray & data ) { disconnectJobFromStatusBarProgress( err ); if ( err ) { showCertificateExportError( this, err ); return; } kdDebug() << "CertManager::slotCertificateExportResult(): got " << data.size() << " bytes" << endl; const QString filter = QString("*.pem|") + i18n("ASCII Armored Certificate Bundles (*.pem)"); const KURL url = KFileDialog::getOpenURL( QString::null, filter, this, i18n( "Save Certificate" ) ); if ( !url.isValid() ) return; bool overwrite = false; if ( !checkOverwrite( url, overwrite, this ) ) return; KIO::Job* uploadJob = KIOext::put( data, url, -1, overwrite, false /*resume*/ ); uploadJob->setWindow( this ); connect( uploadJob, SIGNAL( result( KIO::Job* ) ), this, SLOT( slotUploadResult( KIO::Job* ) ) ); } void CertManager::slotExportSecretKey() { Kleo::KeySelectionDialog dlg( i18n("Secret Key Export"), i18n("Select the secret key to export " "(Warning: The PKCS#12 format is insecure; " "exporting secret keys is discouraged):"), std::vector(), Kleo::KeySelectionDialog::SecretKeys|Kleo::KeySelectionDialog::SMIMEKeys, false /* no multiple selection */, false /* no remember choice box */, this, "secret key export key selection dialog" ); //dlg.setHideInvalidKeys( false ); if ( dlg.exec() != QDialog::Accepted ) return; startSecretKeyExport( dlg.fingerprint() ); } static void showSecretKeyExportError( QWidget * parent, const GpgME::Error & err ) { assert( err ); const QString msg = i18n("

An error occurred while trying to export " "the secret key:

" "

%1

") .arg( QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n("Secret-Key Export Failed") ); } void CertManager::startSecretKeyExport( const QString & fingerprint ) { if ( fingerprint.isEmpty() ) return; // PENDING(marc): let user choose between binary and PEM format? Kleo::ExportJob * job = Kleo::CryptoBackendFactory::instance()->smime()->secretKeyExportJob( false ); assert( job ); connect( job, SIGNAL(result(const GpgME::Error&,const QByteArray&)), SLOT(slotSecretKeyExportResult(const GpgME::Error&,const QByteArray&)) ); connectJobToStatusBarProgress( job, i18n("Exporting secret key...") ); const GpgME::Error err = job->start( fingerprint ); if ( err ) showSecretKeyExportError( this, err ); else mProgressBar->setProgress( 0, 0 ); } void CertManager::slotSecretKeyExportResult( const GpgME::Error & err, const QByteArray & data ) { disconnectJobFromStatusBarProgress( err ); if ( err ) { showSecretKeyExportError( this, err ); return; } kdDebug() << "CertManager::slotSecretKeyExportResult(): got " << data.size() << " bytes" << endl; QString filter = QString("*.p12|") + i18n("PKCS#12 Key Bundle (*.p12)"); KURL url = KFileDialog::getOpenURL( QString::null, filter, this, i18n( "Save Certificate" ) ); if ( !url.isValid() ) return; bool overwrite = false; if ( !checkOverwrite( url, overwrite, this ) ) return; KIO::Job* uploadJob = KIOext::put( data, url, -1, overwrite, false /*resume*/ ); uploadJob->setWindow( this ); connect( uploadJob, SIGNAL( result( KIO::Job* ) ), this, SLOT( slotUploadResult( KIO::Job* ) ) ); } void CertManager::slotUploadResult( KIO::Job* job ) { if ( job->error() ) job->showErrorDialog(); } void CertManager::slotDropped(const KURL::List& lst) { mURLsToImport = lst; if ( !lst.empty() ) importNextURLOrRedisplay(); } void CertManager::importNextURLOrRedisplay() { if ( !mURLsToImport.empty() ) { // We can only import them one by one, otherwise the jobs would run into each other KURL url = mURLsToImport.front(); mURLsToImport.pop_front(); slotImportCertFromFile( url ); } else { if ( isRemote() ) return; startKeyListing( false, true, mPreviouslySelectedFingerprints ); } } void CertManager::slotStartWatchGnuPG() { KProcess certManagerProc; certManagerProc << "kwatchgnupg"; if( !certManagerProc.start( KProcess::DontCare ) ) KMessageBox::error( this, i18n( "Could not start GnuPG LogViewer (kwatchgnupg). " "Please check your installation!" ), i18n( "Kleopatra Error" ) ); } #include "certmanager.moc" diff --git a/certmanager/certmanager.h b/certmanager/certmanager.h index 1c0e7cb422..50e87712fc 100644 --- a/certmanager/certmanager.h +++ b/certmanager/certmanager.h @@ -1,214 +1,216 @@ /* -*- mode: c++; c-basic-offset:4 -*- certmanager.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef _CERTMANAGER_H_ #define _CERTMANAGER_H_ //#include #include #include #include #include #include #include #include namespace Kleo { class KeyListView; class KeyListViewItem; class ProgressBar; class Job; } namespace KIO { class Job; } class KProcess; class KToolBar; class KAction; class CRLView; class HierarchyAnalyser; class LineEditAction; class ComboAction; class KURL; class QFile; class QStringList; class QLabel; namespace GpgME { class ImportResult; class KeyListResult; class Error; class Key; } class KDE_EXPORT CertManager : public KMainWindow { Q_OBJECT public: CertManager( bool remote = false, const QString& query = QString::null, const QString& import=QString::null, QWidget * parent=0, const char * name=0, WFlags f=0 ); ~CertManager(); bool isRemote() const { return mRemote; } signals: void stopOperations(); void enableOperations( bool ); private slots: void slotStartCertificateDownload( const QString & fingerprint, const QString& displayName ); void newCertificate(); void revokeCertificate(); void extendCertificate(); void slotDeleteCertificate(); void slotExportSecretKey(); void slotExportCertificate(); void slotUploadResult( KIO::Job* job ); void slotImportCertFromFile(); void slotImportCertFromFile( const KURL & filename ); void slotImportResult( KIO::Job* ); void slotCertificateImportResult( const GpgME::ImportResult & result ); void slotCertificateDownloadResult( const GpgME::Error & error, const QByteArray & keyData ); void slotKeyListResult( const GpgME::KeyListResult & result ); void slotDeleteResult( const GpgME::Error & error, const GpgME::Key & ); void slotSecretKeyExportResult( const GpgME::Error & error, const QByteArray & keyData ); void slotCertificateExportResult( const GpgME::Error & error, const QByteArray & keyData ); void slotClearCRLsResult(); void importCRLFromFile(); void importCRLFromLDAP(); void slotImportCRLJobFinished( KIO::Job * ); void slotDirmngrExited(); void slotStderr( KProcess*, char*, int ); void slotToggleRemote(int idx); void slotToggleHierarchicalView( bool ); void slotViewCRLs(); void slotClearCRLs(); void slotViewDetails(); void slotViewDetails( Kleo::KeyListViewItem * item ); void slotSelectionChanged(); void slotDownloadCertificate(); void slotStartWatchGnuPG(); void slotEditKeybindings(); void slotShowConfigurationDialog(); void slotConfigureGpgME(); void slotContextMenu(Kleo::KeyListViewItem*, const QPoint& point); void slotDropped(const KURL::List&); /** Schedule a repaint for the listview items. E.g. when the colour config has changed */ void slotRepaint(); /** Schedule a validating keylisting for the selected items (or all items, if none is selected). */ void slotValidate() { startRedisplay( true ); } /** Schedule a non-validating keylisting for the selected items (or all items, if none are selected). */ void slotRedisplay() { startRedisplay( false ); } /** Start a keylisting with the current value of the query text as pattern. */ void slotSearch(); void slotExpandAll(); void slotCollapseAll(); void slotRefreshKeys(); void slotRefreshKeysResult( const GpgME::Error & ); private: void createStatusBar(); void createActions(); void updateStatusBarLabels(); void updateImportActions( bool enable ); void startKeyListing( bool, bool, const QStringList & ); void startKeyListing( bool, bool, const std::set & ); void startCertificateImport( const QByteArray & keyData, const QString& certDisplayName ); void startImportCRL( const QString& fileName, bool isTempFile ); void startClearCRLs(); void startSecretKeyExport( const QString & fingerprint ); void startCertificateExport( const QStringList & fingerprints ); bool connectAndStartDirmngr( const char*, const char* ); void connectJobToStatusBarProgress( Kleo::Job * job, const QString & initialText ); void disconnectJobFromStatusBarProgress( const GpgME::Error & err ); void importNextURLOrRedisplay(); void startRedisplay( bool validating ); QString displayNameForJob( const Kleo::Job *job ); + void readConfig(); + void writeConfig(); private: Kleo::KeyListView * mKeyListView; CRLView * mCrlView; Kleo::ProgressBar * mProgressBar; QLabel * mStatusLabel; KProcess * mDirmngrProc; QString mErrorbuffer; QPtrList mItemsToDelete; KURL::List mURLsToImport; typedef QMap JobsDisplayNameMap; JobsDisplayNameMap mJobsDisplayNameMap; HierarchyAnalyser * mHierarchyAnalyser; LineEditAction * mLineEditAction; ComboAction * mComboAction; KAction * mFindAction; KAction * mImportCertFromFileAction; KAction * mImportCRLFromFileAction; KAction * mExportCertificateAction; KAction * mViewCertDetailsAction; KAction * mDeleteCertificateAction; #ifdef NOT_IMPLEMENTED_ANYWAY KAction * mRevokeCertificateAction; KAction * mExtendCertificateAction; #endif KAction * mExportSecretKeyAction; KAction * mDownloadCertificateAction; KAction * mValidateCertificateAction; QString mImportCRLTempFile; QString mCurrentQuery; std::set mPreviouslySelectedFingerprints; bool mNextFindRemote : 1; // state of the combo, i.e. whether the next find action will be remote bool mRemote : 1; // whether the currently displayed items are from a remote listing bool mDirMngrFound : 1; }; #endif // _CERTMANAGER_H_ diff --git a/certmanager/conf/appearanceconfigpage.cpp b/certmanager/conf/appearanceconfigpage.cpp index 6c06e414c6..5d2a434cc3 100644 --- a/certmanager/conf/appearanceconfigpage.cpp +++ b/certmanager/conf/appearanceconfigpage.cpp @@ -1,87 +1,87 @@ /* appearanceconfigpage.cpp This file is part of kleopatra, the KDE key manager Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "appearanceconfigpage.h" #include #include "appearanceconfigwidget.h" #include #include #include #include AppearanceConfigurationPage::AppearanceConfigurationPage( QWidget * parent, const char * name ) : KCModule( parent, name ) { QVBoxLayout* lay = new QVBoxLayout( this ); mWidget = new Kleo::AppearanceConfigWidget( this ); lay->addWidget( mWidget ); connect( mWidget, SIGNAL( changed() ), this, SLOT( slotChanged() ) ); #ifndef HAVE_UNBROKEN_KCMULTIDIALOG load(); #endif } void AppearanceConfigurationPage::load() { mWidget->load(); } void AppearanceConfigurationPage::save() { mWidget->save(); } void AppearanceConfigurationPage::defaults() { mWidget->defaults(); } extern "C" { KDE_EXPORT KCModule *create_kleopatra_config_appear( QWidget *parent, const char * ) { AppearanceConfigurationPage *page = new AppearanceConfigurationPage( parent, "kleopatra_config_appear" ); return page; } } // kdelibs-3.2 didn't have the changed signal in KCModule... void AppearanceConfigurationPage::slotChanged() { emit changed(true); } #include "appearanceconfigpage.moc" diff --git a/certmanager/conf/appearanceconfigpage.h b/certmanager/conf/appearanceconfigpage.h index 9bba65b9a1..c3acea0079 100644 --- a/certmanager/conf/appearanceconfigpage.h +++ b/certmanager/conf/appearanceconfigpage.h @@ -1,60 +1,60 @@ /* appearanceconfigpage.h This file is part of kleopatra, the KDE key manager Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef _APPEARANCE_CONFIGURE_PAGE_H_ #define _APPEARANCE_CONFIGURE_PAGE_H_ #include namespace Kleo { class AppearanceConfigWidget; } /** * "Appearance" configuration page for kleopatra's configuration dialog */ class AppearanceConfigurationPage : public KCModule { Q_OBJECT public: AppearanceConfigurationPage( QWidget * parent=0, const char * name=0 ); virtual void load(); virtual void save(); virtual void defaults(); private slots: void slotChanged(); private: Kleo::AppearanceConfigWidget* mWidget; }; #endif // _APPEARANCE_CONFIGURE_DIALOG_PRIVATE_H_ diff --git a/certmanager/conf/appearanceconfigwidget.cpp b/certmanager/conf/appearanceconfigwidget.cpp index 3de945aec4..a3d177c2ae 100644 --- a/certmanager/conf/appearanceconfigwidget.cpp +++ b/certmanager/conf/appearanceconfigwidget.cpp @@ -1,358 +1,358 @@ /* appearanceconfigwidget.cpp This file is part of kleopatra, the KDE key manager Copyright (c) 2002,2004 Klarlvdalens Datakonsult AB Copyright (c) 2002,2003 Marc Mutz Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "appearanceconfigwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Kleo; class CategoryListViewItem : public QListViewItem { public: CategoryListViewItem( QListView* lv, QListViewItem* prev, const KConfigBase& config ) : QListViewItem( lv, prev ) { setName( config.readEntry( "Name", i18n("") ) ); mForegroundColor = config.readColorEntry( "foreground-color" ); mBackgroundColor = config.readColorEntry( "background-color" ); mHasFont = config.hasKey( "font" ); if ( mHasFont ) { setFont( config.readFontEntry( "font" ) ); // sets mItalic and mBold } else { mItalic = config.readBoolEntry( "font-italic", false ); mBold = config.readBoolEntry( "font-bold", false ); } mStrikeOut = config.readBoolEntry( "font-strikeout", false ); mIsExpired = config.readBoolEntry( "is-expired", false ); mDirty = false; } void save( KConfigBase& config ) { config.writeEntry( "Name", text( 0 ) ); config.writeEntry( "foreground-color", mForegroundColor ); config.writeEntry( "background-color", mBackgroundColor ); if ( mHasFont ) config.writeEntry( "font", mFont ); else { config.deleteEntry( "font" ); config.writeEntry( "font-italic", mItalic ); config.writeEntry( "font-bold", mBold ); } config.writeEntry( "font-strikeout", mStrikeOut ); } void setForegroundColor( const QColor& foreground ) { mForegroundColor = foreground; mDirty = true; } void setBackgroundColor( const QColor& background ) { mBackgroundColor = background; mDirty = true; } void setFont( const QFont& font ) { mFont = font; mHasFont = true; mItalic = font.italic(); mBold = font.bold(); mDirty = true; } QColor foregroundColor() const { return mForegroundColor; } QColor backgroundColor() const { return mBackgroundColor; } QFont font() const { return mFont; } void setDefaultAppearance() { mForegroundColor = mIsExpired ? Qt::red : QColor(); mBackgroundColor = QColor(); mHasFont = false; mFont = QFont(); mBold = false; mItalic = false; mStrikeOut = false; mDirty = true; } bool isDirty() const { return mDirty; } bool isItalic() const { return mItalic; } bool isBold() const { return mBold; } bool isStrikeout() const { return mStrikeOut; } bool hasFont() const { return mHasFont; } void toggleItalic() { mItalic = !mItalic; if ( mHasFont ) mFont.setItalic( mItalic ); mDirty = true; } void toggleBold() { mBold = !mBold; if ( mHasFont ) mFont.setBold( mBold ); mDirty = true; } void toggleStrikeout() { mStrikeOut = !mStrikeOut; mDirty = true; } private: void setName( const QString& name ) { setText( 0, name ); } void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); private: QColor mForegroundColor, mBackgroundColor; QFont mFont; bool mHasFont; bool mIsExpired; // used for default settings bool mItalic; bool mBold; bool mStrikeOut; bool mDirty; }; void CategoryListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { QColorGroup _cg = cg; QFont font = p->font(); if ( mHasFont ) font = mFont; else { if ( mItalic ) font.setItalic( true ); if ( mBold ) font.setBold( true ); } if ( mStrikeOut ) font.setStrikeOut( true ); p->setFont( font ); if ( mForegroundColor.isValid() ) _cg.setColor( QColorGroup::Text, mForegroundColor ); if ( mBackgroundColor.isValid() ) _cg.setColor( QColorGroup::Base, mBackgroundColor ); QListViewItem::paintCell( p, _cg, column, width, alignment ); } //// Kleo::AppearanceConfigWidget::AppearanceConfigWidget ( QWidget* parent, const char* name, WFlags fl ) : AppearanceConfigWidgetBase( parent, name, fl ) { categoriesLV->setSorting( -1 ); load(); } /* * Destroys the object and frees any allocated resources */ AppearanceConfigWidget::~AppearanceConfigWidget() { // no need to delete child widgets, Qt does it all for us } void AppearanceConfigWidget::slotSelectionChanged( QListViewItem* item ) { bool sel = item != 0; foregroundButton->setEnabled( sel ); backgroundButton->setEnabled( sel ); fontButton->setEnabled( sel ); italicCB->setEnabled( item ); boldCB->setEnabled( item ); strikeoutCB->setEnabled( item ); defaultLookPB->setEnabled( sel ); if ( item ) { CategoryListViewItem* clvi = static_cast( item ); italicCB->setChecked( clvi->isItalic() ); boldCB->setChecked( clvi->isBold() ); strikeoutCB->setChecked( clvi->isStrikeout() ); } else { italicCB->setChecked( false ); boldCB->setChecked( false ); strikeoutCB->setChecked( false ); } } /* * set default appearance for selected category */ void AppearanceConfigWidget::slotDefaultClicked() { CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); if ( !item ) return; item->setDefaultAppearance(); item->repaint(); slotSelectionChanged( item ); emit changed(); } void AppearanceConfigWidget::load() { categoriesLV->clear(); KConfig * config = Kleo::CryptoBackendFactory::instance()->configObject(); if ( !config ) return; QStringList groups = config->groupList().grep( QRegExp( "^Key Filter #\\d+$" ) ); for ( QStringList::const_iterator it = groups.begin() ; it != groups.end() ; ++it ) { KConfigGroup cfg( config, *it ); (void) new CategoryListViewItem( categoriesLV, categoriesLV->lastItem(), cfg ); } } void AppearanceConfigWidget::save() { KConfig * config = Kleo::CryptoBackendFactory::instance()->configObject(); if ( !config ) return; // We know (assume) that the groups in the config object haven't changed, // so we just iterate over them and over the listviewitems, and map one-to-one. QStringList groups = config->groupList().grep( QRegExp( "^Key Filter #\\d+$" ) ); if ( groups.isEmpty() ) { // If we created the default categories ourselves just now, then we need to make up their list QListViewItemIterator lvit( categoriesLV ); for ( ; lvit.current() ; ++lvit ) groups << lvit.current()->text( 0 ); } QListViewItemIterator lvit( categoriesLV ); for ( QStringList::const_iterator it = groups.begin() ; it != groups.end() && lvit.current(); ++it, ++lvit ) { CategoryListViewItem* item = static_cast(lvit.current() ); KConfigGroup cfg( config, *it ); item->save( cfg ); } config->sync(); Kleo::KeyFilterManager::instance()->reload(); } void AppearanceConfigWidget::slotForegroundClicked() { CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); Q_ASSERT( item ); if( !item ) return; QColor fg = item->foregroundColor(); int result = KColorDialog::getColor( fg ); if ( result == KColorDialog::Accepted ) { item->setForegroundColor( fg ); item->repaint(); emit changed(); } } void AppearanceConfigWidget::slotBackgroundClicked() { CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); Q_ASSERT( item ); if( !item ) return; QColor bg = item->backgroundColor(); int result = KColorDialog::getColor( bg ); if ( result == KColorDialog::Accepted ) { item->setBackgroundColor( bg ); item->repaint(); emit changed(); } } void AppearanceConfigWidget::slotFontClicked() { CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); Q_ASSERT( item ); if( !item ) return; QFont font = item->font(); int result = KFontDialog::getFont( font ); if ( result == KFontDialog::Accepted ) { item->setFont( font ); item->repaint(); emit changed(); } } void AppearanceConfigWidget::defaults() { // This simply means "default look for every category" QListViewItemIterator lvit( categoriesLV ); for ( ; lvit.current() ; ++lvit ) { CategoryListViewItem* item = static_cast( lvit.current() ); item->setDefaultAppearance(); item->repaint(); } emit changed(); } void AppearanceConfigWidget::slotItalicClicked() { CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); if ( item ) { item->toggleItalic(); item->repaint(); emit changed(); } } void AppearanceConfigWidget::slotBoldClicked() { CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); if ( item ) { item->toggleBold(); item->repaint(); emit changed(); } } void AppearanceConfigWidget::slotStrikeoutClicked() { CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); if ( item ) { item->toggleStrikeout(); item->repaint(); emit changed(); } } #include "appearanceconfigwidget.moc" diff --git a/certmanager/conf/appearanceconfigwidget.h b/certmanager/conf/appearanceconfigwidget.h index 356ffa6203..dc5c79766a 100644 --- a/certmanager/conf/appearanceconfigwidget.h +++ b/certmanager/conf/appearanceconfigwidget.h @@ -1,73 +1,73 @@ /* appearanceconfigwidget.h This file is part of kleopatra, the KDE key manager Copyright (c) 2002,2004 Klarlvdalens Datakonsult AB Copyright (c) 2002,2003 Marc Mutz Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef APPEARANCECONFIGWIDGET_H #define APPEARANCECONFIGWIDGET_H #include "appearanceconfigwidgetbase.h" #include class KConfig; namespace Kleo { class AppearanceConfigWidget : public AppearanceConfigWidgetBase { Q_OBJECT public: AppearanceConfigWidget( QWidget * parent=0, const char * name=0, WFlags f=0 ); ~AppearanceConfigWidget(); void load(); void save(); public slots: void defaults(); signals: void changed(); protected slots: // reimplemented from the base class virtual void slotDefaultClicked(); virtual void slotSelectionChanged( QListViewItem * ); virtual void slotForegroundClicked(); virtual void slotBackgroundClicked(); virtual void slotFontClicked(); virtual void slotItalicClicked(); virtual void slotBoldClicked(); virtual void slotStrikeoutClicked(); }; } #endif // APPEARANCECONFIGWIDGET_H diff --git a/certmanager/conf/configuredialog.cpp b/certmanager/conf/configuredialog.cpp index b7ed744220..87976f1060 100644 --- a/certmanager/conf/configuredialog.cpp +++ b/certmanager/conf/configuredialog.cpp @@ -1,73 +1,73 @@ /* configuredialog.cpp This file is part of kleopatra Copyright (C) 2000 Espen Sand, espen@kde.org Copyright (C) 2001-2002 Marc Mutz Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "configuredialog.h" #include #include #include #include ConfigureDialog::ConfigureDialog( QWidget *parent, const char *name, bool modal ) : KCMultiDialog( KDialogBase::IconList, i18n( "Configure" ), parent, name, modal ) { KWin::setIcons( winId(), kapp->icon(), kapp->miniIcon() ); showButton( User1, true ); addModule( "kleopatra_config_dirserv", false ); addModule( "kleopatra_config_appear", false ); addModule( "kleopatra_config_dnorder", false ); // We store the size of the dialog on hide, because otherwise // the KCMultiDialog starts with the size of the first kcm, not // the largest one. This way at least after the first showing of // the largest kcm the size is kept. const KConfigGroup geometry( KGlobal::config(), "Geometry" ); const int width = geometry.readNumEntry( "ConfigureDialogWidth" ); const int height = geometry.readNumEntry( "ConfigureDialogHeight" ); if ( width != 0 && height != 0 ) { setMinimumSize( width, height ); } } void ConfigureDialog::hideEvent( QHideEvent * ) { KConfigGroup geometry( KGlobal::config(), "Geometry" ); geometry.writeEntry( "ConfigureDialogWidth", width() ); geometry.writeEntry( "ConfigureDialogHeight",height() ); } ConfigureDialog::~ConfigureDialog() { } #include "configuredialog.moc" diff --git a/certmanager/conf/configuredialog.h b/certmanager/conf/configuredialog.h index 3dea0b9d2c..40b7e371b4 100644 --- a/certmanager/conf/configuredialog.h +++ b/certmanager/conf/configuredialog.h @@ -1,52 +1,52 @@ /* configuredialog.cpp This file is part of kleopatra Copyright (C) 2000 Espen Sand, espen@kde.org Copyright (C) 2001-2002 Marc Mutz Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef _CONFIGURE_DIALOG_H_ #define _CONFIGURE_DIALOG_H_ #include class ConfigureDialog : public KCMultiDialog { Q_OBJECT public: ConfigureDialog( QWidget *parent=0, const char *name=0, bool modal=true ); ~ConfigureDialog(); protected: void hideEvent( QHideEvent *i ); }; #endif diff --git a/certmanager/conf/dirservconfigpage.cpp b/certmanager/conf/dirservconfigpage.cpp index ed551d6ca8..30b21005d5 100644 --- a/certmanager/conf/dirservconfigpage.cpp +++ b/certmanager/conf/dirservconfigpage.cpp @@ -1,291 +1,291 @@ /* dirservconfigpage.cpp This file is part of kleopatra Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "dirservconfigpage.h" #include "directoryserviceswidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include // For sync'ing kabldaprc class KABSynchronizer { public: KABSynchronizer() : mConfig( "kabldaprc" ) { mConfig.setGroup( "LDAP" ); } KURL::List readCurrentList() const { KURL::List lst; // stolen from kabc/ldapclient.cpp const uint numHosts = mConfig.readUnsignedNumEntry( "NumSelectedHosts" ); for ( uint j = 0; j < numHosts; j++ ) { const QString num = QString::number( j ); KURL url; url.setProtocol( "ldap" ); url.setPath( "/" ); // workaround KURL parsing bug const QString host = mConfig.readEntry( QString( "SelectedHost" ) + num ).stripWhiteSpace(); url.setHost( host ); const int port = mConfig.readUnsignedNumEntry( QString( "SelectedPort" ) + num ); if ( port != 0 ) url.setPort( port ); const QString base = mConfig.readEntry( QString( "SelectedBase" ) + num ).stripWhiteSpace(); url.setQuery( base ); const QString bindDN = mConfig.readEntry( QString( "SelectedBind" ) + num ).stripWhiteSpace(); url.setUser( bindDN ); const QString pwdBindDN = mConfig.readEntry( QString( "SelectedPwdBind" ) + num ).stripWhiteSpace(); url.setPass( pwdBindDN ); lst.append( url ); } return lst; } void writeList( const KURL::List& lst ) { mConfig.writeEntry( "NumSelectedHosts", lst.count() ); KURL::List::const_iterator it = lst.begin(); KURL::List::const_iterator end = lst.end(); unsigned j = 0; for( ; it != end; ++it, ++j ) { const QString num = QString::number( j ); KURL url = *it; Q_ASSERT( url.protocol() == "ldap" ); mConfig.writeEntry( QString( "SelectedHost" ) + num, url.host() ); mConfig.writeEntry( QString( "SelectedPort" ) + num, url.port() ); // KURL automatically encoded the query (e.g. for spaces inside it), // so decode it before writing it out const QString base = KURL::decode_string( url.query().mid(1) ); mConfig.writeEntry( QString( "SelectedBase" ) + num, base ); mConfig.writeEntry( QString( "SelectedBind" ) + num, url.user() ); mConfig.writeEntry( QString( "SelectedPwdBind" ) + num, url.pass() ); } mConfig.sync(); } private: KConfig mConfig; }; static const char s_dirserv_componentName[] = "dirmngr"; static const char s_dirserv_groupName[] = "LDAP"; static const char s_dirserv_entryName[] = "LDAP Server"; static const char s_timeout_componentName[] = "dirmngr"; static const char s_timeout_groupName[] = "LDAP"; static const char s_timeout_entryName[] = "ldaptimeout"; static const char s_maxitems_componentName[] = "dirmngr"; static const char s_maxitems_groupName[] = "LDAP"; static const char s_maxitems_entryName[] = "max-replies"; static const char s_addnewservers_componentName[] = "dirmngr"; static const char s_addnewservers_groupName[] = "LDAP"; static const char s_addnewservers_entryName[] = "add-servers"; DirectoryServicesConfigurationPage::DirectoryServicesConfigurationPage( QWidget * parent, const char * name ) : KCModule( parent, name ) { mConfig = Kleo::CryptoBackendFactory::instance()->config(); QVBoxLayout* lay = new QVBoxLayout( this, 0, KDialog::spacingHint() ); Kleo::CryptoConfigEntry* entry = configEntry( s_dirserv_componentName, s_dirserv_groupName, s_dirserv_entryName, Kleo::CryptoConfigEntry::ArgType_LDAPURL, true ); mWidget = new Kleo::DirectoryServicesWidget( entry, this ); lay->addWidget( mWidget ); connect( mWidget, SIGNAL( changed() ), this, SLOT( slotChanged() ) ); // LDAP timeout QHBox* box = new QHBox( this ); box->setSpacing( KDialog::spacingHint() ); lay->addWidget( box ); QLabel* label = new QLabel( i18n( "LDAP &timeout (minutes:seconds)" ), box ); mTimeout = new QTimeEdit( box ); mTimeout->setDisplay( QTimeEdit::Minutes | QTimeEdit::Seconds ); connect( mTimeout, SIGNAL( valueChanged( const QTime& ) ), this, SLOT( slotChanged() ) ); label->setBuddy( mTimeout ); QWidget* stretch = new QWidget( box ); box->setStretchFactor( stretch, 2 ); // Max number of items returned by queries box = new QHBox( this ); box->setSpacing( KDialog::spacingHint() ); lay->addWidget( box ); mMaxItems = new KIntNumInput( box ); mMaxItems->setLabel( i18n( "&Maximum number of items returned by query" ), Qt::AlignLeft | Qt::AlignVCenter ); mMaxItems->setMinValue( 0 ); connect( mMaxItems, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) ); stretch = new QWidget( box ); box->setStretchFactor( stretch, 2 ); #ifdef NOT_USEFUL_CURRENTLY mAddNewServersCB = new QCheckBox( i18n( "Automatically add &new servers discovered in CRL distribution points" ), this ); connect( mAddNewServersCB, SIGNAL( clicked() ), this, SLOT( slotChanged() ) ); lay->addWidget( mAddNewServersCB ); #endif #ifndef HAVE_UNBROKEN_KCMULTIDIALOG load(); #endif } void DirectoryServicesConfigurationPage::load() { mWidget->load(); mTimeoutConfigEntry = configEntry( s_timeout_componentName, s_timeout_groupName, s_timeout_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false ); if ( mTimeoutConfigEntry ) { QTime time = QTime().addSecs( mTimeoutConfigEntry->uintValue() ); //kdDebug() << "timeout:" << mTimeoutConfigEntry->uintValue() << " -> " << time << endl; mTimeout->setTime( time ); } mMaxItemsConfigEntry = configEntry( s_maxitems_componentName, s_maxitems_groupName, s_maxitems_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false ); if ( mMaxItemsConfigEntry ) { mMaxItems->blockSignals( true ); // KNumInput emits valueChanged from setValue! mMaxItems->setValue( mMaxItemsConfigEntry->uintValue() ); mMaxItems->blockSignals( false ); } #ifdef NOT_USEFUL_CURRENTLY mAddNewServersConfigEntry = configEntry( s_addnewservers_componentName, s_addnewservers_groupName, s_addnewservers_entryName, Kleo::CryptoConfigEntry::ArgType_None, false ); if ( mAddNewServersConfigEntry ) { mAddNewServersCB->setChecked( mAddNewServersConfigEntry->boolValue() ); } #endif } void DirectoryServicesConfigurationPage::save() { mWidget->save(); QTime time( mTimeout->time() ); unsigned int timeout = time.minute() * 60 + time.second(); if ( mTimeoutConfigEntry && mTimeoutConfigEntry->uintValue() != timeout ) mTimeoutConfigEntry->setUIntValue( timeout ); if ( mMaxItemsConfigEntry && mMaxItemsConfigEntry->uintValue() != (uint)mMaxItems->value() ) mMaxItemsConfigEntry->setUIntValue( mMaxItems->value() ); #ifdef NOT_USEFUL_CURRENTLY if ( mAddNewServersConfigEntry && mAddNewServersConfigEntry->boolValue() != mAddNewServersCB->isChecked() ) mAddNewServersConfigEntry->setBoolValue( mAddNewServersCB->isChecked() ); #endif mConfig->sync( true ); // Also write the LDAP URLs to kabldaprc so that they are used by kaddressbook KABSynchronizer sync; const KURL::List toAdd = mWidget->urlList(); KURL::List currentList = sync.readCurrentList(); KURL::List::const_iterator it = toAdd.begin(); KURL::List::const_iterator end = toAdd.end(); for( ; it != end; ++it ) { // check if the URL is already in currentList if ( currentList.find( *it ) == currentList.end() ) // if not, add it currentList.append( *it ); } sync.writeList( currentList ); } void DirectoryServicesConfigurationPage::defaults() { mWidget->defaults(); if ( mTimeoutConfigEntry ) mTimeoutConfigEntry->resetToDefault(); if ( mMaxItemsConfigEntry ) mMaxItemsConfigEntry->resetToDefault(); #ifdef NOT_USEFUL_CURRENTLY if ( mAddNewServersConfigEntry ) mAddNewServersConfigEntry->resetToDefault(); #endif load(); } extern "C" { KDE_EXPORT KCModule *create_kleopatra_config_dirserv( QWidget *parent, const char * ) { DirectoryServicesConfigurationPage *page = new DirectoryServicesConfigurationPage( parent, "kleopatra_config_dirserv" ); return page; } } // kdelibs-3.2 didn't have the changed signal in KCModule... void DirectoryServicesConfigurationPage::slotChanged() { emit changed(true); } // Find config entry for ldap servers. Implements runtime checks on the configuration option. Kleo::CryptoConfigEntry* DirectoryServicesConfigurationPage::configEntry( const char* componentName, const char* groupName, const char* entryName, Kleo::CryptoConfigEntry::ArgType argType, bool isList ) { Kleo::CryptoConfigEntry* entry = mConfig->entry( componentName, groupName, entryName ); if ( !entry ) { KMessageBox::error( this, i18n( "Backend error: gpgconf does not seem to know the entry for %1/%2/%3" ).arg( componentName, groupName, entryName ) ); return 0; } if( entry->argType() != argType || entry->isList() != isList ) { KMessageBox::error( this, i18n( "Backend error: gpgconf has wrong type for %1/%2/%3: %4 %5" ).arg( componentName, groupName, entryName ).arg( entry->argType() ).arg( entry->isList() ) ); return 0; } return entry; } #include "dirservconfigpage.moc" diff --git a/certmanager/conf/dirservconfigpage.h b/certmanager/conf/dirservconfigpage.h index 02fe639b10..8c7c754397 100644 --- a/certmanager/conf/dirservconfigpage.h +++ b/certmanager/conf/dirservconfigpage.h @@ -1,84 +1,84 @@ /* dirservconfigpage.h This file is part of kleopatra Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef DIRSERVCONFIGPAGE_H #define DIRSERVCONFIGPAGE_H #include #include #include class QCheckBox; class QTimeEdit; class KIntNumInput; namespace Kleo { class CryptoConfig; class CryptoConfigEntry; class DirectoryServicesWidget; } /** * "Directory Services" configuration page for kleopatra's configuration dialog * The user can configure LDAP servers in this page, to be used for listing/fetching * remote certificates in kleopatra. */ class KDE_EXPORT DirectoryServicesConfigurationPage : public KCModule { Q_OBJECT public: DirectoryServicesConfigurationPage( QWidget * parent=0, const char * name=0 ); virtual void load(); virtual void save(); virtual void defaults(); private slots: void slotChanged(); private: Kleo::CryptoConfigEntry* configEntry( const char* componentName, const char* groupName, const char* entryName, Kleo::CryptoConfigEntry::ArgType argType, bool isList ); Kleo::DirectoryServicesWidget* mWidget; QTimeEdit* mTimeout; KIntNumInput* mMaxItems; QCheckBox* mAddNewServersCB; Kleo::CryptoConfigEntry* mTimeoutConfigEntry; Kleo::CryptoConfigEntry* mMaxItemsConfigEntry; Kleo::CryptoConfigEntry* mAddNewServersConfigEntry; Kleo::CryptoConfig* mConfig; }; #endif diff --git a/certmanager/conf/dnorderconfigpage.cpp b/certmanager/conf/dnorderconfigpage.cpp index 7abe46cfc6..44b86b5b85 100644 --- a/certmanager/conf/dnorderconfigpage.cpp +++ b/certmanager/conf/dnorderconfigpage.cpp @@ -1,77 +1,77 @@ /* dnorderconfigpage.cpp This file is part of kleopatra, the KDE key manager Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "dnorderconfigpage.h" #include #include #include #include DNOrderConfigPage::DNOrderConfigPage( QWidget * parent, const char * name ) : KCModule( parent, name ) { QVBoxLayout * vlay = new QVBoxLayout( this ); mWidget = Kleo::DNAttributeMapper::instance()->configWidget( this, "mWidget" ); vlay->addWidget( mWidget ); connect( mWidget, SIGNAL(changed()), SLOT(slotChanged()) ); #ifndef HAVE_UNBROKEN_KCMULTIDIALOG load(); #endif } void DNOrderConfigPage::load() { mWidget->load(); } void DNOrderConfigPage::save() { mWidget->save(); } void DNOrderConfigPage::defaults() { mWidget->defaults(); } // kdelibs-3.2 didn't have the changed signal in KCModule... void DNOrderConfigPage::slotChanged() { emit changed(true); } extern "C" KDE_EXPORT KCModule * create_kleopatra_config_dnorder( QWidget * parent, const char * ) { return new DNOrderConfigPage( parent, "kleopatra_config_dnorder" ); } #include "dnorderconfigpage.moc" diff --git a/certmanager/conf/dnorderconfigpage.h b/certmanager/conf/dnorderconfigpage.h index 9ab6b0d52d..c874c7527f 100644 --- a/certmanager/conf/dnorderconfigpage.h +++ b/certmanager/conf/dnorderconfigpage.h @@ -1,63 +1,63 @@ /* dnorderconfigpage.h This file is part of kleopatra, the KDE key manager Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEOPATRA_CONF_DNORDERCONFIGPAGE_H__ #define __KLEOPATRA_CONF_DNORDERCONFIGPAGE_H__ #include namespace Kleo { class DNAttributeOrderConfigWidget; } /** * "DN Order" configuration page for kleopatra's configuration dialog */ class DNOrderConfigPage : public KCModule { Q_OBJECT public: DNOrderConfigPage( QWidget * parent=0, const char * name=0 ); /*! reimplementation */ void load(); /*! reimplementation */ void save(); /*! reimplementation */ void defaults(); private slots: void slotChanged(); private: Kleo::DNAttributeOrderConfigWidget * mWidget; }; #endif // __KLEOPATRA_CONF_DNORDERCONFIGPAGE_H__ diff --git a/certmanager/conf/kleopatra_config_dnorder.desktop b/certmanager/conf/kleopatra_config_dnorder.desktop index a11132f526..e10879022c 100644 --- a/certmanager/conf/kleopatra_config_dnorder.desktop +++ b/certmanager/conf/kleopatra_config_dnorder.desktop @@ -1,122 +1,124 @@ [Desktop Entry] Encoding=UTF-8 Icon=looknfeel Type=Service ServiceTypes=KCModule DocPath=kleopatra/configuration-dn-order.html X-KDE-ModuleType=Library X-KDE-Library=kleopatra X-KDE-FactoryName=kleopatra_config_dnorder X-KDE-HasReadOnlyMode=false X-KDE-ParentApp=kleopatra X-KDE-ParentComponents=kleopatra X-KDE-CfgDlgHierarchy=Kleopatra Name=DN-Attribute Order Name[bg]=Подредба Name[bs]=Redoslijed DN atributa Name[ca]=Ordre d'atributs DN Name[cs]=Pořadí DN atributů Name[da]=DN-Attributrækkefølge Name[de]=DN-Attribut-Ordnung Name[es]=Orden de atributos DN Name[et]=DN-atribuutide järjekord Name[fi]=DN-attribuuttien järjestys Name[fr]=Ordre des attributs DN Name[gl]=Orde de DN-Attribute Name[he]=סדר של מאפייני DN Name[hu]=DN-attribútumsorrend Name[is]=DN eiginleikaröðun Name[it]=Attributi DN, ordine Name[ja]=DNー属性 オーダー Name[nb]=DN-Attributtrekkefølge Name[nl]=DN-Attribuutvolgorde Name[nn]=DN-attributtrekkjefølgje Name[pl]=Porządek atrybutów DN Name[pt]=Ordem de Atributos DN Name[pt_BR]=Ordem do Atributo DN Name[ru]=Порядок атрибутов DN Name[se]=DN-attribuhttaortnet Name[sk]=Poradie atribútov DN Name[sl]=Vrstni red atributov DN Name[sr]=DN-Атрибут ред Name[sr@Latn]=DN-Atribut red Name[sv]=DN-egenskapsordning Name[ta]=DN-பண்புக்கூறு வரிசை Name[tg]=Тартиби мушаххасияти DN Name[tr]=DN-Öznitelik Sırası Name[uk]=Порядок атрибутів DN Name[xx]=xxDN-Attribute Orderxx Name[zh_CN]=DN 属性顺序 Comment=Configure the order in which DN attributes are shown Comment[bg]=Настройки на подредбата на атрибутите на индекса (DN) Comment[bs]=Podesite redoslijed kojim će biti prikazani DN atributi Comment[ca]=Configura l'ordre en que es mostren els atributs DN +Comment[cs]=Nastavení pořadí zobrazení DN atributů Comment[da]=Indstil rækkefølgen i hvilken DN-attributter vises Comment[de]=Konfiguration für die Anzeigeordnung der DN-Attribute Comment[es]=Configura el orden en el que se muestran los atributos DN Comment[et]=DN-atribuutide näitamise järjekorra seadistamine Comment[fi]=Määrittele, missä järjestyksessä DN-attribuutit näytetään Comment[fr]=Configurer l'ordre dans lequel les attributs DN sont affichés Comment[gl]=Configurar a orde en que se amosan os atributos DN Comment[he]=הגדרה של הסדר שבהם מאפייני DN מוצגים Comment[hu]=A DN-attribútumok megjelenítési sorrendjének beállítása Comment[is]=Stilla röð DN eiginleikanna Comment[it]=Configuraz l'ordine in cui sono mostrati gli attributi DN Comment[ja]=DN-属性が示されるオーダーを設定します。 Comment[nb]=Still inn rekkefølgen DN-attributtene er sortert i Comment[nl]=Stel de volgorde in van de DN-attributen Comment[nn]=Vel kva rekkjefølgje DN-attributtane er sorterte i Comment[pl]=Konfiguracja kolejności wyświetlania atrybutów DN Comment[pt]=Configuração da order em que os atributos DN são mostrados Comment[pt_BR]=Configura a ordem na qual os atributos DN são mostrados Comment[ru]=Настройка порядка показываемых атрибутов DN Comment[se]=Vállje makkár ortnegis DN-attribuhttat sorterejuvvojit Comment[sk]=Nastavenie poradia, v ktorom sú zobrazené atribúty DN Comment[sl]=Nastavite vrstni red, v katerem so prikazani atributi DN Comment[sr]=Подешава ред којим су приказани DN атрибути Comment[sr@Latn]=Podešava red kojim su prikazani DN atributi Comment[sv]=Anpassa ordningen som DN-egenskaper visas Comment[ta]= DN விவரங்கள் எந்த வரிசையில் உள்ளதோ அப்படியே அமை Comment[tg]=Танзимоти мушаххасиятҳои намоишшавандаи тартибии DN Comment[tr]=DN özniteliklerinin hangi sıralama ile gösterileceğini yapılandır Comment[uk]=Налаштування порядку показу атрибутів DN Comment[xx]=xxConfigure the order in which DN attributes are shownxx Comment[zh_CN]=配置 DN 属性显示的顺序 Keywords=DN,order,RDN,attribute Keywords[be]=парадак,атрыбут,DN,order,RDN,attribute Keywords[bg]=индекс, ред, подредба, атрибут DN, order, RDN, attribute Keywords[bs]=DN,order,RDN,attribute,redoslijed,atribut Keywords[ca]=DN,ordre,RDN,atribut +Keywords[cs]=DN,pořadí,RDN,atribut Keywords[da]=DN,rækkefølge,RDN,attribut Keywords[de]=DN,Ordnung,RDN,Attribut Keywords[es]=DN,orden,RDN,atributo Keywords[et]=DN,järjekord,RDN,atribuut Keywords[fi]=DN,järjestys,RDN,attribuutti Keywords[fr]=DN,ordre,RDN,attribut Keywords[gl]=DN,orde,RDN,atributo Keywords[he]=DN,סדר,RDN,מאפיין Keywords[hu]=DN,sorrend,RDN,attribútum Keywords[is]=DN,röð,order,RDN,attribute Keywords[it]=DN,ordine,RDN,attributi Keywords[ja]=DN,オーダー,RDN,属性 Keywords[nb]=DN,orden,RDN,attributt Keywords[nl]=DN,volgorde,RDN,attribuut Keywords[nn]=DN,rekkjefølgje,RDN,attributt Keywords[pl]=DN,kolejność,RDN,atrybuty Keywords[pt]=DN,ordem,RDN,atributo Keywords[pt_BR]=DN, ordem, RDN,atributo Keywords[ru]=DN,порядок,RDN,атрибут Keywords[se]=DN,ortnet,RDN,attribuhtta Keywords[sk]=DN,poradie,RDN,atribút Keywords[sl]=DN,vrstni red,RDN,atribut Keywords[sr]=DN,ред,RDN,атрибут Keywords[sr@Latn]=DN,red,RDN,atribut Keywords[sv]=DN,ordning,RDN,egenskap Keywords[ta]=DN,வரிசை,RDN,குணம் Keywords[tg]=DN,тартибот,RDN,мушаххасот Keywords[tr]=DN,sıralama,RDN,öznitelik Keywords[uk]=DN,порядок,RDN,атрибут Keywords[xx]=xxDN,order,RDN,attributexx Keywords[zh_CN]=DN,order,RDN,attribute,顺序,属性 diff --git a/certmanager/crlview.cpp b/certmanager/crlview.cpp index faac926a6a..6cf7ddeaa0 100644 --- a/certmanager/crlview.cpp +++ b/certmanager/crlview.cpp @@ -1,138 +1,138 @@ /* crlview.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "crlview.h" #include #include #include #include #include #include #include #include #include #include #include CRLView::CRLView( QWidget* parent, const char* name, bool modal ) : QDialog( parent, name, modal ), _process(0) { QVBoxLayout* topLayout = new QVBoxLayout( this, 10, 4 ); topLayout->addWidget( new QLabel( i18n("CRL cache dump:"), this ) ); _textView = new QTextEdit( this ); _textView->setFont( KGlobalSettings::fixedFont() ); _textView->setTextFormat( QTextEdit::LogText ); topLayout->addWidget( _textView ); QHBoxLayout* hbLayout = new QHBoxLayout( topLayout ); _updateButton = new KPushButton( i18n("&Update"), this ); _closeButton = new KPushButton( KStdGuiItem::close(), this ); hbLayout->addWidget( _updateButton ); hbLayout->addStretch(); hbLayout->addWidget( _closeButton ); // connections: connect( _updateButton, SIGNAL( clicked() ), this, SLOT( slotUpdateView() ) ); connect( _closeButton, SIGNAL( clicked() ), this, SLOT( close() ) ); resize( _textView->fontMetrics().width( 'M' ) * 80, _textView->fontMetrics().lineSpacing() * 25 ); _timer = new QTimer( this ); connect( _timer, SIGNAL(timeout()), SLOT(slotAppendBuffer()) ); } CRLView::~CRLView() { delete _process; _process = 0; } void CRLView::closeEvent( QCloseEvent * e ) { QDialog::closeEvent( e ); delete _process; _process = 0; } void CRLView::slotUpdateView() { _updateButton->setEnabled( false ); _textView->clear(); _buffer = QString::null; if( _process == 0 ) { _process = new KProcess(); *_process << "gpgsm" << "--call-dirmngr" << "listcrls"; connect( _process, SIGNAL( receivedStdout( KProcess*, char*, int) ), this, SLOT( slotReadStdout( KProcess*, char*, int ) ) ); connect( _process, SIGNAL( processExited( KProcess* ) ), this, SLOT( slotProcessExited() ) ); } if( _process->isRunning() ) _process->kill(); if( !_process->start( KProcess::NotifyOnExit, KProcess::Stdout ) ) { KMessageBox::error( this, i18n( "Unable to start gpgsm process. Please check your installation." ), i18n( "Certificate Manager Error" ) ); slotProcessExited(); } _timer->start( 1000 ); } void CRLView::slotReadStdout( KProcess*, char* buf, int len) { _buffer.append( QString::fromUtf8( buf, len ) ); } void CRLView::slotAppendBuffer() { _textView->append( _buffer ); _buffer = QString::null; } void CRLView::slotProcessExited() { _timer->stop(); slotAppendBuffer(); _updateButton->setEnabled( true ); if( !_process->normalExit() ) { KMessageBox::error( this, i18n( "The GpgSM process ended prematurely because of an unexpected error." ), i18n( "Certificate Manager Error" ) ); } } #include "crlview.moc" diff --git a/certmanager/crlview.h b/certmanager/crlview.h index 93af23efb5..55828a90fb 100644 --- a/certmanager/crlview.h +++ b/certmanager/crlview.h @@ -1,69 +1,69 @@ /* crlview.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef CRLVIEW_H #define CRLVIEW_H #include #include class QTextEdit; class QPushButton; class KProcess; class QTimer; class CRLView : public QDialog { Q_OBJECT public: CRLView( QWidget* parent = 0, const char* name = 0, bool modal = false ); ~CRLView(); public slots: void slotUpdateView(); protected slots: void slotReadStdout( KProcess*, char* buf, int len); void slotProcessExited(); void slotAppendBuffer(); protected: void closeEvent( QCloseEvent * ); private: QTextEdit* _textView; QPushButton* _updateButton; QPushButton* _closeButton; KProcess* _process; QTimer* _timer; QString _buffer; }; #endif // CRLVIEW_H diff --git a/certmanager/customactions.cpp b/certmanager/customactions.cpp index 569607d50b..6a48a47680 100644 --- a/certmanager/customactions.cpp +++ b/certmanager/customactions.cpp @@ -1,134 +1,134 @@ /* customactions.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "customactions.h" #include #include #include #include LabelAction::LabelAction( const QString & text, KActionCollection * parent, const char* name ) : KAction( text, QIconSet(), KShortcut(), 0, 0, parent, name ) { } int LabelAction::plug( QWidget * widget, int index ) { if ( kapp && !kapp->authorizeKAction( name() ) ) return -1; if ( widget->inherits( "KToolBar" ) ) { KToolBar * bar = (KToolBar *)widget; int id_ = getToolButtonID(); QLabel* label = new QLabel( text(), bar, "kde toolbar widget" ); bar->insertWidget( id_, label->width(), label, index ); addContainer( bar, id_ ); connect( bar, SIGNAL( destroyed() ), this, SLOT( slotDestroyed() ) ); return containerCount() - 1; } return KAction::plug( widget, index ); } LineEditAction::LineEditAction( const QString & text, KActionCollection * parent, QObject * receiver, const char * member, const char * name ) : KAction( text, QIconSet(), KShortcut(), 0, 0, parent, name ), _le(0), _receiver(receiver), _member(member) { } int LineEditAction::plug( QWidget * widget, int index ) { if ( kapp && !kapp->authorizeKAction( name() ) ) return -1; if ( widget->inherits( "KToolBar" ) ) { KToolBar *bar = (KToolBar *)widget; int id_ = getToolButtonID(); // The toolbar trick doesn't seem to work for lineedits //_le = new QLineEdit( bar, "kde toolbar widget" ); _le = new QLineEdit( bar ); bar->insertWidget( id_, _le->width(), _le, index ); bar->setStretchableWidget( _le ); addContainer( bar, id_ ); connect( bar, SIGNAL( destroyed() ), this, SLOT( slotDestroyed() ) ); connect( _le, SIGNAL( returnPressed() ), _receiver, _member ); return containerCount() - 1; } return KAction::plug( widget, index ); } void LineEditAction::clear() { _le->clear(); } void LineEditAction::focusAll() { _le->selectAll(); _le->setFocus(); } QString LineEditAction::text() const { return _le->text(); } void LineEditAction::setText( const QString & txt ) { _le->setText(txt); } ComboAction::ComboAction( const QStringList & lst, KActionCollection * parent, QObject * receiver, const char * member, const char * name ) : KAction( QString::null, QIconSet(), KShortcut(), 0, 0, parent, name ), _lst(lst), _receiver(receiver), _member(member) { } int ComboAction::plug( QWidget * widget, int index ) { if ( kapp && !kapp->authorizeKAction( name() ) ) return -1; if ( widget->inherits( "KToolBar" ) ) { KToolBar *bar = (KToolBar *)widget; int id_ = getToolButtonID(); bar->insertCombo( _lst, id_, false, SIGNAL( highlighted(int) ), _receiver, _member ); addContainer( bar, id_ ); connect( bar, SIGNAL( destroyed() ), this, SLOT( slotDestroyed() ) ); return containerCount() - 1; } return KAction::plug( widget, index ); } #include "customactions.moc" diff --git a/certmanager/customactions.h b/certmanager/customactions.h index d0396a1133..dfbaf54613 100644 --- a/certmanager/customactions.h +++ b/certmanager/customactions.h @@ -1,84 +1,84 @@ /* customactions.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __CUSTOMACTIONS_H__ #define __CUSTOMACTIONS_H__ #include #include class QLineEdit; class LabelAction : public KAction { Q_OBJECT public: LabelAction( const QString & text, KActionCollection * parent, const char* name ); int plug( QWidget * widget, int index=-1 ); }; class LineEditAction : public KAction { Q_OBJECT public: LineEditAction( const QString & text, KActionCollection * parent, QObject * receiver, const char * member, const char * name ); int plug( QWidget * widget, int index=-1 ); void clear(); void focusAll(); QString text() const; void setText( const QString & txt ); private: QLineEdit* _le; QObject * _receiver; const char * _member; }; class ComboAction : public KAction { Q_OBJECT public: ComboAction( const QStringList & lst, KActionCollection * parent, QObject * receiver, const char * member, const char * name ); int plug( QWidget * widget, int index=-1 ); private: QStringList _lst; QObject * _receiver; const char * _member; }; #endif // __CUSTOMACTIONS_H__ diff --git a/certmanager/hierarchyanalyser.cpp b/certmanager/hierarchyanalyser.cpp index 2935dca1a8..8e8c13803e 100644 --- a/certmanager/hierarchyanalyser.cpp +++ b/certmanager/hierarchyanalyser.cpp @@ -1,81 +1,81 @@ /* hierarchyanalyser.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "hierarchyanalyser.h" #include #include HierarchyAnalyser::HierarchyAnalyser( QObject * parent, const char * name ) : QObject( parent, name ) { } HierarchyAnalyser::~HierarchyAnalyser() { } void HierarchyAnalyser::slotNextKey( const GpgME::Key & key ) { if ( key.isNull() ) return; if ( key.isRoot() || !key.chainID() || !*key.chainID() ) // root keys have themselves as issuer - we don't want them to // have parents, though: mSubjectsByIssuer[0].push_back( key ); else mSubjectsByIssuer[key.chainID()].push_back( key ); } const std::vector & HierarchyAnalyser::subjectsForIssuer( const char * issuer_dn ) const { static const std::vector empty; std::map< QCString, std::vector >::const_iterator it = mSubjectsByIssuer.find( issuer_dn ); return it == mSubjectsByIssuer.end() ? empty : it->second ; } std::vector HierarchyAnalyser::subjectsForIssuerRecursive( const char * issuer_dn ) const { std::vector keys = subjectsForIssuer( issuer_dn ); for ( unsigned int i = 0 ; i < keys.size() ; ++i ) // can't use iterators here, since appending would invalidate them if ( const char * fpr = keys[i].primaryFingerprint() ) { const std::vector & tmp = subjectsForIssuer( fpr ); std::copy( tmp.begin(), tmp.end(), std::back_inserter( keys ) ); } return keys; } #include "hierarchyanalyser.moc" diff --git a/certmanager/hierarchyanalyser.h b/certmanager/hierarchyanalyser.h index aec927e2a6..ccf07d4f30 100644 --- a/certmanager/hierarchyanalyser.h +++ b/certmanager/hierarchyanalyser.h @@ -1,66 +1,66 @@ /* -*- mode: c++ -*- hierarchyanalyser.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __HIERARCHYANALYSER_H__ #define __HIERARCHYANALYSER_H__ #include #include #include #include #include class HierarchyAnalyser : public QObject { Q_OBJECT public: HierarchyAnalyser( QObject * parent=0, const char * name=0 ); ~HierarchyAnalyser(); const std::vector & rootItems() const { return subjectsForIssuer( 0 ); } const std::vector & subjectsForIssuer( const char * issuer_fpr ) const; std::vector subjectsForIssuerRecursive( const char * issuer_fpr ) const; void clear() { mSubjectsByIssuer.clear(); } public slots: void slotNextKey( const GpgME::Key & key ); private: std::map< QCString, std::vector > mSubjectsByIssuer; }; #endif // __HIERARCHYANALYSER_H__ diff --git a/certmanager/kwatchgnupg/aboutdata.cpp b/certmanager/kwatchgnupg/aboutdata.cpp index ddb4200d48..4bde521901 100644 --- a/certmanager/kwatchgnupg/aboutdata.cpp +++ b/certmanager/kwatchgnupg/aboutdata.cpp @@ -1,69 +1,73 @@ /* aboutdata.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2004 Klar�vdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "aboutdata.h" #include static const char kwatchgnupg_version[] = "1.0"; static const char description[] = I18N_NOOP("GnuPG log viewer"); struct about_data { const char * name; const char * desc; const char * email; const char * web; }; static const about_data authors[] = { - // PENDING(steffen) review { "Steffen Hansen", I18N_NOOP("Original Author"), "hansen@kde.org", 0 }, }; +#if 0 +// can't create zero size array - doesn't compile static const about_data credits[] = { // PENDING(steffen) add stuff }; +#endif AboutData::AboutData() : KAboutData( "kwatchgnupg", I18N_NOOP("KWatchGnuPG"), kwatchgnupg_version, description, License_GPL, "(c) 2004 Klar\xC3\xA4lvdalens Datakonsult AB\n" ) { using ::authors; - using ::credits; + //using ::credits; for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i ) addAuthor( authors[i].name, authors[i].desc, authors[i].email, authors[i].web ); +#if 0 for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i ) addCredit( credits[i].name, credits[i].desc, credits[i].email, credits[i].web ); +#endif } diff --git a/certmanager/kwatchgnupg/aboutdata.h b/certmanager/kwatchgnupg/aboutdata.h index 1cae735654..0e1f9f6318 100644 --- a/certmanager/kwatchgnupg/aboutdata.h +++ b/certmanager/kwatchgnupg/aboutdata.h @@ -1,43 +1,43 @@ /* aboutdata.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef ABOUTDATA_H #define ABOUTDATA_H #include class AboutData : public KAboutData { public: AboutData(); }; #endif // ABOUTDATA_H diff --git a/certmanager/kwatchgnupg/kwatchgnupgconfig.cpp b/certmanager/kwatchgnupg/kwatchgnupgconfig.cpp index 0c53f53b6a..b621e92b89 100644 --- a/certmanager/kwatchgnupg/kwatchgnupgconfig.cpp +++ b/certmanager/kwatchgnupg/kwatchgnupgconfig.cpp @@ -1,206 +1,206 @@ /* kwatchgnupgconfig.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "kwatchgnupgconfig.h" #include #include #include #include #include #include #include #include #include #include #include #include static const char* log_levels[] = { "none", "basic", "advanced", "expert", "guru" }; static int log_level_to_int( const QString& loglevel ) { if( loglevel == "none" ) { return 0; } else if( loglevel == "basic" ) { return 1; } else if( loglevel == "advanced" ) { return 2; } else if( loglevel == "expert" ) { return 3; } else if( loglevel == "guru" ) { return 4; } else { // default return 1; } } KWatchGnuPGConfig::KWatchGnuPGConfig( QWidget* parent, const char* name ) : KDialogBase( Plain, i18n("Configure KWatchGnuPG"), Ok|Cancel, Ok, parent, name ) { // tmp vars: QWidget * w; QGridLayout * glay; QGroupBox * group; QWidget * top = plainPage(); QVBoxLayout * vlay = new QVBoxLayout( top, 0, spacingHint() ); group = new QVGroupBox( i18n("WatchGnuPG"), top ); group->layout()->setSpacing( spacingHint() ); w = new QWidget( group ); glay = new QGridLayout( w, 3, 2, 0, spacingHint() ); glay->setColStretch( 1, 1 ); int row = -1; ++row; mExeED = new KURLRequester( w ); glay->addWidget( new QLabel( mExeED, i18n("&Executable:"), w ), row, 0 ); glay->addWidget( mExeED, row, 1 ); connect( mExeED, SIGNAL(textChanged(const QString&)), SLOT(slotChanged()) ); ++row; mSocketED = new KURLRequester( w ); glay->addWidget( new QLabel( mSocketED, i18n("&Socket:"), w ), row, 0 ); glay->addWidget( mSocketED, row, 1 ); connect( mSocketED, SIGNAL(textChanged(const QString&)), SLOT(slotChanged()) ); ++row; mLogLevelCB = new QComboBox( false, w ); mLogLevelCB->insertItem( i18n("None") ); mLogLevelCB->insertItem( i18n("Basic") ); mLogLevelCB->insertItem( i18n("Advanced") ); mLogLevelCB->insertItem( i18n("Expert") ); mLogLevelCB->insertItem( i18n("Guru") ); glay->addWidget( new QLabel( mLogLevelCB, i18n("Default &log level:"), w ), row, 0 ); glay->addWidget( mLogLevelCB, row, 1 ); connect( mLogLevelCB, SIGNAL(activated(int)), SLOT(slotChanged()) ); vlay->addWidget( group ); /******************* Log Window group *******************/ group = new QVGroupBox( i18n("Log Window"), top ); group->layout()->setSpacing( spacingHint() ); w = new QWidget( group ); glay = new QGridLayout( w, 2, 3, 0, spacingHint() ); glay->setColStretch( 1, 1 ); row = -1; ++row; mLoglenSB = new QSpinBox( 0, 1000000, 100, w ); mLoglenSB->setSuffix( i18n("history size spinbox suffix"," lines") ); mLoglenSB->setSpecialValueText( i18n("unlimited") ); glay->addWidget( new QLabel( mLoglenSB, i18n("&History size:"), w ), row, 0 ); glay->addWidget( mLoglenSB, row, 1 ); QPushButton * button = new QPushButton( i18n("Set &Unlimited"), w ); glay->addWidget( button, row, 2 ); connect( mLoglenSB, SIGNAL(valueChanged(int)), SLOT(slotChanged()) ); connect( button, SIGNAL(clicked()), SLOT(slotSetHistorySizeUnlimited()) ); ++row; mWordWrapCB = new QCheckBox( i18n("Enable &word wrapping"), w ); mWordWrapCB->hide(); // QTextEdit doesn't support word wrapping in LogText mode glay->addMultiCellWidget( mWordWrapCB, row, row, 0, 2 ); connect( mWordWrapCB, SIGNAL(clicked()), SLOT(slotChanged()) ); vlay->addWidget( group ); vlay->addStretch( 1 ); connect( this, SIGNAL(applyClicked()), SLOT(slotSave()) ); connect( this, SIGNAL(okClicked()), SLOT(slotSave()) ); } void KWatchGnuPGConfig::slotSetHistorySizeUnlimited() { mLoglenSB->setValue( 0 ); } void KWatchGnuPGConfig::loadConfig() { KConfig* config = kapp->config(); config->setGroup("WatchGnuPG"); mExeED->setURL( config->readEntry( "Executable", "watchgnupg" ) ); mSocketED->setURL( config->readEntry( "Socket", QDir::home().canonicalPath() + "/.gnupg/log-socket") ); mLogLevelCB->setCurrentItem( log_level_to_int( config->readEntry( "LogLevel", "basic" ) ) ); config->setGroup("LogWindow"); mLoglenSB->setValue( config->readNumEntry( "MaxLogLen", 10000 ) ); mWordWrapCB->setChecked( config->readBoolEntry("WordWrap", false ) ); config->setGroup( QString::null ); enableButtonOK( false ); enableButtonApply( false ); } void KWatchGnuPGConfig::saveConfig() { KConfig* config = kapp->config(); config->setGroup("WatchGnuPG"); config->writeEntry( "Executable", mExeED->url() ); config->writeEntry( "Socket", mSocketED->url() ); config->writeEntry( "LogLevel", log_levels[mLogLevelCB->currentItem()] ); config->setGroup("LogWindow"); config->writeEntry( "MaxLogLen", mLoglenSB->value() ); config->writeEntry( "WordWrap", mWordWrapCB->isChecked() ); config->setGroup( QString::null ); config->sync(); enableButtonOK( false ); enableButtonApply( false ); } void KWatchGnuPGConfig::slotChanged() { enableButtonOK( true ); enableButtonApply( true ); } void KWatchGnuPGConfig::slotSave() { saveConfig(); emit reconfigure(); } #include "kwatchgnupgconfig.moc" diff --git a/certmanager/kwatchgnupg/kwatchgnupgconfig.h b/certmanager/kwatchgnupg/kwatchgnupgconfig.h index efb6a75aba..4a93b463ba 100644 --- a/certmanager/kwatchgnupg/kwatchgnupgconfig.h +++ b/certmanager/kwatchgnupg/kwatchgnupgconfig.h @@ -1,68 +1,68 @@ /* kwatchgnupgconfig.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef KWATCHGNUPGCONFIG_H #define KWATCHGNUPGCONFIG_H #include class QCheckBox; class QComboBox; class QSpinBox; class KURLRequester; class KWatchGnuPGConfig : public KDialogBase { Q_OBJECT public: KWatchGnuPGConfig( QWidget* parent, const char* name = 0 ); void loadConfig(); void saveConfig(); signals: void reconfigure(); private slots: void slotChanged(); void slotSave(); void slotSetHistorySizeUnlimited(); private: KURLRequester* mExeED; KURLRequester* mSocketED; QComboBox* mLogLevelCB; QSpinBox* mLoglenSB; QCheckBox* mWordWrapCB; }; #endif /* KWATCHGNUPGCONFIG_H */ diff --git a/certmanager/kwatchgnupg/kwatchgnupgmainwin.cpp b/certmanager/kwatchgnupg/kwatchgnupgmainwin.cpp index 0df498cbc4..19bda278b7 100644 --- a/certmanager/kwatchgnupg/kwatchgnupgmainwin.cpp +++ b/certmanager/kwatchgnupg/kwatchgnupgmainwin.cpp @@ -1,292 +1,292 @@ /* kwatchgnupgmainwin.cpp This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB + Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "kwatchgnupgmainwin.h" #include "kwatchgnupgconfig.h" #include "tray.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define WATCHGNUPGBINARY "watchgnupg" #define WATCHGNUPGSOCKET ( QDir::home().canonicalPath() + "/.gnupg/log-socket") KWatchGnuPGMainWindow::KWatchGnuPGMainWindow( QWidget* parent, const char* name ) : KMainWindow( parent, name, WType_TopLevel ), mConfig(0) { createActions(); createGUI(); mCentralWidget = new QTextEdit( this, "central log view" ); mCentralWidget->setTextFormat( QTextEdit::LogText ); setCentralWidget( mCentralWidget ); mWatcher = new KProcIO( QTextCodec::codecForMib( 106 /*utf-8*/ ) ); connect( mWatcher, SIGNAL( processExited(KProcess*) ), this, SLOT( slotWatcherExited() ) ); connect( mWatcher, SIGNAL( readReady(KProcIO*) ), this, SLOT( slotReadStdout() ) ); slotReadConfig(); mSysTray = new KWatchGnuPGTray( this ); mSysTray->show(); connect( mSysTray, SIGNAL( quitSelected() ), this, SLOT( slotQuit() ) ); setAutoSaveSettings(); } KWatchGnuPGMainWindow::~KWatchGnuPGMainWindow() { delete mWatcher; } void KWatchGnuPGMainWindow::slotClear() { mCentralWidget->clear(); mCentralWidget->append( tr("[%1] Log cleared").arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) ); } void KWatchGnuPGMainWindow::createActions() { (void)new KAction( i18n("C&lear History"), "history_clear", CTRL+Key_L, this, SLOT( slotClear() ), actionCollection(), "clear_log" ); (void)KStdAction::saveAs( this, SLOT(slotSaveAs()), actionCollection() ); (void)KStdAction::close( this, SLOT(close()), actionCollection() ); (void)KStdAction::quit( this, SLOT(slotQuit()), actionCollection() ); (void)KStdAction::preferences( this, SLOT(slotConfigure()), actionCollection() ); ( void )KStdAction::keyBindings(this, SLOT(configureShortcuts()), actionCollection()); ( void )KStdAction::configureToolbars(this, SLOT(slotConfigureToolbars()), actionCollection()); #if 0 (void)new KAction( i18n("Configure KWatchGnuPG..."), QString::fromLatin1("configure"), 0, this, SLOT( slotConfigure() ), actionCollection(), "configure" ); #endif } void KWatchGnuPGMainWindow::configureShortcuts() { KKeyDialog::configure( actionCollection(), this ); } void KWatchGnuPGMainWindow::slotConfigureToolbars() { KEditToolbar dlg( factory() ); dlg.exec(); } void KWatchGnuPGMainWindow::startWatcher() { disconnect( mWatcher, SIGNAL( processExited(KProcess*) ), this, SLOT( slotWatcherExited() ) ); if( mWatcher->isRunning() ) { mWatcher->kill(); while( mWatcher->isRunning() ) { kapp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput); } mCentralWidget->append(tr("[%1] Log stopped") .arg( QDateTime::currentDateTime().toString(Qt::ISODate))); } mWatcher->clearArguments(); KConfig* config = kapp->config(); config->setGroup("WatchGnuPG"); *mWatcher << config->readEntry("Executable", WATCHGNUPGBINARY); *mWatcher << "--force"; *mWatcher << config->readEntry("Socket", WATCHGNUPGSOCKET); config->setGroup(QString::null); if( !mWatcher->start() ) { KMessageBox::sorry( this, i18n("The watchgnupg logging process could not be started.\nPlease install watchgnupg somewhere in your $PATH.\nThis log window is now completely useless." ) ); } else { mCentralWidget->append( tr("[%1] Log started") .arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) ); } connect( mWatcher, SIGNAL( processExited(KProcess*) ), this, SLOT( slotWatcherExited() ) ); } void KWatchGnuPGMainWindow::setGnuPGConfig() { QStringList logclients; // Get config object Kleo::CryptoConfig* cconfig = Kleo::CryptoBackendFactory::instance()->config(); if ( !cconfig ) return; //Q_ASSERT( cconfig ); KConfig* config = kapp->config(); config->setGroup("WatchGnuPG"); QStringList comps = cconfig->componentList(); for( QStringList::const_iterator it = comps.begin(); it != comps.end(); ++it ) { Kleo::CryptoConfigComponent* comp = cconfig->component( *it ); Q_ASSERT(comp); // Look for log-file entry in Debug group Kleo::CryptoConfigGroup* group = comp->group("Debug"); if( group ) { Kleo::CryptoConfigEntry* entry = group->entry("log-file"); if( entry ) { entry->setStringValue( QString("socket://")+ config->readEntry("Socket", WATCHGNUPGSOCKET )); logclients << QString("%1 (%2)").arg(*it).arg(comp->description()); } entry = group->entry("debug-level"); if( entry ) { entry->setStringValue( config->readEntry("LogLevel", "basic") ); } } } cconfig->sync(true); if( logclients.isEmpty() ) { KMessageBox::sorry( 0, i18n("There are no components available that support logging." ) ); } } void KWatchGnuPGMainWindow::slotWatcherExited() { - if( KMessageBox::questionYesNo( this, i18n("The watchgnupg logging process died.\nDo you want to try to restart it?") ) == KMessageBox::Yes ) { + if( KMessageBox::questionYesNo( this, i18n("The watchgnupg logging process died.\nDo you want to try to restart it?"), QString::null, i18n("Try Restart"), i18n("Do Not Try") ) == KMessageBox::Yes ) { mCentralWidget->append( i18n("====== Restarting logging process =====") ); startWatcher(); } else { KMessageBox::sorry( this, i18n("The watchgnupg logging process is not running.\nThis log window is now completely useless." ) ); } } void KWatchGnuPGMainWindow::slotReadStdout() { if ( !mWatcher ) return; QString str; while( mWatcher->readln(str,false) > 0 ) { mCentralWidget->append( str ); if( !isVisible() ) { // Change tray icon to show something happened // PENDING(steffen) mSysTray->setAttention(true); } } QTimer::singleShot( 0, this, SLOT(slotAckRead()) ); } void KWatchGnuPGMainWindow::slotAckRead() { if ( mWatcher ) mWatcher->ackRead(); } void KWatchGnuPGMainWindow::show() { mSysTray->setAttention(false); KMainWindow::show(); } void KWatchGnuPGMainWindow::slotSaveAs() { QString filename = KFileDialog::getSaveFileName( QString::null, QString::null, this, i18n("Save Log to File") ); if( filename.isEmpty() ) return; QFile file(filename); if( file.exists() ) { if( KMessageBox::Yes != KMessageBox::warningYesNo( this, i18n("The file named \"%1\" already " "exists. Are you sure you want " "to overwrite it?").arg(filename), - i18n("Overwrite File") ) ) { + i18n("Overwrite File"), i18n("Overwrite"), KStdGuiItem::cancel() ) ) { return; } } if( file.open( IO_WriteOnly ) ) { QTextStream st(&file); st << mCentralWidget->text(); file.close(); } } void KWatchGnuPGMainWindow::slotQuit() { disconnect( mWatcher, SIGNAL( processExited(KProcess*) ), this, SLOT( slotWatcherExited() ) ); mWatcher->kill(); kapp->quit(); } void KWatchGnuPGMainWindow::slotConfigure() { if( !mConfig ) { mConfig = new KWatchGnuPGConfig( this, "config dialog" ); connect( mConfig, SIGNAL( reconfigure() ), this, SLOT( slotReadConfig() ) ); } mConfig->loadConfig(); mConfig->exec(); } void KWatchGnuPGMainWindow::slotReadConfig() { KConfig* config = kapp->config(); config->setGroup("LogWindow"); mCentralWidget->setWordWrap( config->readBoolEntry("WordWrap", false) ?QTextEdit::WidgetWidth :QTextEdit::NoWrap ); mCentralWidget->setMaxLogLines( config->readNumEntry( "MaxLogLen", 10000 ) ); setGnuPGConfig(); startWatcher(); } bool KWatchGnuPGMainWindow::queryClose() { if ( !kapp->sessionSaving() ) { hide(); return false; } return KMainWindow::queryClose(); } #include "kwatchgnupgmainwin.moc" diff --git a/certmanager/kwatchgnupg/kwatchgnupgmainwin.h b/certmanager/kwatchgnupg/kwatchgnupgmainwin.h index 778eb7ca14..2021a65799 100644 --- a/certmanager/kwatchgnupg/kwatchgnupgmainwin.h +++ b/certmanager/kwatchgnupg/kwatchgnupgmainwin.h @@ -1,78 +1,78 @@ /* main.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef KWATCHGNUPGMAINWIN_H #define KWATCHGNUPGMAINWIN_H #include class KWatchGnuPGTray; class KWatchGnuPGConfig; class KProcIO; class QTextEdit; class KWatchGnuPGMainWindow : public KMainWindow { Q_OBJECT public: KWatchGnuPGMainWindow( QWidget* parent = 0, const char* name = 0 ); virtual ~KWatchGnuPGMainWindow(); public slots: void slotWatcherExited(); void slotReadStdout(); void slotAckRead(); void slotSaveAs(); void slotQuit(); void slotClear(); void slotConfigure(); void slotConfigureToolbars(); void configureShortcuts(); void slotReadConfig(); virtual void show(); protected: virtual bool queryClose(); private: void createActions(); void startWatcher(); void setGnuPGConfig(); KProcIO* mWatcher; QTextEdit* mCentralWidget; KWatchGnuPGTray* mSysTray; KWatchGnuPGConfig* mConfig; }; #endif /* KWATCHGNUPGMAINWIN_H */ diff --git a/certmanager/kwatchgnupg/main.cpp b/certmanager/kwatchgnupg/main.cpp index d202838153..7c25a8da0d 100644 --- a/certmanager/kwatchgnupg/main.cpp +++ b/certmanager/kwatchgnupg/main.cpp @@ -1,96 +1,96 @@ /* main.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "aboutdata.h" #include "kwatchgnupgmainwin.h" #include #include #include #include #include #include #include class KWatchGnuPGApplication : public KUniqueApplication { public: KWatchGnuPGApplication(); ~KWatchGnuPGApplication(); virtual int newInstance(); private: KWatchGnuPGMainWindow* mMainWin; }; KWatchGnuPGApplication::KWatchGnuPGApplication() : KUniqueApplication(), mMainWin(0) { } KWatchGnuPGApplication::~KWatchGnuPGApplication() { delete mMainWin; } int KWatchGnuPGApplication::newInstance() { if( !mMainWin ) { mMainWin = new KWatchGnuPGMainWindow( 0, "kwatchgnupg mainwin" ); setMainWidget( mMainWin ); } mMainWin->show(); return KUniqueApplication::newInstance(); } int main( int argc, char** argv ) { AboutData aboutData; KCmdLineArgs::init(argc, argv, &aboutData); static const KCmdLineOptions options[] = { KCmdLineLastOption// End of options. }; KCmdLineArgs::addCmdLineOptions( options ); KWatchGnuPGApplication::addCmdLineOptions(); #if 0 if (!KWatchGnuPGApplication::start()) { kdError() << "KWatchGnuPG is already running!" << endl; return 0; } #endif KWatchGnuPGApplication app; return app.exec(); } diff --git a/certmanager/kwatchgnupg/tray.cpp b/certmanager/kwatchgnupg/tray.cpp index a1170bbd19..62024b14a1 100644 --- a/certmanager/kwatchgnupg/tray.cpp +++ b/certmanager/kwatchgnupg/tray.cpp @@ -1,66 +1,66 @@ /* main.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "tray.h" #include "kwatchgnupgmainwin.h" #include #include #include #include #include KWatchGnuPGTray::KWatchGnuPGTray( KWatchGnuPGMainWindow* mainwin ) : KSystemTray( mainwin, "KWatchGnuPG Tray Window" ) { kdDebug() << "KWatchGnuPGTray::KWatchGnuPGTray" << endl; KGlobal::iconLoader()->addAppDir( "kwatchgnupg" ); mNormalPix = loadIcon("kwatchgnupg"); mAttentionPix = loadIcon("kwatchgnupg2"); setPixmap( mNormalPix ); QToolTip::add( this, i18n("KWatchGnuPG Log Viewer") ); } KWatchGnuPGTray::~KWatchGnuPGTray() { } void KWatchGnuPGTray::setAttention( bool att ) { if( att ) setPixmap( mAttentionPix ); else setPixmap( mNormalPix ); } #include "tray.moc" diff --git a/certmanager/kwatchgnupg/tray.h b/certmanager/kwatchgnupg/tray.h index 5c63637713..7f220ecad9 100644 --- a/certmanager/kwatchgnupg/tray.h +++ b/certmanager/kwatchgnupg/tray.h @@ -1,55 +1,55 @@ /* main.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef TRAY_H #define TRAY_H #include #include class KWatchGnuPGMainWindow; class KWatchGnuPGTray : public KSystemTray { Q_OBJECT public: KWatchGnuPGTray( KWatchGnuPGMainWindow* mainwin ); virtual ~KWatchGnuPGTray(); public slots: void setAttention( bool att ); private: QPixmap mNormalPix; QPixmap mAttentionPix; }; #endif /* TRAY_H */ diff --git a/certmanager/lib/Makefile.am b/certmanager/lib/Makefile.am index d6921542e8..ae101fd0e0 100644 --- a/certmanager/lib/Makefile.am +++ b/certmanager/lib/Makefile.am @@ -1,43 +1,49 @@ INCLUDES = -I$(top_srcdir)/libkdenetwork $(GPGME_CFLAGS) $(all_includes) SUBDIRS = pics kleo backends ui . tests lib_LTLIBRARIES = libkleopatra.la libkleopatra_la_SOURCES = \ cryptplug.cpp \ cryptplugwrapper.cpp \ cryptplugwrapperlist.cpp \ cryptplugfactory.cpp libkleopatra_la_LIBADD = \ kleo/libkleopatra_core.la \ backends/qgpgme/libkleopatra_backend_qgpgme.la \ + backends/chiasmus/libkleopatra_backend_chiasmus.la \ ui/libkleopatra_ui.la \ \ $(top_builddir)/libkdenetwork/qgpgme/libqgpgme.la \ - $(LIB_KDEUI) + $(LIB_KIO) $(LIB_KDEUI) # Disabled for kdepim-3.3, see also kleo/cryptobackendfactory.cpp # backends/kpgp/libkleopatra_backend_kpgp.la -libkleopatra_la_LDFLAGS = $(all_libraries) -version-info 0:0:0 -no-undefined +# --version-info CURRENT:REVISION:AGE +# (Code changed: REVISION++) +# (Interfaces added/removed/changed: CURRENT++, REVISION=0) +# (Interfaces added: AGE++) +# (Interfaces removed/changed: AGE=0) +libkleopatra_la_LDFLAGS = $(all_libraries) -version-info 1:0:0 -no-undefined METASOURCES = AUTO # remove the .desktop suffix on install (which is needed for translation) install-data-local: $(mkinstalldirs) $(DESTDIR)$(kde_confdir) $(INSTALL_DATA) $(srcdir)/libkleopatrarc.desktop $(DESTDIR)$(kde_confdir)/libkleopatrarc uninstall-local: rm -f $(DESTDIR)$(kde_confdir)/libkleopatrarc messages: #rc.cpp $(EXTRACTRC) */*.ui > rc.cpp $(XGETTEXT) *.cpp *.h \ kleo/*.cpp kleo/*.h \ ui/*.cpp ui/*.h \ backends/*/*.cpp backends/*/*.h -o $(podir)/libkleopatra.pot -include $(top_srcdir)/doc/api/Doxyfile.am +include $(top_srcdir)/admin/Doxyfile.am diff --git a/certmanager/lib/backends/Makefile.am b/certmanager/lib/backends/Makefile.am index 77ccf98cbe..0219d76277 100644 --- a/certmanager/lib/backends/Makefile.am +++ b/certmanager/lib/backends/Makefile.am @@ -1 +1 @@ -SUBDIRS = qgpgme +SUBDIRS = qgpgme chiasmus diff --git a/kleopatra/lib/backends/chiasmus/Makefile.am b/certmanager/lib/backends/chiasmus/Makefile.am similarity index 100% rename from kleopatra/lib/backends/chiasmus/Makefile.am rename to certmanager/lib/backends/chiasmus/Makefile.am diff --git a/kleopatra/lib/backends/chiasmus/chiasmusbackend.cpp b/certmanager/lib/backends/chiasmus/chiasmusbackend.cpp similarity index 100% rename from kleopatra/lib/backends/chiasmus/chiasmusbackend.cpp rename to certmanager/lib/backends/chiasmus/chiasmusbackend.cpp diff --git a/kleopatra/lib/backends/chiasmus/chiasmusbackend.h b/certmanager/lib/backends/chiasmus/chiasmusbackend.h similarity index 100% rename from kleopatra/lib/backends/chiasmus/chiasmusbackend.h rename to certmanager/lib/backends/chiasmus/chiasmusbackend.h diff --git a/kleopatra/lib/backends/chiasmus/chiasmusjob.cpp b/certmanager/lib/backends/chiasmus/chiasmusjob.cpp similarity index 100% rename from kleopatra/lib/backends/chiasmus/chiasmusjob.cpp rename to certmanager/lib/backends/chiasmus/chiasmusjob.cpp diff --git a/kleopatra/lib/backends/chiasmus/chiasmusjob.h b/certmanager/lib/backends/chiasmus/chiasmusjob.h similarity index 100% rename from kleopatra/lib/backends/chiasmus/chiasmusjob.h rename to certmanager/lib/backends/chiasmus/chiasmusjob.h diff --git a/kleopatra/lib/backends/chiasmus/chiasmuslibrary.cpp b/certmanager/lib/backends/chiasmus/chiasmuslibrary.cpp similarity index 100% rename from kleopatra/lib/backends/chiasmus/chiasmuslibrary.cpp rename to certmanager/lib/backends/chiasmus/chiasmuslibrary.cpp diff --git a/kleopatra/lib/backends/chiasmus/chiasmuslibrary.h b/certmanager/lib/backends/chiasmus/chiasmuslibrary.h similarity index 100% rename from kleopatra/lib/backends/chiasmus/chiasmuslibrary.h rename to certmanager/lib/backends/chiasmus/chiasmuslibrary.h diff --git a/kleopatra/lib/backends/chiasmus/config_data.c b/certmanager/lib/backends/chiasmus/config_data.c similarity index 100% rename from kleopatra/lib/backends/chiasmus/config_data.c rename to certmanager/lib/backends/chiasmus/config_data.c diff --git a/kleopatra/lib/backends/chiasmus/config_data.h b/certmanager/lib/backends/chiasmus/config_data.h similarity index 100% rename from kleopatra/lib/backends/chiasmus/config_data.h rename to certmanager/lib/backends/chiasmus/config_data.h diff --git a/kleopatra/lib/backends/chiasmus/configure.in.in b/certmanager/lib/backends/chiasmus/configure.in.in similarity index 100% rename from kleopatra/lib/backends/chiasmus/configure.in.in rename to certmanager/lib/backends/chiasmus/configure.in.in diff --git a/kleopatra/lib/backends/chiasmus/obtainkeysjob.cpp b/certmanager/lib/backends/chiasmus/obtainkeysjob.cpp similarity index 100% rename from kleopatra/lib/backends/chiasmus/obtainkeysjob.cpp rename to certmanager/lib/backends/chiasmus/obtainkeysjob.cpp diff --git a/kleopatra/lib/backends/chiasmus/obtainkeysjob.h b/certmanager/lib/backends/chiasmus/obtainkeysjob.h similarity index 100% rename from kleopatra/lib/backends/chiasmus/obtainkeysjob.h rename to certmanager/lib/backends/chiasmus/obtainkeysjob.h diff --git a/kleopatra/lib/backends/chiasmus/symcryptrunprocessbase.cpp b/certmanager/lib/backends/chiasmus/symcryptrunprocessbase.cpp similarity index 100% rename from kleopatra/lib/backends/chiasmus/symcryptrunprocessbase.cpp rename to certmanager/lib/backends/chiasmus/symcryptrunprocessbase.cpp diff --git a/kleopatra/lib/backends/chiasmus/symcryptrunprocessbase.h b/certmanager/lib/backends/chiasmus/symcryptrunprocessbase.h similarity index 100% rename from kleopatra/lib/backends/chiasmus/symcryptrunprocessbase.h rename to certmanager/lib/backends/chiasmus/symcryptrunprocessbase.h diff --git a/certmanager/lib/backends/kpgp/gpg1backend.h b/certmanager/lib/backends/kpgp/gpg1backend.h index db97f67a6b..f9413accf9 100644 --- a/certmanager/lib/backends/kpgp/gpg1backend.h +++ b/certmanager/lib/backends/kpgp/gpg1backend.h @@ -1,52 +1,52 @@ /* -*- mode: C++; c-file-style: "gnu" -*- gpg1backend.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_GPG1BACKEND_H__ #define __KLEO_GPG1BACKEND_H__ #include "kpgpbackendbase.h" class QString; namespace Kleo { class GPG1Backend : public KpgpBackendBase { public: QString name() const; QString displayName() const; }; } #endif // __KLEO_GPG1BACKEND_H__ diff --git a/certmanager/lib/backends/kpgp/kpgpbackendbase.cpp b/certmanager/lib/backends/kpgp/kpgpbackendbase.cpp index ec0027527a..2d4d17ab2b 100644 --- a/certmanager/lib/backends/kpgp/kpgpbackendbase.cpp +++ b/certmanager/lib/backends/kpgp/kpgpbackendbase.cpp @@ -1,111 +1,111 @@ /* -*- mode: C++; c-file-style: "gnu" -*- kpgpbackendbase.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "kpgpbackendbase.h" #include "pgp2backend.h" #include "pgp5backend.h" #include "pgp6backend.h" #include "gpg1backend.h" #include #include #include "kpgpwrapper.h" Kleo::KpgpBackendBase::KpgpBackendBase() : Kleo::CryptoBackend(), mOpenPGPProtocol( 0 ) { } Kleo::KpgpBackendBase::~KpgpBackendBase() { delete mOpenPGPProtocol; mOpenPGPProtocol = 0; } QString Kleo::GPG1Backend::name() const { return GPG1_BACKEND_NAME; } QString Kleo::GPG1Backend::displayName() const { return i18n("Kpgp/gpg"); } QString Kleo::PGP2Backend::name() const { return PGP2_BACKEND_NAME; } QString Kleo::PGP2Backend::displayName() const { return i18n("Kpgp/pgp v2"); } QString Kleo::PGP5Backend::name() const { return PGP5_BACKEND_NAME; } QString Kleo::PGP5Backend::displayName() const { return i18n("Kpgp/pgp v5"); } QString Kleo::PGP6Backend::name() const { return PGP6_BACKEND_NAME; } QString Kleo::PGP6Backend::displayName() const { return i18n("Kpgp/pgp v6"); } static const QString notSupported() { return i18n("This backend does not support S/MIME"); } bool Kleo::KpgpBackendBase::checkForOpenPGP( QString * /*reason*/ ) const { return true; } bool Kleo::KpgpBackendBase::checkForSMIME( QString * reason ) const { if ( reason ) *reason = notSupported(); return false; } Kleo::CryptoBackend::Protocol * Kleo::KpgpBackendBase::openpgp() const { if ( !mOpenPGPProtocol ) if ( checkForOpenPGP() ) mOpenPGPProtocol = new KpgpWrapper( name() ); return mOpenPGPProtocol; } diff --git a/certmanager/lib/backends/kpgp/kpgpbackendbase.h b/certmanager/lib/backends/kpgp/kpgpbackendbase.h index acfea84b33..854e800c31 100644 --- a/certmanager/lib/backends/kpgp/kpgpbackendbase.h +++ b/certmanager/lib/backends/kpgp/kpgpbackendbase.h @@ -1,73 +1,73 @@ /* -*- mode: C++; c-file-style: "gnu" -*- kpgpbackendbase.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KPGPBACKENDBASE_H__ #define __KLEO_KPGPBACKENDBASE_H__ #include "kleo/cryptobackend.h" #define GPG1_BACKEND_NAME "Kpgp/gpg1" #define PGP2_BACKEND_NAME "Kpgp/pgp2" #define PGP5_BACKEND_NAME "Kpgp/pgp5" #define PGP6_BACKEND_NAME "Kpgp/pgp6" namespace Kleo { class CryptoConfig; } class QString; class KpgpWrapper; namespace Kleo { class KpgpBackendBase : public Kleo::CryptoBackend { public: KpgpBackendBase(); ~KpgpBackendBase(); CryptoConfig * config() const { return 0; } Protocol * openpgp() const; Protocol * smime() const { return 0; } bool supportsOpenPGP() const { return true; } bool supportsSMIME() const { return false; } bool checkForOpenPGP( QString * reason=0 ) const; bool checkForSMIME( QString * reason=0 ) const; private: mutable KpgpWrapper * mOpenPGPProtocol; }; } #endif // __KLEO_KPGPBACKENDBASE_H__ diff --git a/certmanager/lib/backends/kpgp/kpgpkeylistjob.cpp b/certmanager/lib/backends/kpgp/kpgpkeylistjob.cpp index e8f785a18e..4c328adeef 100644 --- a/certmanager/lib/backends/kpgp/kpgpkeylistjob.cpp +++ b/certmanager/lib/backends/kpgp/kpgpkeylistjob.cpp @@ -1,303 +1,303 @@ /* kpgpkeylistjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Ingo Kloecker Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "kpgpkeylistjob.h" #include #include #include #include #include #include #include #include #include Kleo::KpgpKeyListJob::KpgpKeyListJob( Kpgp::Base * pgpBase ) : KeyListJob( 0, "Kleo::KpgpKeyListJob" ), mPgpBase( pgpBase ) { } Kleo::KpgpKeyListJob::~KpgpKeyListJob() { } // the following function is a verbatim copy from gpgme/key.c static char * set_user_id_part (char *tail, const char *buf, size_t len) { while (len && (buf[len - 1] == ' ' || buf[len - 1] == '\t')) len--; for (; len; len--) *tail++ = *buf++; *tail++ = 0; return tail; } // the following function is a verbatim copy from gpgme/key.c static void parse_user_id (char *src, char **name, char **email, char **comment, char *tail) { const char *start = NULL; int in_name = 0; int in_email = 0; int in_comment = 0; while (*src) { if (in_email) { if (*src == '<') /* Not legal but anyway. */ in_email++; else if (*src == '>') { if (!--in_email && !*email) { *email = tail; tail = set_user_id_part (tail, start, src - start); } } } else if (in_comment) { if (*src == '(') in_comment++; else if (*src == ')') { if (!--in_comment && !*comment) { *comment = tail; tail = set_user_id_part (tail, start, src - start); } } } else if (*src == '<') { if (in_name) { if (!*name) { *name = tail; tail = set_user_id_part (tail, start, src - start); } in_name = 0; } in_email = 1; start = src + 1; } else if (*src == '(') { if (in_name) { if (!*name) { *name = tail; tail = set_user_id_part (tail, start, src - start); } in_name = 0; } in_comment = 1; start = src + 1; } else if (!in_name && *src != ' ' && *src != '\t') { in_name = 1; start = src; } src++; } if (in_name) { if (!*name) { *name = tail; tail = set_user_id_part (tail, start, src - start); } } /* Let unused parts point to an EOS. */ tail--; if (!*name) *name = tail; if (!*email) *email = tail; if (!*comment) *comment = tail; } gpgme_user_id_t KpgpUserID2GPGMEUserID( const Kpgp::UserID * kUserId ) { // inspired by _gpgme_key_append_name const QCString text = kUserId->text().utf8(); const int src_len = text.length(); gpgme_user_id_t uid; /* Allocate enough memory for the _gpgme_user_id struct, for the actual user id (the text) and for the parsed version. */ uid = (gpgme_user_id_t) malloc( sizeof( *uid ) + 2 * src_len + 3 ); memset( uid, 0, sizeof *uid ); uid->revoked = kUserId->revoked(); uid->invalid = kUserId->invalid(); uid->validity = (gpgme_validity_t) kUserId->validity(); uid->uid = ((char *) uid) + sizeof (*uid); char *dst = uid->uid; memcpy( dst, text.data(), src_len + 1 ); dst += src_len + 1; parse_user_id( uid->uid, &uid->name, &uid->email, &uid->comment, dst ); return uid; } gpgme_subkey_t KpgpSubkey2GPGMESubKey( const Kpgp::Subkey * kSubkey ) { gpgme_subkey_t subkey; const QCString fpr = kSubkey->fingerprint(); const unsigned int fpr_len = fpr.length(); const QCString keyId = kSubkey->longKeyID(); subkey = (gpgme_subkey_t) calloc( 1, sizeof( *subkey ) + fpr_len + 1 ); subkey->revoked = kSubkey->revoked(); subkey->expired = kSubkey->expired(); subkey->disabled = kSubkey->disabled(); subkey->invalid = kSubkey->invalid(); subkey->can_encrypt = kSubkey->canEncrypt(); subkey->can_sign = kSubkey->canSign(); subkey->can_certify = kSubkey->canCertify(); subkey->secret = kSubkey->secret(); subkey->pubkey_algo = (gpgme_pubkey_algo_t) kSubkey->keyAlgorithm(); subkey->length = kSubkey->keyLength(); subkey->keyid = subkey->_keyid; memcpy( subkey->_keyid, keyId.data(), keyId.length() + 1 ); subkey->fpr = ((char *) subkey) + sizeof( *subkey ); memcpy( subkey->fpr, fpr.data(), fpr_len + 1 ); subkey->timestamp = kSubkey->creationDate(); subkey->expires = kSubkey->expirationDate(); return subkey; } gpgme_key_t KpgpKey2gpgme_key( const Kpgp::Key * kKey ) { gpgme_key_t key; key = (gpgme_key_t) calloc( 1, sizeof( *key ) ); key->revoked = kKey->revoked(); key->expired = kKey->expired(); key->disabled = kKey->disabled(); key->invalid = kKey->invalid(); key->can_encrypt = kKey->canEncrypt(); key->can_sign = kKey->canSign(); key->can_certify = kKey->canCertify(); key->secret = kKey->secret(); key->protocol = GPGME_PROTOCOL_OpenPGP; key->owner_trust = GPGME_VALIDITY_UNKNOWN; // FIXME? Kpgp::UserIDList kUserIDs = kKey->userIDs(); for ( Kpgp::UserIDListIterator it( kUserIDs ); it.current(); ++it ) { gpgme_user_id_t uid = KpgpUserID2GPGMEUserID( *it ); if ( !key->uids ) key->uids = uid; if ( key->_last_uid ) key->_last_uid->next = uid; key->_last_uid = uid; } Kpgp::SubkeyList kSubkeys = kKey->subkeys(); for ( Kpgp::SubkeyListIterator it( kSubkeys ); it.current(); ++it ) { gpgme_subkey_t subkey = KpgpSubkey2GPGMESubKey( *it ); if (!key->subkeys) key->subkeys = subkey; if (key->_last_subkey) key->_last_subkey->next = subkey; key->_last_subkey = subkey; } return key; } GpgME::Error Kleo::KpgpKeyListJob::start( const QStringList & patterns, bool secretOnly ) { mPatterns = patterns; mSecretOnly = secretOnly; QTimer::singleShot( 0, this, SLOT( slotDoIt() ) ); return GpgME::Error( 0 ); } void Kleo::KpgpKeyListJob::slotDoIt() { std::vector keys; GpgME::KeyListResult res = exec( mPatterns, mSecretOnly, keys ); for ( std::vector::const_iterator it = keys.begin(); it != keys.end(); ++it ) emit nextKey( *it ); emit done(); emit result( res ); deleteLater(); } GpgME::KeyListResult Kleo::KpgpKeyListJob::exec( const QStringList & patterns, bool secretOnly, std::vector & keys ) { Kpgp::KeyList kKeys; if ( secretOnly ) kKeys = mPgpBase->secretKeys( patterns ); else kKeys = mPgpBase->publicKeys( patterns ); keys.clear(); for ( Kpgp::KeyListIterator it( kKeys ); it.current(); ++it ) { keys.push_back( GpgME::Key( KpgpKey2gpgme_key(*it), true ) ); } _gpgme_op_keylist_result res; res.truncated = 0; // key list is not truncated res._unused = 0; return GpgME::KeyListResult( GpgME::Error( 0 ), res ); } #include "kpgpkeylistjob.moc" diff --git a/certmanager/lib/backends/kpgp/kpgpkeylistjob.h b/certmanager/lib/backends/kpgp/kpgpkeylistjob.h index fbe608dfe4..779680c2dd 100644 --- a/certmanager/lib/backends/kpgp/kpgpkeylistjob.h +++ b/certmanager/lib/backends/kpgp/kpgpkeylistjob.h @@ -1,79 +1,79 @@ /* -*- mode: C++ -*- kpgpkeylistjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Ingo Kloecker Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KPGPKEYLISTJOB_H__ #define __KLEO_KPGPKEYLISTJOB_H__ #include #include namespace GpgME { class Error; class Context; class Key; } namespace Kpgp { class Base; } namespace Kleo { class KpgpKeyListJob : public KeyListJob { Q_OBJECT public: KpgpKeyListJob( Kpgp::Base * pgpBase ); ~KpgpKeyListJob(); /*! \reimp from KeyListJob */ GpgME::Error start( const QStringList & patterns, bool secretOnly ); /*! \reimp from KeyListJob */ GpgME::KeyListResult exec( const QStringList & patterns, bool secretOnly, std::vector & keys ); /*! \reimp from Job */ void slotCancel() { /*FIXME*/ } private slots: void slotDoIt(); private: Kpgp::Base * mPgpBase; QStringList mPatterns; bool mSecretOnly; }; } #endif // __KLEO_KPGPKEYLISTJOB_H__ diff --git a/certmanager/lib/backends/kpgp/kpgpwrapper.cpp b/certmanager/lib/backends/kpgp/kpgpwrapper.cpp index 4e7b058b69..20d885dd51 100644 --- a/certmanager/lib/backends/kpgp/kpgpwrapper.cpp +++ b/certmanager/lib/backends/kpgp/kpgpwrapper.cpp @@ -1,173 +1,173 @@ /* -*- mode: C++; c-file-style: "gnu" -*- kpgpwrapper.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Ingo Kloecker Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "kpgpwrapper.h" #include "kpgpbackendbase.h" #include #include //#include //#include //#include //#include //#include //#include //#include //#include //#include //#include //#include //#include //#include //#include KpgpWrapper::KpgpWrapper( const QString & name ) : mName( name ), mPgpBase( 0 ) { } KpgpWrapper::~KpgpWrapper() { } QString KpgpWrapper::name() const { return mName; } QString KpgpWrapper::displayName() const { return mName; } Kleo::KeyListJob * KpgpWrapper::keyListJob( bool /*remote*/, bool /*includeSigs*/, bool /*validate*/ ) const { return new Kleo::KpgpKeyListJob( pgpBase() ); } Kleo::EncryptJob * KpgpWrapper::encryptJob( bool /*armor*/, bool /*textmode*/ ) const { return 0; } Kleo::DecryptJob * KpgpWrapper::decryptJob() const { return 0; } Kleo::SignJob * KpgpWrapper::signJob( bool /*armor*/, bool /*textMode*/ ) const { return 0; } Kleo::VerifyDetachedJob * KpgpWrapper::verifyDetachedJob( bool /*textmode*/ ) const { return 0; } Kleo::VerifyOpaqueJob * KpgpWrapper::verifyOpaqueJob( bool /*textmode*/ ) const { return 0; } Kleo::KeyGenerationJob * KpgpWrapper::keyGenerationJob() const { return 0; } Kleo::ImportJob * KpgpWrapper::importJob() const { return 0; } Kleo::ExportJob * KpgpWrapper::publicKeyExportJob( bool /*armor*/ ) const { return 0; } Kleo::ExportJob * KpgpWrapper::secretKeyExportJob( bool /*armor*/ ) const { return 0; } Kleo::DownloadJob * KpgpWrapper::downloadJob( bool /*armor*/ ) const { return 0; } Kleo::DeleteJob * KpgpWrapper::deleteJob() const { return 0; } Kleo::SignEncryptJob * KpgpWrapper::signEncryptJob( bool /*armor*/, bool /*textMode*/ ) const { return 0; } Kleo::DecryptVerifyJob * KpgpWrapper::decryptVerifyJob( bool /*textmode*/ ) const { return 0; } Kleo::RefreshKeysJob * KpgpWrapper::refreshKeysJob() const { return 0; } Kpgp::Base * KpgpWrapper::pgpBase() const { if ( !mPgpBase ) { if ( name() == GPG1_BACKEND_NAME ) mPgpBase = new Kpgp::BaseG(); else if ( name() == PGP2_BACKEND_NAME ) mPgpBase = new Kpgp::Base2(); else if ( name() == PGP5_BACKEND_NAME ) mPgpBase = new Kpgp::Base5(); else if ( name() == PGP6_BACKEND_NAME ) mPgpBase = new Kpgp::Base6(); } return mPgpBase; } diff --git a/certmanager/lib/backends/kpgp/kpgpwrapper.h b/certmanager/lib/backends/kpgp/kpgpwrapper.h index 00ef297ead..182661ec48 100644 --- a/certmanager/lib/backends/kpgp/kpgpwrapper.h +++ b/certmanager/lib/backends/kpgp/kpgpwrapper.h @@ -1,97 +1,97 @@ /* -*- mode: C++; c-file-style: "gnu" -*- kpgpwrapper.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Ingo Kloecker Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KPGPWRAPPER_H__ #define __KLEO_KPGPWRAPPER_H__ #include #include namespace Kleo { class KeyListJob; class EncryptJob; class DecryptJob; class SignJob; class VerifyDetachedJob; class VerifyOpaqueJob; class KeyGenerationJob; class ImportJob; class ExportJob; class DownloadJob; class DeleteJob; class SignEncryptJob; class DecryptVerifyJob; class CryptoConfig; class RefreshKeysJob; } namespace Kpgp { class Base; } class KpgpWrapper : public Kleo::CryptoBackend::Protocol { public: KpgpWrapper( const QString & name ); ~KpgpWrapper(); QString name() const; QString displayName() const; Kleo::KeyListJob * keyListJob( bool remote=false, bool includeSigs=false, bool validate=false ) const; Kleo::EncryptJob * encryptJob( bool armor=false, bool textmode=false ) const; Kleo::DecryptJob * decryptJob() const; Kleo::SignJob * signJob( bool armor=false, bool textMode=false ) const; Kleo::VerifyDetachedJob * verifyDetachedJob( bool textmode=false) const; Kleo::VerifyOpaqueJob * verifyOpaqueJob( bool textmode=false ) const; Kleo::KeyGenerationJob * keyGenerationJob() const; Kleo::ImportJob * importJob() const; Kleo::ExportJob * publicKeyExportJob( bool armor=false ) const; Kleo::ExportJob * secretKeyExportJob( bool armor=false ) const; Kleo::DownloadJob * downloadJob( bool armor=false ) const; Kleo::DeleteJob * deleteJob() const; Kleo::SignEncryptJob * signEncryptJob( bool armor=false, bool textMode=false ) const; Kleo::DecryptVerifyJob * decryptVerifyJob( bool textmode=false ) const; Kleo::RefreshKeysJob * refreshKeysJob() const; private: Kpgp::Base * pgpBase() const; private: QString mName; mutable Kpgp::Base * mPgpBase; }; #endif // __KLEO_KPGPWRAPPER_H__ diff --git a/certmanager/lib/backends/kpgp/pgp2backend.h b/certmanager/lib/backends/kpgp/pgp2backend.h index 59248311f7..fc053a20c4 100644 --- a/certmanager/lib/backends/kpgp/pgp2backend.h +++ b/certmanager/lib/backends/kpgp/pgp2backend.h @@ -1,52 +1,52 @@ /* -*- mode: C++; c-file-style: "gnu" -*- pgp2backend.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_PGP2BACKEND_H__ #define __KLEO_PGP2BACKEND_H__ #include "kpgpbackendbase.h" class QString; namespace Kleo { class PGP2Backend : public KpgpBackendBase { public: QString name() const; QString displayName() const; }; } #endif // __KLEO_PGP2BACKEND_H__ diff --git a/certmanager/lib/backends/kpgp/pgp5backend.h b/certmanager/lib/backends/kpgp/pgp5backend.h index 0ba69a2afb..bf323b6fb2 100644 --- a/certmanager/lib/backends/kpgp/pgp5backend.h +++ b/certmanager/lib/backends/kpgp/pgp5backend.h @@ -1,52 +1,52 @@ /* -*- mode: C++; c-file-style: "gnu" -*- pgp5backend.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_PGP5BACKEND_H__ #define __KLEO_PGP5BACKEND_H__ #include "kpgpbackendbase.h" class QString; namespace Kleo { class PGP5Backend : public KpgpBackendBase { public: QString name() const; QString displayName() const; }; } #endif // __KLEO_PGP5BACKEND_H__ diff --git a/certmanager/lib/backends/kpgp/pgp6backend.h b/certmanager/lib/backends/kpgp/pgp6backend.h index b8d5f344db..827cf239b8 100644 --- a/certmanager/lib/backends/kpgp/pgp6backend.h +++ b/certmanager/lib/backends/kpgp/pgp6backend.h @@ -1,52 +1,52 @@ /* -*- mode: C++; c-file-style: "gnu" -*- pgp6backend.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_PGP6BACKEND_H__ #define __KLEO_PGP6BACKEND_H__ #include "kpgpbackendbase.h" class QString; namespace Kleo { class PGP6Backend : public KpgpBackendBase { public: QString name() const; QString displayName() const; }; } #endif // __KLEO_PGP6BACKEND_H__ diff --git a/certmanager/lib/backends/qgpgme/gnupgprocessbase.cpp b/certmanager/lib/backends/qgpgme/gnupgprocessbase.cpp index 3aabf223b7..2d3ca74096 100644 --- a/certmanager/lib/backends/qgpgme/gnupgprocessbase.cpp +++ b/certmanager/lib/backends/qgpgme/gnupgprocessbase.cpp @@ -1,198 +1,198 @@ /* gnupgprocessbase.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "gnupgprocessbase.h" #include #include #include #include #include #include #include #include #include struct Kleo::GnuPGProcessBase::Private { Private() : useStatusFD( false ), statnot( 0 ) { statusFD[0] = statusFD[1] = -1; } bool useStatusFD; int statusFD[2]; QSocketNotifier * statnot; QCString statusBuffer; }; Kleo::GnuPGProcessBase::GnuPGProcessBase( QObject * parent, const char * name ) : KProcess( parent, name ) { d = new Private(); } Kleo::GnuPGProcessBase::~GnuPGProcessBase() { delete d; d = 0; } void Kleo::GnuPGProcessBase::setUseStatusFD( bool use ) { assert( d ); d->useStatusFD = use; } bool Kleo::GnuPGProcessBase::start( RunMode runmode, Communication comm ) { if ( d->useStatusFD ) { // set up the status-fd. This should be in setupCommunication(), // but then it's too late: we need the fd of the pipe to pass it // as argument to the --status-fd option: // PENDING(marc) find out why KProcess uses both pipe() and socketpair()... if ( ::pipe( d->statusFD ) < 0 ) { kdDebug( 5150 ) << "Kleo::GnuPGProcessBase::start: pipe(2) failed: " << perror << endl; return false; } ::fcntl( d->statusFD[0], F_SETFD, FD_CLOEXEC ); ::fcntl( d->statusFD[1], F_SETFD, FD_CLOEXEC ); if ( !arguments.empty() ) { QValueList::iterator it = arguments.begin(); ++it; arguments.insert( it, "--status-fd" ); char buf[25]; sprintf( buf, "%d", d->statusFD[1] ); arguments.insert( it, buf ); arguments.insert( it, "--no-tty" ); //arguments.insert( it, "--enable-progress-filter" ); // gpgsm doesn't know this } } return KProcess::start( runmode, comm ); } int Kleo::GnuPGProcessBase::setupCommunication( Communication comm ) { if ( int ok = KProcess::setupCommunication( comm ) ) return ok; if ( d->useStatusFD ) { // base class impl returned error, so close our fd's, too ::close( d->statusFD[0] ); ::close( d->statusFD[1] ); d->statusFD[0] = d->statusFD[1] = -1; } return 0; // Error } int Kleo::GnuPGProcessBase::commSetupDoneP() { if ( d->useStatusFD ) { ::close( d->statusFD[1] ); // close the input end of the pipe, we're the reader d->statnot = new QSocketNotifier( d->statusFD[0], QSocketNotifier::Read, this ); connect( d->statnot, SIGNAL(activated(int)), SLOT(slotChildStatus(int)) ); } return KProcess::commSetupDoneP(); } int Kleo::GnuPGProcessBase::commSetupDoneC() { if ( d->useStatusFD ) ::fcntl( d->statusFD[1], F_SETFD, 0 ); return KProcess::commSetupDoneC(); } void Kleo::GnuPGProcessBase::slotChildStatus( int fd ) { if ( !childStatus(fd) ) closeStatus(); } bool Kleo::GnuPGProcessBase::closeStatus() { if ( !d->useStatusFD ) return false; d->useStatusFD = false; delete d->statnot; d->statnot = 0; ::close( d->statusFD[0] ); d->statusFD[0] = -1; return true; } int Kleo::GnuPGProcessBase::childStatus( int fd ) { char buf[1024]; const int len = ::read( fd, buf, sizeof(buf)-1 ); if ( len > 0 ) { buf[len] = 0; d->statusBuffer += buf; parseStatusOutput(); } return len; } static QString fromHexEscapedUtf8( const QCString & str ) { return KURL::decode_string( str.data(), 106 /* utf-8 */ ); } void Kleo::GnuPGProcessBase::parseStatusOutput() { static const char startToken[] = "[GNUPG:] "; static const int startTokenLen = sizeof startToken / sizeof *startToken - 1; int lineStart = 0; for ( int lineEnd = d->statusBuffer.find( '\n' ) ; lineEnd >= 0 ; lineEnd = d->statusBuffer.find( '\n', lineStart = lineEnd+1 ) ) { // get next line: const QCString line = d->statusBuffer.mid( lineStart, lineEnd - lineStart ).stripWhiteSpace(); if ( line.isEmpty() ) continue; // check status token if ( line.left( startTokenLen ) != startToken ) { kdDebug( 5150 ) << "Kleo::GnuPGProcessBase::childStatus: status-fd protocol error: line doesn't begin with \"" << startToken << "\"" << endl; continue; } // remove status token: const QCString command = line.mid( startTokenLen ).simplifyWhiteSpace() + ' '; if ( command == " " ) { kdDebug( 5150 ) << "Kleo::GnuPGProcessBase::childStatus: status-fd protocol error: line without content." << endl; continue; } // split into base and args QString cmd; QStringList args; int tagStart = 0; for ( int tagEnd = command.find( ' ' ) ; tagEnd >= 0 ; tagEnd = command.find( ' ', tagStart = tagEnd+1 ) ) { const QCString tag = command.mid( tagStart, tagEnd - tagStart ); if ( cmd.isNull() ) cmd = fromHexEscapedUtf8( tag ); else args.push_back( fromHexEscapedUtf8( tag ) ); } emit status( this, cmd, args ); } d->statusBuffer = d->statusBuffer.mid( lineStart ); } void Kleo::GnuPGProcessBase::virtual_hook( int id, void * data ) { KProcess::virtual_hook( id, data ); } #include "gnupgprocessbase.moc" diff --git a/certmanager/lib/backends/qgpgme/gnupgprocessbase.h b/certmanager/lib/backends/qgpgme/gnupgprocessbase.h index f772ec6dcc..73e31e2959 100644 --- a/certmanager/lib/backends/qgpgme/gnupgprocessbase.h +++ b/certmanager/lib/backends/qgpgme/gnupgprocessbase.h @@ -1,91 +1,91 @@ /* gnupgprocessbase.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_GNUPGPROCESSBASE_H__ #define __KLEO_GNUPGPROCESSBASE_H__ #include namespace Kleo { /** * @short a base class for GPG and GPGSM processes. * * This KProcess subclass implements the status-fd handling common * to GPG and GPGSM. * * @author Marc Mutz */ class GnuPGProcessBase : public KProcess { Q_OBJECT public: GnuPGProcessBase( QObject * parent=0, const char * name=0 ); ~GnuPGProcessBase(); void setUseStatusFD( bool use ); /*! reimplementation */ bool start( RunMode runmode, Communication comm ); bool closeStatus(); signals: void status( Kleo::GnuPGProcessBase * proc, const QString & type, const QStringList & args ); protected: /*! reimplementation */ int setupCommunication( Communication comm ); /*! reimplementation */ int commSetupDoneP(); /*! reimplementation */ int commSetupDoneC(); int childStatus( int fd ); private slots: void slotChildStatus( int fd ); private: void parseStatusOutput(); private: class Private; Private * d; protected: /*! reimplementation */ void virtual_hook( int id, void * data ); }; } #endif // __KLEO_GNUPGPROCESSBASE_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmebackend.cpp b/certmanager/lib/backends/qgpgme/qgpgmebackend.cpp index b7cf0d7929..de05eb1603 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmebackend.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmebackend.cpp @@ -1,123 +1,153 @@ /* -*- mode: C++; c-file-style: "gnu" -*- qgpgmebackend.cpp This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB + Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmebackend.h" #include "qgpgmecryptoconfig.h" #include "cryptplugwrapper.h" #include #include #include #include #include #include Kleo::QGpgMEBackend::QGpgMEBackend() : Kleo::CryptoBackend(), mCryptoConfig( 0 ), mOpenPGPProtocol( 0 ), mSMIMEProtocol( 0 ) { } Kleo::QGpgMEBackend::~QGpgMEBackend() { delete mCryptoConfig; mCryptoConfig = 0; delete mOpenPGPProtocol; mOpenPGPProtocol = 0; delete mSMIMEProtocol; mSMIMEProtocol = 0; } QString Kleo::QGpgMEBackend::name() const { return "gpgme"; } QString Kleo::QGpgMEBackend::displayName() const { return i18n( "GpgME" ); } Kleo::CryptoConfig * Kleo::QGpgMEBackend::config() const { if ( !mCryptoConfig ) { static bool hasGpgConf = !KStandardDirs::findExe( "gpgconf" ).isEmpty(); if ( hasGpgConf ) mCryptoConfig = new QGpgMECryptoConfig(); } return mCryptoConfig; } static bool check( GpgME::Context::Protocol proto, QString * reason ) { if ( !GpgME::checkEngine( proto ) ) return true; if ( !reason ) return false; // error, check why: const GpgME::EngineInfo ei = GpgME::engineInfo( proto ); if ( ei.isNull() ) *reason = i18n("GPGME was compiled without support for %1.").arg( proto == GpgME::Context::CMS ? "S/MIME" : "OpenPGP" ); else if ( ei.fileName() && !ei.version() ) *reason = i18n("Engine %1 is not installed properly.").arg( QFile::decodeName( ei.fileName() ) ); else if ( ei.fileName() && ei.version() && ei.requiredVersion() ) *reason = i18n("Engine %1 version %2 installed, " "but at least version %3 is required.") .arg( QFile::decodeName( ei.fileName() ), ei.version(), ei.requiredVersion() ); else *reason = i18n("Unknown problem with engine for protocol %1.").arg( proto == GpgME::Context::CMS ? "S/MIME" : "OpenPGP" ); return false; } bool Kleo::QGpgMEBackend::checkForOpenPGP( QString * reason ) const { return check( GpgME::Context::OpenPGP, reason ); } bool Kleo::QGpgMEBackend::checkForSMIME( QString * reason ) const { return check( GpgME::Context::CMS, reason ); } +bool Kleo::QGpgMEBackend::checkForProtocol( const char * name, QString * reason ) const { + if ( qstricmp( name, OpenPGP ) == 0 ) + return check( GpgME::Context::OpenPGP, reason ); + if ( qstricmp( name, SMIME ) == 0 ) + return check( GpgME::Context::CMS, reason ); + if ( reason ) + *reason = i18n( "Unsupported protocol \"%1\"" ).arg( name ); + return false; +} + Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::openpgp() const { if ( !mOpenPGPProtocol ) if ( checkForOpenPGP() ) mOpenPGPProtocol = new CryptPlugWrapper( "gpg", "openpgp" ); return mOpenPGPProtocol; } Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::smime() const { if ( !mSMIMEProtocol ) if ( checkForSMIME() ) mSMIMEProtocol = new CryptPlugWrapper( "gpgsm", "smime" ); return mSMIMEProtocol; } + +Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::protocol( const char * name ) const { + if ( qstricmp( name, OpenPGP ) == 0 ) + return openpgp(); + if ( qstricmp( name, SMIME ) == 0 ) + return smime(); + return 0; +} + +bool Kleo::QGpgMEBackend::supportsProtocol( const char * name ) const { + return qstricmp( name, OpenPGP ) == 0 || qstricmp( name, SMIME ); +} + +const char * Kleo::QGpgMEBackend::enumerateProtocols( int i ) const { + switch ( i ) { + case 0: return OpenPGP; + case 1: return SMIME; + default: return 0; + } +} diff --git a/certmanager/lib/backends/qgpgme/qgpgmebackend.h b/certmanager/lib/backends/qgpgme/qgpgmebackend.h index d5fcdd7f2e..fae2dd68e8 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmebackend.h +++ b/certmanager/lib/backends/qgpgme/qgpgmebackend.h @@ -1,76 +1,82 @@ /* -*- mode: C++; c-file-style: "gnu" -*- qgpgmebackend.h This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB + Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEBACKEND_H__ #define __KLEO_QGPGMEBACKEND_H__ #include "kleo/cryptobackend.h" class CryptPlugWrapper; namespace Kleo { class CryptoConfig; } class QGpgMECryptoConfig; class QString; namespace Kleo { class QGpgMEBackend : public Kleo::CryptoBackend { public: QGpgMEBackend(); ~QGpgMEBackend(); QString name() const; QString displayName() const; CryptoConfig * config() const; + Protocol * openpgp() const; Protocol * smime() const; + Protocol * protocol( const char * name ) const; bool checkForOpenPGP( QString * reason=0 ) const; bool checkForSMIME( QString * reason=0 ) const; + bool checkForProtocol( const char * name, QString * reason ) const; bool supportsOpenPGP() const { return true; } bool supportsSMIME() const { return true; } + bool supportsProtocol( const char * name ) const; + + const char * enumerateProtocols( int i ) const; private: mutable QGpgMECryptoConfig * mCryptoConfig; mutable CryptPlugWrapper * mOpenPGPProtocol; mutable CryptPlugWrapper * mSMIMEProtocol; }; } #endif // __KLEO_QGPGMEBACKEND_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmecryptoconfig.cpp b/certmanager/lib/backends/qgpgme/qgpgmecryptoconfig.cpp index 6d94400cfc..f8aa068b3e 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmecryptoconfig.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmecryptoconfig.cpp @@ -1,830 +1,831 @@ /* qgpgmecryptoconfig.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "qgpgmecryptoconfig.h" #include #include #include #include #include #include #include #include #include #include // Just for the Q_ASSERT in the dtor. Not thread-safe, but who would // have 2 threads talking to gpgconf anyway? :) static bool s_duringClear = false; #define GPGCONF_FLAG_GROUP 1 #define GPGCONF_FLAG_OPTIONAL 2 #define GPGCONF_FLAG_LIST 4 #define GPGCONF_FLAG_RUNTIME 8 #define GPGCONF_FLAG_DEFAULT 16 // fixed default value available #define GPGCONF_FLAG_DEFAULT_DESC 32 // runtime default value available #define GPGCONF_FLAG_NOARG_DESC 64 // option with optional arg; special meaning if no arg set // Change size of mFlags bitfield if adding new values here QGpgMECryptoConfig::QGpgMECryptoConfig() : mComponents( 7 ), mParsed( false ) { mComponents.setAutoDelete( true ); } QGpgMECryptoConfig::~QGpgMECryptoConfig() { } void QGpgMECryptoConfig::runGpgConf( bool showErrors ) { // Run gpgconf --list-components to make the list of components KProcIO proc( QTextCodec::codecForName( "utf8" ) ); proc << "gpgconf"; // must be in the PATH proc << "--list-components"; QObject::connect( &proc, SIGNAL( readReady(KProcIO*) ), this, SLOT( slotCollectStdOut(KProcIO*) ) ); // run the process: int rc = 0; if ( !proc.start( KProcess::Block ) ) rc = -1; else rc = ( proc.normalExit() ) ? proc.exitStatus() : -2 ; // handle errors, if any (and if requested) if ( showErrors && rc != 0 ) { QString wmsg = i18n("Failed to execute gpgconf:
%1
"); if ( rc == -1 ) wmsg = wmsg.arg( i18n( "program not found" ) ); else if ( rc == -2 ) wmsg = wmsg.arg( i18n( "program cannot be executed" ) ); else wmsg = wmsg.arg( strerror(rc) ); kdWarning(5150) << wmsg << endl; // to see it from test_cryptoconfig.cpp KMessageBox::error(0, wmsg); } mParsed = true; } void QGpgMECryptoConfig::slotCollectStdOut( KProcIO* proc ) { QString line; int result; while( ( result = proc->readln(line) ) != -1 ) { //kdDebug(5150) << "GOT LINE:" << line << endl; // Format: NAME:DESCRIPTION QStringList lst = QStringList::split( ':', line, true ); if ( lst.count() >= 2 ) { mComponents.insert( lst[0], new QGpgMECryptoConfigComponent( this, lst[0], lst[1] ) ); } else { kdWarning(5150) << "Parse error on gpgconf --list-components output: " << line << endl; } } } QStringList QGpgMECryptoConfig::componentList() const { if ( !mParsed ) const_cast( this )->runGpgConf( true ); QDictIterator it( mComponents ); QStringList names; for( ; it.current(); ++it ) names.push_back( it.currentKey() ); return names; } Kleo::CryptoConfigComponent* QGpgMECryptoConfig::component( const QString& name ) const { if ( !mParsed ) const_cast( this )->runGpgConf( false ); return mComponents.find( name ); } void QGpgMECryptoConfig::sync( bool runtime ) { QDictIterator it( mComponents ); for( ; it.current(); ++it ) it.current()->sync( runtime ); } void QGpgMECryptoConfig::clear() { s_duringClear = true; mComponents.clear(); s_duringClear = false; mParsed = false; // next call to componentList/component will need to run gpgconf again } //// QGpgMECryptoConfigComponent::QGpgMECryptoConfigComponent( QGpgMECryptoConfig*, const QString& name, const QString& description ) : mGroups( 7 ), mName( name ), mDescription( description ) { mGroups.setAutoDelete( true ); runGpgConf(); } QGpgMECryptoConfigComponent::~QGpgMECryptoConfigComponent() { } void QGpgMECryptoConfigComponent::runGpgConf() { // Run gpgconf --list-options , and create all groups and entries for that component KProcIO proc( QTextCodec::codecForName( "utf8" ) ); proc << "gpgconf"; // must be in the PATH proc << "--list-options"; proc << mName; //kdDebug(5150) << "Running gpgconf --list-options " << mName << endl; QObject::connect( &proc, SIGNAL( readReady(KProcIO*) ), this, SLOT( slotCollectStdOut(KProcIO*) ) ); mCurrentGroup = 0; // run the process: int rc = 0; if ( !proc.start( KProcess::Block ) ) rc = -1; else rc = ( proc.normalExit() ) ? proc.exitStatus() : -1 ; if( rc != 0 ) // can happen when using the wrong version of gpg... kdWarning(5150) << "Running 'gpgconf --list-options " << mName << "' failed. " << strerror( rc ) << ", but try that command to see the real output" << endl; else { if ( mCurrentGroup && !mCurrentGroup->mEntries.isEmpty() ) // only add non-empty groups mGroups.insert( mCurrentGroupName, mCurrentGroup ); } } void QGpgMECryptoConfigComponent::slotCollectStdOut( KProcIO* proc ) { QString line; int result; while( ( result = proc->readln(line) ) != -1 ) { //kdDebug(5150) << "GOT LINE:" << line << endl; // Format: NAME:FLAGS:LEVEL:DESCRIPTION:TYPE:ALT-TYPE:ARGNAME:DEFAULT:ARGDEF:VALUE - QStringList lst = QStringList::split( ':', line, true ); + const QStringList lst = QStringList::split( ':', line, true ); if ( lst.count() >= 10 ) { - int flags = lst[1].toInt(); - int level = lst[2].toInt(); + const int flags = lst[1].toInt(); + const int level = lst[2].toInt(); if ( level > 2 ) // invisible or internal -> skip it; continue; if ( flags & GPGCONF_FLAG_GROUP ) { if ( mCurrentGroup && !mCurrentGroup->mEntries.isEmpty() ) // only add non-empty groups mGroups.insert( mCurrentGroupName, mCurrentGroup ); //else // kdDebug(5150) << "Discarding empty group " << mCurrentGroupName << endl; - mCurrentGroup = new QGpgMECryptoConfigGroup( lst[3], level ); + mCurrentGroup = new QGpgMECryptoConfigGroup( lst[0], lst[3], level ); mCurrentGroupName = lst[0]; } else { // normal entry if ( !mCurrentGroup ) { // first toplevel entry -> create toplevel group - mCurrentGroup = new QGpgMECryptoConfigGroup( QString::null, 0 ); + mCurrentGroup = new QGpgMECryptoConfigGroup( "", QString::null, 0 ); mCurrentGroupName = ""; } mCurrentGroup->mEntries.insert( lst[0], new QGpgMECryptoConfigEntry( lst ) ); } } else { // This happens on lines like // dirmngr[31465]: error opening `/home/dfaure/.gnupg/dirmngr_ldapservers.conf': No such file or directory // so let's not bother the user with it. //kdWarning(5150) << "Parse error on gpgconf --list-options output: " << line << endl; } } } QStringList QGpgMECryptoConfigComponent::groupList() const { QDictIterator it( mGroups ); QStringList names; for( ; it.current(); ++it ) names.push_back( it.currentKey() ); return names; } Kleo::CryptoConfigGroup* QGpgMECryptoConfigComponent::group(const QString& name ) const { return mGroups.find( name ); } void QGpgMECryptoConfigComponent::sync( bool runtime ) { KTempFile tmpFile; tmpFile.setAutoDelete( true ); QValueList dirtyEntries; // Collect all dirty entries QDictIterator groupit( mGroups ); for( ; groupit.current(); ++groupit ) { QDictIterator it( groupit.current()->mEntries ); for( ; it.current(); ++it ) { if ( it.current()->isDirty() ) { // OK, we can set it.currentKey() to it.current()->outputString() QString line = it.currentKey(); if ( it.current()->isSet() ) { // set option line += ":0:"; line += it.current()->outputString(); } else { // unset option line += ":16:"; } line += '\n'; QCString line8bit = line.utf8(); // encode with utf8, and KProcIO uses utf8 when reading. tmpFile.file()->writeBlock( line8bit.data(), line8bit.size()-1 /*no 0*/ ); dirtyEntries.append( it.current() ); } } } tmpFile.close(); if ( dirtyEntries.isEmpty() ) return; // Call gpgconf --change-options QString commandLine = "gpgconf"; if ( runtime ) commandLine += " --runtime"; commandLine += " --change-options "; commandLine += KProcess::quote( mName ); commandLine += " < "; commandLine += KProcess::quote( tmpFile.name() ); //kdDebug(5150) << commandLine << endl; //system( QCString( "cat " ) + tmpFile.name().latin1() ); // DEBUG KProcess proc; proc.setUseShell( true ); proc << commandLine; // run the process: int rc = 0; if ( !proc.start( KProcess::Block ) ) rc = -1; else rc = ( proc.normalExit() ) ? proc.exitStatus() : -1 ; if ( rc == -1 ) { QString wmsg = i18n( "Could not start gpgconf\nCheck that gpgconf is in the PATH and that it can be started" ); kdWarning(5150) << wmsg << endl; KMessageBox::error(0, wmsg); } else if( rc != 0 ) // Happens due to bugs in gpgconf (e.g. issues 104/115) { QString wmsg = i18n( "Error from gpgconf while saving configuration: %1" ).arg( strerror( rc ) ); kdWarning(5150) << k_funcinfo << ":" << strerror( rc ) << endl; KMessageBox::error(0, wmsg); } else { QValueList::Iterator it = dirtyEntries.begin(); for( ; it != dirtyEntries.end(); ++it ) { (*it)->setDirty( false ); } } } //// -QGpgMECryptoConfigGroup::QGpgMECryptoConfigGroup( const QString& description, int level ) +QGpgMECryptoConfigGroup::QGpgMECryptoConfigGroup( const QString & name, const QString& description, int level ) : mEntries( 29 ), + mName( name ), mDescription( description ), mLevel( static_cast( level ) ) { mEntries.setAutoDelete( true ); } QStringList QGpgMECryptoConfigGroup::entryList() const { QDictIterator it( mEntries ); QStringList names; for( ; it.current(); ++it ) names.push_back( it.currentKey() ); return names; } Kleo::CryptoConfigEntry* QGpgMECryptoConfigGroup::entry( const QString& name ) const { return mEntries.find( name ); } //// static QString gpgconf_unescape( const QString& str ) { // Looks like it's the same rules as KURL. return KURL::decode_string( str, 106 ); } static QString gpgconf_escape( const QString& str ) { // Escape special chars (including ':' and '%') QString enc = KURL::encode_string( str, 106 ); // and convert to utf8 first (to get %12%34 for one special char) // Also encode commas, for lists. enc.replace( ',', "%2c" ); return enc; } static QString urlpart_encode( const QString& str ) { QString enc( str ); enc.replace( '%', "%25" ); // first! enc.replace( ':', "%3a" ); //kdDebug() << " urlpart_encode: " << str << " -> " << enc << endl; return enc; } static QString urlpart_decode( const QString& str ) { return KURL::decode_string( str ); } // gpgconf arg type number -> CryptoConfigEntry arg type enum mapping static Kleo::CryptoConfigEntry::ArgType knownArgType( int argType, bool& ok ) { ok = true; switch( argType ) { case 0: // none return Kleo::CryptoConfigEntry::ArgType_None; case 1: // string return Kleo::CryptoConfigEntry::ArgType_String; case 2: // int32 return Kleo::CryptoConfigEntry::ArgType_Int; case 3: // uint32 return Kleo::CryptoConfigEntry::ArgType_UInt; case 32: // pathname return Kleo::CryptoConfigEntry::ArgType_Path; case 33: // ldap server return Kleo::CryptoConfigEntry::ArgType_LDAPURL; default: ok = false; return Kleo::CryptoConfigEntry::ArgType_None; } } QGpgMECryptoConfigEntry::QGpgMECryptoConfigEntry( const QStringList& parsedLine ) { // Format: NAME:FLAGS:LEVEL:DESCRIPTION:TYPE:ALT-TYPE:ARGNAME:DEFAULT:ARGDEF:VALUE assert( parsedLine.count() >= 10 ); // called checked for it already QStringList::const_iterator it = parsedLine.begin(); - ++it; // skip name, stored in group + mName = *it++; mFlags = (*it++).toInt(); mLevel = (*it++).toInt(); - mDescription = (*it++); + mDescription = *it++; bool ok; // we keep the real (int) arg type, since it influences the parsing (e.g. for ldap urls) mRealArgType = (*it++).toInt(); mArgType = knownArgType( mRealArgType, ok ); if ( !ok && !(*it).isEmpty() ) { // use ALT-TYPE mRealArgType = (*it).toInt(); mArgType = knownArgType( mRealArgType, ok ); } if ( !ok ) kdWarning(5150) << "Unsupported datatype: " << parsedLine[4] << " : " << *it << " for " << parsedLine[0] << endl; ++it; // done with alt-type ++it; // skip argname (not useful in GUIs) mSet = false; QString value; if ( mFlags & GPGCONF_FLAG_DEFAULT ) { value = *it; // get default value mDefaultValue = stringToValue( value, true ); } ++it; // done with DEFAULT ++it; // ### skip ARGDEF for now. It's only for options with an "optional arg" //kdDebug(5150) << "Entry " << parsedLine[0] << " val=" << *it << endl; if ( !(*it).isEmpty() ) { // a real value was set mSet = true; value = *it; mValue = stringToValue( value, true ); } else { mValue = mDefaultValue; } mDirty = false; } QVariant QGpgMECryptoConfigEntry::stringToValue( const QString& str, bool unescape ) const { bool isString = isStringType(); if ( isList() ) { QValueList lst; QStringList items = QStringList::split( ',', str ); for( QStringList::const_iterator valit = items.begin(); valit != items.end(); ++valit ) { QString val = *valit; if ( isString ) { if ( val.isEmpty() ) { lst << QString::null; continue; } else if ( unescape ) { if( val[0] != '"' ) // see README.gpgconf kdWarning(5150) << "String value should start with '\"' : " << val << endl; val = val.mid( 1 ); } } lst << QVariant( unescape ? gpgconf_unescape( val ) : val ); } return lst; } else { // not a list QString val( str ); if ( isString ) { if ( val.isEmpty() ) return QVariant( QString::null ); // not set [ok with lists too?] else if ( unescape ) { Q_ASSERT( val[0] == '"' ); // see README.gpgconf val = val.mid( 1 ); } } return QVariant( unescape ? gpgconf_unescape( val ) : val ); } } QGpgMECryptoConfigEntry::~QGpgMECryptoConfigEntry() { #ifndef NDEBUG if ( !s_duringClear && mDirty ) kdWarning(5150) << "Deleting a QGpgMECryptoConfigEntry that was modified (" << mDescription << ")\n" << "You forgot to call sync() (to commit) or clear() (to discard)" << endl; #endif } bool QGpgMECryptoConfigEntry::isOptional() const { return mFlags & GPGCONF_FLAG_OPTIONAL; } bool QGpgMECryptoConfigEntry::isList() const { return mFlags & GPGCONF_FLAG_LIST; } bool QGpgMECryptoConfigEntry::isRuntime() const { return mFlags & GPGCONF_FLAG_RUNTIME; } bool QGpgMECryptoConfigEntry::isSet() const { return mSet; } bool QGpgMECryptoConfigEntry::boolValue() const { Q_ASSERT( mArgType == ArgType_None ); Q_ASSERT( !isList() ); return mValue.toBool(); } QString QGpgMECryptoConfigEntry::stringValue() const { return toString( false ); } int QGpgMECryptoConfigEntry::intValue() const { Q_ASSERT( mArgType == ArgType_Int ); Q_ASSERT( !isList() ); return mValue.toInt(); } unsigned int QGpgMECryptoConfigEntry::uintValue() const { Q_ASSERT( mArgType == ArgType_UInt ); Q_ASSERT( !isList() ); return mValue.toUInt(); } static KURL parseURL( int mRealArgType, const QString& str ) { if ( mRealArgType == 33 ) { // LDAP server // The format is HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN QStringList items = QStringList::split( ':', str, true ); if ( items.count() == 5 ) { QStringList::const_iterator it = items.begin(); KURL url; url.setProtocol( "ldap" ); url.setHost( urlpart_decode( *it++ ) ); url.setPort( (*it++).toInt() ); url.setPath( "/" ); // workaround KURL parsing bug url.setUser( urlpart_decode( *it++ ) ); url.setPass( urlpart_decode( *it++ ) ); url.setQuery( urlpart_decode( *it ) ); return url; } else kdWarning(5150) << "parseURL: malformed LDAP server: " << str << endl; } // other URLs : assume wellformed URL syntax. return KURL( str ); } // The opposite of parseURL static QString splitURL( int mRealArgType, const KURL& url ) { if ( mRealArgType == 33 ) { // LDAP server // The format is HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN Q_ASSERT( url.protocol() == "ldap" ); return urlpart_encode( url.host() ) + ":" + QString::number( url.port() ) + ":" + urlpart_encode( url.user() ) + ":" + urlpart_encode( url.pass() ) + ":" + // KURL automatically encoded the query (e.g. for spaces inside it), // so decode it before writing it out to gpgconf (issue119) urlpart_encode( KURL::decode_string( url.query().mid(1) ) ); } return url.path(); } KURL QGpgMECryptoConfigEntry::urlValue() const { Q_ASSERT( mArgType == ArgType_Path || mArgType == ArgType_URL || mArgType == ArgType_LDAPURL ); Q_ASSERT( !isList() ); QString str = mValue.toString(); if ( mArgType == ArgType_Path ) { KURL url; url.setPath( str ); return url; } return parseURL( mRealArgType, str ); } unsigned int QGpgMECryptoConfigEntry::numberOfTimesSet() const { Q_ASSERT( mArgType == ArgType_None ); Q_ASSERT( isList() ); return mValue.toUInt(); } QStringList QGpgMECryptoConfigEntry::stringValueList() const { Q_ASSERT( isStringType() ); Q_ASSERT( isList() ); return mValue.toStringList(); } QValueList QGpgMECryptoConfigEntry::intValueList() const { Q_ASSERT( mArgType == ArgType_Int ); Q_ASSERT( isList() ); QValueList ret; QValueList lst = mValue.toList(); for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { ret.append( (*it).toInt() ); } return ret; } QValueList QGpgMECryptoConfigEntry::uintValueList() const { Q_ASSERT( mArgType == ArgType_UInt ); Q_ASSERT( isList() ); QValueList ret; QValueList lst = mValue.toList(); for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { ret.append( (*it).toUInt() ); } return ret; } KURL::List QGpgMECryptoConfigEntry::urlValueList() const { Q_ASSERT( mArgType == ArgType_Path || mArgType == ArgType_URL || mArgType == ArgType_LDAPURL ); Q_ASSERT( isList() ); QStringList lst = mValue.toStringList(); KURL::List ret; for( QStringList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { if ( mArgType == ArgType_Path ) { KURL url; url.setPath( *it ); ret << url; } else { ret << parseURL( mRealArgType, *it ); } } return ret; } void QGpgMECryptoConfigEntry::resetToDefault() { mSet = false; mDirty = true; if ( mFlags & GPGCONF_FLAG_DEFAULT ) mValue = mDefaultValue; else if ( mArgType == ArgType_None ) mValue = false; } void QGpgMECryptoConfigEntry::setBoolValue( bool b ) { Q_ASSERT( mArgType == ArgType_None ); Q_ASSERT( !isList() ); // A "no arg" option is either set or not set. // Being set means mSet==true + mValue==true, being unset means resetToDefault(), i.e. both false mValue = b; mSet = b; mDirty = true; } void QGpgMECryptoConfigEntry::setStringValue( const QString& str ) { mValue = stringToValue( str, false ); // When setting a string to empty (and there's no default), we need to act like resetToDefault // Otherwise we try e.g. "ocsp-responder:0:" and gpgconf answers: // "gpgconf: argument required for option ocsp-responder" if ( str.isEmpty() && !isOptional() ) mSet = false; else mSet = true; mDirty = true; } void QGpgMECryptoConfigEntry::setIntValue( int i ) { Q_ASSERT( mArgType == ArgType_Int ); Q_ASSERT( !isList() ); mValue = i; mSet = true; mDirty = true; } void QGpgMECryptoConfigEntry::setUIntValue( unsigned int i ) { mValue = i; mSet = true; mDirty = true; } void QGpgMECryptoConfigEntry::setURLValue( const KURL& url ) { QString str = splitURL( mRealArgType, url ); if ( str.isEmpty() && !isOptional() ) mSet = false; else mSet = true; mValue = str; mDirty = true; } void QGpgMECryptoConfigEntry::setNumberOfTimesSet( unsigned int i ) { Q_ASSERT( mArgType == ArgType_None ); Q_ASSERT( isList() ); setUIntValue( i ); } void QGpgMECryptoConfigEntry::setStringValueList( const QStringList& lst ) { mValue = lst; if ( lst.isEmpty() && !isOptional() ) mSet = false; else mSet = true; mDirty = true; } void QGpgMECryptoConfigEntry::setIntValueList( const QValueList& lst ) { QValueList ret; for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { ret << QVariant( *it ); } mValue = ret; if ( ret.isEmpty() && !isOptional() ) mSet = false; else mSet = true; mDirty = true; } void QGpgMECryptoConfigEntry::setUIntValueList( const QValueList& lst ) { QValueList ret; for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { ret << QVariant( *it ); } if ( ret.isEmpty() && !isOptional() ) mSet = false; else mSet = true; mValue = ret; mDirty = true; } void QGpgMECryptoConfigEntry::setURLValueList( const KURL::List& urls ) { QStringList lst; for( KURL::List::const_iterator it = urls.begin(); it != urls.end(); ++it ) { lst << splitURL( mRealArgType, *it ); } mValue = lst; if ( lst.isEmpty() && !isOptional() ) mSet = false; else mSet = true; mDirty = true; } QString QGpgMECryptoConfigEntry::toString( bool escape ) const { // Basically the opposite of stringToValue if ( isStringType() ) { if ( mValue.isNull() ) return QString::null; else if ( isList() ) { // string list QStringList lst = mValue.toStringList(); if ( escape ) { for( QStringList::iterator it = lst.begin(); it != lst.end(); ++it ) { if ( !(*it).isNull() ) *it = gpgconf_escape( *it ).prepend( "\"" ); } } QString res = lst.join( "," ); kdDebug(5150) << "toString: " << res << endl; return res; } else { // normal string QString res = mValue.toString(); if ( escape ) res = gpgconf_escape( res ).prepend( "\"" ); return res; } } if ( !isList() ) // non-list non-string { if ( mArgType == ArgType_None ) { return mValue.toBool() ? QString::fromLatin1( "1" ) : QString::null; } else { // some int Q_ASSERT( mArgType == ArgType_Int || mArgType == ArgType_UInt ); return mValue.toString(); // int to string conversion } } // Lists (of other types than strings) if ( mArgType == ArgType_None ) return QString::number( numberOfTimesSet() ); QStringList ret; QValueList lst = mValue.toList(); for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { ret << (*it).toString(); // QVariant does the conversion } return ret.join( "," ); } QString QGpgMECryptoConfigEntry::outputString() const { Q_ASSERT( mSet ); return toString( true ); } bool QGpgMECryptoConfigEntry::isStringType() const { return ( mArgType == Kleo::CryptoConfigEntry::ArgType_String || mArgType == Kleo::CryptoConfigEntry::ArgType_Path || mArgType == Kleo::CryptoConfigEntry::ArgType_URL || mArgType == Kleo::CryptoConfigEntry::ArgType_LDAPURL ); } void QGpgMECryptoConfigEntry::setDirty( bool b ) { mDirty = b; } #include "qgpgmecryptoconfig.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmecryptoconfig.h b/certmanager/lib/backends/qgpgme/qgpgmecryptoconfig.h index 3af2087b49..cc3de2a2df 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmecryptoconfig.h +++ b/certmanager/lib/backends/qgpgme/qgpgmecryptoconfig.h @@ -1,177 +1,185 @@ /* qgpgmecryptoconfig.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef KLEO_QGPGMECRYPTOCONFIG_H #define KLEO_QGPGMECRYPTOCONFIG_H #include #include #include #include #include class KProcIO; class QGpgMECryptoConfigComponent; class QGpgMECryptoConfigEntry; /** * CryptoConfig implementation around the gpgconf command-line tool * For method docu, see kleo/cryptoconfig.h */ class QGpgMECryptoConfig : public QObject, public Kleo::CryptoConfig { Q_OBJECT public: /** * Constructor */ QGpgMECryptoConfig(); virtual ~QGpgMECryptoConfig(); virtual QStringList componentList() const; virtual Kleo::CryptoConfigComponent* component( const QString& name ) const; virtual void clear(); virtual void sync( bool runtime ); private slots: void slotCollectStdOut( KProcIO* proc ); private: /// @param showErrors if true, a messagebox will be shown if e.g. gpgconf wasn't found void runGpgConf( bool showErrors ); private: QDict mComponents; bool mParsed; }; class QGpgMECryptoConfigGroup; /// For docu, see kleo/cryptoconfig.h class QGpgMECryptoConfigComponent : public QObject, public Kleo::CryptoConfigComponent { Q_OBJECT public: QGpgMECryptoConfigComponent( QGpgMECryptoConfig*, const QString& name, const QString& description ); - virtual ~QGpgMECryptoConfigComponent(); + ~QGpgMECryptoConfigComponent(); - virtual QString description() const { return mDescription; } - virtual QStringList groupList() const; - virtual Kleo::CryptoConfigGroup* group( const QString& name ) const; + QString name() const { return mName; } + QString iconName() const { return mName; } + QString description() const { return mDescription; } + QStringList groupList() const; + Kleo::CryptoConfigGroup* group( const QString& name ) const; void sync( bool runtime ); private slots: void slotCollectStdOut( KProcIO* proc ); private: void runGpgConf(); private: QDict mGroups; QString mName; QString mDescription; QGpgMECryptoConfigGroup* mCurrentGroup; // during parsing QString mCurrentGroupName; // during parsing }; class QGpgMECryptoConfigGroup : public Kleo::CryptoConfigGroup { public: - QGpgMECryptoConfigGroup( const QString& description, int level ); - virtual ~QGpgMECryptoConfigGroup() {} + QGpgMECryptoConfigGroup( const QString & name, const QString& description, int level ); + ~QGpgMECryptoConfigGroup() {} - virtual QString description() const { return mDescription; } - virtual Kleo::CryptoConfigEntry::Level level() const { return mLevel; } - virtual QStringList entryList() const; - virtual Kleo::CryptoConfigEntry* entry( const QString& name ) const; + QString name() const { return mName; } + QString iconName() const { return QString::null; } + QString description() const { return mDescription; } + Kleo::CryptoConfigEntry::Level level() const { return mLevel; } + QStringList entryList() const; + Kleo::CryptoConfigEntry* entry( const QString& name ) const; private: friend class QGpgMECryptoConfigComponent; // it adds the entries QDict mEntries; + QString mName; QString mDescription; Kleo::CryptoConfigEntry::Level mLevel; }; class QGpgMECryptoConfigEntry : public Kleo::CryptoConfigEntry { public: QGpgMECryptoConfigEntry( const QStringList& parsedLine ); - virtual ~QGpgMECryptoConfigEntry(); - - virtual QString description() const { return mDescription; } - virtual bool isOptional() const; - virtual bool isList() const; - virtual bool isRuntime() const; - virtual Level level() const { return static_cast( mLevel ); } - virtual ArgType argType() const { return static_cast( mArgType ); } - virtual bool isSet() const; - virtual bool boolValue() const; - virtual QString stringValue() const; - virtual int intValue() const; - virtual unsigned int uintValue() const; - virtual KURL urlValue() const; - virtual unsigned int numberOfTimesSet() const; - virtual QStringList stringValueList() const; - virtual QValueList intValueList() const; - virtual QValueList uintValueList() const; - virtual KURL::List urlValueList() const; - virtual void resetToDefault(); - virtual void setBoolValue( bool ); - virtual void setStringValue( const QString& ); - virtual void setIntValue( int ); - virtual void setUIntValue( unsigned int ); - virtual void setURLValue( const KURL& ); - virtual void setNumberOfTimesSet( unsigned int ); - virtual void setStringValueList( const QStringList& ); - virtual void setIntValueList( const QValueList& ); - virtual void setUIntValueList( const QValueList& ); - virtual void setURLValueList( const KURL::List& ); - virtual bool isDirty() const { return mDirty; } + ~QGpgMECryptoConfigEntry(); + + QString name() const { return mName; } + QString description() const { return mDescription; } + bool isOptional() const; + bool isList() const; + bool isRuntime() const; + Level level() const { return static_cast( mLevel ); } + ArgType argType() const { return static_cast( mArgType ); } + bool isSet() const; + bool boolValue() const; + QString stringValue() const; + int intValue() const; + unsigned int uintValue() const; + KURL urlValue() const; + unsigned int numberOfTimesSet() const; + QStringList stringValueList() const; + QValueList intValueList() const; + QValueList uintValueList() const; + KURL::List urlValueList() const; + void resetToDefault(); + void setBoolValue( bool ); + void setStringValue( const QString& ); + void setIntValue( int ); + void setUIntValue( unsigned int ); + void setURLValue( const KURL& ); + void setNumberOfTimesSet( unsigned int ); + void setStringValueList( const QStringList& ); + void setIntValueList( const QValueList& ); + void setUIntValueList( const QValueList& ); + void setURLValueList( const KURL::List& ); + bool isDirty() const { return mDirty; } + void setDirty( bool b ); QString outputString() const; protected: bool isStringType() const; QVariant stringToValue( const QString& value, bool unescape ) const; QString toString( bool escape ) const; private: + QString mName; QString mDescription; QVariant mDefaultValue; QVariant mValue; uint mFlags : 7; // bitfield with 7 bits uint mLevel : 3; // max is 4 (2, in fact) -> 3 bits uint mRealArgType : 6; // max is 33 -> 6 bits uint mArgType : 3; // max is 6 (ArgType enum) -> 3 bits; uint mDirty : 1; uint mSet : 1; }; #endif /* KLEO_QGPGMECRYPTOCONFIG_H */ diff --git a/certmanager/lib/backends/qgpgme/qgpgmedecryptjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmedecryptjob.cpp index c61d4b40e9..884f1a4a05 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmedecryptjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmedecryptjob.cpp @@ -1,90 +1,90 @@ /* qgpgmedecryptjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmedecryptjob.h" #include #include #include #include #include #include Kleo::QGpgMEDecryptJob::QGpgMEDecryptJob( GpgME::Context * context ) : DecryptJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEDecryptJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEDecryptJob::~QGpgMEDecryptJob() { } void Kleo::QGpgMEDecryptJob::setup( const QByteArray & cipherText ) { assert( !mInData ); assert( !mOutData ); createInData( cipherText ); createOutData(); } GpgME::Error Kleo::QGpgMEDecryptJob::start( const QByteArray & cipherText ) { setup( cipherText ); hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startDecryption( *mInData, *mOutData ); if ( err ) deleteLater(); return err; } GpgME::DecryptionResult Kleo::QGpgMEDecryptJob::exec( const QByteArray & cipherText, QByteArray & plainText ) { setup( cipherText ); const GpgME::DecryptionResult result = mCtx->decrypt( *mInData, *mOutData ); plainText = mOutDataDataProvider->data(); return result; } void Kleo::QGpgMEDecryptJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mCtx->decryptionResult(), mOutDataDataProvider->data() ); } #include "qgpgmedecryptjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmedecryptjob.h b/certmanager/lib/backends/qgpgme/qgpgmedecryptjob.h index b43f74262d..7fc89dff22 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmedecryptjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmedecryptjob.h @@ -1,74 +1,74 @@ /* qgpgmedecryptjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEDECRYPTJOB_H__ #define __KLEO_QGPGMEDECRYPTJOB_H__ #include #include "qgpgmejob.h" #include namespace GpgME { class Error; class Context; } namespace Kleo { class QGpgMEDecryptJob : public DecryptJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEDecryptJob( GpgME::Context * context ); ~QGpgMEDecryptJob(); /*! \reimp from DecryptJob */ GpgME::Error start( const QByteArray & cipherText ); /*! \reimp from DecryptJob */ GpgME::DecryptionResult exec( const QByteArray & cipherText, QByteArray & plainText ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); void setup( const QByteArray & cipherText ); }; } #endif // __KLEO_QGPGMEDECRYPTJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmedecryptverifyjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmedecryptverifyjob.cpp index f176758f1a..509327aa84 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmedecryptverifyjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmedecryptverifyjob.cpp @@ -1,94 +1,94 @@ /* qgpgmedecryptverifyjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmedecryptverifyjob.h" #include #include #include #include #include #include #include Kleo::QGpgMEDecryptVerifyJob::QGpgMEDecryptVerifyJob( GpgME::Context * context ) : DecryptVerifyJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEDecryptVerifyJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEDecryptVerifyJob::~QGpgMEDecryptVerifyJob() { } void Kleo::QGpgMEDecryptVerifyJob::setup( const QByteArray & cipherText ) { assert( !mInData ); assert( !mOutData ); createInData( cipherText ); createOutData(); } GpgME::Error Kleo::QGpgMEDecryptVerifyJob::start( const QByteArray & cipherText ) { setup( cipherText ); hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startCombinedDecryptionAndVerification( *mInData, *mOutData ); if ( err ) deleteLater(); return err; } std::pair Kleo::QGpgMEDecryptVerifyJob::exec( const QByteArray & cipherText, QByteArray & plainText ) { setup( cipherText ); const std::pair result = mCtx->decryptAndVerify( *mInData, *mOutData ); plainText = mOutDataDataProvider->data(); return result; } void Kleo::QGpgMEDecryptVerifyJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mCtx->decryptionResult(), mCtx->verificationResult(), mOutDataDataProvider->data() ); } #include "qgpgmedecryptverifyjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmedecryptverifyjob.h b/certmanager/lib/backends/qgpgme/qgpgmedecryptverifyjob.h index 73def958d9..a391887463 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmedecryptverifyjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmedecryptverifyjob.h @@ -1,75 +1,75 @@ /* qgpgmedecryptverifyjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEDECRYPTVERIFYJOB_H__ #define __KLEO_QGPGMEDECRYPTVERIFYJOB_H__ #include #include "qgpgmejob.h" #include #include namespace GpgME { class Error; class Context; } namespace Kleo { class KDE_EXPORT QGpgMEDecryptVerifyJob : public DecryptVerifyJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEDecryptVerifyJob( GpgME::Context * context ); ~QGpgMEDecryptVerifyJob(); /*! \reimp from DecryptVerifyJob */ GpgME::Error start( const QByteArray & cipherText ); /*! \reimp from DecryptVerifyJob */ std::pair exec( const QByteArray & cipherText, QByteArray & plainText ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); void setup( const QByteArray & ); }; } #endif // __KLEO_QGPGMEDECRYPTVERIFYJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmedeletejob.cpp b/certmanager/lib/backends/qgpgme/qgpgmedeletejob.cpp index 87c1997dd5..c06907eeaa 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmedeletejob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmedeletejob.cpp @@ -1,70 +1,70 @@ /* qgpgmedeletejob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmedeletejob.h" #include #include #include Kleo::QGpgMEDeleteJob::QGpgMEDeleteJob( GpgME::Context * context ) : DeleteJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEDeleteJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEDeleteJob::~QGpgMEDeleteJob() { } GpgME::Error Kleo::QGpgMEDeleteJob::start( const GpgME::Key & key, bool allowSecretKeyDeletion ) { hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startKeyDeletion( key, allowSecretKeyDeletion ); if ( err ) deleteLater(); return err; } void Kleo::QGpgMEDeleteJob::doOperationDoneEvent( const GpgME::Error & error ) { emit result( error ); } #include "qgpgmedeletejob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmedeletejob.h b/certmanager/lib/backends/qgpgme/qgpgmedeletejob.h index 9bbedb6ca0..9dec128f75 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmedeletejob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmedeletejob.h @@ -1,68 +1,68 @@ /* qgpgmedeletejob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEDELETEJOB_H__ #define __KLEO_QGPGMEDELETEJOB_H__ #include #include "qgpgmejob.h" namespace GpgME { class Error; class Context; class Key; } namespace Kleo { class QGpgMEDeleteJob : public DeleteJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEDeleteJob( GpgME::Context * context ); ~QGpgMEDeleteJob(); /*! \reimp from DeleteJob */ GpgME::Error start( const GpgME::Key & key, bool allowSecretKeyDeletion ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); }; } #endif // __KLEO_QGPGMEDELETEJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmedownloadjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmedownloadjob.cpp index 9a723b9814..6ee771a046 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmedownloadjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmedownloadjob.cpp @@ -1,78 +1,78 @@ /* qgpgmedownloadjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmedownloadjob.h" #include #include #include #include #include #include Kleo::QGpgMEDownloadJob::QGpgMEDownloadJob( GpgME::Context * context ) : DownloadJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEDownloadJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEDownloadJob::~QGpgMEDownloadJob() { } GpgME::Error Kleo::QGpgMEDownloadJob::start( const QStringList & pats ) { assert( !patterns() ); assert( !mOutData ); createOutData(); setPatterns( pats ); hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startPublicKeyExport( patterns(), *mOutData ); if ( err ) deleteLater(); return err; } void Kleo::QGpgMEDownloadJob::doOperationDoneEvent( const GpgME::Error & error ) { emit result( error, mOutDataDataProvider->data() ); } #include "qgpgmedownloadjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmedownloadjob.h b/certmanager/lib/backends/qgpgme/qgpgmedownloadjob.h index 63b100d7c0..1402b127c8 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmedownloadjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmedownloadjob.h @@ -1,67 +1,67 @@ /* qgpgmedownloadjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEDOWNLOADJOB_H__ #define __KLEO_QGPGMEDOWNLOADJOB_H__ #include #include "qgpgmejob.h" namespace GpgME { class Error; class Context; } namespace Kleo { class QGpgMEDownloadJob : public DownloadJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEDownloadJob( GpgME::Context * context ); ~QGpgMEDownloadJob(); /*! \reimp from DownloadJob */ GpgME::Error start( const QStringList & fingerprints ); private: void doOperationDoneEvent( const GpgME::Error & e ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } }; } #endif // __KLEO_QGPGMEDOWNLOADJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmeencryptjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmeencryptjob.cpp index 330af8a4d1..01ef6b445f 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeencryptjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmeencryptjob.cpp @@ -1,108 +1,108 @@ /* qgpgmeencryptjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmeencryptjob.h" #include #include #include #include #include #include #include #include Kleo::QGpgMEEncryptJob::QGpgMEEncryptJob( GpgME::Context * context ) : EncryptJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEEncryptJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEEncryptJob::~QGpgMEEncryptJob() { } void Kleo::QGpgMEEncryptJob::setup( const QByteArray & plainText ) { assert( !mInData ); assert( !mOutData ); createInData( plainText ); createOutData(); } GpgME::Error Kleo::QGpgMEEncryptJob::start( const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust ) { setup( plainText ); hookupContextToEventLoopInteractor(); const GpgME::Context::EncryptionFlags flags = alwaysTrust ? GpgME::Context::AlwaysTrust : GpgME::Context::None; const GpgME::Error err = mCtx->startEncryption( recipients, *mInData, *mOutData, flags ); if ( err ) deleteLater(); return err; } GpgME::EncryptionResult Kleo::QGpgMEEncryptJob::exec( const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust, QByteArray & ciphertext ) { setup( plainText ); const GpgME::Context::EncryptionFlags flags = alwaysTrust ? GpgME::Context::AlwaysTrust : GpgME::Context::None; mResult = mCtx->encrypt( recipients, *mInData, *mOutData, flags ); ciphertext = mOutDataDataProvider->data(); return mResult; } void Kleo::QGpgMEEncryptJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mResult, mOutDataDataProvider->data() ); } void Kleo::QGpgMEEncryptJob::showErrorDialog( QWidget * parent, const QString & caption ) const { if ( !mResult.error() || mResult.error().isCanceled() ) return; const QString msg = i18n("Encryption failed: %1") .arg( QString::fromLocal8Bit( mResult.error().asString() ) ); KMessageBox::error( parent, msg, caption ); } #include "qgpgmeencryptjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmeencryptjob.h b/certmanager/lib/backends/qgpgme/qgpgmeencryptjob.h index c71e78ed86..362fb4e061 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeencryptjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmeencryptjob.h @@ -1,86 +1,86 @@ /* qgpgmeencryptjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEENCRYPTJOB_H__ #define __KLEO_QGPGMEENCRYPTJOB_H__ #include #include "qgpgmejob.h" #include #include namespace GpgME { class Error; class Context; class Key; } namespace Kleo { class QGpgMEEncryptJob : public EncryptJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEEncryptJob( GpgME::Context * context ); ~QGpgMEEncryptJob(); /*! \reimp from EncryptJob */ GpgME::Error start( const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust ); /*! \reimp from EncryptJob */ GpgME::EncryptionResult exec( const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust, QByteArray & cipherText ); /*! \reimp from Job */ void showErrorDialog( QWidget * parent, const QString & caption ) const; private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); void setup( const QByteArray & ); private: GpgME::EncryptionResult mResult; }; } #endif // __KLEO_QGPGMEENCRYPTJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmeexportjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmeexportjob.cpp index 74ce326dd1..c9274f3b7c 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeexportjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmeexportjob.cpp @@ -1,78 +1,78 @@ /* qgpgmeexportjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmeexportjob.h" #include #include #include #include #include #include Kleo::QGpgMEExportJob::QGpgMEExportJob( GpgME::Context * context ) : ExportJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEExportJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEExportJob::~QGpgMEExportJob() { } GpgME::Error Kleo::QGpgMEExportJob::start( const QStringList & pats ) { assert( !patterns() ); assert( !mOutData ); createOutData(); setPatterns( pats ); hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startPublicKeyExport( patterns(), *mOutData ); if ( err ) deleteLater(); return err; } void Kleo::QGpgMEExportJob::doOperationDoneEvent( const GpgME::Error & error ) { emit result( error, mOutDataDataProvider->data() ); } #include "qgpgmeexportjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmeexportjob.h b/certmanager/lib/backends/qgpgme/qgpgmeexportjob.h index 1a53ee51f6..8b799b583c 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeexportjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmeexportjob.h @@ -1,69 +1,69 @@ /* qgpgmeexportjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEEXPORTJOB_H__ #define __KLEO_QGPGMEEXPORTJOB_H__ #include #include "qgpgmejob.h" #include namespace GpgME { class Error; class Context; } namespace Kleo { class QGpgMEExportJob : public ExportJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEExportJob( GpgME::Context * context ); ~QGpgMEExportJob(); /*! \reimp from ExportJob */ GpgME::Error start( const QStringList & patterns ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); }; } #endif // __KLEO_QGPGMEEXPORTJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmeimportjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmeimportjob.cpp index 53c21694e0..fd1251b654 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeimportjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmeimportjob.cpp @@ -1,86 +1,86 @@ /* qgpgmeimportjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmeimportjob.h" #include #include #include #include #include #include Kleo::QGpgMEImportJob::QGpgMEImportJob( GpgME::Context * context ) : ImportJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEImportJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEImportJob::~QGpgMEImportJob() { } void Kleo::QGpgMEImportJob::setup( const QByteArray & keyData ) { assert( !mInData ); createInData( keyData ); } GpgME::Error Kleo::QGpgMEImportJob::start( const QByteArray & keyData ) { setup( keyData ); hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startKeyImport( *mInData ); if ( err ) deleteLater(); return err; } GpgME::ImportResult Kleo::QGpgMEImportJob::exec( const QByteArray & keyData ) { setup( keyData ); return mCtx->importKeys( *mInData ); } void Kleo::QGpgMEImportJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mCtx->importResult() ); } #include "qgpgmeimportjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmeimportjob.h b/certmanager/lib/backends/qgpgme/qgpgmeimportjob.h index a96f9e8701..8c2ee1ad45 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeimportjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmeimportjob.h @@ -1,73 +1,73 @@ /* qgpgmeimportjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEIMPORTJOB_H__ #define __KLEO_QGPGMEIMPORTJOB_H__ #include #include "qgpgmejob.h" #include namespace GpgME { class Error; class Context; } namespace Kleo { class QGpgMEImportJob : public ImportJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEImportJob( GpgME::Context * context ); ~QGpgMEImportJob(); /*! \reimp from ImportJob */ GpgME::Error start( const QByteArray & keyData ); /*! \reimp from ImportJob */ GpgME::ImportResult exec( const QByteArray & keyData ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); void setup( const QByteArray & ); }; } #endif // __KLEO_QGPGMEIMPORTJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmejob.cpp b/certmanager/lib/backends/qgpgme/qgpgmejob.cpp index 1e7d786ef6..afd58e301b 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmejob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmejob.cpp @@ -1,285 +1,285 @@ /* qgpgmejob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmejob.h" #include "qgpgmeprogresstokenmapper.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { class InvarianceChecker { public: #ifdef NDEBUG InvarianceChecker( const Kleo::QGpgMEJob * ) {} #else InvarianceChecker( const Kleo::QGpgMEJob * job ) : _this( job ) { assert( _this ); _this->checkInvariants(); } ~InvarianceChecker() { _this->checkInvariants(); } private: const Kleo::QGpgMEJob * _this; #endif }; } Kleo::QGpgMEJob::QGpgMEJob( Kleo::Job * _this, GpgME::Context * context ) : GpgME::ProgressProvider(), GpgME::PassphraseProvider(), mThis( _this ), mCtx( context ), mInData( 0 ), mInDataDataProvider( 0 ), mOutData( 0 ), mOutDataDataProvider( 0 ), mPatterns( 0 ), mReplacedPattern( 0 ), mNumPatterns( 0 ), mChunkSize( 1024 ), mPatternStartIndex( 0 ), mPatternEndIndex( 0 ) { InvarianceChecker check( this ); assert( context ); QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(aboutToDestroy()), _this, SLOT(slotCancel()) ); context->setProgressProvider( this ); // (mmutz) work around a gpgme bug in versions at least <= 0.9.0. // These versions will return GPG_ERR_NOT_IMPLEMENTED from // a CMS sign operation when a passphrase callback is set. if ( context->protocol() == GpgME::Context::OpenPGP ) context->setPassphraseProvider( this ); } void Kleo::QGpgMEJob::checkInvariants() const { #ifndef NDEBUG if ( mPatterns ) { assert( mPatterns[mNumPatterns] == 0 ); if ( mPatternEndIndex > 0 ) { assert( mPatternEndIndex > mPatternStartIndex ); assert( mPatternEndIndex - mPatternStartIndex == mChunkSize ); } else { assert( mPatternEndIndex == mPatternStartIndex ); } if ( mPatternEndIndex < mNumPatterns ) { assert( mPatterns[mPatternEndIndex] == 0 ); assert( mReplacedPattern != 0 ); } else { assert( mReplacedPattern == 0 ); } } else { assert( mNumPatterns == 0 ); assert( mPatternStartIndex == 0 ); assert( mPatternEndIndex == 0 ); assert( mReplacedPattern == 0 ); } #endif } Kleo::QGpgMEJob::~QGpgMEJob() { InvarianceChecker check( this ); delete mCtx; mCtx = 0; delete mInData; mInData = 0; delete mInDataDataProvider; mInDataDataProvider = 0; delete mOutData; mOutData = 0; delete mOutDataDataProvider; mOutDataDataProvider = 0; deleteAllPatterns(); } void Kleo::QGpgMEJob::deleteAllPatterns() { if ( mPatterns ) for ( unsigned int i = 0 ; i < mNumPatterns ; ++i ) free( (void*)mPatterns[i] ); free( (void*)mReplacedPattern ); mReplacedPattern = 0; delete[] mPatterns; mPatterns = 0; mPatternEndIndex = mPatternStartIndex = mNumPatterns = 0; } void Kleo::QGpgMEJob::hookupContextToEventLoopInteractor() { mCtx->setManagedByEventLoopInteractor( true ); QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(operationDoneEventSignal(GpgME::Context*,const GpgME::Error&)), mThis, SLOT(slotOperationDoneEvent(GpgME::Context*,const GpgME::Error&)) ); } void Kleo::QGpgMEJob::setPatterns( const QStringList & sl, bool allowEmpty ) { InvarianceChecker check( this ); deleteAllPatterns(); // create a new null-terminated C array of char* from patterns: mPatterns = new const char*[ sl.size() + 1 ]; const char* * pat_it = mPatterns; mNumPatterns = 0; for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it ) { if ( (*it).isNull() ) continue; if ( (*it).isEmpty() && !allowEmpty ) continue; *pat_it++ = strdup( (*it).utf8().data() ); ++mNumPatterns; } *pat_it++ = 0; mReplacedPattern = 0; mPatternEndIndex = mChunkSize = mNumPatterns; } void Kleo::QGpgMEJob::setChunkSize( unsigned int chunksize ) { InvarianceChecker check( this ); if ( mReplacedPattern ) { mPatterns[mPatternEndIndex] = mReplacedPattern; mReplacedPattern = 0; } mChunkSize = std::min( chunksize, mNumPatterns ); mPatternStartIndex = 0; mPatternEndIndex = mChunkSize; mReplacedPattern = mPatterns[mPatternEndIndex]; mPatterns[mPatternEndIndex] = 0; } const char* * Kleo::QGpgMEJob::nextChunk() { InvarianceChecker check( this ); if ( mReplacedPattern ) { mPatterns[mPatternEndIndex] = mReplacedPattern; mReplacedPattern = 0; } mPatternStartIndex += mChunkSize; mPatternEndIndex += mChunkSize; if ( mPatternEndIndex < mNumPatterns ) { // could safely be <=, but the last entry is NULL anyway mReplacedPattern = mPatterns[mPatternEndIndex]; mPatterns[mPatternEndIndex] = 0; } return patterns(); } const char* * Kleo::QGpgMEJob::patterns() const { InvarianceChecker check( this ); if ( mPatternStartIndex < mNumPatterns ) return mPatterns + mPatternStartIndex; return 0; } GpgME::Error Kleo::QGpgMEJob::setSigningKeys( const std::vector & signers ) { mCtx->clearSigningKeys(); for ( std::vector::const_iterator it = signers.begin() ; it != signers.end() ; ++it ) { if ( (*it).isNull() ) continue; if ( const GpgME::Error err = mCtx->addSigningKey( *it ) ) return err; } return 0; } void Kleo::QGpgMEJob::createInData( const QByteArray & in ) { mInDataDataProvider = new QGpgME::QByteArrayDataProvider( in ); mInData = new GpgME::Data( mInDataDataProvider ); assert( !mInData->isNull() ); } void Kleo::QGpgMEJob::createOutData() { mOutDataDataProvider = new QGpgME::QByteArrayDataProvider(); mOutData = new GpgME::Data( mOutDataDataProvider ); assert( !mOutData->isNull() ); } void Kleo::QGpgMEJob::doSlotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { if ( context == mCtx ) { doEmitDoneSignal(); doOperationDoneEvent( e ); mThis->deleteLater(); } } void Kleo::QGpgMEJob::doSlotCancel() { mCtx->cancelPendingOperation(); } void Kleo::QGpgMEJob::showProgress( const char * what, int type, int current, int total ) { doEmitProgressSignal( QGpgMEProgressTokenMapper::instance()->map( what, type, current, total ), current, total ); } char * Kleo::QGpgMEJob::getPassphrase( const char * useridHint, const char * /*description*/, bool previousWasBad, bool & canceled ) { // DF: here, description is the key fingerprint, twice, then "17 0". Not really descriptive. // So I'm ignoring QString::fromLocal8Bit( description ) ) QString msg = previousWasBad ? i18n( "You need a passphrase to unlock the secret key for user:
%1 (retry)" ) : i18n( "You need a passphrase to unlock the secret key for user:
%1" ); msg = msg.arg( QString::fromUtf8( useridHint ) ) + "

"; msg.prepend( "" ); msg += i18n( "This dialog will reappear every time the passphrase is needed. For a more secure solution that also allows caching the passphrase, use gpg-agent." ) + "
"; const QString gpgAgent = KStandardDirs::findExe( "gpg-agent" ); if ( !gpgAgent.isEmpty() ) { msg += i18n( "gpg-agent was found in %1, but does not appear to be running." ) .arg( gpgAgent ); } else { msg += i18n( "gpg-agent is part of gnupg-%1, which you can download from %2" ) .arg( "1.9" ) .arg( "http://www.gnupg.org/download" ); // add #gnupg2 if you can make this a real link } msg += "
"; msg += i18n( "For information on how to set up gpg-agent, see %1" ) .arg( "http://kmail.kde.org/kmail-pgpmime-howto.html" ); msg += "

"; msg += i18n( "Enter passphrase:" ); Kleo::PassphraseDialog dlg( msg, i18n("Passphrase Dialog") ); if ( dlg.exec() != QDialog::Accepted ) { canceled = true; return 0; } canceled = false; // gpgme++ free()s it, and we need to copy as long as dlg isn't deleted :o return strdup( dlg.passphrase() ); } diff --git a/certmanager/lib/backends/qgpgme/qgpgmejob.h b/certmanager/lib/backends/qgpgme/qgpgmejob.h index 01d0211f6b..aff16ce901 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmejob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmejob.h @@ -1,154 +1,154 @@ /* qgpgmejob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEJOB_H__ #define __KLEO_QGPGMEJOB_H__ #include #include #include #include #include #include namespace GpgME { class Error; class Context; class Data; } namespace Kleo { class Job; } namespace QGpgME { class QByteArrayDataProvider; } class QString; class QStringList; namespace Kleo { /** This is a hackish helper class to avoid code duplication in this backend's Kleo::Job subclasses. It contains several workarounds for moc/signal/slot shortcomings, most of which the author of this thinks are Qt bugs (lazy implementations), first and foremost the inability of moc to handle inheritance from multiple QObject-derived subclasses. To use it, inherit from the Job-subclass, then from this class, add QGPGME_JOB to just after Q OBJECT and implement doOperationDoneEvent() by emitting your variant of the result() signal there. Pass "this" as the first argument this QGpgMEJOb's ctor. The rest is dealt with automatically. */ class KDE_EXPORT QGpgMEJob : public GpgME::ProgressProvider, public GpgME::PassphraseProvider { public: QGpgMEJob( Kleo::Job * _this, GpgME::Context * context ); ~QGpgMEJob(); protected: /*! Called on operation-done events, between emitting done() and calling deleteLater(). You should emit your result signal here. */ virtual void doOperationDoneEvent( const GpgME::Error & e ) = 0; /*! Hooks up mCtx to be managed by the event loop interactor */ void hookupContextToEventLoopInteractor(); /*! Fills mPatterns from the stringlist, resets chunking to the full list */ void setPatterns( const QStringList & sl, bool allowEmpty=false ); /*! Returnes the number of patterns set */ unsigned int numPatterns() const { return mNumPatterns; } /*! Skips to the next chunk of patterns. @return patterns() */ const char* * nextChunk(); /*! @return patterns, offset by the current chunk */ const char* * patterns() const; /*! Set the current pattern chunksize to size and reset the chunk index to zero */ void setChunkSize( unsigned int size ); /*! @return current chunksize */ unsigned int chunkSize() const { return mChunkSize; } /*! Creates an empty GpgME::Data/QGpgME::QByteArrayDataProvider pair */ void createOutData(); /*! Creates a GpgME::Data/QGpgME::QByteArrayDataProvider pair, filled with the contents of \a in */ void createInData( const QByteArray & in ); /*! Sets the list of signing keys */ GpgME::Error setSigningKeys( const std::vector & signers ); /*! Call this to implement a slotOperationDoneEvent() */ void doSlotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ); // // only boring stuff below this line... // protected: virtual void doEmitProgressSignal( const QString & what, int current, int total ) = 0; virtual void doEmitDoneSignal() = 0; void doSlotCancel(); private: /*! \reimp from GpgME::ProgressProvider */ void showProgress( const char * what, int type, int current, int total ); char * getPassphrase( const char * useridHint, const char * description, bool previousWasBad, bool & canceled ); void deleteAllPatterns(); public: void checkInvariants() const; protected: Kleo::Job * mThis; GpgME::Context * mCtx; GpgME::Data * mInData; QGpgME::QByteArrayDataProvider * mInDataDataProvider; GpgME::Data * mOutData; QGpgME::QByteArrayDataProvider * mOutDataDataProvider; private: const char* * mPatterns; // holds the entry - if any - in mPattern that was replaced with // NULL to create a temporary end-of-array marker for gpgme: const char * mReplacedPattern; unsigned int mNumPatterns; unsigned int mChunkSize; unsigned int mPatternStartIndex, mPatternEndIndex; }; } #define make_slot_cancel private: void slotCancel() { QGpgMEJob::doSlotCancel(); } #define make_progress_emitter private: void doEmitProgressSignal( const QString & what, int cur, int tot ) { emit progress( what, cur, tot ); } #define make_done_emitter private: void doEmitDoneSignal() { emit done(); } #define QGPGME_JOB make_slot_cancel make_progress_emitter make_done_emitter #endif // __KLEO_QGPGMEJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmekeygenerationjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmekeygenerationjob.cpp index 3d4a5d97a2..a0ab78f237 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmekeygenerationjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmekeygenerationjob.cpp @@ -1,86 +1,86 @@ /* qgpgmekeygenerationjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmekeygenerationjob.h" #include #include #include #include #include #include Kleo::QGpgMEKeyGenerationJob::QGpgMEKeyGenerationJob( GpgME::Context * context ) : KeyGenerationJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEKeyGenerationJob" ), QGpgMEJob( this, context ), mPubKeyDataProvider( 0 ), mPubKey( 0 ) { assert( context ); } Kleo::QGpgMEKeyGenerationJob::~QGpgMEKeyGenerationJob() { delete mPubKey; mPubKey = 0; delete mPubKeyDataProvider; mPubKeyDataProvider = 0; } GpgME::Error Kleo::QGpgMEKeyGenerationJob::start( const QString & parameters ) { assert( !mPubKey ); // set up empty data object for the public key data if ( mCtx->protocol() == GpgME::Context::CMS ) { mPubKeyDataProvider = new QGpgME::QByteArrayDataProvider(); mPubKey = new GpgME::Data( mPubKeyDataProvider ); assert( !mPubKey->isNull() ); } hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startKeyGeneration( parameters.utf8().data(), mPubKey ? *mPubKey : GpgME::Data::null ); if ( err ) deleteLater(); return err; } void Kleo::QGpgMEKeyGenerationJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mCtx->keyGenerationResult(), mPubKeyDataProvider ? mPubKeyDataProvider->data() : QByteArray() ); } #include "qgpgmekeygenerationjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmekeygenerationjob.h b/certmanager/lib/backends/qgpgme/qgpgmekeygenerationjob.h index 0f6f299e15..973aeb12d0 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmekeygenerationjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmekeygenerationjob.h @@ -1,78 +1,78 @@ /* qgpgmekeygenerationjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEKEYGENERATIONJOB_H__ #define __KLEO_QGPGMEKEYGENERATIONJOB_H__ #include #include "qgpgmejob.h" #include namespace GpgME { class Error; class Context; class Key; class Data; } namespace QGpgME { class QByteArrayDataProvider; } namespace Kleo { class KDE_EXPORT QGpgMEKeyGenerationJob : public KeyGenerationJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEKeyGenerationJob( GpgME::Context * context ); ~QGpgMEKeyGenerationJob(); /*! \reimp from KeygenerationJob */ GpgME::Error start( const QString & parameters ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & error ) { QGpgMEJob::doSlotOperationDoneEvent( context, error ); } private: void doOperationDoneEvent( const GpgME::Error & e ); private: QGpgME::QByteArrayDataProvider * mPubKeyDataProvider; GpgME::Data * mPubKey; }; } #endif // __KLEO_QGPGMEKEYGENERATIONJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmekeylistjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmekeylistjob.cpp index cfba8143b1..9c87e3ef62 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmekeylistjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmekeylistjob.cpp @@ -1,188 +1,187 @@ /* qgpgmekeylistjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmekeylistjob.h" #include #include #include #include #include #include #include #include #include #include #include #include #include - Kleo::QGpgMEKeyListJob::QGpgMEKeyListJob( GpgME::Context * context ) : KeyListJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEKeyListJob" ), QGpgMEJob( this, context ), mResult(), mSecretOnly( false ) { assert( context ); } Kleo::QGpgMEKeyListJob::~QGpgMEKeyListJob() { } void Kleo::QGpgMEKeyListJob::setup( const QStringList & pats, bool secretOnly ) { assert( !patterns() ); mSecretOnly = secretOnly; setPatterns( pats ); } GpgME::Error Kleo::QGpgMEKeyListJob::start( const QStringList & pats, bool secretOnly ) { setup( pats, secretOnly ); hookupContextToEventLoopInteractor(); connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(nextKeyEventSignal(GpgME::Context*,const GpgME::Key&)), SLOT(slotNextKeyEvent(GpgME::Context*,const GpgME::Key&)) ); // The communication channel between gpgme and gpgsm is limited in // the number of patterns that can be transported, but they won't // say to how much, so we need to find out ourselves if we get a // LINE_TOO_LONG error back... // We could of course just feed them single patterns, and that would // probably be easier, but the performance penalty would currently // be noticable. while ( const GpgME::Error err = mCtx->startKeyListing( patterns(), mSecretOnly ) ) { if ( err.code() == GPG_ERR_LINE_TOO_LONG ) { setChunkSize( chunkSize()/2 ); if ( chunkSize() >= 1 ) { kdDebug(5150) << "QGpgMEKeyListJob::start(): retrying keylisting with chunksize " << chunkSize() << endl; continue; } } deleteLater(); mResult = GpgME::KeyListResult( 0, err ); return err; } mResult = GpgME::KeyListResult( 0, 0 ); return 0; } GpgME::KeyListResult Kleo::QGpgMEKeyListJob::exec( const QStringList & pats, bool secretOnly, std::vector & keys ) { setup( pats, secretOnly ); // The communication channel between gpgme and gpgsm is limited in // the number of patterns that can be transported, but they won't // say to how much, so we need to find out ourselves if we get a // LINE_TOO_LONG error back... // We could of course just feed them single patterns, and that would // probably be easier, but the performance penalty would currently // be noticable. for (;;) { keys.clear(); mResult = attemptSyncKeyListing( keys ); if ( !mResult.error() || mResult.error().code() != GPG_ERR_LINE_TOO_LONG ) return mResult; // got LINE_TOO_LONG, try a smaller chunksize: setChunkSize( chunkSize()/2 ); if ( chunkSize() < 1 ) // chunks smaller than one can't be -> return the error. return mResult; kdDebug(5150) << "QGpgMEKeyListJob::exec(): retrying keylisting with chunksize " << chunkSize() << endl; } kdFatal(5150) << "QGpgMEKeyListJob::exec(): Oops, this is not supposed to happen!" << endl; return GpgME::KeyListResult(); } GpgME::KeyListResult Kleo::QGpgMEKeyListJob::attemptSyncKeyListing( std::vector & keys ) { GpgME::KeyListResult result; for ( const char* * chunk = patterns() ; chunk ; chunk = nextChunk() ) { if ( const GpgME::Error err = mCtx->startKeyListing( chunk, mSecretOnly ) ) return GpgME::KeyListResult( 0, err ); GpgME::Error err; do keys.push_back( mCtx->nextKey( err ) ); while ( !err ); keys.pop_back(); result.mergeWith( mCtx->endKeyListing() ); if ( result.error() ) break; } return result; } void Kleo::QGpgMEKeyListJob::slotNextKeyEvent( GpgME::Context * context, const GpgME::Key & key ) { if ( context == mCtx ) emit nextKey( key ); } void Kleo::QGpgMEKeyListJob::slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & ) { if ( context != mCtx ) return; mResult.mergeWith( mCtx->keyListResult() ); if ( !mResult.error() ) if ( const char* * chunk = nextChunk() ) { if ( const GpgME::Error err = mCtx->startKeyListing( chunk, mSecretOnly ) ) mResult.mergeWith( GpgME::KeyListResult( 0, err ) ); else return; } emit done(); emit result( mResult ); deleteLater(); } void Kleo::QGpgMEKeyListJob::showErrorDialog( QWidget * parent, const QString & caption ) const { if ( !mResult.error() || mResult.error().isCanceled() ) return; const QString msg = i18n( "

An error occurred while fetching " "the keys from the backend:

" "

%1

" ) .arg( QString::fromLocal8Bit( mResult.error().asString() ) ); KMessageBox::error( parent, msg, caption ); } #include "qgpgmekeylistjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmekeylistjob.h b/certmanager/lib/backends/qgpgme/qgpgmekeylistjob.h index 4267c4d9d2..8320e0134e 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmekeylistjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmekeylistjob.h @@ -1,81 +1,81 @@ /* qgpgmekeylistjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEKEYLISTJOB_H__ #define __KLEO_QGPGMEKEYLISTJOB_H__ #include #include #include "qgpgmejob.h" namespace GpgME { class Error; class Context; class Key; } namespace Kleo { class QGpgMEKeyListJob : public KeyListJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEKeyListJob( GpgME::Context * context ); ~QGpgMEKeyListJob(); /*! \reimp from KeyListJob */ GpgME::Error start( const QStringList & patterns, bool secretOnly ); /*! \reimp from KeyListJob */ GpgME::KeyListResult exec( const QStringList & patterns, bool secretOnly, std::vector & keys ); /*! \reimp from Job */ void showErrorDialog( QWidget * parent, const QString & caption ) const; private slots: void slotNextKeyEvent( GpgME::Context * context, const GpgME::Key & key ); void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ); private: void doOperationDoneEvent( const GpgME::Error &) {} // unused, we implement slotOperationDoneEvent ourselves. void setup( const QStringList &, bool ); GpgME::KeyListResult attemptSyncKeyListing( std::vector & ); private: GpgME::KeyListResult mResult; bool mSecretOnly; }; } #endif // __KLEO_QGPGMEKEYLISTJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmeprogresstokenmapper.cpp b/certmanager/lib/backends/qgpgme/qgpgmeprogresstokenmapper.cpp index 0ff2ea9f9b..792bc2f434 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeprogresstokenmapper.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmeprogresstokenmapper.cpp @@ -1,159 +1,159 @@ /* -*- mode: C++; c-file-style: "gnu" -*- qgpgmeprogresstokenmapper.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmeprogresstokenmapper.h" #include #include #include #include struct Desc { int type; // 0 == fallback const char * display; // add %1 for useCur ^ useTot and %1 %2 for useCur == useTot == true bool useCur : 1; bool useTot : 1; }; static const struct Desc pk_dsa[] = { { 0, I18N_NOOP("Generating DSA key..."), false, false } }; static const struct Desc pk_elg[] = { { 0, I18N_NOOP("Generating ElGamal key..."), false, false } }; static const struct Desc primegen[] = { // FIXME: add all type's? { 0, I18N_NOOP("Searching for a large prime number..."), false, false } }; static const struct Desc need_entropy[] = { { 0, I18N_NOOP("Waiting for new entropy from random number generator (you might want to excercise the harddisks or move the mouse)..."), false, false } }; static const struct Desc tick[] = { { 0, I18N_NOOP("Please wait..."), false, false } }; static const struct Desc starting_agent[] = { { 0, I18N_NOOP("Starting gpg-agent (you should consider starting a global instance instead)..."), false, false } }; static const struct { const char * token; const Desc * desc; unsigned int numDesc; } tokens[] = { #define make_token(x) { #x, x, sizeof(x) / sizeof(*x) } make_token(pk_dsa), make_token(pk_elg), make_token(primegen), make_token(need_entropy), make_token(tick), make_token(starting_agent) #undef make_token }; Kleo::QGpgMEProgressTokenMapper * Kleo::QGpgMEProgressTokenMapper::mSelf = 0; const Kleo::QGpgMEProgressTokenMapper * Kleo::QGpgMEProgressTokenMapper::instance() { if ( !mSelf ) (void) new QGpgMEProgressTokenMapper(); return mSelf; } Kleo::QGpgMEProgressTokenMapper::QGpgMEProgressTokenMapper() { mSelf = this; } Kleo::QGpgMEProgressTokenMapper::~QGpgMEProgressTokenMapper() { mSelf = 0; } typedef std::map< QString, std::map > Map; static const Map & makeMap() { // return a reference to a static to avoid copying static Map map; for ( unsigned int i = 0 ; i < sizeof tokens / sizeof *tokens ; ++i ) { assert( tokens[i].token ); const QString token = QString::fromLatin1( tokens[i].token ).lower(); for ( unsigned int j = 0 ; j < tokens[i].numDesc ; ++j ) { const Desc & desc = tokens[i].desc[j]; assert( desc.display ); map[ token ][ desc.type ] = desc; } } return map; } QString Kleo::QGpgMEProgressTokenMapper::map( const char * tokenUtf8, int subtoken, int cur, int tot ) const { if ( !tokenUtf8 || !*tokenUtf8 ) return QString::null; if ( qstrcmp( tokenUtf8, "file:" ) == 0 ) return QString::null; // gpgme's job return map( QString::fromUtf8( tokenUtf8 ), subtoken, cur, tot ); } QString Kleo::QGpgMEProgressTokenMapper::map( const QString & token, int subtoken, int cur, int tot ) const { if ( token.startsWith( "file:" ) ) return QString::null; // gpgme's job static const Map & tokenMap = makeMap(); const Map::const_iterator it1 = tokenMap.find( token.lower() ); if ( it1 == tokenMap.end() ) return token; std::map::const_iterator it2 = it1->second.find( subtoken ); if ( it2 == it1->second.end() ) it2 = it1->second.find( 0 ); if ( it2 == it1->second.end() ) return token; const Desc & desc = it2->second; QString result = i18n( desc.display ); if ( desc.useCur ) result = result.arg( cur ); if ( desc.useTot ) result = result.arg( tot ); return result; } diff --git a/certmanager/lib/backends/qgpgme/qgpgmeprogresstokenmapper.h b/certmanager/lib/backends/qgpgme/qgpgmeprogresstokenmapper.h index 7590740303..d0a8da6c3a 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeprogresstokenmapper.h +++ b/certmanager/lib/backends/qgpgme/qgpgmeprogresstokenmapper.h @@ -1,58 +1,58 @@ /* qgpgmeprogresstokenmapper.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEPROGRESSTOKENMAPPER_H__ #define __KLEO_QGPGMEPROGRESSTOKENMAPPER_H__ class QString; namespace Kleo { class QGpgMEProgressTokenMapper { QGpgMEProgressTokenMapper(); ~QGpgMEProgressTokenMapper(); public: static const QGpgMEProgressTokenMapper * instance(); QString map( const char * token, int subtoken, int current, int total ) const; QString map( const QString & token, int subtoken, int current, int total ) const; private: static QGpgMEProgressTokenMapper * mSelf; }; } #endif // __KLEO_QGPGMEPROGRESSTOKENMAPPER_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmerefreshkeysjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmerefreshkeysjob.cpp index 9cc3908eb4..325306e8cd 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmerefreshkeysjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmerefreshkeysjob.cpp @@ -1,207 +1,207 @@ /* qgpgmerefreshkeysjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmerefreshkeysjob.h" #include "gnupgprocessbase.h" #include "qgpgmeprogresstokenmapper.h" #include #include #include #include #include #include Kleo::QGpgMERefreshKeysJob::QGpgMERefreshKeysJob() : RefreshKeysJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMERefreshKeysJob" ), mProcess( 0 ), mError( 0 ) { } Kleo::QGpgMERefreshKeysJob::~QGpgMERefreshKeysJob() { } GpgME::Error Kleo::QGpgMERefreshKeysJob::start( const QStringList & patterns ) { assert( mPatternsToDo.empty() ); mPatternsToDo = patterns; if ( mPatternsToDo.empty() ) mPatternsToDo.push_back( " " ); // empty list means all -> mae // sure to fail the first // startAProcess() guard clause return startAProcess(); } #if MAX_CMD_LENGTH < 65 + 128 #error MAX_CMD_LENGTH is too low #endif GpgME::Error Kleo::QGpgMERefreshKeysJob::startAProcess() { if ( mPatternsToDo.empty() ) return 0; // create and start gpgsm process: mProcess = new GnuPGProcessBase( this, "gpgsm -k --with-validation --force-crl-refresh --enable-crl-checks" ); // FIXME: obbtain the path to gpgsm from gpgme, so we use the same instance. *mProcess << "gpgsm" << "-k" << "--with-validation" << "--force-crl-refresh" << "--enable-crl-checks"; unsigned int commandLineLength = MAX_CMD_LENGTH; commandLineLength -= strlen("gpgsm") + 1 + strlen("-k") + 1 + strlen("--with-validation") + 1 + strlen("--force-crl-refresh") + 1 + strlen("--enable-crl-checks") + 1; while ( !mPatternsToDo.empty() ) { const QCString pat = mPatternsToDo.front().utf8().stripWhiteSpace(); const unsigned int patLength = pat.length(); if ( patLength >= commandLineLength ) break; mPatternsToDo.pop_front(); if ( pat.isEmpty() ) continue; *mProcess << pat; commandLineLength -= patLength + 1; } mProcess->setUseStatusFD( true ); connect( mProcess, SIGNAL(processExited(KProcess*)), SLOT(slotProcessExited(KProcess*)) ); connect( mProcess, SIGNAL(receivedStderr(KProcess*,char*,int)), SLOT(slotStderr(KProcess*,char*,int)) ); connect( mProcess, SIGNAL(status(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)), SLOT(slotStatus(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)) ); if ( !mProcess->start( KProcess::NotifyOnExit, KProcess::Stderr ) ) { mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_ENOENT ); // what else? deleteLater(); return mError; } else return 0; } void Kleo::QGpgMERefreshKeysJob::slotCancel() { if ( mProcess ) mProcess->kill(); mProcess = 0; mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_CANCELED ); } void Kleo::QGpgMERefreshKeysJob::slotStatus( GnuPGProcessBase * proc, const QString & type, const QStringList & args ) { if ( proc != mProcess ) return; QStringList::const_iterator it = args.begin(); bool ok = false; if ( type == "ERROR" ) { if ( args.size() < 2 ) { kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() not recognising ERROR with < 2 args!" << endl; return; } const int source = (*++it).toInt( &ok ); if ( !ok ) { kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() expected number for first ERROR arg, got something else" << endl; return; } ok = false; const int code = (*++it).toInt( &ok ); if ( !ok ) { kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() expected number for second ERROR arg, got something else" << endl; return; } mError = gpg_err_make( (gpg_err_source_t)source, (gpg_err_code_t)code ); } else if ( type == "PROGRESS" ) { if ( args.size() < 4 ) { kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() not recognising PROGRESS with < 4 args!" << endl; return; } const QString what = *++it; ++it; // don't use "type"... const int cur = (*++it).toInt( &ok ); if ( !ok ) { kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() expected number for \"cur\", got something else" << endl; return; } ok = false; const int total = (*++it).toInt( &ok ); if ( !ok ) { kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() expected number for \"total\", got something else" << endl; return; } emit progress( QGpgMEProgressTokenMapper::instance()->map( what, 0, cur, total ), cur, total ); } } void Kleo::QGpgMERefreshKeysJob::slotStderr( KProcess *, char *, int ) { // implement? or not? } void Kleo::QGpgMERefreshKeysJob::slotProcessExited( KProcess * proc ) { if ( proc != mProcess ) return; if ( !mError && !mPatternsToDo.empty() ) if ( const GpgME::Error err = startAProcess() ) mError = err; else return; emit done(); if ( !mError && ( !mProcess->normalExit() || mProcess->exitStatus() != 0 ) ) mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_GENERAL ); emit result( mError ); deleteLater(); } #include "qgpgmerefreshkeysjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmerefreshkeysjob.h b/certmanager/lib/backends/qgpgme/qgpgmerefreshkeysjob.h index de379eeb0e..a0132f223b 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmerefreshkeysjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmerefreshkeysjob.h @@ -1,80 +1,80 @@ /* qgpgmerefreshkeysjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEREFRESHKEYSJOB_H__ #define __KLEO_QGPGMEREFRESHKEYSJOB_H__ #include #include namespace Kleo { class GnuPGProcessBase; } namespace GpgME { class Error; } class KProcess; namespace Kleo { class QGpgMERefreshKeysJob : public RefreshKeysJob { Q_OBJECT public: QGpgMERefreshKeysJob(); ~QGpgMERefreshKeysJob(); /*! \reimp from RefreshKeysJob */ GpgME::Error start( const QStringList & patterns ); private slots: /*! \reimp from Job */ void slotCancel(); void slotStatus( Kleo::GnuPGProcessBase *, const QString &, const QStringList & ); void slotStderr( KProcess *, char *, int ); void slotProcessExited( KProcess * ); private: GpgME::Error startAProcess(); private: GnuPGProcessBase * mProcess; int mError; QStringList mPatternsToDo; }; } #endif // __KLEO_QGPGMEREFRESHKEYSJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmesecretkeyexportjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmesecretkeyexportjob.cpp index 103834eb95..afc51b5e21 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmesecretkeyexportjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmesecretkeyexportjob.cpp @@ -1,191 +1,193 @@ /* qgpgmesecretexportjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmesecretkeyexportjob.h" #include "gnupgprocessbase.h" #include "qgpgmeprogresstokenmapper.h" #include #include #include #include #include #include #include #include Kleo::QGpgMESecretKeyExportJob::QGpgMESecretKeyExportJob( bool armour ) : ExportJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMESecretKeyExportJob" ), mProcess( 0 ), mError( 0 ), mArmour( armour ) { } Kleo::QGpgMESecretKeyExportJob::~QGpgMESecretKeyExportJob() { } GpgME::Error Kleo::QGpgMESecretKeyExportJob::start( const QStringList & patterns ) { assert( mKeyData.isEmpty() ); - if ( patterns.size() != 1 || patterns.front().isEmpty() ) + if ( patterns.size() != 1 || patterns.front().isEmpty() ) { + deleteLater(); return mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_INV_VALUE ); + } // create and start gpgsm process: mProcess = new GnuPGProcessBase( this, "gpgsm --export-secret-key-p12" ); // FIXME: obbtain the path to gpgsm from gpgme, so we use the same instance. *mProcess << "gpgsm" << "--export-secret-key-p12"; if ( mArmour ) *mProcess << "--armor"; *mProcess << patterns.front().utf8(); mProcess->setUseStatusFD( true ); connect( mProcess, SIGNAL(processExited(KProcess*)), SLOT(slotProcessExited(KProcess*)) ); connect( mProcess, SIGNAL(receivedStdout(KProcess*,char*,int)), SLOT(slotStdout(KProcess*,char*,int)) ); connect( mProcess, SIGNAL(receivedStderr(KProcess*,char*,int)), SLOT(slotStderr(KProcess*,char*,int)) ); connect( mProcess, SIGNAL(status(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)), SLOT(slotStatus(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)) ); if ( !mProcess->start( KProcess::NotifyOnExit, KProcess::AllOutput ) ) { mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_ENOENT ); // what else? deleteLater(); return mError; } else return 0; } void Kleo::QGpgMESecretKeyExportJob::slotCancel() { if ( mProcess ) mProcess->kill(); mProcess = 0; mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_CANCELED ); } void Kleo::QGpgMESecretKeyExportJob::slotStatus( GnuPGProcessBase * proc, const QString & type, const QStringList & args ) { if ( proc != mProcess ) return; QStringList::const_iterator it = args.begin(); bool ok = false; if ( type == "ERROR" ) { if ( args.size() < 2 ) { kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() not recognising ERROR with < 2 args!" << endl; return; } const int source = (*++it).toInt( &ok ); if ( !ok ) { kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() expected number for first ERROR arg, got something else" << endl; return; } ok = false; const int code = (*++it).toInt( &ok ); if ( !ok ) { kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() expected number for second ERROR arg, got something else" << endl; return; } mError = gpg_err_make( (gpg_err_source_t)source, (gpg_err_code_t)code ); } else if ( type == "PROGRESS" ) { if ( args.size() < 4 ) { kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() not recognising PROGRESS with < 4 args!" << endl; return; } const QString what = *++it; ++it; // don't use "type"... const int cur = (*++it).toInt( &ok ); if ( !ok ) { kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() expected number for \"cur\", got something else" << endl; return; } ok = false; const int total = (*++it).toInt( &ok ); if ( !ok ) { kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() expected number for \"total\", got something else" << endl; return; } emit progress( QGpgMEProgressTokenMapper::instance()->map( what, 0, cur, total ), cur, total ); } } void Kleo::QGpgMESecretKeyExportJob::slotStdout( KProcess * proc, char * buf, int buflen ) { if ( proc != mProcess ) return; if ( buflen <= 0 ) return; if ( !buf ) return; const unsigned int oldlen = mKeyData.size(); mKeyData.resize( oldlen + buflen ); memcpy( mKeyData.data() + oldlen, buf, buflen ); } void Kleo::QGpgMESecretKeyExportJob::slotStderr( KProcess *, char *, int ) { // implement? or not? } void Kleo::QGpgMESecretKeyExportJob::slotProcessExited( KProcess * proc ) { if ( proc != mProcess ) return; emit done(); if ( !mError && ( !mProcess->normalExit() || mProcess->exitStatus() != 0 ) ) mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_GENERAL ); emit result( mError, mKeyData ); deleteLater(); } #include "qgpgmesecretkeyexportjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmesecretkeyexportjob.h b/certmanager/lib/backends/qgpgme/qgpgmesecretkeyexportjob.h index 17684c7933..dca23d7b65 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmesecretkeyexportjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmesecretkeyexportjob.h @@ -1,84 +1,84 @@ /* qgpgmesecretkeyexportjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMESECRETKEYEXPORTJOB_H__ #define __KLEO_QGPGMESECRETKEYEXPORTJOB_H__ #include #include namespace Kleo { class GnuPGProcessBase; } namespace GpgME { class Error; class Data; } namespace QGpgME { class QByteArrayDataProvider; } class KProcess; namespace Kleo { class QGpgMESecretKeyExportJob : public ExportJob { Q_OBJECT public: QGpgMESecretKeyExportJob( bool armour ); ~QGpgMESecretKeyExportJob(); /*! \reimp from ExportJob */ GpgME::Error start( const QStringList & patterns ); private slots: /*! \reimp from Job */ void slotCancel(); void slotStatus( Kleo::GnuPGProcessBase *, const QString &, const QStringList & ); void slotStdout( KProcess *, char *, int ); void slotStderr( KProcess *, char *, int ); void slotProcessExited( KProcess * ); private: GnuPGProcessBase * mProcess; QByteArray mKeyData; int mError; bool mArmour; }; } #endif // __KLEO_QGPGMESECRETKEYEXPORTJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmesignencryptjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmesignencryptjob.cpp index 61eaf9dcc7..1ed6fe0eaf 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmesignencryptjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmesignencryptjob.cpp @@ -1,123 +1,123 @@ /* qgpgmesignencryptjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmesignencryptjob.h" #include #include #include #include #include #include #include #include Kleo::QGpgMESignEncryptJob::QGpgMESignEncryptJob( GpgME::Context * context ) : SignEncryptJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMESignEncryptJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMESignEncryptJob::~QGpgMESignEncryptJob() { } GpgME::Error Kleo::QGpgMESignEncryptJob::setup( const std::vector & signers, const QByteArray & plainText ) { assert( !mInData ); assert( !mOutData ); createInData( plainText ); createOutData(); return setSigningKeys( signers ); } GpgME::Error Kleo::QGpgMESignEncryptJob::start( const std::vector & signers, const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust ) { if ( const GpgME::Error error = setup( signers, plainText ) ) { deleteLater(); return error; } hookupContextToEventLoopInteractor(); const GpgME::Context::EncryptionFlags flags = alwaysTrust ? GpgME::Context::AlwaysTrust : GpgME::Context::None ; const GpgME::Error err = mCtx->startCombinedSigningAndEncryption( recipients, *mInData, *mOutData, flags ); if ( err ) deleteLater(); return err; } std::pair Kleo::QGpgMESignEncryptJob::exec( const std::vector & signers, const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust, QByteArray & cipherText ) { if ( GpgME::Error err = setup( signers, plainText ) ) return std::make_pair( GpgME::SigningResult( 0, err ), GpgME::EncryptionResult() ); const GpgME::Context::EncryptionFlags flags = alwaysTrust ? GpgME::Context::AlwaysTrust : GpgME::Context::None ; const std::pair result = mCtx->signAndEncrypt( recipients, *mInData, *mOutData, flags ); cipherText = mOutDataDataProvider->data(); return result; } void Kleo::QGpgMESignEncryptJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mCtx->signingResult(), mCtx->encryptionResult(), mOutDataDataProvider->data() ); } void Kleo::QGpgMESignEncryptJob::showErrorDialog( QWidget * parent, const QString & caption ) const { if ( !mResult.first.error() && !mResult.second.error() ) return; if ( mResult.first.error().isCanceled() || mResult.second.error().isCanceled() ) return; const QString msg = mResult.first.error() ? i18n("Signing failed: %1" ).arg( QString::fromLocal8Bit( mResult.first.error().asString() ) ) : i18n("Encryption failed: %1").arg( QString::fromLocal8Bit( mResult.second.error().asString() ) ) ; KMessageBox::error( parent, msg, caption ); } #include "qgpgmesignencryptjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmesignencryptjob.h b/certmanager/lib/backends/qgpgme/qgpgmesignencryptjob.h index 5eca9e62f7..a826edcbf7 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmesignencryptjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmesignencryptjob.h @@ -1,91 +1,91 @@ /* qgpgmesignencryptjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMESIGNENCRYPTJOB_H__ #define __KLEO_QGPGMESIGNENCRYPTJOB_H__ #include #include "qgpgmejob.h" #include #include #include #include #include namespace GpgME { class Error; class Context; class Key; } namespace Kleo { class KDE_EXPORT QGpgMESignEncryptJob : public SignEncryptJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMESignEncryptJob( GpgME::Context * context ); ~QGpgMESignEncryptJob(); /*! \reimp from SignEncryptJob */ GpgME::Error start( const std::vector & signers, const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust ); std::pair exec( const std::vector & signers, const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust, QByteArray & cipherText ); /*! \reimp from Job */ void showErrorDialog( QWidget * parent, const QString & caption ) const; private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); GpgME::Error setup( const std::vector &, const QByteArray & ); private: std::pair mResult; }; } #endif // __KLEO_QGPGMESIGNENCRYPTJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmesignjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmesignjob.cpp index bd1dd39cb8..585e898b66 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmesignjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmesignjob.cpp @@ -1,113 +1,113 @@ /* qgpgmesignjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmesignjob.h" #include #include #include #include #include #include #include #include #include Kleo::QGpgMESignJob::QGpgMESignJob( GpgME::Context * context ) : SignJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMESignJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMESignJob::~QGpgMESignJob() { } GpgME::Error Kleo::QGpgMESignJob::setup( const std::vector & signers, const QByteArray & plainText ) { assert( !mInData ); assert( !mOutData ); createInData( plainText ); createOutData(); return setSigningKeys( signers ); } GpgME::Error Kleo::QGpgMESignJob::start( const std::vector & signers, const QByteArray & plainText, GpgME::Context::SignatureMode mode ) { if ( const GpgME::Error error = setup( signers, plainText ) ) { deleteLater(); return error; } hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startSigning( *mInData, *mOutData, mode ); if ( err ) deleteLater(); return err; } GpgME::SigningResult Kleo::QGpgMESignJob::exec( const std::vector & signers, const QByteArray & plainText, GpgME::Context::SignatureMode mode, QByteArray & signature ) { if ( const GpgME::Error err = setup( signers, plainText ) ) return mResult = GpgME::SigningResult( 0, err ); mResult = mCtx->sign( *mInData, *mOutData, mode ); signature = mOutDataDataProvider->data(); return mResult; } void Kleo::QGpgMESignJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mResult, mOutDataDataProvider->data() ); } void Kleo::QGpgMESignJob::showErrorDialog( QWidget * parent, const QString & caption ) const { if ( !mResult.error() || mResult.error().isCanceled() ) return; const QString msg = i18n("Signing failed: %1") .arg( QString::fromLocal8Bit( mResult.error().asString() ) ); KMessageBox::error( parent, msg, caption ); } #include "qgpgmesignjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmesignjob.h b/certmanager/lib/backends/qgpgme/qgpgmesignjob.h index 9f1ccd0816..c2589b4770 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmesignjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmesignjob.h @@ -1,87 +1,87 @@ /* qgpgmesignjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMESIGNJOB_H__ #define __KLEO_QGPGMESIGNJOB_H__ #include #include "qgpgmejob.h" #include #include namespace GpgME { class Error; class Context; class Key; } namespace Kleo { class QGpgMESignJob : public SignJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMESignJob( GpgME::Context * context ); ~QGpgMESignJob(); /*! \reimp from SignJob */ GpgME::Error start( const std::vector & signers, const QByteArray & plainText, GpgME::Context::SignatureMode mode ); /*! \reimp from SignJob */ GpgME::SigningResult exec( const std::vector & signers, const QByteArray & plainText, GpgME::Context::SignatureMode mode, QByteArray & signature ); /*! \reimp from Job */ void showErrorDialog( QWidget * parent, const QString & caption ) const; private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); GpgME::Error setup( const std::vector &, const QByteArray & ); private: GpgME::SigningResult mResult; }; } #endif // __KLEO_QGPGMESIGNJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmeverifydetachedjob.cpp b/certmanager/lib/backends/qgpgme/qgpgmeverifydetachedjob.cpp index 2bfb2ad2ea..1adf12bc28 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeverifydetachedjob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmeverifydetachedjob.cpp @@ -1,94 +1,94 @@ /* qgpgmeverifydetachedjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmeverifydetachedjob.h" #include #include #include #include #include #include Kleo::QGpgMEVerifyDetachedJob::QGpgMEVerifyDetachedJob( GpgME::Context * context ) : VerifyDetachedJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEVerifyDetachedJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEVerifyDetachedJob::~QGpgMEVerifyDetachedJob() { } void Kleo::QGpgMEVerifyDetachedJob::setup( const QByteArray & signature, const QByteArray & signedData ) { assert( !mInData ); assert( !mOutData ); createInData( signature ); // two "in" data objects - (mis|re)use the "out" data object for the second... mOutDataDataProvider = new QGpgME::QByteArrayDataProvider( signedData ); mOutData = new GpgME::Data( mOutDataDataProvider ); assert( !mOutData->isNull() ); } GpgME::Error Kleo::QGpgMEVerifyDetachedJob::start( const QByteArray & signature, const QByteArray & signedData ) { setup( signature, signedData ); hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startDetachedSignatureVerification( *mInData, *mOutData ); if ( err ) deleteLater(); return err; } GpgME::VerificationResult Kleo::QGpgMEVerifyDetachedJob::exec( const QByteArray & signature, const QByteArray & signedData ) { setup( signature, signedData ); return mCtx->verifyDetachedSignature( *mInData, *mOutData ); } void Kleo::QGpgMEVerifyDetachedJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mCtx->verificationResult() ); } #include "qgpgmeverifydetachedjob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmeverifydetachedjob.h b/certmanager/lib/backends/qgpgme/qgpgmeverifydetachedjob.h index 1e59ea3a46..76141fb804 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeverifydetachedjob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmeverifydetachedjob.h @@ -1,75 +1,75 @@ /* qgpgmeverifydetachedjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEVERIFYDETACHEDJOB_H__ #define __KLEO_QGPGMEVERIFYDETACHEDJOB_H__ #include #include "qgpgmejob.h" #include namespace GpgME { class Error; class Context; } namespace Kleo { class QGpgMEVerifyDetachedJob : public VerifyDetachedJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEVerifyDetachedJob( GpgME::Context * context ); ~QGpgMEVerifyDetachedJob(); /*! \reimp from VerifyDetachedJob */ GpgME::Error start( const QByteArray & signature, const QByteArray & signedData ); /*! \reimp from VerifyDetachedJob */ GpgME::VerificationResult exec( const QByteArray & signature, const QByteArray & signedData ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); void setup( const QByteArray &, const QByteArray & ); }; } #endif // __KLEO_QGPGMEVERIFYDETACHEDJOB_H__ diff --git a/certmanager/lib/backends/qgpgme/qgpgmeverifyopaquejob.cpp b/certmanager/lib/backends/qgpgme/qgpgmeverifyopaquejob.cpp index d6ccd055f1..374206bb68 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeverifyopaquejob.cpp +++ b/certmanager/lib/backends/qgpgme/qgpgmeverifyopaquejob.cpp @@ -1,90 +1,90 @@ /* qgpgmeverifyopaquejob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "qgpgmeverifyopaquejob.h" #include #include #include #include #include #include Kleo::QGpgMEVerifyOpaqueJob::QGpgMEVerifyOpaqueJob( GpgME::Context * context ) : VerifyOpaqueJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEVerifyOpaqueJob" ), QGpgMEJob( this, context ) { assert( context ); } Kleo::QGpgMEVerifyOpaqueJob::~QGpgMEVerifyOpaqueJob() { } void Kleo::QGpgMEVerifyOpaqueJob::setup( const QByteArray & signedData ) { assert( !mInData ); assert( !mOutData ); createInData( signedData ); createOutData(); } GpgME::Error Kleo::QGpgMEVerifyOpaqueJob::start( const QByteArray & signedData ) { setup( signedData ); hookupContextToEventLoopInteractor(); const GpgME::Error err = mCtx->startOpaqueSignatureVerification( *mInData, *mOutData ); if ( err ) deleteLater(); return err; } GpgME::VerificationResult Kleo::QGpgMEVerifyOpaqueJob::exec( const QByteArray & signedData, QByteArray & plainText ) { setup( signedData ); const GpgME::VerificationResult res = mCtx->verifyOpaqueSignature( *mInData, *mOutData ); plainText = mOutDataDataProvider->data(); return res; } void Kleo::QGpgMEVerifyOpaqueJob::doOperationDoneEvent( const GpgME::Error & ) { emit result( mCtx->verificationResult(), mOutDataDataProvider->data() ); } #include "qgpgmeverifyopaquejob.moc" diff --git a/certmanager/lib/backends/qgpgme/qgpgmeverifyopaquejob.h b/certmanager/lib/backends/qgpgme/qgpgmeverifyopaquejob.h index 95b5317c5a..2c167fb1de 100644 --- a/certmanager/lib/backends/qgpgme/qgpgmeverifyopaquejob.h +++ b/certmanager/lib/backends/qgpgme/qgpgmeverifyopaquejob.h @@ -1,73 +1,73 @@ /* qgpgmeverifyopaquejob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_QGPGMEVERIFYOPAQUEJOB_H__ #define __KLEO_QGPGMEVERIFYOPAQUEJOB_H__ #include #include "qgpgmejob.h" #include namespace GpgME { class Error; class Context; } namespace Kleo { class QGpgMEVerifyOpaqueJob : public VerifyOpaqueJob, private QGpgMEJob { Q_OBJECT QGPGME_JOB public: QGpgMEVerifyOpaqueJob( GpgME::Context * context ); ~QGpgMEVerifyOpaqueJob(); /*! \reimp from VerifyOpaqueJob */ GpgME::Error start( const QByteArray & signedData ); /*! \reimp form VerifyOpaqueJob */ GpgME::VerificationResult exec( const QByteArray & signedData, QByteArray & plainData ); private slots: void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { QGpgMEJob::doSlotOperationDoneEvent( context, e ); } private: void doOperationDoneEvent( const GpgME::Error & e ); void setup( const QByteArray & ); }; } #endif // __KLEO_QGPGMEVERIFYOPAQUEJOB_H__ diff --git a/certmanager/lib/cryptplug.cpp b/certmanager/lib/cryptplug.cpp index ff9b57206b..7a58cbe048 100644 --- a/certmanager/lib/cryptplug.cpp +++ b/certmanager/lib/cryptplug.cpp @@ -1,2069 +1,1123 @@ /* -*- Mode: C++ -*- this is a C++-ification of: GPGMEPLUG - an GPGME based cryptography plug-in following the common CRYPTPLUG specification. Copyright (C) 2001 by Klarlvdalens Datakonsult AB Copyright (C) 2002 g10 Code GmbH Copyright (C) 2004 Klarlvdalens Datakonsult AB GPGMEPLUG is free software; you can redistribute it and/or modify it under the terms of GNU General Public License as published by the Free Software Foundation; version 2 of the License. GPGMEPLUG is distributed in the hope that it will be useful, it under the terms of GNU General Public License as published by the Free Software Foundation; version 2 of the License 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifdef HAVE_CONFIG_H #include #endif #include "kleo/oidmap.h" #include #include #include /*! \file gpgmeplug.c \brief GPGME implementation of CRYPTPLUG following the specification located in common API header cryptplug.h. CRYPTPLUG is an independent cryptography plug-in API developed for Sphinx-enabeling KMail and Mutt. CRYPTPLUG was designed for the Aegypten project, but it may be used by 3rd party developers as well to design pluggable crypto backends for the above mentioned MUAs. \note All string parameters appearing in this API are to be interpreted as UTF-8 encoded. \see cryptplug.h */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define __GPGMEPLUG_ERROR_CLEARTEXT_IS_ZERO "Error: Cannot run checkMessageSignature() with cleartext == 0" /* Note: The following specification will result in function encryptAndSignMessage() producing _empty_ mails. This must be changed as soon as our plugin is supporting the encryptAndSignMessage() function. */ #ifndef GPGMEPLUG_ENCSIGN_MAKE_MIME_OBJECT #define GPGMEPLUG_ENCSIGN_INCLUDE_CLEARTEXT false #define GPGMEPLUG_ENCSIGN_MAKE_MIME_OBJECT false #define GPGMEPLUG_ENCSIGN_MAKE_MULTI_MIME false #define GPGMEPLUG_ENCSIGN_CTYPE_MAIN "" #define GPGMEPLUG_ENCSIGN_CDISP_MAIN "" #define GPGMEPLUG_ENCSIGN_CTENC_MAIN "" #define GPGMEPLUG_ENCSIGN_CTYPE_VERSION "" #define GPGMEPLUG_ENCSIGN_CDISP_VERSION "" #define GPGMEPLUG_ENCSIGN_CTENC_VERSION "" #define GPGMEPLUG_ENCSIGN_BTEXT_VERSION "" #define GPGMEPLUG_ENCSIGN_CTYPE_CODE "" #define GPGMEPLUG_ENCSIGN_CDISP_CODE "" #define GPGMEPLUG_ENCSIGN_CTENC_CODE "" #define GPGMEPLUG_ENCSIGN_FLAT_PREFIX "" #define GPGMEPLUG_ENCSIGN_FLAT_SEPARATOR "" #define GPGMEPLUG_ENCSIGN_FLAT_POSTFIX "" #endif #include "cryptplug.h" #include SMIMECryptPlug::SMIMECryptPlug() : CryptPlug() { GPGMEPLUG_PROTOCOL = GPGME_PROTOCOL_CMS; mProtocol = GpgME::Context::CMS; /* definitions for signing */ // 1. opaque signatures (only used for S/MIME) GPGMEPLUG_OPA_SIGN_INCLUDE_CLEARTEXT = false; GPGMEPLUG_OPA_SIGN_MAKE_MIME_OBJECT = true; GPGMEPLUG_OPA_SIGN_MAKE_MULTI_MIME = false; GPGMEPLUG_OPA_SIGN_CTYPE_MAIN = "application/pkcs7-mime; smime-type=signed-data; name=\"smime.p7m\""; GPGMEPLUG_OPA_SIGN_CDISP_MAIN = "attachment; filename=\"smime.p7m\""; GPGMEPLUG_OPA_SIGN_CTENC_MAIN = "base64"; GPGMEPLUG_OPA_SIGN_CTYPE_VERSION = ""; GPGMEPLUG_OPA_SIGN_CDISP_VERSION = ""; GPGMEPLUG_OPA_SIGN_CTENC_VERSION = ""; GPGMEPLUG_OPA_SIGN_BTEXT_VERSION = ""; GPGMEPLUG_OPA_SIGN_CTYPE_CODE = ""; GPGMEPLUG_OPA_SIGN_CDISP_CODE = ""; GPGMEPLUG_OPA_SIGN_CTENC_CODE = ""; GPGMEPLUG_OPA_SIGN_FLAT_PREFIX = ""; GPGMEPLUG_OPA_SIGN_FLAT_SEPARATOR = ""; GPGMEPLUG_OPA_SIGN_FLAT_POSTFIX = ""; // 2. detached signatures (used for S/MIME and for OpenPGP) GPGMEPLUG_DET_SIGN_INCLUDE_CLEARTEXT = true; GPGMEPLUG_DET_SIGN_MAKE_MIME_OBJECT = true; GPGMEPLUG_DET_SIGN_MAKE_MULTI_MIME = true; GPGMEPLUG_DET_SIGN_CTYPE_MAIN = "multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha1"; GPGMEPLUG_DET_SIGN_CDISP_MAIN = ""; GPGMEPLUG_DET_SIGN_CTENC_MAIN = ""; GPGMEPLUG_DET_SIGN_CTYPE_VERSION = ""; GPGMEPLUG_DET_SIGN_CDISP_VERSION = ""; GPGMEPLUG_DET_SIGN_CTENC_VERSION = ""; GPGMEPLUG_DET_SIGN_BTEXT_VERSION = ""; GPGMEPLUG_DET_SIGN_CTYPE_CODE = "application/pkcs7-signature; name=\"smime.p7s\""; GPGMEPLUG_DET_SIGN_CDISP_CODE = "attachment; filename=\"smime.p7s\""; GPGMEPLUG_DET_SIGN_CTENC_CODE = "base64"; GPGMEPLUG_DET_SIGN_FLAT_PREFIX = ""; GPGMEPLUG_DET_SIGN_FLAT_SEPARATOR = ""; GPGMEPLUG_DET_SIGN_FLAT_POSTFIX = ""; // 3. common definitions for opaque and detached signing __GPGMEPLUG_SIGNATURE_CODE_IS_BINARY = true; /* definitions for encoding */ GPGMEPLUG_ENC_INCLUDE_CLEARTEXT = false; GPGMEPLUG_ENC_MAKE_MIME_OBJECT = true; GPGMEPLUG_ENC_MAKE_MULTI_MIME = false; GPGMEPLUG_ENC_CTYPE_MAIN = "application/pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\""; GPGMEPLUG_ENC_CDISP_MAIN = "attachment; filename=\"smime.p7m\""; GPGMEPLUG_ENC_CTENC_MAIN = "base64"; GPGMEPLUG_ENC_CTYPE_VERSION = ""; GPGMEPLUG_ENC_CDISP_VERSION = ""; GPGMEPLUG_ENC_CTENC_VERSION = ""; GPGMEPLUG_ENC_BTEXT_VERSION = ""; GPGMEPLUG_ENC_CTYPE_CODE = ""; GPGMEPLUG_ENC_CDISP_CODE = ""; GPGMEPLUG_ENC_CTENC_CODE = ""; GPGMEPLUG_ENC_FLAT_PREFIX = ""; GPGMEPLUG_ENC_FLAT_SEPARATOR = ""; GPGMEPLUG_ENC_FLAT_POSTFIX = ""; __GPGMEPLUG_ENCRYPTED_CODE_IS_BINARY = true; } OpenPGPCryptPlug::OpenPGPCryptPlug() : CryptPlug() { GPGMEPLUG_PROTOCOL = GPGME_PROTOCOL_OpenPGP; mProtocol = GpgME::Context::OpenPGP; /* definitions for signing */ // 1. opaque signatures (only used for S/MIME) GPGMEPLUG_OPA_SIGN_INCLUDE_CLEARTEXT = false; GPGMEPLUG_OPA_SIGN_MAKE_MIME_OBJECT = false; GPGMEPLUG_OPA_SIGN_MAKE_MULTI_MIME = false; GPGMEPLUG_OPA_SIGN_CTYPE_MAIN = ""; GPGMEPLUG_OPA_SIGN_CDISP_MAIN = ""; GPGMEPLUG_OPA_SIGN_CTENC_MAIN = ""; GPGMEPLUG_OPA_SIGN_CTYPE_VERSION = ""; GPGMEPLUG_OPA_SIGN_CDISP_VERSION = ""; GPGMEPLUG_OPA_SIGN_CTENC_VERSION = ""; GPGMEPLUG_OPA_SIGN_BTEXT_VERSION = ""; GPGMEPLUG_OPA_SIGN_CTYPE_CODE = ""; GPGMEPLUG_OPA_SIGN_CDISP_CODE = ""; GPGMEPLUG_OPA_SIGN_CTENC_CODE = ""; GPGMEPLUG_OPA_SIGN_FLAT_PREFIX = ""; GPGMEPLUG_OPA_SIGN_FLAT_SEPARATOR = ""; GPGMEPLUG_OPA_SIGN_FLAT_POSTFIX = ""; // 2. detached signatures (used for S/MIME and for OpenPGP) GPGMEPLUG_DET_SIGN_INCLUDE_CLEARTEXT = true; GPGMEPLUG_DET_SIGN_MAKE_MIME_OBJECT = true; GPGMEPLUG_DET_SIGN_MAKE_MULTI_MIME = true; GPGMEPLUG_DET_SIGN_CTYPE_MAIN = "multipart/signed; protocol=\"application/pgp-signature\"; micalg=pgp-sha1"; GPGMEPLUG_DET_SIGN_CDISP_MAIN = ""; GPGMEPLUG_DET_SIGN_CTENC_MAIN = ""; GPGMEPLUG_DET_SIGN_CTYPE_VERSION = ""; GPGMEPLUG_DET_SIGN_CDISP_VERSION = ""; GPGMEPLUG_DET_SIGN_CTENC_VERSION = ""; GPGMEPLUG_DET_SIGN_BTEXT_VERSION = ""; GPGMEPLUG_DET_SIGN_CTYPE_CODE = "application/pgp-signature"; GPGMEPLUG_DET_SIGN_CDISP_CODE = ""; GPGMEPLUG_DET_SIGN_CTENC_CODE = ""; GPGMEPLUG_DET_SIGN_FLAT_PREFIX = ""; GPGMEPLUG_DET_SIGN_FLAT_SEPARATOR = ""; GPGMEPLUG_DET_SIGN_FLAT_POSTFIX = ""; // 3. common definitions for opaque and detached signing __GPGMEPLUG_SIGNATURE_CODE_IS_BINARY = false; /* definitions for encoding */ GPGMEPLUG_ENC_INCLUDE_CLEARTEXT = false; GPGMEPLUG_ENC_MAKE_MIME_OBJECT = true; GPGMEPLUG_ENC_MAKE_MULTI_MIME = true; GPGMEPLUG_ENC_CTYPE_MAIN = "multipart/encrypted; protocol=\"application/pgp-encrypted\""; GPGMEPLUG_ENC_CDISP_MAIN = ""; GPGMEPLUG_ENC_CTENC_MAIN = ""; GPGMEPLUG_ENC_CTYPE_VERSION = "application/pgp-encrypted"; GPGMEPLUG_ENC_CDISP_VERSION = "attachment"; GPGMEPLUG_ENC_CTENC_VERSION = ""; GPGMEPLUG_ENC_BTEXT_VERSION = "Version: 1"; GPGMEPLUG_ENC_CTYPE_CODE = "application/octet-stream"; GPGMEPLUG_ENC_CDISP_CODE = "inline; filename=\"msg.asc\""; GPGMEPLUG_ENC_CTENC_CODE = ""; GPGMEPLUG_ENC_FLAT_PREFIX = ""; GPGMEPLUG_ENC_FLAT_SEPARATOR = ""; GPGMEPLUG_ENC_FLAT_POSTFIX = ""; __GPGMEPLUG_ENCRYPTED_CODE_IS_BINARY = false; } #define days_from_seconds(x) ((x)/86400) /* Max number of parts in a DN */ #define MAX_GPGME_IDX 20 /* some macros to replace ctype ones and avoid locale problems */ #define spacep(p) (*(p) == ' ' || *(p) == '\t') #define digitp(p) (*(p) >= '0' && *(p) <= '9') #define hexdigitp(a) (digitp (a) \ || (*(a) >= 'A' && *(a) <= 'F') \ || (*(a) >= 'a' && *(a) <= 'f')) /* the atoi macros assume that the buffer has only valid digits */ #define atoi_1(p) (*(p) - '0' ) #define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1)) #define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2)) #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) static void * xmalloc (size_t n) { void *p = malloc (n); if (!p) { fputs ("\nfatal: out of core\n", stderr); exit (4); } return p; } /* Please: Don't call an allocation function xfoo when it may return NULL. */ /* Wrong: #define xstrdup( x ) (x)?strdup(x):0 */ /* Right: */ static char * xstrdup (const char *string) { char *p = (char*)xmalloc (strlen (string)+1); strcpy (p, string); return p; } -/* Wrapper to cope with a bug in gpgme 0.4.4. */ -static void -my_gpgme_key_release (gpgme_key_t key) -{ - if (key) - gpgme_key_release (key); -} - - CryptPlug::CryptPlug() { } CryptPlug::~CryptPlug() { } bool CryptPlug::initialize() { GpgME::setDefaultLocale( LC_CTYPE, setlocale( LC_CTYPE, 0 ) ); GpgME::setDefaultLocale( LC_MESSAGES, setlocale( LC_MESSAGES, 0 ) ); return (gpgme_engine_check_version (GPGMEPLUG_PROTOCOL) == GPG_ERR_NO_ERROR); } bool CryptPlug::hasFeature( Feature flag ) { /* our own plugins are supposed to support everything */ switch ( flag ) { case Feature_SignMessages: case Feature_VerifySignatures: case Feature_EncryptMessages: case Feature_DecryptMessages: case Feature_SendCertificates: case Feature_PinEntrySettings: case Feature_StoreMessagesWithSigs: case Feature_EncryptionCRLs: case Feature_StoreMessagesEncrypted: case Feature_CheckCertificatePath: return true; case Feature_WarnSignCertificateExpiry: case Feature_WarnSignEmailNotInCertificate: case Feature_WarnEncryptCertificateExpiry: case Feature_WarnEncryptEmailNotInCertificate: return GPGMEPLUG_PROTOCOL == GPGME_PROTOCOL_CMS; /* undefined or not yet implemented: */ case Feature_CRLDirectoryService: case Feature_CertificateDirectoryService: case Feature_undef: default: return false; } } -/* Return the current interface version. This is a simple way for a - user to check whether all required fucntions are available. If - MIN_VERSION is not NULL the lowest supported version of the - interface is returned in addition. */ -int CryptPlug::interfaceVersion (int *min_version) -{ - if (min_version) - *min_version = 0; - return 1; -} - -static -int getAttrExpireFormKey( gpgme_key_t* rKey) -{ - int daysLeft = CRYPTPLUG_CERT_DOES_NEVER_EXPIRE; - if ( rKey && *rKey && (*rKey)->subkeys && (*rKey)->subkeys->expires >= 0 ) { - time_t expire_time = (*rKey)->subkeys->expires; - time_t cur_time = time (NULL); - if( cur_time > expire_time ) { - daysLeft = days_from_seconds(cur_time - expire_time); - daysLeft *= -1; - } - else - daysLeft = days_from_seconds(expire_time - cur_time); - } - return daysLeft; -} - - static void storeNewCharPtr( char** dest, const char* src ) { int sLen = strlen( src ); *dest = (char*)xmalloc( sLen + 1 ); strcpy( *dest, src ); } - -bool CryptPlug::signMessage( const char* cleartext, - char** ciphertext, - const size_t* cipherLen, - const char* certificate, - struct StructuringInfo* structuring, - int* errId, - char** errTxt, - SendCertificates sendCertificates, - SignatureCompoundMode signatureCompoundMode ) -{ - bool bIsOpaque; - gpgme_ctx_t ctx; - gpgme_error_t err; - gpgme_key_t rKey; - gpgme_data_t data, sig; - char* rSig = 0; - bool bOk = false; - int sendCerts = 1; - - init_StructuringInfo( structuring ); - - if( !ciphertext ) - return false; - - err = gpgme_new (&ctx); - gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); - - gpgme_set_armor (ctx, __GPGMEPLUG_SIGNATURE_CODE_IS_BINARY ? 0 : 1); - /* gpgme_set_textmode (ctx, 1); */ - - switch ( sendCertificates ) { - case SendCert_undef: - break; - case SendCert_DontSend: - sendCerts = 0; - break; - case SendCert_SendOwn: - sendCerts = 1; - break; - case SendCert_SendChainWithoutRoot: - sendCerts = -2; - break; - case SendCert_SendChainWithRoot: - sendCerts = -1; - break; - default: - sendCerts = 0; - break; - } - gpgme_set_include_certs (ctx, sendCerts); - - /* select the signer's key if provided */ - if (certificate != 0) { - err = gpgme_op_keylist_start(ctx, certificate, 0); - while (!err) { - err = gpgme_op_keylist_next(ctx, &rKey); - if (!err) { - if ( rKey && rKey->can_sign ) { - /* clear existing signers */ - gpgme_signers_clear(ctx); - /* set the signing key */ - gpgme_signers_add(ctx, rKey); - /* we only support one signer for now */ - break; - } - } - } - gpgme_op_keylist_end(ctx); - } - - /* PENDING(g10) Implement this - - gpgme_set_signature_algorithm( ctx, config->signatureAlgorithm ) - --> This does not make sense. The algorithm is a property of - the certificate used [wk 2002-03-23] */ - - gpgme_data_new_from_mem (&data, cleartext, - strlen( cleartext ), 1 ); - gpgme_data_new ( &sig ); - - /* NOTE: Currently we support Opaque signed messages only for S/MIME, - but not for OpenPGP mode! */ - if( GPGMEPLUG_PROTOCOL == GPGME_PROTOCOL_CMS ) - bIsOpaque = (signatureCompoundMode == SignatureCompoundMode_Opaque); - else - bIsOpaque = false; - - err = gpgme_op_sign ( ctx, - data, - sig, - bIsOpaque - ? GPGME_SIG_MODE_NORMAL - : GPGME_SIG_MODE_DETACH ); - - if ( !err ) { - if( __GPGMEPLUG_SIGNATURE_CODE_IS_BINARY ) { - *ciphertext = gpgme_data_release_and_get_mem( sig, (size_t*)cipherLen ); - bOk = true; - } - else { - rSig = gpgme_data_release_and_get_mem( sig, (size_t*)cipherLen ); - *ciphertext = (char*)malloc( *cipherLen + 1 ); - if( *ciphertext ) { - if( *cipherLen ) { - bOk = true; - strncpy((char*)*ciphertext, rSig, *cipherLen ); - } - (*ciphertext)[*cipherLen] = '\0'; - } - free( rSig ); - } - } - else { - gpgme_data_release( sig ); -/* -*ciphertext = malloc( 70 ); -strcpy((char*)*ciphertext, "xyz\nsig-dummy\nzyx" ); -(*ciphertext)[17] = '\0'; -err = 0; -{ -*/ - *ciphertext = 0; - fprintf( stderr, "\n\n gpgme_op_sign() returned this error code: %i\n\n", err ); - if( errId ) - *errId = err; - if( errTxt ) { - const char* _errTxt = gpgme_strerror( err ); - *errTxt = (char*)malloc( strlen( _errTxt ) + 1 ); - if( *errTxt ) - strcpy(*errTxt, _errTxt ); - } -/* -} -*/ - } - gpgme_data_release( data ); - gpgme_release (ctx); - - if( bOk && structuring ) { - if( bIsOpaque ) { - structuring->includeCleartext = GPGMEPLUG_OPA_SIGN_INCLUDE_CLEARTEXT; - structuring->makeMimeObject = GPGMEPLUG_OPA_SIGN_MAKE_MIME_OBJECT; - if( structuring->makeMimeObject ) { - structuring->makeMultiMime = GPGMEPLUG_OPA_SIGN_MAKE_MULTI_MIME; - storeNewCharPtr( &structuring->contentTypeMain, - GPGMEPLUG_OPA_SIGN_CTYPE_MAIN ); - storeNewCharPtr( &structuring->contentDispMain, - GPGMEPLUG_OPA_SIGN_CDISP_MAIN ); - storeNewCharPtr( &structuring->contentTEncMain, - GPGMEPLUG_OPA_SIGN_CTENC_MAIN ); - if( structuring->makeMultiMime ) { - storeNewCharPtr( &structuring->contentTypeVersion, - GPGMEPLUG_OPA_SIGN_CTYPE_VERSION ); - storeNewCharPtr( &structuring->contentDispVersion, - GPGMEPLUG_OPA_SIGN_CDISP_VERSION ); - storeNewCharPtr( &structuring->contentTEncVersion, - GPGMEPLUG_OPA_SIGN_CTENC_VERSION ); - storeNewCharPtr( &structuring->bodyTextVersion, - GPGMEPLUG_OPA_SIGN_BTEXT_VERSION ); - storeNewCharPtr( &structuring->contentTypeCode, - GPGMEPLUG_OPA_SIGN_CTYPE_CODE ); - storeNewCharPtr( &structuring->contentDispCode, - GPGMEPLUG_OPA_SIGN_CDISP_CODE ); - storeNewCharPtr( &structuring->contentTEncCode, - GPGMEPLUG_OPA_SIGN_CTENC_CODE ); - } - } else { - storeNewCharPtr( &structuring->flatTextPrefix, - GPGMEPLUG_OPA_SIGN_FLAT_PREFIX ); - storeNewCharPtr( &structuring->flatTextSeparator, - GPGMEPLUG_OPA_SIGN_FLAT_SEPARATOR ); - storeNewCharPtr( &structuring->flatTextPostfix, - GPGMEPLUG_OPA_SIGN_FLAT_POSTFIX ); - } - } else { - structuring->includeCleartext = GPGMEPLUG_DET_SIGN_INCLUDE_CLEARTEXT; - structuring->makeMimeObject = GPGMEPLUG_DET_SIGN_MAKE_MIME_OBJECT; - if( structuring->makeMimeObject ) { - structuring->makeMultiMime = GPGMEPLUG_DET_SIGN_MAKE_MULTI_MIME; - storeNewCharPtr( &structuring->contentTypeMain, - GPGMEPLUG_DET_SIGN_CTYPE_MAIN ); - storeNewCharPtr( &structuring->contentDispMain, - GPGMEPLUG_DET_SIGN_CDISP_MAIN ); - storeNewCharPtr( &structuring->contentTEncMain, - GPGMEPLUG_DET_SIGN_CTENC_MAIN ); - if( structuring->makeMultiMime ) { - storeNewCharPtr( &structuring->contentTypeVersion, - GPGMEPLUG_DET_SIGN_CTYPE_VERSION ); - storeNewCharPtr( &structuring->contentDispVersion, - GPGMEPLUG_DET_SIGN_CDISP_VERSION ); - storeNewCharPtr( &structuring->contentTEncVersion, - GPGMEPLUG_DET_SIGN_CTENC_VERSION ); - storeNewCharPtr( &structuring->bodyTextVersion, - GPGMEPLUG_DET_SIGN_BTEXT_VERSION ); - storeNewCharPtr( &structuring->contentTypeCode, - GPGMEPLUG_DET_SIGN_CTYPE_CODE ); - storeNewCharPtr( &structuring->contentDispCode, - GPGMEPLUG_DET_SIGN_CDISP_CODE ); - storeNewCharPtr( &structuring->contentTEncCode, - GPGMEPLUG_DET_SIGN_CTENC_CODE ); - } - } else { - storeNewCharPtr( &structuring->flatTextPrefix, - GPGMEPLUG_DET_SIGN_FLAT_PREFIX ); - storeNewCharPtr( &structuring->flatTextSeparator, - GPGMEPLUG_DET_SIGN_FLAT_SEPARATOR ); - storeNewCharPtr( &structuring->flatTextPostfix, - GPGMEPLUG_DET_SIGN_FLAT_POSTFIX ); - } - } - } - return bOk; -} - - - -bool CryptPlug::storeCertificatesFromMessage( const char* ){ return true; } - - -/* returns address if address doesn't contain a part - * else it returns a new string xxx and frees address - */ -static char* parseAddress( char* address ) -{ - char* result = address; - char* i; - char* j; - if( !result ) return result; - i = index( address, '<' ); - if( i ) { - j = index( i+1, '>' ); - if( j == NULL ) j = address+strlen(address); - result = (char*)xmalloc( j-i ); - strncpy( result, i+1, j-i-1 ); - result[j-i-1] = '\0'; - free( address ); - } else { - i = address; - j = i+strlen(address); - } - { - /* remove surrounding whitespace */ - char* k = result+(j-i-1); - char* l = result; - while( isspace( *l ) ) ++l; - while( isspace( *k ) ) --k; - if( l != result || k != result+(j-i-1) ) { - char* result2 = (char*)xmalloc( k-l+2 ); - strncpy( result2, l, k-l+1 ); - result2[k-l+1] = '\0'; - free(result); - result = result2; - } - } - return result; -} - -static char* nextAddress( const char** address ) -{ - const char *start = *address; - char* result = NULL; - int quote = 0; - int comment = 0; - int found = 0; - if( *address == NULL ) return NULL; - while( **address ) { - - switch( **address ) { - case '\\': /* escaped character */ - ++(*address); - break; - case '"': - if( comment == 0 ) { - if( quote > 0 ) --quote; - else ++quote; - } - break; - case '(': /* comment start */ - if( quote == 0 ) ++comment; - break; - case ')': /* comment end */ - if( quote == 0 ) --comment; - break; - case '\0': - case '\1': /* delimiter */ - if( quote == 0 && comment == 0 ) { - found = 1; - } - break; - } - ++(*address); - if( found ) break; - } - if( found || **address == 0 ) { - size_t len; - len = *address - start; - if( len > 0 ) { - if( **address != 0 ) --len; - result = (char*)xmalloc( len*sizeof(char)+1 ); - strncpy( result, start, len ); - result[len] = '\0'; - } - } - return parseAddress(result); -} - -bool CryptPlug::encryptMessage( const char* cleartext, - const char** ciphertext, - const size_t* cipherLen, - const char* certificate, - struct StructuringInfo* structuring, - int* errId, - char** errTxt ) -{ - gpgme_ctx_t ctx; - gpgme_error_t err; - gpgme_data_t gCiphertext, gPlaintext; - char* rCiph = 0; - bool bOk = false; - - init_StructuringInfo( structuring ); - - gpgme_new (&ctx); - gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); - - gpgme_set_armor (ctx, __GPGMEPLUG_ENCRYPTED_CODE_IS_BINARY ? 0 : 1); - /* gpgme_set_textmode (ctx, 1); */ - - gpgme_data_new_from_mem (&gPlaintext, cleartext, - 1+strlen( cleartext ), 1 ); - err = gpgme_data_new ( &gCiphertext ); - - - std::vector recips; - - { - const char* p = certificate; - char* tok; - while( (tok = nextAddress( &p ) ) != 0 ) { - fprintf( stderr, "\nGPGMEPLUG encryptMessage() using addressee %s\n", tok ); - recips.push_back( tok ); - } - } - - recips.push_back( 0 ); - const char ** patterns = new const char*[ recips.size() ]; - const char ** patterns_it = patterns; - std::copy( recips.begin(), recips.end(), patterns_it ); - recips.pop_back(); - - std::vector keys; -#if 0 // BROKEN FOR FINGERPRINTS - err = gpgme_op_keylist_ext_start( ctx, patterns, 0, 0 ); - while ( !err ) { - gpgme_key_t key = 0; - err = gpgme_op_keylist_next( ctx, &key ); - keys.push_back( key ); - } - if ( gpg_err_code( err ) == GPG_ERR_EOF ) - err = GPG_ERR_NO_ERROR; - gpgme_op_keylist_end( ctx ); -#else - for ( const char ** pit = patterns ; *pit && !err ; ++pit ) { - gpgme_key_t key = 0; - err = gpgme_get_key( ctx, *pit, &key, false ); - if ( key ) - keys.push_back( key ); - } -#endif - - keys.push_back( 0 ); - gpgme_key_t * rset = new gpgme_key_t[ keys.size() ]; - gpgme_key_t * rset_it = rset; - std::copy( keys.begin(), keys.end(), rset_it ); - keys.pop_back(); - - std::for_each( recips.begin(), recips.end(), &free ); - delete[] patterns; - - /* PENDING(g10) Implement this - Possible values: RSA = 1, SHA1 = 2, TripleDES = 3 - gpgme_set_encryption_algorithm( ctx, config->encryptionAlgorithm ); - - -> Your are mixing public key and symmetric algorithms. The - latter may be configured but the sphix specifications do opnly - allow 3-DES so this is not nothing we need to do. The proper way - to select the symmetric algorithm is anyway by looking at the - capabilities of the certificate because this is the only way to - know what the recipient can accept. [wk 2002-03-23] - - PENDING(g10) Implement this - gpgme_set_encryption_check_certificate_path( - config->checkCertificatePath ) - - PENDING(g10) Implement this - gpgme_set_encryption_check_certificate_path_to_root( - config->checkEncryptionCertificatePathToRoot ) - - -> Not checking a certificate up to the ROOT CA is dangerous and - stupid. There is no need for those options. [wk 2002-03-23] */ - - - if ( !err ) - err = gpgme_op_encrypt (ctx, rset, (gpgme_encrypt_flags_t)0, gPlaintext, gCiphertext ); - if( err ) { - fprintf( stderr, "\ngpgme_op_encrypt() returned this error code: %i\n", err ); - if( errId ) - *errId = err; - if( errTxt ) { - const char* _errTxt = gpgme_strerror( err ); - const size_t errTxtLen = strlen( _errTxt ) + 100; // leave room for reason string - *errTxt = (char*)malloc( errTxtLen + 1 ); - if( *errTxt ) { - std::string str = _errTxt; - gpgme_encrypt_result_t opInfo = gpgme_op_encrypt_result( ctx ); - if ( opInfo && opInfo->invalid_recipients ) { - str += " - "; - str += gpgme_strerror( opInfo->invalid_recipients->reason ); - // PENDING(kdab): there could be more than one! - } - strncmp( *errTxt, str.c_str(), errTxtLen ); - (*errTxt)[errTxtLen] = '\0'; - } - } - } - - std::for_each( keys.begin(), keys.end(), &my_gpgme_key_release ); - delete[] rset; - gpgme_data_release (gPlaintext); - - if( !err ) { - if( __GPGMEPLUG_ENCRYPTED_CODE_IS_BINARY ) { - *ciphertext = gpgme_data_release_and_get_mem( gCiphertext, (size_t*)cipherLen ); - bOk = true; - } - else { - rCiph = gpgme_data_release_and_get_mem( gCiphertext, (size_t*)cipherLen ); - *ciphertext = (char*)malloc( *cipherLen + 1 ); - if( *ciphertext ) { - if( *cipherLen ) { - bOk = true; - strncpy((char*)*ciphertext, rCiph, *cipherLen ); - } - ((char*)(*ciphertext))[*cipherLen] = 0; - } - free( rCiph ); - } - } - else { - gpgme_data_release ( gCiphertext ); - *ciphertext = 0; - /* error handling is missing: if only one untrusted key was found - (or none at all), gpg won't sign the message. (hier fehlt eine - Fehlerbehandlung: fuer einen Recipient nur ein untrusted key - (oder gar keiner) gefunden wurde, verweigert gpg das signieren.) - */ - } - - gpgme_release (ctx); - - fflush( stderr ); - - if( bOk && structuring ) { - structuring->includeCleartext = GPGMEPLUG_ENC_INCLUDE_CLEARTEXT; - structuring->makeMimeObject = GPGMEPLUG_ENC_MAKE_MIME_OBJECT; - if( structuring->makeMimeObject ) { - structuring->makeMultiMime = GPGMEPLUG_ENC_MAKE_MULTI_MIME; - storeNewCharPtr( &structuring->contentTypeMain, - GPGMEPLUG_ENC_CTYPE_MAIN ); - storeNewCharPtr( &structuring->contentDispMain, - GPGMEPLUG_ENC_CDISP_MAIN ); - storeNewCharPtr( &structuring->contentTEncMain, - GPGMEPLUG_ENC_CTENC_MAIN ); - if( structuring->makeMultiMime ) { - storeNewCharPtr( &structuring->contentTypeVersion, - GPGMEPLUG_ENC_CTYPE_VERSION ); - storeNewCharPtr( &structuring->contentDispVersion, - GPGMEPLUG_ENC_CDISP_VERSION ); - storeNewCharPtr( &structuring->contentTEncVersion, - GPGMEPLUG_ENC_CTENC_VERSION ); - storeNewCharPtr( &structuring->bodyTextVersion, - GPGMEPLUG_ENC_BTEXT_VERSION ); - storeNewCharPtr( &structuring->contentTypeCode, - GPGMEPLUG_ENC_CTYPE_CODE ); - storeNewCharPtr( &structuring->contentDispCode, - GPGMEPLUG_ENC_CDISP_CODE ); - storeNewCharPtr( &structuring->contentTEncCode, - GPGMEPLUG_ENC_CTENC_CODE ); - } - } else { - storeNewCharPtr( &structuring->flatTextPrefix, - GPGMEPLUG_ENC_FLAT_PREFIX ); - storeNewCharPtr( &structuring->flatTextSeparator, - GPGMEPLUG_ENC_FLAT_SEPARATOR ); - storeNewCharPtr( &structuring->flatTextPostfix, - GPGMEPLUG_ENC_FLAT_POSTFIX ); - } - } - return bOk; -} - - -bool CryptPlug::encryptAndSignMessage( const char* /*cleartext*/, - const char** /*ciphertext*/, - const char* /*certificate*/, - struct StructuringInfo* structuring ) -{ - bool bOk; - - init_StructuringInfo( structuring ); - - bOk = false; - - /* implementation of this function is still missing */ - - if( bOk && structuring ) { - structuring->includeCleartext = GPGMEPLUG_ENCSIGN_INCLUDE_CLEARTEXT; - structuring->makeMimeObject = GPGMEPLUG_ENCSIGN_MAKE_MIME_OBJECT; - if( structuring->makeMimeObject ) { - structuring->makeMultiMime = GPGMEPLUG_ENCSIGN_MAKE_MULTI_MIME; - storeNewCharPtr( &structuring->contentTypeMain, - GPGMEPLUG_ENCSIGN_CTYPE_MAIN ); - storeNewCharPtr( &structuring->contentDispMain, - GPGMEPLUG_ENCSIGN_CDISP_MAIN ); - storeNewCharPtr( &structuring->contentTEncMain, - GPGMEPLUG_ENCSIGN_CTENC_MAIN ); - if( structuring->makeMultiMime ) { - storeNewCharPtr( &structuring->contentTypeVersion, - GPGMEPLUG_ENCSIGN_CTYPE_VERSION ); - storeNewCharPtr( &structuring->contentDispVersion, - GPGMEPLUG_ENCSIGN_CDISP_VERSION ); - storeNewCharPtr( &structuring->contentTEncVersion, - GPGMEPLUG_ENCSIGN_CTENC_VERSION ); - storeNewCharPtr( &structuring->bodyTextVersion, - GPGMEPLUG_ENCSIGN_BTEXT_VERSION ); - storeNewCharPtr( &structuring->contentTypeCode, - GPGMEPLUG_ENCSIGN_CTYPE_CODE ); - storeNewCharPtr( &structuring->contentDispCode, - GPGMEPLUG_ENCSIGN_CDISP_CODE ); - storeNewCharPtr( &structuring->contentTEncCode, - GPGMEPLUG_ENCSIGN_CTENC_CODE ); - } - } else { - storeNewCharPtr( &structuring->flatTextPrefix, - GPGMEPLUG_ENCSIGN_FLAT_PREFIX ); - storeNewCharPtr( &structuring->flatTextSeparator, - GPGMEPLUG_ENCSIGN_FLAT_SEPARATOR ); - storeNewCharPtr( &structuring->flatTextPostfix, - GPGMEPLUG_ENCSIGN_FLAT_POSTFIX ); - } - } - return bOk; -} - - bool CryptPlug::decryptMessage( const char* ciphertext, bool cipherIsBinary, int cipherLen, const char** cleartext, const char* /*certificate*/, int* errId, char** errTxt ) { gpgme_ctx_t ctx; gpgme_error_t err; gpgme_data_t gCiphertext, gPlaintext; size_t rCLen = 0; char* rCiph = 0; bool bOk = false; if( !ciphertext ) return false; err = gpgme_new (&ctx); gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); gpgme_set_armor (ctx, cipherIsBinary ? 0 : 1); /* gpgme_set_textmode (ctx, cipherIsBinary ? 0 : 1); */ /* gpgme_data_new_from_mem( &gCiphertext, ciphertext, 1+strlen( ciphertext ), 1 ); */ gpgme_data_new_from_mem( &gCiphertext, ciphertext, cipherIsBinary ? cipherLen : strlen( ciphertext ), 1 ); gpgme_data_new( &gPlaintext ); err = gpgme_op_decrypt( ctx, gCiphertext, gPlaintext ); if( err ) { fprintf( stderr, "\ngpgme_op_decrypt() returned this error code: %i\n\n", err ); if( errId ) *errId = err; if( errTxt ) { const char* _errTxt = gpgme_strerror( err ); *errTxt = (char*)malloc( strlen( _errTxt ) + 1 ); if( *errTxt ) strcpy(*errTxt, _errTxt ); } } gpgme_data_release( gCiphertext ); rCiph = gpgme_data_release_and_get_mem( gPlaintext, &rCLen ); *cleartext = (char*)malloc( rCLen + 1 ); if( *cleartext ) { if( rCLen ) { bOk = true; strncpy((char*)*cleartext, rCiph, rCLen ); } ((char*)(*cleartext))[rCLen] = 0; } free( rCiph ); gpgme_release( ctx ); return bOk; } static char * trim_trailing_spaces( char *string ) { char *p, *mark; for( mark = NULL, p = string; *p; p++ ) { if( isspace( *p ) ) { if( !mark ) mark = p; } else mark = NULL; } if( mark ) *mark = '\0' ; return string ; } /* Parse a DN and return an array-ized one. This is not a validating parser and it does not support any old-stylish syntax; gpgme is expected to return only rfc2253 compatible strings. */ static const unsigned char * parse_dn_part (CryptPlug::DnPair *array, const unsigned char *string) { const unsigned char *s, *s1; size_t n; char *p; /* parse attributeType */ for (s = string+1; *s && *s != '='; s++) ; if (!*s) return NULL; /* error */ n = s - string; if (!n) return NULL; /* empty key */ p = (char*)xmalloc (n+1); memcpy (p, string, n); p[n] = 0; trim_trailing_spaces ((char*)p); // map OIDs to their names: for ( unsigned int i = 0 ; i < numOidMaps ; ++i ) if ( !strcasecmp ((char*)p, oidmap[i].oid) ) { free( p ); p = xstrdup (oidmap[i].name); break; } array->key = p; string = s + 1; if (*string == '#') { /* hexstring */ string++; for (s=string; hexdigitp (s); s++) s++; n = s - string; if (!n || (n & 1)) return NULL; /* empty or odd number of digits */ n /= 2; array->value = p = (char*)xmalloc (n+1); for (s1=string; n; s1 += 2, n--) *p++ = xtoi_2 (s1); *p = 0; } else { /* regular v3 quoted string */ for (n=0, s=string; *s; s++) { if (*s == '\\') { /* pair */ s++; if (*s == ',' || *s == '=' || *s == '+' || *s == '<' || *s == '>' || *s == '#' || *s == ';' || *s == '\\' || *s == '\"' || *s == ' ') n++; else if (hexdigitp (s) && hexdigitp (s+1)) { s++; n++; } else return NULL; /* invalid escape sequence */ } else if (*s == '\"') return NULL; /* invalid encoding */ else if (*s == ',' || *s == '=' || *s == '+' || *s == '<' || *s == '>' || *s == '#' || *s == ';' ) break; else n++; } array->value = p = (char*)xmalloc (n+1); for (s=string; n; s++, n--) { if (*s == '\\') { s++; if (hexdigitp (s)) { *p++ = xtoi_2 (s); s++; } else *p++ = *s; } else *p++ = *s; } *p = 0; } return s; } /* Parse a DN and return an array-ized one. This is not a validating parser and it does not support any old-stylish syntax; gpgme is expected to return only rfc2253 compatible strings. */ static CryptPlug::DnPair * parse_dn (const unsigned char *string) { struct CryptPlug::DnPair *array; size_t arrayidx, arraysize; if( !string ) return NULL; arraysize = 7; /* C,ST,L,O,OU,CN,email */ arrayidx = 0; array = (CryptPlug::DnPair*)xmalloc ((arraysize+1) * sizeof *array); while (*string) { while (*string == ' ') string++; if (!*string) break; /* ready */ if (arrayidx >= arraysize) { /* mutt lacks a real safe_realoc - so we need to copy */ struct CryptPlug::DnPair *a2; arraysize += 5; a2 = (CryptPlug::DnPair*)xmalloc ((arraysize+1) * sizeof *array); for (unsigned int i=0; i < arrayidx; i++) { a2[i].key = array[i].key; a2[i].value = array[i].value; } free (array); array = a2; } array[arrayidx].key = NULL; array[arrayidx].value = NULL; string = parse_dn_part (array+arrayidx, string); arrayidx++; if (!string) goto failure; while (*string == ' ') string++; if (*string && *string != ',' && *string != ';' && *string != '+') goto failure; /* invalid delimiter */ if (*string) string++; } array[arrayidx].key = NULL; array[arrayidx].value = NULL; return array; failure: for (unsigned i=0; i < arrayidx; i++) { free (array[i].key); free (array[i].value); } free (array); return NULL; } static void add_dn_part( QCString& result, struct CryptPlug::DnPair& dnPair ) { /* email hack */ QCString mappedPart( dnPair.key ); for ( unsigned int i = 0 ; i < numOidMaps ; ++i ){ if( !strcasecmp( dnPair.key, oidmap[i].oid ) ) { mappedPart = oidmap[i].name; break; } } result.append( mappedPart ); result.append( "=" ); result.append( dnPair.value ); } static int add_dn_parts( QCString& result, struct CryptPlug::DnPair* dn, const char* part ) { int any = 0; if( dn ) { for(; dn->key; ++dn ) { if( !strcmp( dn->key, part ) ) { if( any ) result.append( "," ); add_dn_part( result, *dn ); any = 1; } } } return any; } static char* reorder_dn( struct CryptPlug::DnPair *dn, char** attrOrder = 0, const char* unknownAttrsHandling = 0 ) { struct CryptPlug::DnPair *dnOrg = dn; /* note: The must parts are: CN, L, OU, O, C */ const char* defaultpart[] = { "CN", "S", "SN", "GN", "T", "UID", "MAIL", "EMAIL", "MOBILE", "TEL", "FAX", "STREET", "L", "PC", "SP", "ST", "OU", "O", "C", NULL }; const char** stdpart = attrOrder ? ((const char**)attrOrder) : defaultpart; int any=0, any2=0, found_X_=0, i; QCString result; QCString resultUnknowns; /* find and save the non-standard parts in their original order */ if( dn ){ for(; dn->key; ++dn ) { for( i = 0; stdpart[i]; ++i ) { if( !strcmp( dn->key, stdpart[i] ) ) { break; } } if( !stdpart[i] ) { if( any2 ) resultUnknowns.append( "," ); add_dn_part( resultUnknowns, *dn ); any2 = 1; } } dn = dnOrg; } /* prepend the unknown attrs if desired */ if( unknownAttrsHandling && !strcmp(unknownAttrsHandling, "PREFIX") && *resultUnknowns ){ result.append( resultUnknowns ); any = 1; }else{ any = 0; } /* add standard parts */ for( i = 0; stdpart[i]; ++i ) { dn = dnOrg; if( any ) { result.append( "," ); } if( any2 && !strcmp(stdpart[i], "_X_") && unknownAttrsHandling && !strcmp(unknownAttrsHandling, "INFIX") ){ if ( !resultUnknowns.isEmpty() ) { result.append( resultUnknowns ); any = 1; } found_X_ = 1; }else{ any = add_dn_parts( result, dn, stdpart[i] ); } } /* append the unknown attrs if desired */ if( !unknownAttrsHandling || !strcmp(unknownAttrsHandling, "POSTFIX") || ( !strcmp(unknownAttrsHandling, "INFIX") && !found_X_ ) ){ if( !resultUnknowns.isEmpty() ) { if( any ){ result.append( "," ); } result.append( resultUnknowns ); } } char* cResult = (char*)xmalloc( (result.length()+1)*sizeof(char) ); if( result.isEmpty() ) *cResult = 0; else strcpy( cResult, result ); return cResult; } -struct CryptPlug::CertIterator { - gpgme_ctx_t ctx; - struct CertificateInfo info; -}; - -CryptPlug::CertIterator* -CryptPlug::startListCertificates( const char* pattern, int remote ) -{ - gpgme_error_t err; - struct CertIterator* it; - const char* patterns[] = { pattern, NULL }; - fprintf( stderr, "startListCertificates( \"%s\", %d )\n", pattern, remote ); - - it = (CertIterator*)xmalloc( sizeof( struct CertIterator ) ); - - err = gpgme_new (&(it->ctx)); - /*fprintf( stderr, "2: gpgme returned %d\n", err );*/ - if( err ) { - free( it ); - return NULL; - } - - gpgme_set_protocol (it->ctx, GPGME_PROTOCOL_CMS); - if( remote ) gpgme_set_keylist_mode ( it->ctx, GPGME_KEYLIST_MODE_EXTERN ); - else gpgme_set_keylist_mode ( it->ctx, GPGME_KEYLIST_MODE_LOCAL ); - err = gpgme_op_keylist_ext_start ( it->ctx, patterns, 0, 0); - memset( &(it->info), 0, sizeof( struct CertificateInfo ) ); - if( err ) { - fprintf( stderr, "gpgme_op_keylist_ext_start returned %d", err ); - endListCertificates( it ); - return NULL; - } - return it; -} - -/* free() each string in a char*[] and the array itself */ -static void -freeStringArray( char** c ) -{ - char** _c = c; - - while( c && *c ) { - /*fprintf( stderr, "freeing \"%s\"\n", *c );*/ - free( *c ); - ++c; - } - free( _c ); -} - -/* free all malloc'ed data in a struct CertificateInfo */ -static void -freeInfo( struct CryptPlug::CertificateInfo* info ) -{ - struct CryptPlug::DnPair* a = info->dnarray; - assert( info ); - freeStringArray( info->userid ); - free( info->serial); - free( info->fingerprint ); - free( info->issuer_org ); - free( info->issuer_reord ); - free( info->chainid ); - free( info->caps ); - while( a && a->key && a->value ) { - free (a->key); - free (a->value); - ++a; - } - free (info->dnarray); - memset( info, 0, sizeof( *info ) ); -} - -/* Format the fingerprint nicely. The caller should - free the returned value using free() */ -static char* make_fingerprint( const char* fpr ) -{ - int len = strlen(fpr); - int i = 0; - char* result = (char*)xmalloc( (len + len/2 + 1)*sizeof(char) ); - - for(; *fpr; ++fpr, ++i ) { - if( i%3 == 2) { - result[i] = ':'; ++i; - } - result[i] = *fpr; - } - result[i] = 0; - return result; -} - -// from gpgme 0.4.3: -static const char * -capabilities_to_string (gpgme_subkey_t subkey) -{ - static const char *const strings[8] = - { - "", - "c", - "s", - "sc", - "e", - "ec", - "es", - "esc" - }; - return strings[(!!subkey->can_encrypt << 2) - | (!!subkey->can_sign << 1) - | (!!subkey->can_certify)]; -} - -int -CryptPlug::nextCertificate( CryptPlug::CertIterator* it, - CryptPlug::CertificateInfo** result, - char** attrOrder, - const char* unknownAttrsHandling ) -{ - gpgme_error_t err; - gpgme_key_t key; - int retval = GPG_ERR_NO_ERROR; - assert( it ); - fprintf( stderr, "nextCertificates( %p, %p )\n", it, result ); - err = gpgme_op_keylist_next ( it->ctx, &key); - if( !err ) { - int idx; - const char* s = 0; - unsigned long u; - char* names[MAX_GPGME_IDX+1]; - struct DnPair *issuer_dn, *tmp_dn; - retval = err; - memset( names, 0, sizeof( names ) ); - freeInfo( &(it->info) ); - - std::cerr << "nextCertificate..." << std::endl; - if ( key ) { - idx = 0; - for ( gpgme_user_id_t uid = key->uids ; uid && idx < MAX_GPGME_IDX ; uid = uid->next, ++idx ) - names[idx] = xstrdup( uid->uid ); - } - std::cerr << "DEBUG: " << s << ":" << names[0] << std::endl; - it->info.userid = (char**)xmalloc( sizeof( char* ) * (idx+1) ); - memset( it->info.userid, 0, sizeof( char* ) * (idx+1) ); - it->info.dnarray = 0; - for( idx = 0; names[idx] != 0; ++idx ) { - - struct DnPair* a = parse_dn( (unsigned char*)names[idx] ); - it->info.userid[idx] = reorder_dn( a, attrOrder, unknownAttrsHandling ); - - if( idx == 0 ) { - it->info.userid_0_org = names[idx]; - it->info.dnarray = a; - }else{ - free (names[idx]); - names[idx] = NULL; - while( a && a->key && a->value ) { - free( a->key ); - free( a->value ); - ++a; - } - } - } - it->info.userid[idx] = 0; - - s = key->issuer_serial; - it->info.serial = s? xstrdup(s) : NULL; - - s = key->subkeys ? key->subkeys->fpr : 0 ; - it->info.fingerprint = make_fingerprint( s ); - - s = key->issuer_name; - it->info.issuer_org = s? xstrdup(s): NULL; - if( s ) { - issuer_dn = tmp_dn = parse_dn( (const unsigned char*)s ); - /*it->info.issuer = xstrdup(s);*/ - it->info.issuer_reord = reorder_dn( issuer_dn, attrOrder, unknownAttrsHandling ); - while( tmp_dn && tmp_dn->key ) { - free( tmp_dn->key ); - free( tmp_dn->value ); - ++tmp_dn; - } - free( issuer_dn ); - issuer_dn = tmp_dn = NULL; - } else { - it->info.issuer_reord = NULL; - } - s = key->chain_id; - it->info.chainid = s? xstrdup(s): NULL; - - s = key->subkeys ? capabilities_to_string( key->subkeys ) : 0 ; - it->info.caps = s? xstrdup(s) : NULL; - - u = key->subkeys && key->subkeys->timestamp >= 0 ? key->subkeys->timestamp : 0 ; - it->info.created = u; - - u = key->subkeys && key->subkeys->expires >= 0 ? key->subkeys->expires : 0 ; - it->info.expire = u; - - u = key->secret; - it->info.secret = u; - - u = key->uids ? key->uids->invalid : 0 ; - it->info.invalid = u; - - u = key->subkeys ? key->subkeys->expired : 0 ; - it->info.expired = u; - - u = key->subkeys ? key->subkeys->disabled : 0 ; - it->info.disabled = u; - - my_gpgme_key_release (key); - /*return &(it->info);*/ - *result = &(it->info); - } else { - *result = NULL; - } - return retval; -} - -int -CryptPlug::endListCertificates( CryptPlug::CertIterator* it ) -{ - fprintf( stderr, "endListCertificates( %p )\n", it ); - assert(it); - gpgme_keylist_result_t result = gpgme_op_keylist_result( it->ctx ); - int truncated = result && result->truncated; - freeInfo( &(it->info) ); - gpgme_op_keylist_end(it->ctx); - gpgme_release (it->ctx); - free( it ); - return truncated; -} - GpgME::ImportResult CryptPlug::importCertificateFromMem( const char* data, size_t length ) { using namespace GpgME; std::auto_ptr context( Context::createForProtocol( mProtocol ) ); if ( !context.get() ) return ImportResult(); Data keydata( data, length, false ); if ( keydata.isNull() ) return ImportResult(); return context->importKeys( keydata ); } /* == == == == == == == == == == == == == == == == == == == == == == == == == == == == Continuation of CryptPlug code == == == == == == == == == == == == == == == == == == == == == == == == == == == == */ - -/* - Find all certificate for a given addressee and return them in a - '\1' separated list. - NOTE: The certificate parameter must point to a not-yet allocated - char*. The function will allocate the memory needed and - return the size in newSize. - If secretOnly is true, only secret keys are returned. -*/ -bool CryptPlug::findCertificates( const char* addressee, - char** certificates, - int* newSize, - bool secretOnly, - char** attrOrder, - const char* unknownAttrsHandling ) -{ -#define MAXCERTS 1024 - /* use const char declarations since all of them are needed twice */ - const char* delimiter = "\1"; - const char* openBracket = " ("; - const char* closeBracket = ")"; - - gpgme_ctx_t ctx; - gpgme_error_t err; - gpgme_key_t rKey; - const char *s; - const char *s2; - char* dn; - struct DnPair* a; - int nFound = 0; - int iFound = 0; - int siz = 0; - char* DNs[MAXCERTS]; - char* FPRs[MAXCERTS]; - - if( ! certificates ){ - fprintf( stderr, "gpgme: findCertificates called with invalid *certificates pointer\n" ); - return false; - } - - if( ! newSize ){ - fprintf( stderr, "gpgme: findCertificates called with invalid newSize pointer\n" ); - return false; - } - - *certificates = 0; - *newSize = 0; - - /* calculate length of buffer needed for certs plus fingerprints */ - gpgme_new (&ctx); - gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); - err = gpgme_op_keylist_start(ctx, addressee, secretOnly ? 1 : 0); - while( !err ) { - err = gpgme_op_keylist_next(ctx, &rKey); - if( !err ) { - s = rKey && rKey->uids ? rKey->uids->uid : 0 ; - if( s ) { - dn = xstrdup( s ); - s2 = rKey && rKey->subkeys ? rKey->subkeys->fpr : 0 ; - if( s2 ) { - if( nFound ) - siz += strlen( delimiter ); - - //fprintf( stderr, "gpgme: before reordering (%s)\n", dn ); - - a = parse_dn( (unsigned char*)dn ); - free( dn ); - dn = reorder_dn( a, attrOrder, unknownAttrsHandling ); - - //fprintf( stderr, "gpgme: after reordering (%s)\n\n", dn ); - - siz += strlen( dn ); - siz += strlen( openBracket ); - siz += strlen( s2 ); - siz += strlen( closeBracket ); - DNs[ nFound ] = dn; - dn = NULL; /* prevent it from being free'ed below. */ - FPRs[nFound ] = xstrdup( s2 ); - ++nFound; - if( nFound >= MAXCERTS ) { - fprintf( stderr, - "gpgme: findCertificates found too many certificates (%d)\n", - MAXCERTS ); - break; - } - } - free (dn); - } - } - } - gpgme_op_keylist_end( ctx ); - gpgme_release (ctx); - - - if( 0 < siz ) { - /* add one for trailing ZERO char */ - ++siz; - *newSize = siz; - /* allocate the buffer */ - *certificates = (char*)xmalloc( sizeof(char) * siz ); - memset( *certificates, 0, sizeof(char) * siz ); - /* fill the buffer */ - for (iFound=0; iFound < nFound; iFound++) { - if( !iFound ) - strcpy(*certificates, DNs[iFound] ); - else { - strcat(*certificates, delimiter ); - strcat(*certificates, DNs[iFound] ); - } - strcat( *certificates, openBracket ); - strcat( *certificates, FPRs[iFound] ); - strcat( *certificates, closeBracket ); - free( DNs[ iFound ] ); - free( FPRs[iFound ] ); - } - } - - return ( 0 < nFound ); -} - // these are from gpgme-0.4.3: static gpgme_sig_stat_t sig_stat_from_status( gpgme_error_t err ) { switch ( gpg_err_code(err) ) { case GPG_ERR_NO_ERROR: return GPGME_SIG_STAT_GOOD; case GPG_ERR_BAD_SIGNATURE: return GPGME_SIG_STAT_BAD; case GPG_ERR_NO_PUBKEY: return GPGME_SIG_STAT_NOKEY; case GPG_ERR_NO_DATA: return GPGME_SIG_STAT_NOSIG; case GPG_ERR_SIG_EXPIRED: return GPGME_SIG_STAT_GOOD_EXP; case GPG_ERR_KEY_EXPIRED: return GPGME_SIG_STAT_GOOD_EXPKEY; default: return GPGME_SIG_STAT_ERROR; } } static gpgme_sig_stat_t intersect_stati( gpgme_signature_t first ) { if ( !first ) return GPGME_SIG_STAT_NONE; gpgme_sig_stat_t result = sig_stat_from_status( first->status ); for ( gpgme_signature_t sig = first->next ; sig ; sig = sig->next ) if ( sig_stat_from_status( sig->status ) != result ) return GPGME_SIG_STAT_DIFF; return result; } static const char* sig_status_to_string( gpgme_sig_stat_t status ) { const char *result; switch (status) { case GPGME_SIG_STAT_NONE: result = "Oops: Signature not verified"; break; case GPGME_SIG_STAT_NOSIG: result = "No signature found"; break; case GPGME_SIG_STAT_GOOD: result = "Good signature"; break; case GPGME_SIG_STAT_BAD: result = "BAD signature"; break; case GPGME_SIG_STAT_NOKEY: result = "No public key to verify the signature"; break; case GPGME_SIG_STAT_ERROR: result = "Error verifying the signature"; break; case GPGME_SIG_STAT_DIFF: result = "Different results for signatures"; break; default: result = "Error: Unknown status"; break; } return result; } // WARNING: if you fix a bug here, you have to likely fix it in the // gpgme 0.3 version below, too! static void obtain_signature_information( gpgme_ctx_t ctx, gpgme_sig_stat_t & overallStatus, struct CryptPlug::SignatureMetaData* sigmeta, char** attrOrder, const char* unknownAttrsHandling, bool * signatureFound=0 ) { gpgme_error_t err; unsigned long sumGPGME; SigStatusFlags sumPlug; struct CryptPlug::DnPair* a; int sig_idx=0; assert( ctx ); assert( sigmeta ); sigmeta->extended_info = 0; gpgme_verify_result_t result = gpgme_op_verify_result( ctx ); if ( !result ) return; for ( gpgme_signature_t signature = result->signatures ; signature ; signature = signature->next, ++sig_idx ) { void* alloc_return = realloc( sigmeta->extended_info, sizeof( CryptPlug::SignatureMetaDataExtendedInfo ) * ( sig_idx + 1 ) ); if ( !alloc_return ) break; sigmeta->extended_info = (CryptPlug::SignatureMetaDataExtendedInfo*)alloc_return; /* shorthand notation :) */ CryptPlug::SignatureMetaDataExtendedInfo & this_info = sigmeta->extended_info[sig_idx]; /* clear the data area */ memset( &this_info, 0, sizeof (CryptPlug::SignatureMetaDataExtendedInfo) ); /* the creation time */ if ( signature->timestamp ) { this_info.creation_time = (tm*)malloc( sizeof( struct tm ) ); if ( this_info.creation_time ) { struct tm * ctime_val = localtime( (time_t*)&signature->timestamp ); memcpy( this_info.creation_time, ctime_val, sizeof( struct tm ) ); } } /* the extended signature verification status */ sumGPGME = signature->summary; fprintf( stderr, "gpgmeplug checkMessageSignature status flags: %lX\n", sumGPGME ); /* translate GPGME status flags to common CryptPlug status flags */ sumPlug = 0; #define convert(X) if ( sumGPGME & GPGME_SIGSUM_##X ) sumPlug |= SigStat_##X convert(VALID); convert(GREEN); convert(RED); convert(KEY_REVOKED); convert(KEY_EXPIRED); convert(SIG_EXPIRED); convert(KEY_MISSING); convert(CRL_MISSING); convert(CRL_TOO_OLD); convert(BAD_POLICY); convert(SYS_ERROR); #undef convert if( sumGPGME && !sumPlug ) sumPlug = SigStat_NUMERICAL_CODE | sumGPGME; this_info.sigStatusFlags = sumPlug; /* extract finger print */ if ( signature->fpr ) storeNewCharPtr( &this_info.fingerprint, signature->fpr ); /* validity */ this_info.validity = GPGME_VALIDITY_UNKNOWN; /* sig key data */ gpgme_key_t key = 0; // PENDING(marc) if this is deprecated, how shall we get at all // the infos below? err = gpgme_get_sig_key (ctx, sig_idx, &key); if ( !err && key ) { const char* attr_string; unsigned long attr_ulong; /* extract key identidy */ attr_string = key->subkeys ? key->subkeys->keyid : 0 ; if ( attr_string ) storeNewCharPtr( &this_info.keyid, attr_string ); /* pubkey algorithm */ attr_string = key->subkeys ? gpgme_pubkey_algo_name( key->subkeys->pubkey_algo ) : 0 ; if (attr_string != 0) storeNewCharPtr( &this_info.algo, attr_string ); attr_ulong = key->subkeys ? key->subkeys->pubkey_algo : 0 ; this_info.algo_num = attr_ulong; /* extract key validity */ attr_ulong = key->uids ? key->uids->validity : 0 ; this_info.validity = attr_ulong; /* extract user id, according to the documentation it's representable * as a number, but it seems that it also has a string representation */ attr_string = key->uids ? key->uids->uid : 0 ; if (attr_string != 0) { a = parse_dn( (const unsigned char*)attr_string ); this_info.userid = reorder_dn( a, attrOrder, unknownAttrsHandling ); } attr_ulong = 0; this_info.userid_num = attr_ulong; /* extract the length */ this_info.keylen = key->subkeys ? key->subkeys->length : 0 ; /* extract the creation time of the key */ attr_ulong = key->subkeys ? key->subkeys->timestamp : 0 ; this_info.key_created = attr_ulong; /* extract the expiration time of the key */ attr_ulong = key->subkeys ? key->subkeys->expires : 0 ; this_info.key_expires = attr_ulong; /* extract user name */ attr_string = key->uids ? key->uids->name : 0 ; if (attr_string != 0) { a = parse_dn( (const unsigned char*)attr_string ); this_info.name = reorder_dn( a, attrOrder, unknownAttrsHandling ); } /* extract email(s) */ this_info.emailCount = 0; this_info.emailList = 0; for ( gpgme_user_id_t uid = key->uids ; uid ; uid = uid->next ) { attr_string = uid->email; if ( attr_string && *attr_string) { fprintf( stderr, "gpgmeplug checkMessageSignature found email: %s\n", attr_string ); if( !this_info.emailCount ) alloc_return = malloc( sizeof( char*) ); else alloc_return = realloc( this_info.emailList, sizeof( char*) * (this_info.emailCount + 1) ); if( alloc_return ) { this_info.emailList = (char**)alloc_return; storeNewCharPtr( &( this_info.emailList[ this_info.emailCount ] ), attr_string ); ++this_info.emailCount; } } } if( !this_info.emailCount ) fprintf( stderr, "gpgmeplug checkMessageSignature found NO EMAIL\n" ); /* extract the comment */ attr_string = key->uids ? key->uids->comment : 0 ; if (attr_string != 0) storeNewCharPtr( &this_info.comment, attr_string ); } gpgme_sig_stat_t status = sig_stat_from_status( signature->status ); const char* sig_status = sig_status_to_string( status ); storeNewCharPtr( &this_info.status_text, sig_status ); } sigmeta->extended_info_count = sig_idx; overallStatus = intersect_stati( result->signatures ); sigmeta->status_code = overallStatus; storeNewCharPtr( &sigmeta->status, sig_status_to_string( overallStatus ) ); if ( signatureFound ) *signatureFound = ( overallStatus != GPGME_SIG_STAT_NONE ); } - bool CryptPlug::checkMessageSignature( char** cleartext, const char* signaturetext, bool signatureIsBinary, int signatureLen, struct CryptPlug::SignatureMetaData* sigmeta, char** attrOrder, const char* unknownAttrsHandling ) { gpgme_ctx_t ctx; gpgme_sig_stat_t status = GPGME_SIG_STAT_NONE; gpgme_data_t datapart, sigpart; char* rClear = 0; size_t clearLen; bool isOpaqueSigned; if( !cleartext ) { if( sigmeta ) storeNewCharPtr( &sigmeta->status, __GPGMEPLUG_ERROR_CLEARTEXT_IS_ZERO ); return false; } isOpaqueSigned = !*cleartext; gpgme_new( &ctx ); gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); gpgme_set_armor (ctx, signatureIsBinary ? 0 : 1); /* gpgme_set_textmode (ctx, signatureIsBinary ? 0 : 1); */ if( isOpaqueSigned ) gpgme_data_new( &datapart ); else gpgme_data_new_from_mem( &datapart, *cleartext, strlen( *cleartext ), 1 ); gpgme_data_new_from_mem( &sigpart, signaturetext, signatureIsBinary ? signatureLen : strlen( signaturetext ), 1 ); if ( isOpaqueSigned ) gpgme_op_verify( ctx, sigpart, 0, datapart ); else gpgme_op_verify( ctx, sigpart, datapart, 0 ); if( isOpaqueSigned ) { rClear = gpgme_data_release_and_get_mem( datapart, &clearLen ); *cleartext = (char*)malloc( clearLen + 1 ); if( *cleartext ) { if( clearLen ) strncpy(*cleartext, rClear, clearLen ); (*cleartext)[clearLen] = '\0'; } free( rClear ); } else gpgme_data_release( datapart ); gpgme_data_release( sigpart ); obtain_signature_information( ctx, status, sigmeta, attrOrder, unknownAttrsHandling ); gpgme_release( ctx ); return ( status == GPGME_SIG_STAT_GOOD ); } - bool CryptPlug::decryptAndCheckMessage( const char* ciphertext, bool cipherIsBinary, int cipherLen, const char** cleartext, const char* /*certificate*/, bool* signatureFound, struct CryptPlug::SignatureMetaData* sigmeta, int* errId, char** errTxt, char** attrOrder, const char* unknownAttrsHandling ) { gpgme_ctx_t ctx; gpgme_error_t err; gpgme_decrypt_result_t decryptresult; gpgme_data_t gCiphertext, gPlaintext; gpgme_sig_stat_t sigstatus = GPGME_SIG_STAT_NONE; size_t rCLen = 0; char* rCiph = 0; bool bOk = false; bool bWrongKeyUsage = false; if( !ciphertext ) return false; err = gpgme_new (&ctx); gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); gpgme_set_armor (ctx, cipherIsBinary ? 0 : 1); /* gpgme_set_textmode (ctx, cipherIsBinary ? 0 : 1); */ /* gpgme_data_new_from_mem( &gCiphertext, ciphertext, 1+strlen( ciphertext ), 1 ); */ gpgme_data_new_from_mem( &gCiphertext, ciphertext, cipherIsBinary ? cipherLen : strlen( ciphertext ), 1 ); gpgme_data_new( &gPlaintext ); err = gpgme_op_decrypt_verify( ctx, gCiphertext, gPlaintext ); gpgme_data_release( gCiphertext ); - + decryptresult = gpgme_op_decrypt_result( ctx ); #ifdef HAVE_GPGME_WRONG_KEY_USAGE if( decryptresult->wrong_key_usage ) bWrongKeyUsage = true; #endif - + if( err ) { fprintf( stderr, "\ngpgme_op_decrypt_verify() returned this error code: %i\n\n", err ); if( errId ) *errId = err; if( errTxt ) { const char* _errTxt = gpgme_strerror( err ); *errTxt = (char*)malloc( strlen( _errTxt ) + 1 ); if( *errTxt ) strcpy(*errTxt, _errTxt ); } gpgme_data_release( gPlaintext ); gpgme_release( ctx ); return bOk; } - + if( bWrongKeyUsage ) { if( errId ) *errId = CRYPTPLUG_ERR_WRONG_KEY_USAGE; // report the wrong key usage - } - + } + rCiph = gpgme_data_release_and_get_mem( gPlaintext, &rCLen ); *cleartext = (char*)malloc( rCLen + 1 ); if( *cleartext ) { if( rCLen ) { bOk = true; strncpy((char*)*cleartext, rCiph, rCLen ); } ((char*)(*cleartext))[rCLen] = 0; } free( rCiph ); obtain_signature_information( ctx, sigstatus, sigmeta, attrOrder, unknownAttrsHandling, signatureFound ); gpgme_release( ctx ); return bOk; } diff --git a/certmanager/lib/cryptplug.h b/certmanager/lib/cryptplug.h index b0eab02b81..0e3ccb6961 100644 --- a/certmanager/lib/cryptplug.h +++ b/certmanager/lib/cryptplug.h @@ -1,1176 +1,954 @@ /* -*- Mode: C++ -*- this is a C++-ification of: CRYPTPLUG - an independent cryptography plug-in API Copyright (C) 2001,2004 Klarlvdalens Datakonsult AB CRYPTPLUG is free software; you can redistribute it and/or modify it under the terms of GNU General Public License as published by the Free Software Foundation; version 2 of the License. CRYPTPLUG 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef CRYPTPLUG_H #define CRYPTPLUG_H #include #include #include // need it for gpgme_protocol_t :( #include namespace GpgME { class ImportResult; } /*! \file cryptplug.h \brief Common API header for CRYPTPLUG. CRYPTPLUG is an independent cryptography plug-in API developed for Sphinx-enabeling KMail and Mutt. CRYPTPLUG was designed for the Aegypten project, but it may be used by 3rd party developers as well to design pluggable crypto backends for the above mentioned MUAs. \note All string parameters appearing in this API are to be interpreted as UTF-8 encoded. \see pgpplugin.c \see gpgplugin.c */ /*! \defgroup groupGeneral Loading and Unloading the Plugin, General Functionality The functions in this section are used for loading and unloading plugins. Note that the actual locating of the plugin and the loading and unloading of the dynamic library is not covered here; this is MUA-specific code for which support code might already exist in the programming environments. */ /*! \defgroup groupDisplay Graphical Display Functionality The functions in this section return stationery that the MUAs can use in order to display security functionality graphically. This can be toolbar icons, shortcuts, tooltips, etc. Not all MUAs will use all this functionality. */ /*! \defgroup groupConfig Configuration Support The functions in this section provide the necessary functionality to configure the security functionality as well as to query configuration settings. Since all configuration settings will not be saved with the plugin, but rather with the MUA, there are also functions to set configuration settings programmatically; these will be used on startup of the plugin when the MUA transfers the configuration values it has read into the plugin. Usually, the functions to query and set the configuration values are not needed for anything but saving to and restoring from configuration files. */ /*! \defgroup groupConfigSign Signature Configuration \ingroup groupConfig The functions in this section provide the functionality to configure signature handling and set and query the signature configuration. */ /*! \defgroup groupConfigCrypt Encryption Configuration \ingroup groupConfig The functions in this section provide the functionality to configure encryption handling and set and query the encryption configuration. \note Whenever the term encryption is used here, it is supposed to mean both encryption and decryption, unless otherwise specified. */ /*! \defgroup groupConfigDir Directory Service Configuration \ingroup groupConfig This section contains messages for configuring the directory service. */ /*! \defgroup groupCertHand Certificate Handling The following methods are used to maintain and query certificates. */ /*! \defgroup groupSignCryptAct Signing and Encrypting Actions This section describes methods and structures used for signing and/or encrypting your mails. */ /*! \defgroup groupSignAct Signature Actions \ingroup groupSignCryptAct This section describes methods that are used for working with signatures. */ /*! \defgroup groupCryptAct Encryption and Decryption \ingroup groupSignCryptAct The following methods are used to encrypt and decrypt email messages. */ /*! \defgroup groupCertAct Certificate Handling Actions The functions in this section provide local certificate management. */ /*! \defgroup groupCRLAct CRL Handling Actions This section describes functions for managing CRLs. */ /*! \defgroup groupAdUsoInterno Important functions to be used by plugin implementors ONLY. This section describes functions that have to be used by plugin implementors but should not be used by plugin users directly. If you are not planning to write your own cryptography plugin you should ignore this section! */ /*! \defgroup certList Certificate Info listing functions */ typedef enum { Feature_undef = 0, Feature_SignMessages = 1, Feature_VerifySignatures = 2, Feature_EncryptMessages = 3, Feature_DecryptMessages = 4, Feature_SendCertificates = 5, Feature_WarnSignCertificateExpiry = 6, Feature_WarnSignEmailNotInCertificate = 7, Feature_PinEntrySettings = 8, Feature_StoreMessagesWithSigs = 9, Feature_EncryptionCRLs = 10, Feature_WarnEncryptCertificateExpiry = 11, Feature_WarnEncryptEmailNotInCertificate = 12, Feature_StoreMessagesEncrypted = 13, Feature_CheckCertificatePath = 14, Feature_CertificateDirectoryService = 15, Feature_CRLDirectoryService = 16, Feature_CertificateInfo = 17 } Feature; /* dummy values */ typedef enum { PinRequest_undef = 0, PinRequest_Always = 1, PinRequest_WhenAddingCerts = 2, PinRequest_AlwaysWhenSigning = 3, PinRequest_OncePerSession = 4, PinRequest_AfterMinutes = 5 } PinRequests; typedef enum { SignatureCompoundMode_undef = 0, SignatureCompoundMode_Opaque = 1, SignatureCompoundMode_Detached = 2 } SignatureCompoundMode; typedef enum { SendCert_undef = 0, SendCert_DontSend = 1, SendCert_SendOwn = 2, SendCert_SendChainWithoutRoot = 3, SendCert_SendChainWithRoot = 4 } SendCertificates; typedef enum { SignAlg_undef = 0, SignAlg_SHA1 = 1 } SignatureAlgorithm; typedef enum { EncryptAlg_undef = 0, EncryptAlg_RSA = 1, EncryptAlg_SHA1 = 2, EncryptAlg_TripleDES = 3 } EncryptionAlgorithm; typedef enum { SignEmail_undef = 0, SignEmail_SignAll = 1, SignEmail_Ask = 2, SignEmail_DontSign = 3 } SignEmail; typedef enum { EncryptEmail_undef = 0, EncryptEmail_EncryptAll = 1, EncryptEmail_Ask = 2, EncryptEmail_DontEncrypt = 3 } EncryptEmail; typedef enum { CertSrc_undef = 0, CertSrc_Server = 1, CertSrc_Local = 2, CertSrc_ServerLocal = CertSrc_Server | CertSrc_Local } CertificateSource; /*! \ingroup groupSignAct \brief Flags used to compose the SigStatusFlags value. This status flags are used to compose the SigStatusFlags value returned in \c SignatureMetaDataExtendedInfo after trying to verify a signed message part's signature status. The normal flags may not be used together with the special SigStat_NUMERICAL_CODE flag. When finding the special SigStat_NUMERICAL_CODE flag in a SigStatusFlags value you can obtain the respective error code number by substracting the SigStatusFlags value by SigStat_NUMERICAL_CODE: this is used to transport special status information NOT matching any of the normal predefined status codes. \note to PlugIn developers: Implementations of the CryptPlug API should try to express their signature states by bit-wise OR'ing the normal SigStatusFlags values. Using the SigStat_NUMERICAL_CODE flag should only be used as for exceptional situations where no other flag(s) could be used. By using the normal status flags your PlugIn's users will be told an understandable description of the status - when using (SigStat_NUMERICAL_CODE + internalCode) they will only be shown the respective code number and have to look into your PlugIn's manual to learn about it's meaning... */ enum { SigStat_VALID = 0x0001, /* The signature is fully valid */ SigStat_GREEN = 0x0002, /* The signature is good. */ SigStat_RED = 0x0004, /* The signature is bad. */ SigStat_KEY_REVOKED = 0x0010, /* One key has been revoked. */ SigStat_KEY_EXPIRED = 0x0020, /* One key has expired. */ SigStat_SIG_EXPIRED = 0x0040, /* The signature has expired. */ SigStat_KEY_MISSING = 0x0080, /* Can't verify: key missing. */ SigStat_CRL_MISSING = 0x0100, /* CRL not available. */ SigStat_CRL_TOO_OLD = 0x0200, /* Available CRL is too old. */ SigStat_BAD_POLICY = 0x0400, /* A policy was not met. */ - SigStat_SYS_ERROR = 0x0800, /* A system error occured. */ + SigStat_SYS_ERROR = 0x0800, /* A system error occurred. */ - SigStat_NUMERICAL_CODE = 0x8000 /* An other error occured. */ + SigStat_NUMERICAL_CODE = 0x8000 /* An other error occurred. */ }; typedef unsigned long SigStatusFlags; class CryptPlugWrapper; class KDE_EXPORT CryptPlug { friend class CryptPlugWrapper; protected: CryptPlug(); virtual ~CryptPlug(); // these must be set by subclasses: gpgme_protocol_t GPGMEPLUG_PROTOCOL; GpgME::Context::Protocol mProtocol; /* definitions for signing */ // 1. opaque signatures (only used for S/MIME) int GPGMEPLUG_OPA_SIGN_INCLUDE_CLEARTEXT; int GPGMEPLUG_OPA_SIGN_MAKE_MIME_OBJECT; int GPGMEPLUG_OPA_SIGN_MAKE_MULTI_MIME; const char * GPGMEPLUG_OPA_SIGN_CTYPE_MAIN; const char * GPGMEPLUG_OPA_SIGN_CDISP_MAIN; const char * GPGMEPLUG_OPA_SIGN_CTENC_MAIN; const char * GPGMEPLUG_OPA_SIGN_CTYPE_VERSION; const char * GPGMEPLUG_OPA_SIGN_CDISP_VERSION; const char * GPGMEPLUG_OPA_SIGN_CTENC_VERSION; const char * GPGMEPLUG_OPA_SIGN_BTEXT_VERSION; const char * GPGMEPLUG_OPA_SIGN_CTYPE_CODE; const char * GPGMEPLUG_OPA_SIGN_CDISP_CODE; const char * GPGMEPLUG_OPA_SIGN_CTENC_CODE; const char * GPGMEPLUG_OPA_SIGN_FLAT_PREFIX; const char * GPGMEPLUG_OPA_SIGN_FLAT_SEPARATOR; const char * GPGMEPLUG_OPA_SIGN_FLAT_POSTFIX; // 2. detached signatures (used for S/MIME and for OpenPGP) int GPGMEPLUG_DET_SIGN_INCLUDE_CLEARTEXT; int GPGMEPLUG_DET_SIGN_MAKE_MIME_OBJECT; int GPGMEPLUG_DET_SIGN_MAKE_MULTI_MIME; const char * GPGMEPLUG_DET_SIGN_CTYPE_MAIN; const char * GPGMEPLUG_DET_SIGN_CDISP_MAIN; const char * GPGMEPLUG_DET_SIGN_CTENC_MAIN; const char * GPGMEPLUG_DET_SIGN_CTYPE_VERSION; const char * GPGMEPLUG_DET_SIGN_CDISP_VERSION; const char * GPGMEPLUG_DET_SIGN_CTENC_VERSION; const char * GPGMEPLUG_DET_SIGN_BTEXT_VERSION; const char * GPGMEPLUG_DET_SIGN_CTYPE_CODE; const char * GPGMEPLUG_DET_SIGN_CDISP_CODE; const char * GPGMEPLUG_DET_SIGN_CTENC_CODE; const char * GPGMEPLUG_DET_SIGN_FLAT_PREFIX; const char * GPGMEPLUG_DET_SIGN_FLAT_SEPARATOR; const char * GPGMEPLUG_DET_SIGN_FLAT_POSTFIX; // 3. common definitions for opaque and detached signing int __GPGMEPLUG_SIGNATURE_CODE_IS_BINARY; /* definitions for encoding */ int GPGMEPLUG_ENC_INCLUDE_CLEARTEXT; int GPGMEPLUG_ENC_MAKE_MIME_OBJECT; int GPGMEPLUG_ENC_MAKE_MULTI_MIME; const char * GPGMEPLUG_ENC_CTYPE_MAIN; const char * GPGMEPLUG_ENC_CDISP_MAIN; const char * GPGMEPLUG_ENC_CTENC_MAIN; const char * GPGMEPLUG_ENC_CTYPE_VERSION; const char * GPGMEPLUG_ENC_CDISP_VERSION; const char * GPGMEPLUG_ENC_CTENC_VERSION; const char * GPGMEPLUG_ENC_BTEXT_VERSION; const char * GPGMEPLUG_ENC_CTYPE_CODE; const char * GPGMEPLUG_ENC_CDISP_CODE; const char * GPGMEPLUG_ENC_CTENC_CODE; const char * GPGMEPLUG_ENC_FLAT_PREFIX; const char * GPGMEPLUG_ENC_FLAT_SEPARATOR; const char * GPGMEPLUG_ENC_FLAT_POSTFIX; int __GPGMEPLUG_ENCRYPTED_CODE_IS_BINARY; // end-of(these must be set by subclasses) public: #define CRYPTPLUG_CERT_DOES_NEVER_EXPIRE 365000 - - - - -/*! \ingroup groupGeneral - \brief This function returns the version string of this cryptography - plug-in. - - If the plugins initialization fails the calling process might want - to display the library version number to the user for checking if - there is an old version of the library installed... - - \note This function must be implemented by each plug-in using - this API specification. -*/ -const char* libVersion( void ); - -/*! \ingroup groupGeneral - \brief This function returns a URL to be used for reporting a bug that - you found (or suspect, resp.) in this cryptography plug-in. - - If the plugins for some reason cannot specify an appropriate URL you - should at least be provided with a text giving you some advise on - how to report a bug. - - \note This function must be implemented by each plug-in using - this API specification. -*/ -const char* bugURL( void ); - - -/*! \ingroup groupGeneral - \brief Return the current interface version of the plugin. - - Return the current interface version. This is a simple way for a - user to check whether all required fucntions are available. If - MIN_VERSION is not NULL the lowest supported version of the - interface is returned in addition. - - The version is a positive integer. A user should check for the - existance of this function before using it; if the fucntion does - not exist, a interface version of 0 should be assumed. - - This function may be called prior to initialize(). - */ -int interfaceVersion (int *min_version); #define CRYPTPLUG_ERR_WRONG_KEY_USAGE 0x7070 /*! \ingroup groupGeneral \brief This function sets up all internal structures. Plugins that need no initialization should provide an empty implementation. The method returns \c true if the initialization was successful and \c false otherwise. Before this function is called, no other plugin functions should be called; the behavior is undefined in this case. \note This function must be implemented by each plug-in using this API specification. */ bool initialize( void ); /*! \ingroup groupGeneral \brief This function frees all internal structures. Plugins that do not keep any internal structures should provide an empty implementation. After this function has been called, no other plugin functions should be called; the behavior is undefined in this case. \note This function must be implemented by each plug-in using this API specification. */ //void deinitialize( void ); /*! \ingroup groupGeneral \brief This function returns \c true if the specified feature is available in the plugin, and \c false otherwise. Not all plugins will support all features; a complete Sphinx implementation will support all features contained in the enum, however. \note This function must be implemented by each plug-in using this API specification. */ bool hasFeature( Feature ); /*! \ingroup groupSignCryptAct \brief Information record returned by signing and by encrypting functions - this record should be used together with a corresponding \c free_StructuringInfo() function call. Use this information to compose a MIME object containing signed and/or encrypted content (or to build a text frame around your flat non-MIME message body, resp.) If value returned in \c makeMimeObject is TRUE the text strings returned in \c contentTypeMain and \c contentDispMain and \c contentTEncMain (and, if required, \c content[..]Version and \c bodyTextVersion and \c content[..]Sig) should be used to compose a respective MIME object.
If FALSE the texts returned in \c flatTextPrefix and \c flatTextSeparator and \c flatTextPostfix are to be used instead.
Allways either the \c content[..] and \c bodyTextVersion parameters or the \c flatText[..] parameters are holding valid data - never both of them may be used simultaneously as plugins will just ignore the parameters not matching their \c makeMimeObject setting. When creating your MIME object please observe these common rules: \li Parameters named \c contentType[..] and \c contentDisp[..] and \c contentTEnc[..] will return the values for the respective MIME headers 'Content-Type' and 'Content-Disposition' and 'Content-Transfer-Encoding'. The following applies to these parameters: \li The relevant MIME part may only be created if the respective \c contentType[..] parameter is holding a non-zero-length string. If the \c contentType[..] parameter value is invalid or holding an empty string the respective \c contentDisp[..] and \c contentTEnc[..] parameters should be ignored. \li If the respective \c contentDisp[..] or \c contentTEnc[..] parameter is NULL or holding a zero-length string it is up to you whether you want to add the relevant MIME header yourself, but since it in in the responsibility of the plugin implementors to provide you with all neccessary 'Content-[..]' header information you should not need to define them if they are not returned by the signing or encrypting function - otherwise this may be considered as a bug in the plugin and you could report the missing MIME header information to the address returned by the \c bugURL() function. If \c makeMultiMime returns FALSE the \c contentTypeMain returned must not be altered but used to specify a single part mime object holding the code bloc, e.g. this is used for 'enveloped-data' single part MIME objects. In this case you should ignore both the \c content[..]Version and \c content[..]Code parameters. If \c makeMultiMime returns TRUE also the following rules apply: \li If \c includeCleartext is TRUE you should include the cleartext as first part of our multipart MIME object, typically this is TRUE when signing mails but FALSE when encrypting. \li The \c contentTypeMain returned typically starts with "multipart/" while providing a "protocol" and a "micalg" parameter: just add an appropriate \c "; boundary=[your \c boundary \c string]" to get the complete Content-Type value to be used for the MIME object embedding both the signed part and the signature part (or - in case of encrypting - the version part and the code part, resp.). \li If \c contentTypeVersion is holding a non-zero-length string an additional MIME part must added immediately before the code part, this version part's MIME headers must have the unaltered values of \c contentTypeVersion and (if they are holding non-zero-length strings) \c contentDispVersion and \c contentTEncVersion, the unaltered contents of \c bodyTextVersion must be it's body. \li The value returned in \c contentTypeCode is specifying the complete Content-Type to be used for this multipart MIME object's signature part (or - in case of encrypting - for the code part following after the version part, resp.), you should not add/change/remove anything here but just use it's unaltered value for specifying the Content-Type header of the respective MIME part. \li The same applies to the \c contentDispCode value: just use it's unaltered value to specify the Content-Disposition header entry of the respective MIME part. \li The same applies to the \c contentTEncCode value: just use it's unaltered value to specify the Content-Transfer-Encoding header of the respective MIME part. If value returned in \c makeMimeObject is FALSE the text strings returned in \c flatTextPrefix and \c flatTextPostfix should be used to build a frame around the cleartext and the code bloc holding the signature (or - in case of encrypting - the encoded data bloc, resp.).
If \c includeCleartext is TRUE this frame should also include the cleartext as first bloc, this bloc should be divided from the code bloc by the contents of \c flatTextSeparator - typically this is used for signing but not when encrypting.
If \c includeCleartext is FALSE you should ignore both the cleartext and the \c flatTextSeparator parameter. How to use StructuringInfo data in your program: \li To compose a signed message please act as described below. \li For constructing an encrypted message just replace the \c signMessage() call by the respective \c encryptMessage() call and then proceed exactly the same way. \li In any case make sure to free your \c ciphertext and to call \c free_StructuringInfo() when you are done with processing the data returned by the signing (or encrypting, resp.) function. \verbatim char* ciphertext; StructuringInfo structInf; if( ! signMessage( cleartext, &ciphertext, certificate, &structuring ) ) { myErrorDialog( "Error: could not sign the message!" ); } else { if( structInf.makeMimeObject ) { // Build the main MIME object. // This is done by // using the header values returned in // structInf.contentTypeMain and in // structInf.contentDispMain and in // structInf.contentTEncMain. .. if( ! structInf.makeMultiMime ) { // Build the main MIME object's body. // This is done by // using the code bloc returned in // ciphertext. .. } else { // Build the encapsulated MIME parts. if( structInf.includeCleartext ) { // Build a MIME part holding the cleartext. // This is done by // using the original cleartext's headers and by // taking it's original body text. .. } if( structInf.contentTypeVersion && 0 < strlen( structInf.contentTypeVersion ) ) { // Build a MIME part holding the version information. // This is done by // using the header values returned in // structInf.contentTypeVersion and // structInf.contentDispVersion and // structInf.contentTEncVersion and by // taking the body contents returned in // structInf.bodyTextVersion. .. } if( structInf.contentTypeCode && 0 < strlen( structInf.contentTypeCode ) ) { // Build a MIME part holding the code information. // This is done by // using the header values returned in // structInf.contentTypeCode and // structInf.contentDispCode and // structInf.contentTEncCode and by // taking the body contents returned in // ciphertext. .. } else { // Plugin error! myErrorDialog( "Error: Cryptography plugin returned a main" "Content-Type=Multipart/.. but did not " "specify the code bloc's Content-Type header." "\nYou may report this bug:" "\n" + cryptplug.bugURL() ); } } } else { // Build a plain message body // based on the values returned in structInf. // Note: We do _not_ insert line breaks between the parts since // it is the plugin job to provide us with ready-to-use // texts containing all neccessary line breaks. strcpy( myMessageBody, structInf.plainTextPrefix ); if( structInf.includeCleartext ) { strcat( myMessageBody, cleartext ); strcat( myMessageBody, structInf.plainTextSeparator ); } strcat( myMessageBody, *ciphertext ); strcat( myMessageBody, structInf.plainTextPostfix ); } // free the memory that was allocated // for the ciphertext free( ciphertext ); // free the memory that was allocated // for our StructuringInfo's char* members free_StructuringInfo( &structuring ); } \endverbatim \note Make sure to call \c free_StructuringInfo() when you are done with processing the StructuringInfo data! \see free_StructuringInfo \see signMessage, encryptMessage, encryptAndSignMessage */ struct StructuringInfo { bool includeCleartext; /*!< specifies whether we should include the cleartext as first part of our multipart MIME object (or - for non-MIME messages - as flat text to be set before the ciphertext, resp.), typically this is TRUE when signing mails but FALSE when encrypting
(this parameter is relevant no matter whether \c makeMimeObject is TRUE or FALSE) */ bool makeMimeObject; /*!< specifies whether we should create a MIME object or a flat text message body */ /* the following are used for MIME messages only */ bool makeMultiMime; /*!< specifies whether we should create a 'Multipart' MIME object or a single part object, if FALSE only \c contentTypeMain, \c contentDispMain and \c contentTEncMain may be used and all other parameters have to be ignored
(ignore this parameter if \c makeMimeObject is FALSE) */ char* contentTypeMain; /*!< value of the main 'Content-Type' header
(ignore this parameter if \c makeMimeObject is FALSE) */ char* contentDispMain; /*!< value of the main 'Content-Disposition' header
(ignore this parameter if \c makeMimeObject is FALSE) */ char* contentTEncMain; /*!< value of the main 'Content-TransferEncoding' header
(ignore this parameter if \c makeMimeObject is FALSE) */ char* contentTypeVersion; /*!< 'Content-Type' of the additional version part that might preceed the code part - if NULL or zero length no version part must be created
(ignore this parameter if either \c makeMimeObject or \c makeMultiMime is FALSE) */ char* contentDispVersion; /*!< 'Content-Disposition' of the additional preceeding the code part (only valid if \c contentTypeVersion holds a non-zero-length string)
(ignore this parameter if either \c makeMimeObject or \c makeMultiMime is FALSE or if \c contentTypeVersion does not return a non-zero-length string) */ char* contentTEncVersion; /*!< 'Content-Transfer-Encoding' of the additional version part (only valid if \c contentTypeVersion holds a non-zero-length string)
(ignore this parameter if either \c makeMimeObject or \c makeMultiMime is FALSE or if \c contentTypeVersion does not return a non-zero-length string) */ char* bodyTextVersion; /*!< body text of the additional version part (only valid if \c contentTypeVersion holds a non-zero-length string)
(ignore this parameter if either \c makeMimeObject or \c makeMultiMime is FALSE or if \c contentTypeVersion does not return a non-zero-length string) */ char* contentTypeCode; /*!< 'Content-Type' of the code part holding the signature code (or the encrypted data, resp.)
(ignore this parameter if either \c makeMimeObject or \c makeMultiMime is FALSE) */ char* contentDispCode; /*!< 'Content-Disposition' of the code part
(ignore this parameter if either \c makeMimeObject or \c makeMultiMime is FALSE or if \c contentTypeCode does not return a non-zero-length string) */ char* contentTEncCode; /*!< 'Content-Type' of the code part
(ignore this parameter if either \c makeMimeObject or \c makeMultiMime is FALSE or if \c contentTypeCode does not return a non-zero-length string) */ /* the following are used for flat non-MIME messages only */ char* flatTextPrefix; /*!< text to preceed the main text (or the code bloc containing the encrypted main text, resp.)
(ignore this parameter if \c makeMimeObject is TRUE) */ char* flatTextSeparator; /*!< text to be put between the main text and the signature code bloc (not used when encrypting)
(ignore this parameter if \c makeMimeObject is TRUE or if \c includeCleartext is FALSE) */ char* flatTextPostfix; /*!< text to follow the signature code bloc (or the encrypted data bloc, resp.)
(ignore this parameter if \c makeMimeObject is TRUE) */ }; /*! \ingroup groupAdUsoInterno \brief If you are not planning to write your own cryptography plugin you should ignore this function! Usage of this function is depreciated for plugin users but highly recommended for plugin implementors since this is an internal function for initializing all char* members of a \c StructuringInfo struct.
This function must be called in any plugin's implementations of the following functions: \c signMessage()
\c encryptMessage()
\c encryptAndSignMessage() Calling this function makes sure the corresponding \c free_StructuringInfo() calls which will be embedded by your plugin's users into their code will be able to determine which of the char* members belonging to the respective's StructuringInfo had been allocated memory for during previous signing or encrypting actions. \see free_StructuringInfo, StructuringInfo \see signMessage, encryptMessage, encryptAndSignMessage */ inline void init_StructuringInfo( struct StructuringInfo* s ) { if( ! s ) return; s->includeCleartext = false; s->makeMimeObject = false; s->makeMultiMime = false; s->contentTypeMain = 0; s->contentDispMain = 0; s->contentTEncMain = 0; s->contentTypeVersion = 0; s->contentDispVersion = 0; s->contentTEncVersion = 0; s->bodyTextVersion = 0; s->contentTypeCode = 0; s->contentDispCode = 0; s->contentTEncCode = 0; s->flatTextPrefix = 0; s->flatTextSeparator = 0; s->flatTextPostfix = 0; } /*! \ingroup groupSignCryptAct \brief Important method for freeing all memory that was allocated for the char* members of a \c StructuringInfo struct - use this function after each signing or encrypting function call. \note Even when intending to call \c encryptMessage() immediately after having called \c signMessage() you first must call the \c free_StructuringInfo() function to make sure all memory is set free that was allocated for your StructuringInfo's char* members by the \c signMessage() function! \see StructuringInfo */ inline void free_StructuringInfo( struct StructuringInfo* s ) { if( ! s ) return; if( s->contentTypeMain ) free( s->contentTypeMain ); if( s->contentDispMain ) free( s->contentDispMain ); if( s->contentTEncMain ) free( s->contentTEncMain ); if( s->contentTypeVersion ) free( s->contentTypeVersion ); if( s->contentDispVersion ) free( s->contentDispVersion ); if( s->contentTEncVersion ) free( s->contentTEncVersion ); if( s->bodyTextVersion ) free( s->bodyTextVersion ); if( s->contentTypeCode ) free( s->contentTypeCode ); if( s->contentDispCode ) free( s->contentDispCode ); if( s->contentTEncCode ) free( s->contentTEncCode ); if( s->flatTextPrefix ) free( s->flatTextPrefix ); if( s->flatTextSeparator ) free( s->flatTextSeparator ); if( s->flatTextPostfix ) free( s->flatTextPostfix ); } -/*! \ingroup groupSignAct - \brief Signs a message \c cleartext and returns - in \c *ciphertext the signature data bloc that - is to be added to the message. The length returned - in \c *cipherLen tells you the size (==amount of bytes) - of the ciphertext, if the structuring information - would return with contentTEncCode set to "base64" - the ciphertext might contain a char 0x00 - and has to be converted into base64 before sending. - - The signature role is specified by \c certificate. - If \c certificate is \c NULL, the default certificate is used. - - If the message could be signed, the function returns - \c true, otherwise - \c false. - - Use the StructuringInfo data returned in parameter \c structuring - to find out how to build the respective MIME object (or the plain - text message body, resp.). - - \note The function allocates memory for the \c *ciphertext, so - make sure you set free that memory when no longer needing - it (as shown in example code provided with documentation - of the struct \c StructuringInfo). - - \note The function also allocates memory for some char* members - of the StructuringInfo* parameter that you are providing, - therefore you must call the \c free_StructuringInfo() function - to make sure all memory is set free that was allocated. This must be - done before calling the next cryptography function - even if - you intend to call \c encryptMessage() immediately after - \c signMessage(). - - \see StructuringInfo, free_StructuringInfo -*/ -bool signMessage( const char* cleartext, - char** ciphertext, - const size_t* cipherLen, - const char* certificate, - struct StructuringInfo* structuring, - int* errId, - char** errTxt, - SendCertificates sendCertificates, - SignatureCompoundMode signatureCompoundMode ); - - /*! \ingroup groupSignAct */ struct SignatureMetaDataExtendedInfo { struct tm* creation_time; SigStatusFlags sigStatusFlags; char* status_text; char* keyid; char* fingerprint; char* algo; char* userid; char* name; char* comment; char** emailList; int emailCount; unsigned long algo_num; unsigned long validity; unsigned long userid_num; unsigned long keylen; unsigned long key_created; unsigned long key_expires; }; /*! \ingroup groupSignAct */ struct SignatureMetaData { char* status; struct SignatureMetaDataExtendedInfo* extended_info; int extended_info_count; int status_code; }; /*! \ingroup groupSignAct \brief Checks whether the signature of a message is valid. \c cleartext must never be 0 but be a valid pointer. If \c *cleartext > 0 then **cleartext specifies the message text that was signed and \c signaturetext is the signature itself. If \c *cleartext == 0 is an empty string then \c signaturetext is supposed to contain an opaque signed message part. After checking the data and verifying the signature the cleartext of the message will be returned in \c cleartext. The user must free the respective memory ocupied by *cleartext. Depending on the configuration, MUAs might not need to use this. If \c sigmeta is non-null, the \c SignatureMetaData object pointed to will contain meta information about the signature after the function call. */ bool checkMessageSignature( char** cleartext, const char* signaturetext, bool signatureIsBinary, int signatureLen, struct SignatureMetaData* sigmeta, char** attrOrder, const char* unknownAttrsHandling ); -/*! \ingroup groupSignAct - \brief Stores the certificates that follow with the message - \c ciphertext locally. -*/ -bool storeCertificatesFromMessage( const char* ciphertext ); - - -/*! \ingroup groupCryptAct - \brief Find all certificate for a given addressee. - - NOTE: The certificate parameter must point to a not-yet allocated - char*. The function will allocate the memory needed and - return the size in newSize. - If secretOnly is true, only secret keys are returned. -*/ -bool findCertificates( const char* addressee, - char** certificates, - int* newSize, - bool secretOnly, - char** attrOrder, - const char* unknownAttrsHandling ); - -/*! \ingroup groupCryptAct - \brief Encrypts an email message in - \c cleartext according to the \c addressee and - the current settings (algorithm, etc.) and - returns the encoded data bloc in \c *ciphertext. - The length returned in \c *cipherLen tells you the - size (==amount of bytes) of the ciphertext, if the - structuring information would return with - contentTEncCode set to "base64" the ciphertext - might contain a char 0x00 and has to be converted - into base64 before sending. - - If the message could be encrypted, the function returns - \c true, otherwise - \c false. - - Use the StructuringInfo data returned in parameter \c structuring - to find out how to build the respective MIME object (or the plain - text message body, resp.). - - \note The function allocates memory for the \c *ciphertext, so - make sure you set free that memory when no longer needing - it (as shown in example code provided with documentation - of the struct \c StructuringInfo). - - \note The function also allocates memory for some char* members - of the StructuringInfo* parameter that you are providing, - therefore you must call the \c free_StructuringInfo() function - to make sure all memory is set free that was allocated. This must be - done before calling the next cryptography function! - - \see StructuringInfo, free_StructuringInfo -*/ -bool encryptMessage( const char* cleartext, - const char** ciphertext, - const size_t* cipherLen, - const char* addressee, - struct StructuringInfo* structuring, - int* errId, - char** errTxt ); - - -/*! \ingroup groupCryptAct - \brief Combines the functionality of - \c encryptMessage() and - \c signMessage(). - - If \c certificate is \c NULL, - the default certificate will be used. - - If the message could be signed and encrypted, the function returns - \c true, otherwise - \c false. - - Use the StructuringInfo data returned in parameter \c structuring - to find out how to build the respective MIME object (or the plain - text message body, resp.). - - \note The function allocates memory for the \c *ciphertext, so - make sure you set free that memory when no longer needing - it (as shown in example code provided with documentation - of the struct \c StructuringInfo). - - \note The function also allocates memory for some char* members - of the StructuringInfo* parameter that you are providing, - therefore you must call the \c free_StructuringInfo() function - to make sure all memory is set free that was allocated. This must be - done before calling the next cryptography function! - - \see StructuringInfo, free_StructuringInfo -*/ -bool encryptAndSignMessage( const char* cleartext, - const char** ciphertext, - const char* certificate, - struct StructuringInfo* structuring ); /*! \ingroup groupCryptAct \brief Tries to decrypt an email message \c ciphertext and returns the decrypted message in \c cleartext. The \c certificate is used for decryption. If the message could be decrypted, the function returns \c true, otherwise \c false. */ bool decryptMessage( const char* ciphertext, bool cipherIsBinary, int cipherLen, const char** cleartext, const char* certificate, int* errId, char** errTxt ); /*! \ingroup groupCryptAct \brief Combines the functionality of \c checkMessageSignature() and \c decryptMessage(). If \c certificate is \c NULL, the default certificate will be used. If \c sigmeta is non-null, the \c SignatureMetaData object pointed to will contain meta information about the signature after the function call. */ bool decryptAndCheckMessage( const char* ciphertext, bool cipherIsBinary, int cipherLen, const char** cleartext, const char* certificate, bool* signatureFound, struct SignatureMetaData* sigmeta, int* errId, char** errTxt, char** attrOrder, const char* unknownAttrsHandling ); - -struct CertIterator; - struct DnPair { char *key; char *value; }; struct CertificateInfo { char** userid; char* userid_0_org; char* serial; char* fingerprint; char* issuer_org; char* issuer_reord; char* chainid; char* caps; unsigned long created; unsigned long expire; int secret : 1; int invalid : 1; int expired : 1; int disabled : 1; struct DnPair *dnarray; /* parsed values from userid[0] */ }; -/*! \fn struct CertIterator* startListCertificates( const char* pattern ); - \fn struct CertificateInfo* nextCertificate( struct CertIterator* ); - \fn void endListCertificates( struct CertIterator* ); - - \ingroup certList - Example that runs through certs matching "Steffen": -\verbatim - struct CertificateInfo* info; - struct CertIterator* it = startListCertificates("Steffen", 0 ); - while( nextCertificate( it, &info ) == GPGME_No_Error && info ) { - do something with info. - dont free() it, the struct will be reused - by the next call to nextCertificate() - } - int truncated = endListCertificates( it ); -\endverbatim -*/ -struct CertIterator* -startListCertificates( const char* pattern, int remote ); - -int -nextCertificate( struct CertIterator*, - struct CertificateInfo** result, - char** attrOrder, - const char* unknownAttrsHandling ); - -int -endListCertificates( struct CertIterator* ); - /*! Import a certificate from memory. */ GpgME::ImportResult importCertificateFromMem( const char* data, size_t length ); }; // class CryptPlug class SMIMECryptPlug : public CryptPlug { public: SMIMECryptPlug(); }; class OpenPGPCryptPlug : public CryptPlug { public: OpenPGPCryptPlug(); }; #endif /*CRYPTPLUG_H*/ diff --git a/certmanager/lib/cryptplugfactory.cpp b/certmanager/lib/cryptplugfactory.cpp index e6f15aa678..7000d9a905 100644 --- a/certmanager/lib/cryptplugfactory.cpp +++ b/certmanager/lib/cryptplugfactory.cpp @@ -1,119 +1,119 @@ /* cryptplugfactory.cpp This file is part of libkleopatra, the KDE key management library Copyright (c) 2001,2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "cryptplugfactory.h" #include "cryptplugwrapperlist.h" #include #include #include #include #include #include KMail::CryptPlugFactory * KMail::CryptPlugFactory::mSelf = 0; // // // KMail::CryptPlugFactory: backwards compat stuff (ugly) // // KMail::CryptPlugFactory::CryptPlugFactory() : Kleo::CryptoBackendFactory(), mCryptPlugWrapperList( 0 ) { mSelf = this; mCryptPlugWrapperList = new CryptPlugWrapperList(); mCryptPlugWrapperList->setAutoDelete( false ); updateCryptPlugWrapperList(); } KMail::CryptPlugFactory::~CryptPlugFactory() { mSelf = 0; delete mCryptPlugWrapperList; mCryptPlugWrapperList = 0; } KMail::CryptPlugFactory * KMail::CryptPlugFactory::instance() { if ( !mSelf ) mSelf = new CryptPlugFactory(); return mSelf; } CryptPlugWrapper * KMail::CryptPlugFactory::active() const { if ( smime() && smime()->active() ) return smime(); if ( openpgp() && openpgp()->active() ) return openpgp(); return 0; } CryptPlugWrapper * KMail::CryptPlugFactory::createForProtocol( const QString & proto ) const { QString p = proto.lower(); if ( p == "application/pkcs7-signature" || p == "application/x-pkcs7-signature" ) return smime(); if ( p == "application/pgp-signature" || p == "application/x-pgp-signature" ) return openpgp(); return 0; } CryptPlugWrapper * KMail::CryptPlugFactory::smime() const { return mCryptPlugWrapperList->findForLibName( "smime" ); } CryptPlugWrapper * KMail::CryptPlugFactory::openpgp() const { return mCryptPlugWrapperList->findForLibName( "openpgp" ); } void KMail::CryptPlugFactory::scanForBackends( QStringList * reason ) { Kleo::CryptoBackendFactory::scanForBackends( reason ); updateCryptPlugWrapperList(); } void KMail::CryptPlugFactory::updateCryptPlugWrapperList() { mCryptPlugWrapperList->clear(); - for ( QValueVector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { + for ( std::vector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { if ( CryptPlugWrapper * w = dynamic_cast( (*it)->openpgp() ) ) mCryptPlugWrapperList->append( w ); if ( CryptPlugWrapper * w = dynamic_cast( (*it)->smime() ) ) mCryptPlugWrapperList->append( w ); } } #include "cryptplugfactory.moc" diff --git a/certmanager/lib/cryptplugfactory.h b/certmanager/lib/cryptplugfactory.h index 920e5d6a03..a50c3909ca 100644 --- a/certmanager/lib/cryptplugfactory.h +++ b/certmanager/lib/cryptplugfactory.h @@ -1,83 +1,83 @@ /* cryptplugfactory.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_CRYPTPLUGFACTORY_H__ #define __KLEO_CRYPTPLUGFACTORY_H__ #include "kleo/cryptobackendfactory.h" #include #ifndef LIBKLEOPATRA_NO_COMPAT namespace Kleo { //typedef CryptoBackendFactory CryptPlugFactory KDE_DEPRECATED; } class CryptPlugWrapper; class CryptPlugWrapperList; namespace KMail { class KDE_EXPORT CryptPlugFactory : public Kleo::CryptoBackendFactory { Q_OBJECT protected: CryptPlugFactory(); ~CryptPlugFactory(); public: static CryptPlugFactory * instance(); CryptPlugWrapper * active() const; CryptPlugWrapper * smime() const; CryptPlugWrapper * openpgp() const; CryptPlugWrapperList & list() const { return *mCryptPlugWrapperList; } CryptPlugWrapper * createForProtocol( const QString & proto ) const; void scanForBackends( QStringList * reason ); private: void updateCryptPlugWrapperList(); private: CryptPlugFactory( const CryptPlugFactory & ); void operator=( const CryptPlugFactory & ); CryptPlugWrapperList * mCryptPlugWrapperList; static CryptPlugFactory * mSelf; }; } #endif #endif // __KLEO_CRYPTPLUGFACTORY_H__ diff --git a/certmanager/lib/cryptplugwrapper.cpp b/certmanager/lib/cryptplugwrapper.cpp index dedc8acdbd..7ab112171c 100644 --- a/certmanager/lib/cryptplugwrapper.cpp +++ b/certmanager/lib/cryptplugwrapper.cpp @@ -1,1356 +1,850 @@ /** * cryptplugwrapper.cpp * * Copyright (c) 2001 Karl-Heinz Zimmer, Klaraelvdalens Datakonsult AB * * This CRYPTPLUG wrapper implementation is based on cryptplug.h by * Karl-Heinz Zimmer which is based on 'The Aegypten Plugin API' as * specified by Matthias Kalle Dalheimer, Klaraelvdalens Datakonsult AB, * see file mua-integration.sgml located on Aegypten CVS: * http://www.gnupg.org/aegypten/development.en.html * * purpose: Wrap up all Aegypten Plugin API functions in one C++ class * for usage by KDE programs, e.g. KMail (or KMime, resp.) * * 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; version 2 of the License. * * 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. + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "cryptplugwrapper.h" #include "cryptplug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // qgpgme #include // gpgme++ #include #include #include // kde #include #include #include #include #include // other #include #include #include #include /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file's source comments - as well as those in interface file * * cryptplugwrapper.h - are optimized for processing by Doxygen. * * * * To obtain best results please get an updated version of Doxygen, * * for sources and binaries goto http://www.doxygen.org/index.html * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*! \file cryptplugwrapper.cpp \brief C++ wrapper for the CRYPTPLUG library API. This CRYPTPLUG wrapper implementation is based on cryptplug.h by Karl-Heinz Zimmer which is based on 'The Aegypten Plugin API' as specified by Matthias Kalle Dalheimer, Klaraelvdalens Datakonsult AB, see file mua-integration.sgml located on Aegypten CVS: http://www.gnupg.org/aegypten/development.en.html purpose: Wrap up all Aegypten Plugin API functions in one C++ class for usage by KDE programs, e.g. KMail (or KMime, resp.) CRYPTPLUG is an independent cryptography plug-in API developed for Sphinx-enabeling KMail and Mutt. CRYPTPLUG was designed for the Aegypten project, but it may be used by 3rd party developers as well to design pluggable crypto backends for the above mentioned MUAs. \note All string parameters appearing in this API are to be interpreted as UTF-8 encoded. \see cryptplugwrapper.h */ // a little helper class for reordering of DN attributes class DNBeautifier { public: enum UnknownAttrsHandling { unknownAttrsHide, unknownAttrsPrefix, unknownAttrsPostfix, unknownAttrsInfix }; // infix: at the position of "_X_", if any, else Postfix DNBeautifier() { // the attrOrder is defaulted to an empty string automatically _unknownAttrsHandling = unknownAttrsInfix; _unknownAttrsHandlingChar = "INFIX"; } DNBeautifier( KConfig* config, const QString& cfgGroup, const QString& cfgAttributeOrderEntry, const QString& cfgUnknownAttrsEntry, const QStringList& fallbackAttrOrder = QStringList(), UnknownAttrsHandling fallbackUnknowAttrsHandling = unknownAttrsInfix ) { _unknownAttrsHandling = unknownAttrsInfix; _unknownAttrsHandlingChar = "INFIX"; if( config ){ const QString oldGroup( config->group() ); config->setGroup( cfgGroup ); // e.g. "General" _attrOrder = config->readListEntry( cfgAttributeOrderEntry ); // e.g. "DNAttributeOrder" _unknownAttrsHandlingChar = config->readEntry( cfgUnknownAttrsEntry ).upper().latin1(); // e.g. "DNUnknownAttributes" config->setGroup( oldGroup ); if( _unknownAttrsHandlingChar == "HIDE" ) _unknownAttrsHandling = unknownAttrsHide; else if( _unknownAttrsHandlingChar == "PREFIX" ) _unknownAttrsHandling = unknownAttrsPrefix; else if( _unknownAttrsHandlingChar == "POSTFIX" ) _unknownAttrsHandling = unknownAttrsPostfix; else if( _unknownAttrsHandlingChar == "INFIX" ) _unknownAttrsHandling = unknownAttrsInfix; else _unknownAttrsHandlingChar = "INFIX"; } if( _attrOrder.isEmpty() && ! fallbackAttrOrder.isEmpty() ) _attrOrder = fallbackAttrOrder; if( _attrOrder.isEmpty() ){ _attrOrderChar = 0; }else{ _attrOrderChar = new char*[ _attrOrder.count()+1 ]; int i=0; for( QStringList::ConstIterator itOrder = _attrOrder.begin(); itOrder != _attrOrder.end(); ++itOrder ){ _attrOrderChar[ i ] = (char*)malloc( ((*itOrder).length()+1)*sizeof(char) ); strcpy( _attrOrderChar[ i ], (*itOrder).latin1() ); ++i; } _attrOrderChar[ i ] = NULL; } } ~DNBeautifier() { int i=0; for( QStringList::ConstIterator itOrder = _attrOrder.begin(); itOrder != _attrOrder.end(); ++itOrder ){ free( _attrOrderChar[ i ] ); ++i; } delete[] _attrOrderChar; } QStringList attrOrder() const { return _attrOrder; } char** attrOrderChar() { return _attrOrderChar; } UnknownAttrsHandling unknownAttrsHandling() const { return _unknownAttrsHandling; } const char* unknownAttrsHandlingChar() const { return _unknownAttrsHandlingChar; } QValueList< QPair > reorder( const QValueList< QPair > & dn ) const { return reorder( dn, _attrOrder, _unknownAttrsHandling ); } static QValueList< QPair > reorder( const QValueList< QPair > & dn, QStringList attrOrder, UnknownAttrsHandling unknownAttrsHandling ) { if( !attrOrder.isEmpty() ){ QPtrList< QPair > unknownEntries; QValueList< QPair > dnNew; QPair* unknownEntry; QStringList::ConstIterator itOrder; QValueList< QPair >::ConstIterator itDN; bool bFound; if( unknownAttrsHandling != unknownAttrsHide ){ // find all unknown entries in their order of appearance for( itDN = dn.begin(); itDN != dn.end(); ++itDN ){ bFound = false; for( itOrder = attrOrder.begin(); itOrder != attrOrder.end(); ++itOrder ){ if( (*itOrder) == (*itDN).first ){ bFound = true; break; } } if( !bFound ) unknownEntries.append( &(*itDN) ); } } // prepend the unknown attrs (if desired) if( unknownAttrsHandling == unknownAttrsPrefix ){ for( unknownEntry = unknownEntries.first(); unknownEntry; unknownEntry = unknownEntries.next() ){ dnNew << *unknownEntry; } } // process the known attrs in the desired order bool b_X_declared = false; for( itOrder = attrOrder.begin(); itOrder != attrOrder.end(); ++itOrder ){ if( (*itOrder) == "_X_" ){ b_X_declared = true; // insert the unknown attrs (if desired) if( unknownAttrsHandling == unknownAttrsInfix ){ for( unknownEntry = unknownEntries.first(); unknownEntry; unknownEntry = unknownEntries.next() ){ dnNew << *unknownEntry; } } }else{ for( itDN = dn.begin(); itDN != dn.end(); ++itDN ){ if( (*itOrder) == (*itDN).first ){ dnNew << *itDN; //kdDebug(5150) << QString((*itDN).first) <<" = " << QString((*itDN).second) << endl;; } } } } // append the unknown attrs (if desired) if( unknownAttrsHandling == unknownAttrsPostfix || ( unknownAttrsHandling == unknownAttrsInfix && ! b_X_declared ) ){ for( unknownEntry = unknownEntries.first(); unknownEntry; unknownEntry = unknownEntries.next() ){ dnNew << *unknownEntry; } } return dnNew; } return dn; } private: QStringList _attrOrder; char** _attrOrderChar; UnknownAttrsHandling _unknownAttrsHandling; QCString _unknownAttrsHandlingChar; }; /* special helper class to be used by signing/encrypting functions *******/ StructuringInfoWrapper::StructuringInfoWrapper( CryptPlugWrapper* wrapper ) : _initDone( false ), _wrapper( wrapper ) { initMe(); } StructuringInfoWrapper::~StructuringInfoWrapper() { freeMe(); } void StructuringInfoWrapper::reset() { freeMe(); initMe(); } void StructuringInfoWrapper::initMe() { if ( _wrapper && _wrapper->cryptPlug() ) { _wrapper->cryptPlug()->init_StructuringInfo( &data ); _initDone = true; } } void StructuringInfoWrapper::freeMe() { if( _wrapper && _wrapper->cryptPlug() && _initDone ) { _wrapper->cryptPlug()->free_StructuringInfo( &data ); _initDone = false; } } class CryptPlugWrapper::Config { public: Config( gpgme_protocol_t proto ); ~Config(); const char* signatureKeyCertificate; SignatureAlgorithm signatureAlgorithm; SignatureCompoundMode signatureCompoundMode; SendCertificates sendCertificates; bool saveSentSignatures; bool warnNoCertificate; bool signatureUseCRLs; EncryptionAlgorithm encryptionAlgorithm; EncryptEmail encryptEmail; bool saveMessagesEncrypted; bool encryptionUseCRLs; bool encryptionCRLExpiryNearWarning; int encryptionCRLNearExpiryInterval; CertificateSource certificateSource; bool warnSendUnsigned; bool signatureCertificateExpiryNearWarning; int signatureCertificateExpiryNearInterval; bool cACertificateExpiryNearWarning; int cACertificateExpiryNearInterval; bool rootCertificateExpiryNearWarning; int rootCertificateExpiryNearInterval; bool warnSendUnencrypted; bool checkCertificatePath; bool receiverCertificateExpiryNearWarning; int receiverCertificateExpiryNearWarningInterval; bool certificateInChainExpiryNearWarning; int certificateInChainExpiryNearWarningInterval; bool receiverEmailAddressNotInCertificateWarning; const char* libVersion; /* a statically allocated string with the GPGME Version used */ }; static const int NEAR_EXPIRY = 14; CryptPlugWrapper::Config::Config( gpgme_protocol_t proto ) { signatureAlgorithm = SignAlg_SHA1; if ( proto == GPGME_PROTOCOL_CMS ) signatureCompoundMode = SignatureCompoundMode_Opaque; else signatureCompoundMode = SignatureCompoundMode_Detached; sendCertificates = SendCert_SendChainWithRoot; saveSentSignatures = true; warnNoCertificate = true; signatureUseCRLs = true; encryptionAlgorithm = EncryptAlg_RSA; encryptEmail = EncryptEmail_Ask; saveMessagesEncrypted = true; encryptionUseCRLs = true; encryptionCRLExpiryNearWarning = false; encryptionCRLNearExpiryInterval = NEAR_EXPIRY; certificateSource = CertSrc_Server; warnSendUnsigned = true; signatureCertificateExpiryNearWarning = true; signatureCertificateExpiryNearInterval = NEAR_EXPIRY; cACertificateExpiryNearWarning = true; cACertificateExpiryNearInterval = NEAR_EXPIRY; rootCertificateExpiryNearWarning = true; rootCertificateExpiryNearInterval = NEAR_EXPIRY; warnSendUnencrypted = false; checkCertificatePath = true; receiverCertificateExpiryNearWarning = true; receiverCertificateExpiryNearWarningInterval = NEAR_EXPIRY; certificateInChainExpiryNearWarning = true; certificateInChainExpiryNearWarningInterval = NEAR_EXPIRY; receiverEmailAddressNotInCertificateWarning = true; libVersion = gpgme_check_version (NULL); } CryptPlugWrapper::Config::~Config() { } -const char* CryptPlugWrapper::bugURL(){ return "http://www.gnupg.org/aegypten/"; } - - -void CryptPlugWrapper::setSignatureAlgorithm( SignatureAlgorithm sigAlg ) -{ - _config->signatureAlgorithm = sigAlg; -} - -SignatureAlgorithm CryptPlugWrapper::signatureAlgorithm() -{ - return _config->signatureAlgorithm; -} - - - - -void CryptPlugWrapper::setWarnSendUnsigned( bool flag ) -{ - _config->warnSendUnsigned = flag; -} - -bool CryptPlugWrapper::warnSendUnsigned() -{ - return _config->warnSendUnsigned; -} - - - - - - - - - -void CryptPlugWrapper::setSignatureCertificateExpiryNearWarning( bool flag ) -{ - _config->signatureCertificateExpiryNearWarning = flag; -} - -bool CryptPlugWrapper::signatureCertificateExpiryNearWarning( void ) -{ - return _config->signatureCertificateExpiryNearWarning; -} - -void CryptPlugWrapper::setSignatureCertificateExpiryNearInterval( int interval ) -{ - _config->signatureCertificateExpiryNearInterval = interval; -} - -int CryptPlugWrapper::signatureCertificateExpiryNearInterval( void ) -{ - return _config->signatureCertificateExpiryNearInterval; -} - -void CryptPlugWrapper::setCACertificateExpiryNearWarning( bool flag ) -{ - _config->cACertificateExpiryNearWarning = flag; -} - -bool CryptPlugWrapper::caCertificateExpiryNearWarning( void ) -{ - return _config->cACertificateExpiryNearWarning; -} - -void CryptPlugWrapper::setCACertificateExpiryNearInterval( int interval ) -{ - _config->cACertificateExpiryNearInterval = interval; -} - -int CryptPlugWrapper::caCertificateExpiryNearInterval( void ) -{ - return _config->cACertificateExpiryNearInterval; -} - -void CryptPlugWrapper::setRootCertificateExpiryNearWarning( bool flag ) -{ - _config->rootCertificateExpiryNearWarning = flag; -} - -bool CryptPlugWrapper::rootCertificateExpiryNearWarning( void ) -{ - return _config->rootCertificateExpiryNearWarning; -} - -void CryptPlugWrapper::setRootCertificateExpiryNearInterval( int interval ) -{ - _config->rootCertificateExpiryNearInterval = interval; -} - -int CryptPlugWrapper::rootCertificateExpiryNearInterval( void ) -{ - return _config->rootCertificateExpiryNearInterval; -} - - - - - -void CryptPlugWrapper::setEncryptionAlgorithm( EncryptionAlgorithm cryptAlg ) -{ - _config->encryptionAlgorithm = cryptAlg; -} - -EncryptionAlgorithm CryptPlugWrapper::encryptionAlgorithm() -{ - return _config->encryptionAlgorithm; -} - -void CryptPlugWrapper::setEncryptEmail( EncryptEmail cryptMode ) -{ - _config->encryptEmail = cryptMode; -} - -EncryptEmail CryptPlugWrapper::encryptEmail() -{ - return _config->encryptEmail; -} - - - - - - -void CryptPlugWrapper::setWarnSendUnencrypted( bool flag ) -{ - _config->warnSendUnencrypted = flag; -} - -bool CryptPlugWrapper::warnSendUnencrypted() -{ - return _config->warnSendUnencrypted; -} - - - - - - - - - -void CryptPlugWrapper::setSaveMessagesEncrypted( bool flag ) -{ - _config->saveMessagesEncrypted = flag; -} - -bool CryptPlugWrapper::saveMessagesEncrypted() -{ - return _config->saveMessagesEncrypted; -} - - - - - - - -void CryptPlugWrapper::setCheckCertificatePath( bool flag ) -{ - _config->checkCertificatePath = flag; -} - -bool CryptPlugWrapper::checkCertificatePath() -{ - return _config->checkCertificatePath; -} - - - - - - - - - - - - -void CryptPlugWrapper::setReceiverCertificateExpiryNearWarning( bool flag ) -{ - _config->receiverCertificateExpiryNearWarning = flag; -} - -bool CryptPlugWrapper::receiverCertificateExpiryNearWarning() -{ - return _config->receiverCertificateExpiryNearWarning; -} - - -void CryptPlugWrapper::setReceiverCertificateExpiryNearWarningInterval( int interval ) -{ - _config->receiverCertificateExpiryNearWarningInterval = interval; -} - -int CryptPlugWrapper::receiverCertificateExpiryNearWarningInterval() -{ - return _config->receiverCertificateExpiryNearWarningInterval; -} - -void CryptPlugWrapper::setCertificateInChainExpiryNearWarning( bool flag ) -{ - _config->certificateInChainExpiryNearWarning = flag; -} - -bool CryptPlugWrapper::certificateInChainExpiryNearWarning() -{ - return _config->certificateInChainExpiryNearWarning; -} - - -void CryptPlugWrapper::setCertificateInChainExpiryNearWarningInterval( int interval ) -{ - _config->certificateInChainExpiryNearWarningInterval = interval; -} - -int CryptPlugWrapper::certificateInChainExpiryNearWarningInterval() -{ - return _config->certificateInChainExpiryNearWarningInterval; -} - -void CryptPlugWrapper::setReceiverEmailAddressNotInCertificateWarning( bool flag ) -{ - _config->receiverEmailAddressNotInCertificateWarning = flag; -} - -bool CryptPlugWrapper::receiverEmailAddressNotInCertificateWarning() -{ - return _config->receiverEmailAddressNotInCertificateWarning; -} - - - - - - - - -void CryptPlugWrapper::setEncryptionUseCRLs( bool flag ) -{ - _config->encryptionUseCRLs = flag; - - /* PENDING(g10) Store this setting in gpgme and use it. If true, - every certificate used for encryption should be checked against - applicable CRLs. - */ -} - -bool CryptPlugWrapper::encryptionUseCRLs() -{ - return _config->encryptionUseCRLs; -} - - -void CryptPlugWrapper::setEncryptionCRLExpiryNearWarning( bool flag ) -{ - _config->encryptionCRLExpiryNearWarning = flag; -} - -bool CryptPlugWrapper::encryptionCRLExpiryNearWarning() -{ - return _config->encryptionCRLExpiryNearWarning; -} - -void CryptPlugWrapper::setEncryptionCRLNearExpiryInterval( int interval ) -{ - _config->encryptionCRLNearExpiryInterval = interval; -} - -int CryptPlugWrapper::encryptionCRLNearExpiryInterval() -{ - return _config->encryptionCRLNearExpiryInterval; -} - - -void CryptPlugWrapper::setCertificateSource( CertificateSource source ) -{ - _config->certificateSource = source; -} - -CertificateSource CryptPlugWrapper::certificateSource() -{ - return _config->certificateSource; -} - - - - - -QString CryptPlugWrapper::libVersion() const { - return _config && _config->libVersion ? QString::fromUtf8( _config->libVersion ) : QString::null ; -} - /* Some multi purpose functions ******************************************/ QString CryptPlugWrapper::errorIdToText( int errId, bool & isPassphraseError ) { const GpgME::Error err( errId ); isPassphraseError = err.isCanceled() || gpgme_err_code( errId ) == GPG_ERR_NO_SECKEY ; // FIXME: more? return QString::fromLocal8Bit( err.asString() ); -#if 0 - switch( errId ){ - case /*GPGME_EOF = */-1: - return(i18n("End of File reached during operation.")); - case /*GPGME_No_Error = */0: - return(i18n("No error.")); - case /*GPGME_General_Error = */1: - return(i18n("General error.")); - case /*GPGME_Out_Of_Core = */2: - return(i18n("Out of core.")); - case /*GPGME_Invalid_Value = */3: - return(i18n("Invalid value.")); - case /*GPGME_Busy = */4: - return(i18n("Engine is busy.")); - case /*GPGME_No_Request = */5: - return(i18n("No request.")); - case /*GPGME_Exec_Error = */6: - return(i18n("Execution error.")); - case /*GPGME_Too_Many_Procs = */7: - return(i18n("Too many processes.")); - case /*GPGME_Pipe_Error = */8: - return(i18n("Pipe error.")); - case /*GPGME_No_Recipients = */9: - return(i18n("No recipients.")); - case /*GPGME_No_Data = */10: - return(i18n("No data.")); - case /*GPGME_Conflict = */11: - return(i18n("Conflict.")); - case /*GPGME_Not_Implemented = */12: - return(i18n("Not implemented.")); - case /*GPGME_Read_Error = */13: - return(i18n("Read error.")); - case /*GPGME_Write_Error = */14: - return(i18n("Write error.")); - case /*GPGME_Invalid_Type = */15: - return(i18n("Invalid type.")); - case /*GPGME_Invalid_Mode = */16: - return(i18n("Invalid mode.")); - case /*GPGME_File_Error = */17: // errno is set in this case. - return(i18n("File error.")); - case /*GPGME_Decryption_Failed = */18: - return(i18n("Decryption failed.")); - case /*GPGME_No_Passphrase = */19: - isPassphraseError = true; - return(i18n("No passphrase.")); - case /*GPGME_Canceled = */20: - isPassphraseError = true; - return(i18n("Canceled.")); - case /*GPGME_Invalid_Key = */21: - isPassphraseError = true; // ### ??? - return(i18n("Invalid key.")); - case /*GPGME_Invalid_Engine = */22: - return(i18n("Invalid engine.")); - case /*GPGME_Invalid_Recipients = */23: - return(i18n("Invalid recipients.")); - default: - return(i18n("Unknown error.")); - } -#endif } /* some special functions ************************************************/ CryptPlugWrapper::CryptPlugWrapper( const QString& name, const QString& libName, const QString& update, bool active ) : Kleo::CryptoBackend::Protocol(), _name( name ), _libName( libName ), _updateURL( update ), _active( active ), _initStatus( InitStatus_undef ), _cp( 0 ), _config( 0 ), _cryptoConfig( 0 ) { const bool ok = initialize( 0, 0 ); assert( ok ); } CryptPlugWrapper::~CryptPlugWrapper() { deinitialize(); } void CryptPlugWrapper::setActive( bool active ) { _active = active; } bool CryptPlugWrapper::active() const { return _active; } bool CryptPlugWrapper::setLibName( const QString& libName ) { bool bOk = ! _cp; // Changing the lib name is only allowed if( bOk ) // when either no initialization took _libName = libName; // place or 'deinitialize()' has been return bOk; // called afterwards. } QString CryptPlugWrapper::libName() const { return _libName; } QString CryptPlugWrapper::protocol() const { if ( _libName.contains( "smime" ) ) - return "smime"; + return "SMIME"; if ( _libName.contains( "openpgp" ) ) - return "openpgp"; + return "OpenPGP"; return QString::null; } void CryptPlugWrapper::setDisplayName( const QString& name ) { _name = name; } QString CryptPlugWrapper::displayName() const { if ( !_name.isEmpty() ) return _name; if ( _libName.contains( "smime" ) ) return "gpgsm"; if ( _libName.contains( "openpgp" ) ) return "gpg"; return i18n("(Unknown Protocol)"); } - -void CryptPlugWrapper::setUpdateURL( const QString& url ) -{ - _updateURL = url; -} - - -QString CryptPlugWrapper::updateURL() const -{ - return _updateURL; -} - -bool CryptPlugWrapper::alwaysEncryptToSelf() { - return true; -} - - -void CryptPlugWrapper::setAlwaysEncryptToSelf( bool enc ) { - mAlwaysEncryptToSelf = enc; -} - bool CryptPlugWrapper::initialize( InitStatus* initStatus, QString* errorMsg ) { if ( _cp ) return true; _initStatus = InitStatus_undef; /* make sure we have a lib name */ if ( _libName.isEmpty() ) { _initStatus = InitStatus_NoLibName; kdDebug(5150) << "No library name was given.\n" << endl; } else { if ( _libName.contains( "smime" ) ) { _cp = new SMIMECryptPlug(); _config = new Config( GPGME_PROTOCOL_CMS ); } else if ( _libName.contains( "openpgp" ) ) { _cp = new OpenPGPCryptPlug(); _config = new Config( GPGME_PROTOCOL_OpenPGP ); } else { _cp = 0; _config = 0; } if ( !_cp ) { _initStatus = InitStatus_LoadError; kdDebug(5150) << "Couldn't create '" << _libName.latin1() << "'" << endl; } else { /* now call the init function */ if( !_cp->initialize() ) { _initStatus = InitStatus_InitError; kdDebug(5150) << "Error while executing function 'initialize' on plugin " << _libName << endl; _lastError = i18n("Error while initializing plugin \"%1\"").arg( _libName ); if ( errorMsg ) *errorMsg = _lastError; delete _cp; _cp = 0; delete _config; _config = 0; } else { _initStatus = InitStatus_Ok; } } } if( initStatus ) *initStatus = _initStatus; return _initStatus == InitStatus_Ok; } void CryptPlugWrapper::deinitialize() { delete _cp; _cp = 0; delete _config; _config = 0; delete _cryptoConfig; _cryptoConfig = 0; } CryptPlugWrapper::InitStatus CryptPlugWrapper::initStatus( QString* errorMsg ) const { if( errorMsg ) *errorMsg = _lastError; return _initStatus; } bool CryptPlugWrapper::hasFeature( Feature flag ) { return _cp && _cp->hasFeature( flag ); } /* normal functions ******************************************************/ - -bool CryptPlugWrapper::signMessage( const char* cleartext, - char** ciphertext, - const size_t* cipherLen, - const char* certificate, - StructuringInfoWrapper& structuring, - int* errId, - char** errTxt ) -{ - return _cp && _cp->signMessage( cleartext, ciphertext, cipherLen, certificate, - &structuring.data, errId, errTxt, - _config->sendCertificates, _config->signatureCompoundMode ); -} - - bool CryptPlugWrapper::checkMessageSignature( char** cleartext, const char* signaturetext, bool signatureIsBinary, int signatureLen, CryptPlug::SignatureMetaData* sigmeta ) { DNBeautifier dnBeautifier( kapp->config(), "DN", "AttributeOrder", "UnknownAttributes" ); return _cp && _cp->checkMessageSignature( cleartext, signaturetext, signatureIsBinary, signatureLen, sigmeta, dnBeautifier.attrOrderChar(), dnBeautifier.unknownAttrsHandlingChar() ); } -bool CryptPlugWrapper::storeCertificatesFromMessage( const char* ciphertext ) -{ - return _cp && _cp->storeCertificatesFromMessage( ciphertext ); -} - - -bool CryptPlugWrapper::findCertificates( const char* addressee, - char** certificates, - int* newSize, - bool secretOnly ) -{ - DNBeautifier dnBeautifier( kapp->config(), - "DN", - "AttributeOrder", - "UnknownAttributes" ); - return _cp && _cp->findCertificates( addressee, - certificates, - newSize, - secretOnly, - dnBeautifier.attrOrderChar(), - dnBeautifier.unknownAttrsHandlingChar() ); -} - -bool CryptPlugWrapper::encryptMessage( const char* cleartext, - const char** ciphertext, - const size_t* cipherLen, - const char* addressee, - StructuringInfoWrapper& structuring, - int* errId, - char** errTxt ) -{ - return _cp && _cp->encryptMessage( cleartext, ciphertext, cipherLen, addressee, - &structuring.data, errId, errTxt ); -} - - -bool CryptPlugWrapper::encryptAndSignMessage( const char* cleartext, - const char** ciphertext, - const char* certificate, - StructuringInfoWrapper& structuring ) -{ - return _cp && _cp->encryptAndSignMessage( cleartext, ciphertext, certificate, - &structuring.data ); -} - - bool CryptPlugWrapper::decryptMessage( const char* ciphertext, bool cipherIsBinary, int cipherLen, char** cleartext, const char* certificate, int* errId, char** errTxt ) { return _cp && _cp->decryptMessage( ciphertext, cipherIsBinary, cipherLen, (const char**)cleartext, certificate, errId, errTxt ); } bool CryptPlugWrapper::decryptAndCheckMessage( const char* ciphertext, bool cipherIsBinary, int cipherLen, char** cleartext, const char* certificate, bool* signatureFound, CryptPlug::SignatureMetaData* sigmeta, int* errId, char** errTxt ) { DNBeautifier dnBeautifier( kapp->config(), "DN", "AttributeOrder", "UnknownAttributes" ); return _cp && _cp->decryptAndCheckMessage( ciphertext, cipherIsBinary, cipherLen, (const char**)cleartext, certificate, signatureFound, sigmeta, errId, errTxt, dnBeautifier.attrOrderChar(), dnBeautifier.unknownAttrsHandlingChar() ); } void CryptPlugWrapper::freeSignatureMetaData( CryptPlug::SignatureMetaData* sigmeta ) { if ( !sigmeta ) return; free( sigmeta->status ); for( int i = 0; i < sigmeta->extended_info_count; ++i ) { free( sigmeta->extended_info[i].creation_time ); free( (void*)sigmeta->extended_info[i].status_text ); free( (void*)sigmeta->extended_info[i].keyid ); free( (void*)sigmeta->extended_info[i].fingerprint ); free( (void*)sigmeta->extended_info[i].algo ); free( (void*)sigmeta->extended_info[i].userid ); free( (void*)sigmeta->extended_info[i].name ); free( (void*)sigmeta->extended_info[i].comment ); if( sigmeta->extended_info[i].emailCount ){ for( int j=0; j < sigmeta->extended_info[i].emailCount; ++j) if( sigmeta->extended_info[i].emailList[j] ) free( (void*)sigmeta->extended_info[i].emailList[j] ); free( (void*)sigmeta->extended_info[i].emailList ); } } free( sigmeta->extended_info ); } -CryptPlugWrapper::CertificateInfoList CryptPlugWrapper::listKeys( const QString& pattern, - bool remote, - bool* truncated ) -{ - CertificateInfoList result; - if ( truncated ) *truncated = false; - if ( !_cp ) - return result; - - CryptPlug::CertIterator * it = _cp->startListCertificates( pattern.utf8().data(), remote ); - if ( !it ) - return result; - - DNBeautifier dnBeautifier( kapp->config(), - "DN", - "AttributeOrder", - "UnknownAttributes" ); - - while ( true ) { - CryptPlug::CertificateInfo* info = 0; - if ( _cp->nextCertificate( it, - &info, - dnBeautifier.attrOrderChar(), - dnBeautifier.unknownAttrsHandlingChar() ) != 0 ) { - kdDebug(5150) << "error" << endl; - break; - } - if ( !info ) - break; - - CryptPlugWrapper::CertificateInfo cpwinfo; - for ( char** ptr = info->userid; *ptr; ++ptr ) - cpwinfo.userid << QString::fromUtf8( *ptr ); - cpwinfo.userid_0_org = QString::fromUtf8( info->userid_0_org ); - - kdDebug(5150) << "CryptPlugWrapper got " << cpwinfo.userid[0] << endl; - cpwinfo.serial = QString::fromUtf8( info->serial ); - kdDebug(5150) << "fpr=" << info->fingerprint << endl; - cpwinfo.fingerprint = QString::fromUtf8( info->fingerprint ); - kdDebug(5150) << "Done getting fpr" << endl; - - cpwinfo.issuer_org = QString::fromUtf8( info->issuer_org ); - cpwinfo.issuer_reord = QString::fromUtf8( info->issuer_reord ); - cpwinfo.chainid = QString::fromUtf8( info->chainid ); - QString caps = QString::fromUtf8( info->caps ); - - cpwinfo.sign = caps.contains('s'); - cpwinfo.encrypt = caps.contains('e'); - cpwinfo.certify = caps.contains('c'); - - cpwinfo.created.setTime_t(info->created ); - cpwinfo.expire.setTime_t( info->expire ); - - cpwinfo.secret = info->secret; - cpwinfo.invalid = info->invalid; - cpwinfo.expired = info->expired; - cpwinfo.disabled = info->disabled; - - for ( CryptPlug::DnPair * a = info->dnarray ; a && a->key&& a->value ; ++a ) - //kdDebug(5150) << "CryptPlugWrapper::listKeys() " << a->key << " = " << a->value << endl; - cpwinfo.dn.push_back( qMakePair( QString::fromUtf8( a->key ), QString::fromUtf8( a->value ) ) ); - - //cpwinfo.dn = dnBeautifier.reorder( cpwinfo.dn ); - - result.push_back( cpwinfo ); - } - - if ( _cp->endListCertificates( it ) != 0 ) - if ( truncated ) *truncated = true; - - return result; -} - GpgME::ImportResult CryptPlugWrapper::importCertificate( const char* data, size_t length ) { if ( !_cp ) return GpgME::ImportResult(); return _cp->importCertificateFromMem( data, length ); } Kleo::KeyListJob * CryptPlugWrapper::keyListJob( bool remote, bool includeSigs, bool validate ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; unsigned int mode = context->keyListMode(); if ( remote ) { mode |= GpgME::Context::Extern; mode &= ~GpgME::Context::Local; } else { mode |= GpgME::Context::Local; mode &= ~GpgME::Context::Extern; } if ( includeSigs ) mode |= GpgME::Context::Signatures; if ( validate ) mode |= GpgME::Context::Validate; context->setKeyListMode( mode ); return new Kleo::QGpgMEKeyListJob( context ); } Kleo::EncryptJob * CryptPlugWrapper::encryptJob( bool armor, bool textmode ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; context->setArmor( armor ); context->setTextMode( textmode ); return new Kleo::QGpgMEEncryptJob( context ); } Kleo::DecryptJob * CryptPlugWrapper::decryptJob() const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; return new Kleo::QGpgMEDecryptJob( context ); } Kleo::SignJob * CryptPlugWrapper::signJob( bool armor, bool textMode ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; context->setArmor( armor ); context->setTextMode( textMode ); return new Kleo::QGpgMESignJob( context ); } Kleo::VerifyDetachedJob * CryptPlugWrapper::verifyDetachedJob( bool textMode ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; context->setTextMode( textMode ); return new Kleo::QGpgMEVerifyDetachedJob( context ); } Kleo::VerifyOpaqueJob * CryptPlugWrapper::verifyOpaqueJob( bool textMode ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; context->setTextMode( textMode ); return new Kleo::QGpgMEVerifyOpaqueJob( context ); } Kleo::KeyGenerationJob * CryptPlugWrapper::keyGenerationJob() const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; return new Kleo::QGpgMEKeyGenerationJob( context ); } Kleo::ImportJob * CryptPlugWrapper::importJob() const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; return new Kleo::QGpgMEImportJob( context ); } Kleo::ExportJob * CryptPlugWrapper::publicKeyExportJob( bool armor ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; context->setArmor( armor ); return new Kleo::QGpgMEExportJob( context ); } Kleo::ExportJob * CryptPlugWrapper::secretKeyExportJob( bool armor ) const { if ( !_cp || _cp->mProtocol != GpgME::Context::CMS ) // fixme: add support for gpg, too return 0; // this operation is not supported by gpgme, so we have to call gpgsm ourselves: return new Kleo::QGpgMESecretKeyExportJob( armor ); } Kleo::RefreshKeysJob * CryptPlugWrapper::refreshKeysJob() const { if ( !_cp || _cp->mProtocol != GpgME::Context::CMS ) // fixme: add support for gpg, too return 0; // this operation is not supported by gpgme, so we have to call gpgsm ourselves: return new Kleo::QGpgMERefreshKeysJob(); } Kleo::DownloadJob * CryptPlugWrapper::downloadJob( bool armor ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; context->setArmor( armor ); // this is the hackish interface for downloading from keyserers currently: context->setKeyListMode( GpgME::Context::Extern ); return new Kleo::QGpgMEDownloadJob( context ); } Kleo::DeleteJob * CryptPlugWrapper::deleteJob() const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; return new Kleo::QGpgMEDeleteJob( context ); } Kleo::SignEncryptJob * CryptPlugWrapper::signEncryptJob( bool armor, bool textMode ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; context->setArmor( armor ); context->setTextMode( textMode ); return new Kleo::QGpgMESignEncryptJob( context ); } Kleo::DecryptVerifyJob * CryptPlugWrapper::decryptVerifyJob( bool textMode ) const { if ( !_cp ) return 0; GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); if ( !context ) return 0; context->setTextMode( textMode ); return new Kleo::QGpgMEDecryptVerifyJob( context ); } diff --git a/certmanager/lib/cryptplugwrapper.h b/certmanager/lib/cryptplugwrapper.h index ff2aa30b1f..1cd851a69e 100644 --- a/certmanager/lib/cryptplugwrapper.h +++ b/certmanager/lib/cryptplugwrapper.h @@ -1,1344 +1,839 @@ /** * cryptplugwrapper.h * * Copyright (c) 2001 Karl-Heinz Zimmer, Klaraelvdalens Datakonsult AB * * This CRYPTPLUG wrapper interface is based on cryptplug.h by * Karl-Heinz Zimmer which is based on 'The Aegypten Plugin API' as * specified by Matthias Kalle Dalheimer, Klaraelvdalens Datakonsult AB, * see file mua-integration.sgml located on Aegypten CVS: * http://www.gnupg.org/aegypten/development.en.html * * purpose: Wrap up all Aegypten Plugin API functions in one C++ class * for usage by KDE programs, e.g. KMail (or KMime, resp.) * * 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; version 2 of the License. * * 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. + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef cryptplugwrapper_h #define cryptplugwrapper_h #include "cryptplug.h" #ifndef LIBKLEOPATRA_NO_COMPAT /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file's source comments are optimized for processing by Doxygen. * * * * To obtain best results please get an updated version of Doxygen, * * for sources and binaries goto http://www.doxygen.org/index.html * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "kleo/cryptobackend.h" #include #include #include #include #include #include class KConfigBase; class QGpgMECryptoConfig; namespace GpgME { class ImportResult; class KeyGenerationResult; } namespace Kleo { class KeyListJob; class EncryptJob; class DecryptJob; class SignJob; class VerifyDetachedJob; class VerifyOpaqueJob; class KeyGenerationJob; class ImportJob; class ExportJob; class DownloadJob; class DeleteJob; class SignEncryptJob; class DecryptVerifyJob; class CryptoConfig; class RefreshKeysJob; + class SpecialJob; } /*! \file cryptplugwrapper.h \brief C++ wrapper for the CRYPTPLUG library API. This CRYPTPLUG wrapper interface is based on cryptplug.h by Karl-Heinz Zimmer which is based on 'The Aegypten Plugin API' as specified by Matthias Kalle Dalheimer, Klaraelvdalens Datakonsult AB, see file mua-integration.sgml located on Aegypten CVS: http://www.gnupg.org/aegypten/development.en.html purpose: Wrap up all Aegypten Plugin API functions in one C++ class for usage by KDE programs, e.g. KMail (or KMime, resp.) CRYPTPLUG is an independent cryptography plug-in API developed for Sphinx-enabeling KMail and Mutt. CRYPTPLUG was designed for the Aegypten project, but it may be used by 3rd party developers as well to design pluggable crypto backends for the above mentioned MUAs. \note All string parameters appearing in this API are to be interpreted as UTF-8 encoded. \see cryptplugwrapper.cpp */ /*! \defgroup groupAdmin Constructor, destructor and setting of 'active' flag The functions in this section are used for general administration of this CRYPTPLUG wrapper class and for maintaining a separate \c active flag for environments using more than one CRYPTPLUG library simultaneously. */ /*! \defgroup groupGeneral Loading and Unloading the Plugin, General Functionality The functions in this section are used for loading and unloading the respective CRYPTPLUG library, for (re)setting it's internal data structures and for retrieving information on the implementation state of all functions covered by the CRYPTPLUG API. */ /*! \defgroup groupDisplay Graphical Display Functionality The functions in this section return stationery that the MUAs can use in order to display security functionality graphically. This can be toolbar icons, shortcuts, tooltips, etc. Not all MUAs will use all this functionality. */ /*! \defgroup groupConfig Configuration Support The functions in this section provide the necessary functionality to configure the security functionality as well as to query configuration settings. Since all configuration settings will not be saved with the plugin, but rather with the MUA, there are also functions to set configuration settings programmatically; these will be used on startup of the plugin when the MUA transfers the configuration values it has read into the plugin. Usually, the functions to query and set the configuration values are not needed for anything but saving to and restoring from configuration files. */ /*! \defgroup groupConfigSign Signature Configuration \ingroup groupConfig The functions in this section provide the functionality to configure signature handling and set and query the signature configuration. */ /*! \defgroup groupConfigCrypt Encryption Configuration \ingroup groupConfig The functions in this section provide the functionality to configure encryption handling and set and query the encryption configuration. \note Whenever the term encryption is used here, it is supposed to mean both encryption and decryption, unless otherwise specified. */ /*! \defgroup groupConfigDir Directory Service Configuration \ingroup groupConfig This section contains messages for configuring the directory service. */ /*! \defgroup groupCertHand Certificate Handling The following methods are used to maintain and query certificates. */ /*! \defgroup groupSignCryptAct Signing and Encrypting Actions This section describes methods and structures used for signing and/or encrypting your mails. */ /*! \defgroup groupSignAct Signature Actions \ingroup groupSignCryptAct This section describes methods that are used for working with signatures. */ /*! \defgroup groupCryptAct Encryption and Decryption \ingroup groupSignCryptAct The following methods are used to encrypt and decrypt email messages. */ /*! \defgroup groupCertAct Certificate Handling Actions The functions in this section provide local certificate management. */ /*! \defgroup groupCRLAct CRL Handling Actions This section describes functions for managing CRLs. */ /*! \defgroup groupAdUsoInterno Important functions to be used by plugin implementors ONLY. This section describes functions that have to be used by plugin implementors but should not be used by plugin users directly. If you are not planning to write your own cryptography plugin you should ignore this section! */ class CryptPlugWrapper; /*! \ingroup groupSignCryptAct \brief This class provides C++ access to the StructuringInfo helper struct that is specified in cryptplug.h to hold information returned by signing and by encrypting functions. Use this information to compose a MIME object containing signed and/or encrypted content (or to build a text frame around your flat non-MIME message body, resp.) \note This class is different from the respective cryptplug.h class because this one takes care for freeing the char** members' memory automatically. You must not call the \c free function for any of it's members - just ignore the advise given in the cryptplug.h documentation! If value returned in \c makeMimeObject is TRUE the text strings returned in \c contentTypeMain and \c contentDispMain and \c contentTEncMain (and, if required, \c content[..]Version and \c bodyTextVersion and \c content[..]Sig) should be used to compose a respective MIME object.
If FALSE the texts returned in \c flatTextPrefix and \c flatTextSeparator and \c flatTextPostfix are to be used instead.
Always either the \c content[..] and \c bodyTextVersion parameters or the \c flatText[..] parameters are holding valid data - never both of them may be used simultaneously as plugins will just ignore the parameters not matching their \c makeMimeObject setting. When creating your MIME object please observe these common rules: \li Parameters named \c contentType[..] and \c contentDisp[..] and \c contentTEnc[..] will return the values for the respective MIME headers 'Content-Type' and 'Content-Disposition' and 'Content-Transfer-Encoding'. The following applies to these parameters: \li The relevant MIME part may only be created if the respective \c contentType[..] parameter is holding a non-zero-length string. If the \c contentType[..] parameter value is invalid or holding an empty string the respective \c contentDisp[..] and \c contentTEnc[..] parameters should be ignored. \li If the respective \c contentDisp[..] or \c contentTEnc[..] parameter is NULL or holding a zero-length string it is up to you whether you want to add the relevant MIME header yourself, but since it in in the responsibility of the plugin implementors to provide you with all necessary 'Content-[..]' header information you should not need to define them if they are not returned by the signing or encrypting function - otherwise this may be considered as a bug in the plugin and you could report the missing MIME header information to the address returned by the \c bugURL() function. If \c makeMultiMime returns FALSE the \c contentTypeMain returned must not be altered but used to specify a single part mime object holding the code bloc, e.g. this is used for 'enveloped-data' single part MIME objects. In this case you should ignore both the \c content[..]Version and \c content[..]Code parameters. If \c makeMultiMime returns TRUE also the following rules apply: \li If \c includeCleartext is TRUE you should include the cleartext as first part of our multipart MIME object, typically this is TRUE when signing mails but FALSE when encrypting. \li The \c contentTypeMain returned typically starts with "multipart/" while providing a "protocol" and a "micalg" parameter: just add an appropriate \c "; boundary=[your \c boundary \c string]" to get the complete Content-Type value to be used for the MIME object embedding both the signed part and the signature part (or - in case of encrypting - the version part and the code part, resp.). \li If \c contentTypeVersion is holding a non-zero-length string an additional MIME part must added immediately before the code part, this version part's MIME headers must have the unaltered values of \c contentTypeVersion and (if they are holding non-zero-length strings) \c contentDispVersion and \c contentTEncVersion, the unaltered contents of \c bodyTextVersion must be it's body. \li The value returned in \c contentTypeCode is specifying the complete Content-Type to be used for this multipart MIME object's signature part (or - in case of encrypting - for the code part following after the version part, resp.), you should not add/change/remove anything here but just use it's unaltered value for specifying the Content-Type header of the respective MIME part. \li The same applies to the \c contentDispCode value: just use it's unaltered value to specify the Content-Disposition header entry of the respective MIME part. \li The same applies to the \c contentTEncCode value: just use it's unaltered value to specify the Content-Transfer-Encoding header of the respective MIME part. If value returned in \c makeMimeObject is FALSE the text strings returned in \c flatTextPrefix and \c flatTextPostfix should be used to build a frame around the cleartext and the code bloc holding the signature (or - in case of encrypting - the encoded data bloc, resp.).
If \c includeCleartext is TRUE this frame should also include the cleartext as first bloc, this bloc should be divided from the code bloc by the contents of \c flatTextSeparator - typically this is used for signing but not when encrypting.
If \c includeCleartext is FALSE you should ignore both the cleartext and the \c flatTextSeparator parameter. How to use StructuringInfoWrapper data in your program: \li To compose a signed message please act as described below. \li For constructing an encrypted message just replace the \c signMessage() call by the respective \c encryptMessage() call and then proceed exactly the same way. \li In any case make sure to free your \c ciphertext when you are done with processing the data returned by the signing (or encrypting, resp.) function. \verbatim char* ciphertext; StructuringInfoWrapper structInf; if( ! signMessage( cleartext, &ciphertext, certificate, structInf ) ) { myErrorDialog( "Error: could not sign the message!" ); } else { if( structInf.data.makeMimeObject ) { // Build the main MIME object. // This is done by // using the header values returned in // structInf.data.contentTypeMain and in // structInf.data.contentDispMain and in // structInf.data.contentTEncMain. .. if( ! structInf.data.makeMultiMime ) { // Build the main MIME object's body. // This is done by // using the code bloc returned in // ciphertext. .. } else { // Build the encapsulated MIME parts. if( structInf.data.includeCleartext ) { // Build a MIME part holding the cleartext. // This is done by // using the original cleartext's headers and by // taking it's original body text. .. } if( structInf.data.contentTypeVersion && 0 < strlen( structInf.data.contentTypeVersion ) ) { // Build a MIME part holding the version information. // This is done by // using the header values returned in // structInf.data.contentTypeVersion and // structInf.data.contentDispVersion and // structInf.data.contentTEncVersion and by // taking the body contents returned in // structInf.data.bodyTextVersion. .. } if( structInf.data.contentTypeCode && 0 < strlen( structInf.data.contentTypeCode ) ) { // Build a MIME part holding the code information. // This is done by // using the header values returned in // structInf.data.contentTypeCode and // structInf.data.contentDispCode and // structInf.data.contentTEncCode and by // taking the body contents returned in // ciphertext. .. } else { // Plugin error! myErrorDialog( "Error: Cryptography plugin returned a main" "Content-Type=Multipart/.. but did not " "specify the code bloc's Content-Type header." "\nYou may report this bug:" "\n" + cryptplug.bugURL() ); } } } else { // Build a plain message body // based on the values returned in structInf. // Note: We do _not_ insert line breaks between the parts since // it is the plugin job to provide us with ready-to-use // texts containing all necessary line breaks. strcpy( myMessageBody, structInf.data.plainTextPrefix ); if( structInf.data.includeCleartext ) { strcat( myMessageBody, cleartext ); strcat( myMessageBody, structInf.data.plainTextSeparator ); } strcat( myMessageBody, *ciphertext ); strcat( myMessageBody, structInf.data.plainTextPostfix ); } // free the memory that was allocated // for the ciphertext free( ciphertext ); } \endverbatim \see signMessage, encryptMessage, encryptAndSignMessage */ class StructuringInfoWrapper { public: StructuringInfoWrapper( CryptPlugWrapper* wrapper ); ~StructuringInfoWrapper(); void reset(); CryptPlug::StructuringInfo data; private: void initMe(); void freeMe(); bool _initDone; CryptPlugWrapper* _wrapper; }; /*! \brief This class provides C++ access to the CRYPTPLUG API. */ class KDE_EXPORT CryptPlugWrapper : public Kleo::CryptoBackend::Protocol { public: static QString errorIdToText( int errId, bool & isPassphraseError ); /*! \ingroup groupGeneral \brief Current initialization state. This flag holding status of previous call of initialize function. If initialize was not called before return value will be \c CryptPlugInit_undef. \sa initStatus, initialize */ typedef enum { InitStatus_undef = 0, InitStatus_Ok = 1, InitStatus_NoLibName = 2, InitStatus_LoadError = 0x1000, InitStatus_InitError = 0x2000 } InitStatus; /*! \ingroup groupSignAct \brief Flags used to compose the SigStatusFlags value. This status flags are used to compose the SigStatusFlags value returned in \c SignatureMetaDataExtendedInfo after trying to verify a signed message part's signature status. The normal flags may not be used together with the special SigStatus_NUMERICAL_CODE flag. When finding the special SigStatus_NUMERICAL_CODE flag in a SigStatusFlags value you can obtain the respective error code number by substracting the SigStatusFlags value by SigStatus_NUMERICAL_CODE: this is used to transport special status information NOT matching any of the normal predefined status codes. \note to PlugIn developers: Implementations of the CryptPlug API should try to express their signature states by bit-wise OR'ing the normal SigStatusFlags values. Using the SigStatus_NUMERICAL_CODE flag should only be used as for exceptional situations where no other flag(s) could be used. By using the normal status flags your PlugIn's users will be told an understandable description of the status - when using (SigStatus_NUMERICAL_CODE + internalCode) they will only be shown the respective code number and have to look into your PlugIn's manual to learn about it's meaning... */ enum { SigStatus_UNKNOWN = 0x0000, SigStatus_VALID = SigStat_VALID, SigStatus_GREEN = SigStat_GREEN, SigStatus_RED = SigStat_RED, SigStatus_KEY_REVOKED = SigStat_KEY_REVOKED, SigStatus_KEY_EXPIRED = SigStat_KEY_EXPIRED, SigStatus_SIG_EXPIRED = SigStat_SIG_EXPIRED, SigStatus_KEY_MISSING = SigStat_KEY_MISSING, SigStatus_CRL_MISSING = SigStat_CRL_MISSING, SigStatus_CRL_TOO_OLD = SigStat_CRL_TOO_OLD, SigStatus_BAD_POLICY = SigStat_BAD_POLICY, SigStatus_SYS_ERROR = SigStat_SYS_ERROR, SigStatus_NUMERICAL_CODE = 0x8000 /* An other error occurred. */ }; typedef unsigned long SigStatusFlags; enum { CertStatus_EXPIRES_NEVER = CRYPTPLUG_CERT_DOES_NEVER_EXPIRE }; /*! \ingroup groupAdmin \brief Constructor of CRYPTPLUG wrapper class. This constructor does not call the initialize() method but just stores some information for later use. \note Since more than one crypto plug-in might be specified (using multiple instances of the warpper class) it is necessary to set \c active at least one them. Only wrappers that have been activated may be initialized or configured or used to perform crypto actions. \param name The external name that is visible in lists, messages, etc. \param libName Complete path+name of CRYPTPLUG library that is to be used by this instance of CryptPlugWrapper. \param update the URL from where updates can be downloaded \param active Specify whether the relative library is to be used or not. \sa ~CryptPlugWrapper, setActive, active, initialize, deinitialize \sa initStatus */ CryptPlugWrapper( const QString& name=QString::null, const QString& libName=QString::null, const QString& update=QString::null, bool active = false ); /*! \ingroup groupAdmin \brief Destructor of CRYPTPLUG wrapper class. This destructor does call the deinitialize() method in case this was not done by explicitly calling it before. \sa deinitialize, initialize, CryptPlugWrapper(), setActive, active \sa */ ~CryptPlugWrapper(); QString protocol() const; QString name() const { return protocol(); } /*! \ingroup groupAdmin \brief Set this CRYPTPLUG wrapper's internal \c active flag. Since more than one crypto plug-in might be specified (using multiple instances of the warpper class) it is necessary to set \c active at least one them. Only wrappers that have been activated may be initialized or configured or used to perform crypto actions. This flag may be set in the constructor or by calling setActive(). \note Deactivating does not mean resetting the internal structures - if just prevents the normal functions from being called erroneously. When deactivated only the following functions are operational: constructor , destructor , setActive , active, setLibName , libName , initStatus; calling other functions will be ignored and their return values will be undefined. \param active Specify whether the relative library is to be used or not. \sa active, CryptPlugWrapper(), ~CryptPlugWrapper \sa deinitialize, initialize, initStatus */ void setActive( bool active ); /*! \ingroup groupAdmin \brief Returns this CRYPTPLUG wrapper's internal \c active flag. \return whether the relative library is to be used or not. \sa setActive */ bool active() const; /*! \ingroup groupAdmin \brief Set the CRYPTPLUG library name. Complete path+name of CRYPTPLUG library that is to be used by this instance of CryptPlugWrapper. This name may be set in the constructor or by calling setLibName(). \note Setting/changing the library name may only be done when the initStatus() is not \c InitStatus_Ok. If you want to change the name of the library after successfully having called initialize() please make sure to unload it by calling the deinitialize() function. \param libName libName Complete path+name of CRYPTPLUG library that is to be used by this CryptPlugWrapper. \return whether the library name could be changed; library name can only be changed when library is not initialized - see above 'note'. \sa libName, CryptPlugWrapper(), ~CryptPlugWrapper \sa deinitialize, initialize, initStatus */ bool setLibName( const QString& libName ); /*! \ingroup groupAdmin \brief Returns the CRYPTPLUG library name. \return the complete path+name of CRYPTPLUG library that is to be used by this instance of CryptPlugWrapper. \sa setLibName */ QString libName() const; /*! \ingroup groupAdmin \brief Specifies the external name that is visible in lists, messages, etc. */ void setDisplayName( const QString& name ); /*! \ingroup groupAdmin \brief Returns the external name. \return the external name used for display purposes */ QString displayName() const; - - /*! \ingroup groupAdmin - \brief Returns the version string of the CRYPTPLUG library - specified in the constructor. - - \return the version string of the CRYPTPLUG library - specified in the constructor - */ - QString libVersion() const; - - /*! \ingroup groupAdmin - \brief Returns the update URL. - \return the update URL - */ - QString updateURL() const; - - /*! \ingroup groupAdmin - \brief Specifies the update URL. - */ - void setUpdateURL( const QString& url ); - private: /*! \ingroup groupGeneral \brief This function does two things: (a) load the lib and (b) set up all internal structures. The method tries to load the CRYPTPLUG library specified in the constructor and returns \c true if the both loading and initializing the internal data structures was successful and \c false otherwise. Before this function is called, no other plugin functions should be called; the behavior is undefined in this case, this rule does not apply to the functions \c setActive() and \c setLibName(). \param initStatus will receive the resulting InitStatus if not NULL \param errorMsg will receive the system error message if not NULL \sa initStatus, deinitialize, CryptPlugWrapper(), ~CryptPlugWrapper \sa setActive, active */ bool initialize( InitStatus* initStatus, QString* errorMsg ); public: /*! \ingroup groupGeneral \brief This function unloads the lib and frees all internal structures. After this function has been called, no other plugin functions should be called; the behavior is undefined in this case. \note Deinitializing sets the internal initStatus value back to \c InitStatus_undef. \sa initStatus, initialize, CryptPlugWrapper, ~CryptPlugWrapper \sa setActive, active */ void deinitialize(); /*! \ingroup groupGeneral \brief Returns this CRYPTPLUG wrapper's initialization state. \param errorMsg receives the last system error message, this value should be ignored if InitStatus value equals \c InitStatus_Ok. \return whether the relative library was loaded and initialized correctly \sa initialize, deinitialize, CryptPlugWrapper(), ~CryptPlugWrapper \sa setActive, active */ InitStatus initStatus( QString* errorMsg ) const; /*! \ingroup groupGeneral \brief This function returns \c true if the specified feature is available in the plugin, and \c false otherwise. Not all plugins will support all features; a complete Sphinx implementation will support all features contained in the enum, however. \note In case this function cannot be executed the system's error message may be retrieved by calling initStatus( QString* ). \return whether the relative feature is implemented or not */ bool hasFeature( Feature ); - /*! \ingroup groupGeneral - \brief This function returns a URL to be used for reporting a bug that - you found (or suspect, resp.) in this cryptography plug-in. - - If the plugins for some reason cannot specify an appropriate URL you - should at least be provided with a text giving you some advise on - how to report a bug. - - \note This function must be implemented by each plug-in using - this API specification. - */ - const char* bugURL(); - - - /*! \ingroup groupConfigSign - \brief Sets the algorithm used for signing. - */ - void setSignatureAlgorithm( SignatureAlgorithm ); - - /*! \ingroup groupConfigSign - \brief Returns the algorithm used for signing. - */ - SignatureAlgorithm signatureAlgorithm(); - - /*! \ingroup groupConfigSign - \brief Specifies whether a warning should be emitted when the user - tries to send an email message unsigned. - */ - void setWarnSendUnsigned( bool ); - - - /*! \ingroup groupConfigSign - \brief Returns whether a warning should be emitted when the user - tries to send an email message unsigned. - */ - bool warnSendUnsigned(); - - - /*! \ingroup groupConfigSign - \brief Specifies whether a warning should be emitted if the - signature certificate expires in the near future. - */ - void setSignatureCertificateExpiryNearWarning( bool ); - - /*! \ingroup groupConfigSign - \brief Returns whether a warning should be emitted if - the signature certificate expires in the near future. - */ - bool signatureCertificateExpiryNearWarning( void ); - - /*! \ingroup groupConfigSign - \brief Specifies the number of days which a signature certificate must - be valid before it is considered to expire in the near - future. - */ - void setSignatureCertificateExpiryNearInterval( int ); - - /*! \ingroup groupConfigSign - \brief Returns the number of days which a signature certificate must - be valid before it is considered to expire in the near - future. - */ - int signatureCertificateExpiryNearInterval( void ); - - /*! \ingroup groupConfigSign - \brief Specifies whether a warning should be emitted if the - CA certificate expires in the near future. - */ - void setCACertificateExpiryNearWarning( bool ); - - /*! \ingroup groupConfigSign - \brief Returns whether a warning should be emitted if - the CA certificate expires in the near future. - */ - bool caCertificateExpiryNearWarning( void ); - - /*! \ingroup groupConfigSign - \brief Specifies the number of days which a CA certificate must - be valid before it is considered to expire in the near - future. - */ - void setCACertificateExpiryNearInterval( int ); - - /*! \ingroup groupConfigSign - \brief Returns the number of days which a CA certificate must - be valid before it is considered to expire in the near - future. - */ - int caCertificateExpiryNearInterval( void ); - - /*! \ingroup groupConfigSign - \brief Specifies whether a warning should be emitted if the - root certificate expires in the near future. - */ - void setRootCertificateExpiryNearWarning( bool ); - - /*! \ingroup groupConfigSign - \brief Returns whether a warning should be emitted if - the root certificate expires in the near future. - */ - bool rootCertificateExpiryNearWarning( void ); - - /*! \ingroup groupConfigSign - \brief Specifies the number of days which a root certificate must - be valid before it is considered to expire in the near - future. - */ - void setRootCertificateExpiryNearInterval( int ); - - /*! \ingroup groupConfigSign - \brief Returns the number of days which a signature certificate must - be valid before it is considered to expire in the near - future. - */ - int rootCertificateExpiryNearInterval( void ); - - - /*! \ingroup groupConfigCrypt - \brief Sets the algorithm used for encrypting. - */ - void setEncryptionAlgorithm( EncryptionAlgorithm ); - - /*! \ingroup groupConfigCrypt - \brief Returns the algorithm used for encrypting. - */ - EncryptionAlgorithm encryptionAlgorithm(); - - /*! \ingroup groupConfigCrypt - \brief Specifies whether email should be automatically - encrypted, encrypted after confirmation, encrypted after - confirmation for each part or not encrypted at all. - */ - void setEncryptEmail( EncryptEmail ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether email should be automatically - encrypted, encrypted after confirmation, encrypted after - confirmation for each part or not encrypted at all. - */ - EncryptEmail encryptEmail(); - - /*! \ingroup groupConfigCrypt - \brief Specifies whether a warning should be emitted when the user - tries to send an email message unencrypted. - */ - void setWarnSendUnencrypted( bool ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether a warning should be emitted when the user - tries to send an email message unencrypted. - */ - bool warnSendUnencrypted(); - - /*! \ingroup groupConfigCrypt - \brief Specifies whether messages outgoing in encrypted form should - also be encrypted using the sender's certificate to enable her/him - to read these messages later. - */ - void setAlwaysEncryptToSelf( bool ) KDE_DEPRECATED; - - /*! \ingroup groupConfigCrypt - \brief Returns whether messages outgoing in encrypted form should - also be encrypted using the sender's certificate to enable her/him - to read these messages later. - */ - bool alwaysEncryptToSelf() KDE_DEPRECATED; - - - /*! \ingroup groupConfigCrypt - \brief Specifies whether encrypted email messages should be - stored encrypted or decrypted. - */ - void setSaveMessagesEncrypted( bool ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether encrypted email messages should be stored - encrypted or decrypted. - */ - bool saveMessagesEncrypted(); - - /*! \ingroup groupConfigCrypt - \brief Specifies whether the certificate path should be checked - during encryption. - */ - void setCheckCertificatePath( bool ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether the certificate path should be checked - during encryption. - */ - bool checkCertificatePath(); - - - /*! \ingroup groupConfigCrypt - \brief Specifies whether a warning should be emitted if the - certificate of the receiver expires in the near future. - */ - void setReceiverCertificateExpiryNearWarning( bool ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether a warning should be emitted if the - certificate of the receiver expires in the near future. - */ - bool receiverCertificateExpiryNearWarning(); - - /*! \ingroup groupConfigCrypt - \brief Specifies the number of days which a receiver certificate - must be valid before it is considered to expire in the near future. - */ - void setReceiverCertificateExpiryNearWarningInterval( int ); - - /*! \ingroup groupConfigCrypt - \brief Returns the number of days which a receiver certificate - must be valid before it is considered to expire in the near future. - */ - int receiverCertificateExpiryNearWarningInterval(); - - - /*! \ingroup groupConfigCrypt - \brief Specifies whether a warning should be emitted if - a certificate in the chain expires in the near future. - */ - void setCertificateInChainExpiryNearWarning( bool ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether a warning should be emitted if a - certificate in the chain expires in the near future. - */ - bool certificateInChainExpiryNearWarning(); - - /*! \ingroup groupConfigCrypt - \brief Specifies the number of days which a certificate in the chain - must be valid before it is considered to expire in the near future. - */ - void setCertificateInChainExpiryNearWarningInterval( int ); - - /*! \ingroup groupConfigCrypt - \brief Returns the number of days which a certificate in the chain - must be valid before it is considered to expire in the near future. - */ - int certificateInChainExpiryNearWarningInterval(); - - - /*! \ingroup groupConfigCrypt - \brief Specifies whether a warning is emitted if the email address - of the receiver does not appear in the certificate. - */ - void setReceiverEmailAddressNotInCertificateWarning( bool ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether a warning is emitted if the email address - of the receiver does not appear in the certificate. - */ - bool receiverEmailAddressNotInCertificateWarning(); - - - /*! \ingroup groupConfigCrypt - \brief Specifies whether certificate revocation lists should - be used. - */ - void setEncryptionUseCRLs( bool ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether certificate revocation lists should - be used. - */ - bool encryptionUseCRLs(); - - /*! \ingroup groupConfigCrypt - \brief Specifies whether a warning should be emitted if any - of the certificates involved in the signing process - expires in the near future. - */ - void setEncryptionCRLExpiryNearWarning( bool ); - - /*! \ingroup groupConfigCrypt - \brief Returns whether a warning should be emitted if any - of the certificates involved in the signing process - expires in the near future. - */ - bool encryptionCRLExpiryNearWarning(); - - /*! \ingroup groupConfigCrypt - \brief Specifies the number of days which a certificate must - be valid before it is considered to expire in the near - future. - */ - void setEncryptionCRLNearExpiryInterval( int ); - - /*! \ingroup groupConfigCrypt - \brief Returns the number of days which a certificate must - be valid before it is considered to expire in the near - future. - */ - int encryptionCRLNearExpiryInterval(); - - - /*! \ingroup groupConfigDir - \brief Specifies whether certificates should be retrieved - from a directory server, only locally, or both. - */ - void setCertificateSource( CertificateSource ); - - /*! \ingroup groupConfigDir - \brief Returns whether certificates should be retrieved - from a directory server, only locally, or both. - */ - CertificateSource certificateSource(); - - - /*! \ingroup groupSignAct - \brief Signs a message \c cleartext and returns - in \c *ciphertext the signature data bloc that - is to be added to the message. The length returned - in \c *cipherLen tells you the size (==amount of bytes) - of the ciphertext, if the structuring information - would return with contentTEncCode set to "base64" - the ciphertext might contain a char 0x00 - and has to be converted into base64 before sending. - - The signature role is specified by \c certificate. - If \c certificate is \c NULL, the default certificate is used. - - If the message could be signed, the function returns - \c true, otherwise - \c false. - - Use the StructuringInfoWrapper data returned in parameter - \c structuring to find out how to build the respective - MIME object (or the plain text message body, resp.). - - \note The function allocates memory for the \c *ciphertext, so - make sure you set free that memory when no longer needing - it (as shown in example code provided with documentation - of the class \c StructuringInfoWrapper). - - \note The function also does not use a pure StructuringInfo* struct - parameter (as defined in cryptplug.h) but a convenient - StructuringInfoWrapper& class parameter. - Therefore you must not call the \c free_StructuringInfo() - function: all memory that will be occupied for structuring info - by the signing function will be freed automatically by the - StructuringInfoWrapper's destructor. - - \see StructuringInfoWrapper - */ - bool signMessage( const char* cleartext, - char** ciphertext, - const size_t* cipherLen, - const char* certificate, - StructuringInfoWrapper& structuring, - int* errId, - char** errTxt ); - - /* \ingroup groupSignAct * Frees the members of a signature meta data struct, but not the * signature meta data struct itself as this could be allocated on * the stack. */ void freeSignatureMetaData( CryptPlug::SignatureMetaData* ); - /*! \ingroup groupSignAct \brief Checks whether the signature of a message is valid. \c cleartext must never be 0 but be a valid pointer. If \c *cleartext > 0 then **cleartext specifies the message text that was signed and \c signaturetext is the signature itself. If \c *cleartext == 0 is an empty string then \c signaturetext is supposed to contain an opaque signed message part. After checking the data and verifying the signature the cleartext of the message will be returned in \c cleartext. The user must free the respective memory occupied by *cleartext. Depending on the configuration, MUAs might not need to use this. If \c sigmeta is non-null, the \c SignatureMetaData object pointed to will contain meta information about the signature after the function call. */ bool checkMessageSignature( char** cleartext, const char* signaturetext, bool signatureIsBinary, int signatureLen, CryptPlug::SignatureMetaData* sigmeta ); - /*! \ingroup groupSignAct - \brief Stores the certificates that follow with the message - \c ciphertext locally. - */ - bool storeCertificatesFromMessage( const char* ciphertext ); - - - /*! \ingroup groupCryptAct - \brief Find all certificate for a given addressee. - - NOTE: The certificate parameter must point to a not-yet allocated - char*. The function will allocate the memory needed and - return the size in newSize. - If secretOnly is true, only secret keys are returned. - */ - bool findCertificates( const char* addressee, - char** certificates, - int* newSize, - bool secretOnly ); - - /*! \ingroup groupCryptAct - \brief Encrypts an email message in - \c cleartext according to the \c addressee and - the current settings (algorithm, etc.) and - returns the encoded data bloc in \c *ciphertext. - The length returned in \c *cipherLen tells you the - size (==amount of bytes) of the ciphertext, if the - structuring information would return with - contentTEncCode set to "base64" the ciphertext - might contain a char 0x00 and has to be converted - into base64 before sending. - - If the message could be encrypted, the function returns - \c true, otherwise - \c false. - - Use the StructuringInfoWrapper data returned in parameter - \c structuring to find out how to build the respective - MIME object (or the plain text message body, resp.). - - \note The function allocates memory for the \c *ciphertext, so - make sure you set free that memory when no longer needing - it (as shown in example code provided with documentation - of the class \c StructuringInfoWrapper). - - \note The function also does not use a pure StructuringInfo* struct - parameter (as defined in cryptplug.h) but a convenient - StructuringInfoWrapper& class parameter. - Therefore you must not call the \c free_StructuringInfo() - function: all memory that will be occupied for structuring info - by the signing function will be freed automatically by the - StructuringInfoWrapper's destructor. - - \see StructuringInfoWrapper - */ - bool encryptMessage( const char* cleartext, - const char** ciphertext, - const size_t* cipherLen, - const char* addressee, - StructuringInfoWrapper& structuring, - int* errId, - char** errTxt ); - - /*! \ingroup groupCryptAct - \brief Combines the functionality of - \c encryptMessage() and - \c signMessage(). - - If \c certificate is \c NULL, - the default certificate will be used. - - If the message could be signed and encrypted, the function returns - \c true, otherwise - \c false. - - Use the StructuringInfoWrapper data returned in parameter \c structuring - to find out how to build the respective MIME object (or the plain - text message body, resp.). - - \note The function allocates memory for the \c *ciphertext, so - make sure you set free that memory when no longer needing - it (as shown in example code provided with documentation - of the class \c StructuringInfoWrapper). - - \note The function also does not use a pure StructuringInfo* struct - parameter (as defined in cryptplug.h) but a convenient - StructuringInfoWrapper& class parameter. - Therefore you must not call the \c free_StructuringInfo() - function: all memory that will be occupied for structuring info - by the signing function will be freed automatically by the - StructuringInfoWrapper's destructor. - - \see StructuringInfoWrapper - */ - bool encryptAndSignMessage( const char* cleartext, - const char** ciphertext, - const char* certificate, - StructuringInfoWrapper& structuring ); - /*! \ingroup groupCryptAct \brief Tries to decrypt an email message \c ciphertext and returns the decrypted message in \c cleartext. The \c certificate is used for decryption. If the message could be decrypted, the function returns \c true, otherwise \c false. */ bool decryptMessage( const char* ciphertext, bool cipherIsBinary, int cipherLen, char** cleartext, const char* certificate, int* errId, char** errTxt ); /*! \ingroup groupCryptAct \brief Combines the functionality of \c checkMessageSignature() and \c decryptMessage(). If \c certificate is \c NULL, the default certificate will be used. If \c sigmeta is non-null, the \c SignatureMetaData object pointed to will contain meta information about the signature after the function call. */ bool decryptAndCheckMessage( const char* ciphertext, bool cipherIsBinary, int cipherLen, char** cleartext, const char* certificate, bool* signatureFound, CryptPlug::SignatureMetaData* sigmeta, int* errId, char** errTxt ); - - struct CertificateInfo { - QStringList userid; - QString userid_0_org; - QString serial; - QString fingerprint; - - QString issuer_org; - QString issuer_reord; - QString chainid; - - QDateTime created; - QDateTime expire; - - bool secret : 1; - bool invalid : 1; - bool expired : 1; - bool disabled : 1; - - bool sign : 1; - bool encrypt : 1; - bool certify : 1; - - QValueList< QPair > dn; - }; - - typedef QValueList CertificateInfoList; - - CertificateInfoList listKeys(const QString& pattern = QString::null, - bool remote = false, - bool *truncated = 0 ); - Kleo::KeyListJob * keyListJob( bool remote=false, bool includeSigs=false, bool validate=true ) const; Kleo::EncryptJob * encryptJob( bool armor=false, bool textmode=false ) const; Kleo::DecryptJob * decryptJob() const; Kleo::SignJob * signJob( bool armor=false, bool textMode=false ) const; Kleo::VerifyDetachedJob * verifyDetachedJob( bool textmode=false) const; Kleo::VerifyOpaqueJob * verifyOpaqueJob( bool textmode=false ) const; Kleo::KeyGenerationJob * keyGenerationJob() const; Kleo::ImportJob * importJob() const; Kleo::ExportJob * publicKeyExportJob( bool armor=false ) const; Kleo::ExportJob * secretKeyExportJob( bool armor=false ) const; Kleo::DownloadJob * downloadJob( bool armor=false ) const; Kleo::DeleteJob * deleteJob() const; Kleo::SignEncryptJob * signEncryptJob( bool armor=false, bool textmode=false ) const; Kleo::DecryptVerifyJob * decryptVerifyJob( bool textmode=false ) const; Kleo::RefreshKeysJob * refreshKeysJob() const; + Kleo::SpecialJob * specialJob( const char *, const QMap & ) const { return 0; } + GpgME::ImportResult importCertificate( const char* data, size_t length ); CryptPlug * cryptPlug() const { return _cp; } private: QString _name; QString _libName; QString _updateURL; bool _active; InitStatus _initStatus; QString _lastError; CryptPlug* _cp; // local parameters without representation in cryptplug.h bool mAlwaysEncryptToSelf; class Config; Config * _config; QGpgMECryptoConfig * _cryptoConfig; }; #endif // !LIBKLEOPATRA_NO_COMPAT #endif // cryptplugwrapper_h diff --git a/certmanager/lib/cryptplugwrapperlist.cpp b/certmanager/lib/cryptplugwrapperlist.cpp index dcf4c7400b..3ff38ddd8c 100644 --- a/certmanager/lib/cryptplugwrapperlist.cpp +++ b/certmanager/lib/cryptplugwrapperlist.cpp @@ -1,34 +1,34 @@ /* -*- c++ -*- CRYPTPLUG - an independent cryptography plug-in API. CryptPlugWrapperList holds any number of crypto plug-ins. Copyright (C) 2001 by Klarlvdalens Datakonsult AB CRYPTPLUG is free software; you can redistribute it and/or modify it under the terms of GNU General Public License as published by the Free Software Foundation; version 2 of the License. CRYPTPLUG 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifdef HAVE_CONFIG_H #include #endif #include "cryptplugwrapperlist.h" CryptPlugWrapper * CryptPlugWrapperList::findForLibName( const QString & libName ) const { for ( QPtrListIterator it( *this ) ; it.current() ; ++it ) if ( (*it)->libName().find( libName, 0, false ) >= 0 ) return *it; return 0; } diff --git a/certmanager/lib/cryptplugwrapperlist.h b/certmanager/lib/cryptplugwrapperlist.h index 1d5946201c..3fab5799c1 100644 --- a/certmanager/lib/cryptplugwrapperlist.h +++ b/certmanager/lib/cryptplugwrapperlist.h @@ -1,37 +1,37 @@ /* -*- Mode: C++ -*- CRYPTPLUG - an independent cryptography plug-in API. CryptPlugWrapperList holds any number of crypto plug-ins. Copyright (C) 2001,2004 by Klarlvdalens Datakonsult AB CRYPTPLUG is free software; you can redistribute it and/or modify it under the terms of GNU General Public License as published by the Free Software Foundation; version 2 of the License. CRYPTPLUG 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef __CRYPTPLUGWRAPPERLIST_H__ #define __CRYPTPLUGWRAPPERLIST_H__ #include "cryptplugwrapper.h" #include class CryptPlugWrapperList : public QPtrList { public: CryptPlugWrapper * findForLibName( const QString & libName ) const; }; typedef QPtrListIterator CryptPlugWrapperListIterator; #endif diff --git a/certmanager/lib/kleo/Makefile.am b/certmanager/lib/kleo/Makefile.am index bd6e4ddbda..0465bb2daf 100644 --- a/certmanager/lib/kleo/Makefile.am +++ b/certmanager/lib/kleo/Makefile.am @@ -1,36 +1,37 @@ INCLUDES = -I$(top_srcdir)/libkdenetwork \ -I$(top_srcdir)/certmanager/lib \ $(GPGME_CFLAGS) $(all_includes) noinst_LTLIBRARIES = libkleopatra_core.la libkleopatra_core_la_SOURCES = \ + cryptobackend.cpp \ cryptobackendfactory.cpp \ enum.cpp \ dn.cpp \ job.cpp \ \ multideletejob.cpp \ hierarchicalkeylistjob.cpp \ \ kconfigbasedkeyfilter.cpp \ keyfiltermanager.cpp kleodir = $(includedir)/kleo kleo_HEADERS = \ enum.h \ cryptobackend.h \ cryptobackendfactory.h \ cryptoconfig.h \ dn.h \ job.h \ keylistjob.h keygenerationjob.h importjob.h exportjob.h downloadjob.h deletejob.h \ encryptjob.h decryptjob.h signjob.h verifydetachedjob.h verifyopaquejob.h \ decryptverifyjob.h signencryptjob.h refreshkeysjob.h \ multideletejob.h \ hierarchicalkeylistjob.h \ \ keyfilter.h \ keyfiltermanager.h METASOURCES = AUTO diff --git a/kleopatra/lib/kleo/cryptobackend.cpp b/certmanager/lib/kleo/cryptobackend.cpp similarity index 100% rename from kleopatra/lib/kleo/cryptobackend.cpp rename to certmanager/lib/kleo/cryptobackend.cpp diff --git a/certmanager/lib/kleo/cryptobackend.h b/certmanager/lib/kleo/cryptobackend.h index 08454cfaf0..8d1f42e704 100644 --- a/certmanager/lib/kleo/cryptobackend.h +++ b/certmanager/lib/kleo/cryptobackend.h @@ -1,105 +1,119 @@ /* kleo/cryptobackend.h This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB + Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_CRYPTOBACKEND_H__ #define __KLEO_CRYPTOBACKEND_H__ namespace Kleo { class CryptoConfig; class KeyListJob; class KeyGenerationJob; class ImportJob; class ExportJob; class DownloadJob; class DeleteJob; class EncryptJob; class DecryptJob; class SignJob; class VerifyDetachedJob; class VerifyOpaqueJob; class SignEncryptJob; class DecryptVerifyJob; class RefreshKeysJob; + class SpecialJob; } class QString; +class QVariant; +template class QMap; namespace Kleo { class CryptoBackend { public: class Protocol; + static const char OpenPGP[]; + static const char SMIME[]; + virtual ~CryptoBackend() {} virtual QString name() const = 0; virtual QString displayName() const = 0; virtual bool checkForOpenPGP( QString * reason=0 ) const = 0; virtual bool checkForSMIME( QString * reason=0 ) const = 0; + virtual bool checkForProtocol( const char * name, QString * reason=0 ) const = 0; virtual bool supportsOpenPGP() const = 0; virtual bool supportsSMIME() const = 0; + virtual bool supportsProtocol( const char * name ) const = 0; virtual CryptoConfig * config() const = 0; + virtual Protocol * openpgp() const = 0; virtual Protocol * smime() const = 0; + virtual Protocol * protocol( const char * name ) const = 0; + + virtual const char * enumerateProtocols( int i ) const = 0; }; class CryptoBackend::Protocol { public: virtual ~Protocol() {} virtual QString name() const = 0; virtual QString displayName() const = 0; virtual KeyListJob * keyListJob( bool remote=false, bool includeSigs=false, bool validate=false ) const = 0; virtual EncryptJob * encryptJob( bool armor=false, bool textmode=false ) const = 0; virtual DecryptJob * decryptJob() const = 0; virtual SignJob * signJob( bool armor=false, bool textMode=false ) const = 0; virtual VerifyDetachedJob * verifyDetachedJob( bool textmode=false) const = 0; virtual VerifyOpaqueJob * verifyOpaqueJob( bool textmode=false ) const = 0; virtual KeyGenerationJob * keyGenerationJob() const = 0; virtual ImportJob * importJob() const = 0; virtual ExportJob * publicKeyExportJob( bool armor=false ) const = 0; virtual ExportJob * secretKeyExportJob( bool armor=false ) const = 0; virtual DownloadJob * downloadJob( bool armor=false ) const = 0; virtual DeleteJob * deleteJob() const = 0; virtual SignEncryptJob * signEncryptJob( bool armor=false, bool textMode=false ) const = 0; virtual DecryptVerifyJob * decryptVerifyJob( bool textmode=false ) const = 0; virtual RefreshKeysJob * refreshKeysJob() const = 0; + + virtual SpecialJob * specialJob( const char * type, const QMap & args ) const = 0; }; } #endif // __KLEO_CRYPTOBACKEND_H__ diff --git a/certmanager/lib/kleo/cryptobackendfactory.cpp b/certmanager/lib/kleo/cryptobackendfactory.cpp index d9a7671bab..c56a7096f6 100644 --- a/certmanager/lib/kleo/cryptobackendfactory.cpp +++ b/certmanager/lib/kleo/cryptobackendfactory.cpp @@ -1,182 +1,275 @@ /* cryptobackendfactory.cpp This file is part of libkleopatra, the KDE key management library - Copyright (c) 2001,2004 Klarlvdalens Datakonsult AB + Copyright (c) 2001,2004,2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "cryptobackendfactory.h" #include +#if 0 // disabled for kde-3.3 #include #include #include #include +#endif +#include #include #include #include #include #include #include -#include +#include +#include + +#include Kleo::CryptoBackendFactory * Kleo::CryptoBackendFactory::mSelf = 0; +static const char * availableProtocols[] = { + "Chiasmus", + "OpenPGP", "SMIME", +}; +static const unsigned int numAvailableProtocols = sizeof availableProtocols / sizeof *availableProtocols; + Kleo::CryptoBackendFactory::CryptoBackendFactory() - : QObject( qApp, "CryptoBackendFactory::instance()" ) + : QObject( qApp, "CryptoBackendFactory::instance()" ), + mConfigObject( 0 ), + mAvailableProtocols( availableProtocols, availableProtocols + numAvailableProtocols ) { - mSelf = this; - mConfigObject = 0; mBackendList.push_back( new QGpgMEBackend() ); #if 0 // disabled for kde-3.3 mBackendList.push_back( new PGP2Backend() ); mBackendList.push_back( new PGP5Backend() ); mBackendList.push_back( new PGP6Backend() ); mBackendList.push_back( new GPG1Backend() ); #endif + mBackendList.push_back( new ChiasmusBackend() ); scanForBackends(); readConfig(); + + mSelf = this; // last! } Kleo::CryptoBackendFactory::~CryptoBackendFactory() { - mSelf = 0; + mSelf = 0; // first! - for ( QValueVector::iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { + for ( std::vector::iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { delete *it; *it = 0; } delete mConfigObject; mConfigObject = 0; } Kleo::CryptoBackendFactory * Kleo::CryptoBackendFactory::instance() { if ( !mSelf ) mSelf = new CryptoBackendFactory(); return mSelf; } // const Kleo::CryptoBackend* Kleo::CryptoBackendFactory::smimeBackend() const { // return mSMIMEBackend; // } // const Kleo::CryptoBackend* Kleo::CryptoBackendFactory::openpgpBackend() const { // return mOpenPGPBackend; // } const Kleo::CryptoBackend::Protocol * Kleo::CryptoBackendFactory::smime() const { - return mSMIMEBackend ? mSMIMEBackend->smime() : 0 ; + const BackendMap::const_iterator it = mBackends.find( "SMIME" ); + if ( it == mBackends.end() ) + return 0; + if ( !it->second ) + return 0; + return it->second->smime(); } const Kleo::CryptoBackend::Protocol * Kleo::CryptoBackendFactory::openpgp() const { - return mOpenPGPBackend ? mOpenPGPBackend->openpgp() : 0 ; + const BackendMap::const_iterator it = mBackends.find( "OpenPGP" ); + if ( it == mBackends.end() ) + return 0; + if ( !it->second ) + return 0; + return it->second->openpgp(); +} + +const Kleo::CryptoBackend::Protocol * Kleo::CryptoBackendFactory::protocol( const char * name ) const { + const BackendMap::const_iterator it = mBackends.find( name ); + if ( it == mBackends.end() ) + return 0; + if ( !it->second ) + return 0; + return it->second->protocol( name ); } Kleo::CryptoConfig * Kleo::CryptoBackendFactory::config() const { // ## should we use mSMIMEBackend? mOpenPGPBackend? backend(0) i.e. always qgpgme? return backend( 0 ) ? backend( 0 )->config() : 0; } bool Kleo::CryptoBackendFactory::hasBackends() const { return !mBackendList.empty(); } void Kleo::CryptoBackendFactory::scanForBackends( QStringList * reasons ) { - if ( !reasons ) - return; - for ( QValueVector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { + for ( std::vector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { assert( *it ); - QString reason; - if ( (*it)->supportsOpenPGP() && !(*it)->checkForOpenPGP( &reason ) ) { - reasons->push_back( i18n("While scanning for OpenPGP support in backend %1:") - .arg( (*it)->displayName() ) ); - reasons->push_back( " " + reason ); - } - if ( (*it)->supportsSMIME() && !(*it)->checkForSMIME( &reason ) ) { - reasons->push_back( i18n("While scanning for S/MIME support in backend %1:") - .arg( (*it)->displayName() ) ); - reasons->push_back( " " + reason ); + for ( int i = 0 ; const char * protocol = (*it)->enumerateProtocols( i ) ; ++i ) { + QString reason; + if ( (*it)->supportsProtocol( protocol ) && !(*it)->checkForProtocol( protocol, &reason ) ) { + if ( reasons ) { + reasons->push_back( i18n("While scanning for %1 support in backend %2:") + .arg( protocol, (*it)->displayName() ) ); + reasons->push_back( " " + reason ); + } + } } } } const Kleo::CryptoBackend * Kleo::CryptoBackendFactory::backend( unsigned int idx ) const { return ( idx < mBackendList.size() ) ? mBackendList[idx] : 0 ; } const Kleo::CryptoBackend * Kleo::CryptoBackendFactory::backendByName( const QString& name ) const { - for ( QValueVector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { + for ( std::vector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { if ( (*it)->name() == name ) return *it; } return 0; } Kleo::BackendConfigWidget * Kleo::CryptoBackendFactory::configWidget( QWidget * parent, const char * name ) const { return new Kleo::BackendConfigWidget( mSelf, parent, name ); } KConfig* Kleo::CryptoBackendFactory::configObject() const { if ( !mConfigObject ) + // this is unsafe. We're a lib, used by concurrent apps. mConfigObject = new KConfig( "libkleopatrarc" ); return mConfigObject; } void Kleo::CryptoBackendFactory::setSMIMEBackend( const CryptoBackend* backend ) { - const QString name = backend ? backend->name() : QString::null; - KConfigGroup group( configObject(), "Backends" ); - group.writeEntry( "SMIME", name ); - configObject()->sync(); - mSMIMEBackend = backend; + setProtocolBackend( "SMIME", backend ); } void Kleo::CryptoBackendFactory::setOpenPGPBackend( const CryptoBackend* backend ) { - const QString name = backend ? backend->name() : QString::null; + setProtocolBackend( "OpenPGP", backend ); +} + +void Kleo::CryptoBackendFactory::setProtocolBackend( const char * protocol, const CryptoBackend * backend ) { + const QString name = backend ? backend->name() : QString::null ; KConfigGroup group( configObject(), "Backends" ); - group.writeEntry( "OpenPGP", name ); + group.writeEntry( protocol, name ); configObject()->sync(); - mOpenPGPBackend = backend; + mBackends[protocol] = backend; +} + +static const char * defaultBackend( const char * proto ) { + static const struct { + const char * proto; + const char * backend; + } defaults[] = { + { "OpenPGP", "gpgme" }, + { "SMIME", "gpgme" }, + { "Chiasmus", "chiasmus" }, + }; + for ( unsigned int i = 0 ; i < sizeof defaults / sizeof *defaults ; ++i ) + if ( qstricmp( proto, defaults[i].proto ) == 0 ) + return defaults[i].backend; + return 0; } void Kleo::CryptoBackendFactory::readConfig() { + mBackends.clear(); const KConfigGroup group( configObject(), "Backends" ); - const QString smimeBackend = group.readEntry( "SMIME", "gpgme" ); - mSMIMEBackend = backendByName( smimeBackend ); + for ( ProtocolSet::const_iterator it = mAvailableProtocols.begin(), end = mAvailableProtocols.end() ; it != end ; ++it ) { + const QString backend = group.readEntry( *it, defaultBackend( *it ) ); + mBackends[*it] = backendByName( backend ); + } +} + +const char * Kleo::CryptoBackendFactory::enumerateProtocols( int i ) const { + if ( i < 0 || static_cast( i ) >= mAvailableProtocols.size() ) + return 0; + return mAvailableProtocols[i]; +} + +namespace { + class CaseInsensitiveString { + const char * m; + public: + CaseInsensitiveString( const char * s ) : m( s ) {} +#define make_operator( op ) \ + bool operator op( const CaseInsensitiveString & other ) const { \ + return qstricmp( m, other.m ) op 0; \ + } \ + bool operator op( const char * other ) const { \ + return qstricmp( m, other ) op 0; \ + } + make_operator( == ) + make_operator( != ) + make_operator( < ) + make_operator( > ) + make_operator( <= ) + make_operator( >= ) +#undef make_operator + operator const char *() const { return m; } + }; +#define make_ext_operator( op, inv_op ) \ + inline bool operator op( const char * lhs, const CaseInsensitiveString & rhs ) { \ + return rhs.operator inv_op( lhs ); \ + } + make_ext_operator( ==, == ) + make_ext_operator( !=, != ) + make_ext_operator( <, > ) + make_ext_operator( >, < ) + make_ext_operator( <=, >= ) + make_ext_operator( >=, <= ) +#undef make_ext_operator + +} - const QString openPGPBackend = group.readEntry( "OpenPGP", "gpgme" ); - mOpenPGPBackend = backendByName( openPGPBackend ); +bool Kleo::CryptoBackendFactory::knowsAboutProtocol( const char * name ) const { + return std::find( mAvailableProtocols.begin(), mAvailableProtocols.end(), + CaseInsensitiveString( name ) ) != mAvailableProtocols.end(); } #include "cryptobackendfactory.moc" diff --git a/certmanager/lib/kleo/cryptobackendfactory.h b/certmanager/lib/kleo/cryptobackendfactory.h index ed9145323b..7a54e9fd18 100644 --- a/certmanager/lib/kleo/cryptobackendfactory.h +++ b/certmanager/lib/kleo/cryptobackendfactory.h @@ -1,101 +1,117 @@ /* kleo/cryptobackendfactory.h This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB + Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_CRYPTOBACKENDFACTORY_H__ #define __KLEO_CRYPTOBACKENDFACTORY_H__ #include -#include #include "cryptobackend.h" #include +#include +#include + namespace Kleo { class BackendConfigWidget; } class QString; class KConfig; namespace Kleo { + struct lt_i_str { + bool operator()( const char * one, const char * two ) const { + return qstricmp( one, two ) < 0; + } + }; + class KDE_EXPORT CryptoBackendFactory : public QObject { Q_OBJECT protected: CryptoBackendFactory(); ~CryptoBackendFactory(); public: static CryptoBackendFactory * instance(); const CryptoBackend::Protocol * smime() const; const CryptoBackend::Protocol * openpgp() const; + const CryptoBackend::Protocol * protocol( const char * name ) const; CryptoConfig * config() const; const CryptoBackend * backend( unsigned int idx ) const; bool hasBackends() const; Kleo::BackendConfigWidget * configWidget( QWidget * parent=0, const char * name=0 ) const; KConfig* configObject() const; // The preferred backend for smime (can be 0) - currently unused //const CryptoBackend* smimeBackend() const; // The preferred backend for openpgp (can be 0) - currently unused //const CryptoBackend* openpgpBackend() const; // For BackendConfigWidget to save the configuration // 0 means no backend selected. void setSMIMEBackend( const CryptoBackend* backend ); void setOpenPGPBackend( const CryptoBackend* backend ); + void setProtocolBackend( const char * name, const CryptoBackend * backend ); void scanForBackends( QStringList * reasons=0 ); + const char * enumerateProtocols( int i ) const; + + bool knowsAboutProtocol( const char * name ) const; + protected: - QValueVector mBackendList; + std::vector mBackendList; mutable KConfig* mConfigObject; - const CryptoBackend* mSMIMEBackend; - const CryptoBackend* mOpenPGPBackend; + typedef std::map BackendMap; + BackendMap mBackends; + typedef std::vector ProtocolSet; + ProtocolSet mAvailableProtocols; private: const CryptoBackend * backendByName( const QString& name ) const; void readConfig(); CryptoBackendFactory( const CryptoBackendFactory & ); void operator=( const CryptoBackendFactory & ); static CryptoBackendFactory * mSelf; }; } #endif // __KLEO_CRYPTOBACKENDFACTORY_H__ diff --git a/certmanager/lib/kleo/cryptoconfig.h b/certmanager/lib/kleo/cryptoconfig.h index b173213048..6ed0cfec07 100644 --- a/certmanager/lib/kleo/cryptoconfig.h +++ b/certmanager/lib/kleo/cryptoconfig.h @@ -1,346 +1,382 @@ /* cryptoconfig.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef CRYPTOCONFIG_H #define CRYPTOCONFIG_H +#ifdef __cplusplus +/* we read this file from a C compiler, and are only interested in the + * enums... */ + #include -// Start reading this file from the bottom up :) +/* Start reading this file from the bottom up :) */ namespace Kleo { /** * Description of a single option */ class CryptoConfigEntry { public: +#endif /* __cplusplus */ /** @li basic This option should always be offered to the user. @li advanced This option may be offered to advanced users. @li expert This option should only be offered to expert users. */ enum Level { Level_Basic = 0, Level_Advanced = 1, Level_Expert = 2 }; /** Type of the argument @li ArgType_None The option is set or not set, but no argument. @li ArgType_String An unformatted string. @li ArgType_Int A signed integer number. @li ArgType_UInt An unsigned integer number. @li ArgType_Path A string that describes the pathname of a file. The file does not necessarily need to exist. Separated from string so that e.g. a KURLRequester can be used. + @li ArgType_DirPath A string that describes the pathname of a directory. + The directory does not necessarily need to exist. + Separated from path so that e.g. a KURLRequester can be used which only + allows directories to be selected. @li ArgType_URL A URL @li ArgType_LDAPURL A LDAP URL Separated from URL so that a more specific widget can be shown, hiding the url syntax */ enum ArgType { ArgType_None = 0, ArgType_String = 1, ArgType_Int = 2, ArgType_UInt = 3, ArgType_Path = 4, ArgType_URL = 5, - ArgType_LDAPURL = 6 }; + ArgType_LDAPURL = 6, + ArgType_DirPath = 7 }; +#ifdef __cplusplus virtual ~CryptoConfigEntry() {} + /** + * Return the internal name of this entry + */ + virtual QString name() const = 0; + /** * @return user-visible description of this entry */ virtual QString description() const = 0; /** * @return true if the argument is optional */ virtual bool isOptional() const = 0; /** * @return true if the argument can be given multiple times */ virtual bool isList() const = 0; /** * @return true if the argument can be changed at runtime */ virtual bool isRuntime() const = 0; /** * User level */ virtual Level level() const = 0; /** * Argument type */ virtual ArgType argType() const = 0; /** * Return true if the option is set, i.e. different from default */ virtual bool isSet() const = 0; /** * Return value as a bool (only allowed for ArgType_None) */ virtual bool boolValue() const = 0; /** * Return value as a string (available for all argtypes) * The returned string can be empty (explicitely set to empty) or null (not set). */ virtual QString stringValue() const = 0; /** * Return value as a signed int */ virtual int intValue() const = 0; /** * Return value as an unsigned int */ virtual unsigned int uintValue() const = 0; /** * Return value as a URL (only meaningful for Path and URL argtypes) */ virtual KURL urlValue() const = 0; /** * Return number of times the option is set (only valid for ArgType_None, if isList()) */ virtual unsigned int numberOfTimesSet() const = 0; /** * Return value as a list of strings (mostly meaningful for String, Path and URL argtypes, if isList()) */ virtual QStringList stringValueList() const = 0; /** * Return value as a list of signed ints */ virtual QValueList intValueList() const = 0; /** * Return value as a list of unsigned ints */ virtual QValueList uintValueList() const = 0; /** * Return value as a list of URLs (only meaningful for Path and URL argtypes, if isList()) */ virtual KURL::List urlValueList() const = 0; /** * Reset an option to its default value */ virtual void resetToDefault() = 0; /** * Define whether the option is set or not (only allowed for ArgType_None) * #### TODO: and for options with optional args */ virtual void setBoolValue( bool ) = 0; /** * Set string value (allowed for all argtypes) */ virtual void setStringValue( const QString& ) = 0; /** * Set a new signed int value */ virtual void setIntValue( int ) = 0; /** * Set a new unsigned int value */ virtual void setUIntValue( unsigned int ) = 0; /** * Set value as a URL (only meaningful for Path (if local) and URL argtypes) */ virtual void setURLValue( const KURL& ) = 0; /** * Set the number of times the option is set (only valid for ArgType_None, if isList()) */ virtual void setNumberOfTimesSet( unsigned int ) = 0; /** * Set a new string-list value (only allowed for String, Path and URL argtypes, if isList()) */ virtual void setStringValueList( const QStringList& ) = 0; /** * Set a new list of signed int values */ virtual void setIntValueList( const QValueList& ) = 0; /** * Set a new list of unsigned int values */ virtual void setUIntValueList( const QValueList& ) = 0; /** * Set value as a URL list (only meaningful for Path (if all URLs are local) and URL argtypes, if isList()) */ virtual void setURLValueList( const KURL::List& ) = 0; /** * @return true if the value was changed */ virtual bool isDirty() const = 0; }; /** * Group containing a set of config options */ class CryptoConfigGroup { public: virtual ~CryptoConfigGroup() {} /** - * @return user-visible description of this entry + * Return the internal name of this group + */ + virtual QString name() const = 0; + + /** + * Return the name of the icon for this group + */ + virtual QString iconName() const = 0; + + /** + * @return user-visible description of this group */ virtual QString description() const = 0; /** * User level */ virtual CryptoConfigEntry::Level level() const = 0; /** * Returns the list of entries that are known by this group. * * @return list of group entry names. **/ virtual QStringList entryList() const = 0; /** * @return the configuration object for a given entry in this group * The object is owned by CryptoConfigGroup, don't delete it. * Groups cannot be nested, so all entries returned here are pure entries, no groups. */ virtual CryptoConfigEntry* entry( const QString& name ) const = 0; }; /** * Crypto config for one component (e.g. gpg-agent, dirmngr etc.) */ class CryptoConfigComponent { public: virtual ~CryptoConfigComponent() {} + /** + * Return the internal name of this component + */ + virtual QString name() const = 0; + + /** + * Return the name of the icon for this component + */ + virtual QString iconName() const = 0; + /** * Return user-visible description of this component */ virtual QString description() const = 0; /** * Returns the list of groups that are known about. * * @return list of group names. One of them can be "", which is the group where all * "toplevel" options (belonging to no group) are. */ virtual QStringList groupList() const = 0; /** * @return the configuration object for a given group * The object is owned by CryptoConfigComponent, don't delete it. */ virtual CryptoConfigGroup* group( const QString& name ) const = 0; }; /** * Main interface to crypto configuration. */ class CryptoConfig { public: virtual ~CryptoConfig() {} /** * Returns the list of known components (e.g. "gpg-agent", "dirmngr" etc.). * Use @ref component() to retrieve more information about each one. * @return list of component names. **/ virtual QStringList componentList() const = 0; /** * @return the configuration object for a given component * The object is owned by CryptoConfig, don't delete it. */ virtual CryptoConfigComponent* component( const QString& name ) const = 0; /** * Convenience method to get hold of a single configuration entry when * its component, group and name are known. This can be used to read * the value and/or to set a value to it. * * @return the configuration object for a single configuration entry, 0 if not found. * The object is owned by CryptoConfig, don't delete it. */ CryptoConfigEntry* entry( const QString& componentName, const QString& groupName, const QString& entryName ) const { const Kleo::CryptoConfigComponent* comp = component( componentName ); const Kleo::CryptoConfigGroup* group = comp ? comp->group( groupName ) : 0; return group ? group->entry( entryName ) : 0; } /** * Write back changes * * @param runtime If this option is set, the changes will take effect at run-time, as * far as this is possible. Otherwise, they will take effect at the next * start of the respective backend programs. */ virtual void sync( bool runtime ) = 0; /** * Tells the CryptoConfig to discard any cached information, including * all components, groups and entries. * Call this to free some memory when you won't be using the object * for some time. * DON'T call this if you're holding pointers to components, groups or entries. */ virtual void clear() = 0; }; } - +#endif /* __cplusplus */ #endif /* CRYPTOCONFIG_H */ diff --git a/certmanager/lib/kleo/decryptjob.h b/certmanager/lib/kleo/decryptjob.h index d8aaa4ccba..e882152a0c 100644 --- a/certmanager/lib/kleo/decryptjob.h +++ b/certmanager/lib/kleo/decryptjob.h @@ -1,84 +1,84 @@ /* decryptjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_DECRYPTJOB_H__ #define __KLEO_DECRYPTJOB_H__ #include "job.h" #include namespace GpgME { class Error; class Key; class DecryptionResult; } namespace Kleo { /** @short An abstract base class for asynchronous decrypters To use a DecryptJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the decryption with a call to start(). This call might fail, in which case the DecryptJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the DecryptJob will schedule it's own destruction by calling QObject::deleteLater(). */ class DecryptJob : public Job { Q_OBJECT protected: DecryptJob( QObject * parent, const char * name ); public: ~DecryptJob(); /** Starts the decryption operation. \a cipherText is the data to decrypt. */ virtual GpgME::Error start( const QByteArray & cipherText ) = 0; virtual GpgME::DecryptionResult exec( const QByteArray & cipherText, QByteArray & plainText ) = 0; signals: void result( const GpgME::DecryptionResult & result, const QByteArray & plainText ); }; } #endif // __KLEO_DECRYPTJOB_H__ diff --git a/certmanager/lib/kleo/decryptverifyjob.h b/certmanager/lib/kleo/decryptverifyjob.h index 2a4c971d95..f7cdb81a1e 100644 --- a/certmanager/lib/kleo/decryptverifyjob.h +++ b/certmanager/lib/kleo/decryptverifyjob.h @@ -1,90 +1,90 @@ /* decryptverifyjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_DECRYPTVERIFYJOB_H__ #define __KLEO_DECRYPTVERIFYJOB_H__ #include "job.h" #include #include namespace GpgME { class Error; class Key; class DecryptionResult; class VerificationResult; } namespace Kleo { /** @short An abstract base class for asynchronous combined decrypters and verifiers To use a DecryptVerifyJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the operation with a call to start(). This call might fail, in which case the DecryptVerifyJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the DecryptVerifyJob will schedule it's own destruction by calling QObject::deleteLater(). */ class DecryptVerifyJob : public Job { Q_OBJECT protected: DecryptVerifyJob( QObject * parent, const char * name ); public: ~DecryptVerifyJob(); /** Starts the combined decryption and verification operation. \a cipherText is the data to decrypt and later verify. */ virtual GpgME::Error start( const QByteArray & cipherText ) = 0; /** Synchronous equivalent of start() */ virtual std::pair exec( const QByteArray & cipherText, QByteArray & plainText ) = 0; signals: void result( const GpgME::DecryptionResult & decryptionresult, const GpgME::VerificationResult & verificationresult, const QByteArray & plainText ); }; } #endif // __KLEO_DECRYPTVERIFYJOB_H__ diff --git a/certmanager/lib/kleo/deletejob.h b/certmanager/lib/kleo/deletejob.h index 9d2392bca7..fd70ec513d 100644 --- a/certmanager/lib/kleo/deletejob.h +++ b/certmanager/lib/kleo/deletejob.h @@ -1,78 +1,78 @@ /* deletejob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_DELETEJOB_H__ #define __KLEO_DELETEJOB_H__ #include "job.h" namespace GpgME { class Error; class Key; } namespace Kleo { /** @short An abstract base class for asynchronous deleters To use a DeleteJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the delete with a call to start(). This call might fail, in which case the DeleteJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the DeleteJob will schedule it's own destruction by calling QObject::deleteLater(). */ class DeleteJob : public Job { Q_OBJECT protected: DeleteJob( QObject * parent, const char * name ); public: ~DeleteJob(); /** Starts the delete operation. \a key represents the key to delete, \a allowSecretKeyDeletion specifies if a key may also be deleted if the secret key part is available, too. */ virtual GpgME::Error start( const GpgME::Key & key, bool allowSecretKeyDeletion=false ) = 0; signals: void result( const GpgME::Error & result ); }; } #endif // __KLEO_DELETEJOB_H__ diff --git a/certmanager/lib/kleo/dn.cpp b/certmanager/lib/kleo/dn.cpp index eb9754a612..2ea0f6719f 100644 --- a/certmanager/lib/kleo/dn.cpp +++ b/certmanager/lib/kleo/dn.cpp @@ -1,512 +1,512 @@ /* dn.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB DN parsing: Copyright (c) 2002 g10 Code GmbH Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "dn.h" #include "oidmap.h" #include "ui/dnattributeorderconfigwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include struct Kleo::DN::Private { Private() : mRefCount( 0 ) {} Private( const Private & other ) : attributes( other.attributes ), reorderedAttributes( other.reorderedAttributes ), mRefCount( 0 ) { } int ref() { return ++mRefCount; } int unref() { if ( --mRefCount <= 0 ) { delete this; return 0; } else return mRefCount; } int refCount() const { return mRefCount; } DN::Attribute::List attributes; DN::Attribute::List reorderedAttributes; private: int mRefCount; }; namespace { struct DnPair { char * key; char * value; }; } // copied from CryptPlug and adapted to work on DN::Attribute::List: #define digitp(p) (*(p) >= '0' && *(p) <= '9') #define hexdigitp(a) (digitp (a) \ || (*(a) >= 'A' && *(a) <= 'F') \ || (*(a) >= 'a' && *(a) <= 'f')) #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) static char * trim_trailing_spaces( char *string ) { char *p, *mark; for( mark = NULL, p = string; *p; p++ ) { if( isspace( *p ) ) { if( !mark ) mark = p; } else mark = NULL; } if( mark ) *mark = '\0' ; return string ; } /* Parse a DN and return an array-ized one. This is not a validating parser and it does not support any old-stylish syntax; gpgme is expected to return only rfc2253 compatible strings. */ static const unsigned char * parse_dn_part (DnPair *array, const unsigned char *string) { const unsigned char *s, *s1; size_t n; char *p; /* parse attributeType */ for (s = string+1; *s && *s != '='; s++) ; if (!*s) return NULL; /* error */ n = s - string; if (!n) return NULL; /* empty key */ p = (char*)malloc (n+1); memcpy (p, string, n); p[n] = 0; trim_trailing_spaces ((char*)p); // map OIDs to their names: for ( unsigned int i = 0 ; i < numOidMaps ; ++i ) if ( !strcasecmp ((char*)p, oidmap[i].oid) ) { free( p ); p = strdup( oidmap[i].name ); break; } array->key = p; string = s + 1; if (*string == '#') { /* hexstring */ string++; for (s=string; hexdigitp (s); s++) s++; n = s - string; if (!n || (n & 1)) return NULL; /* empty or odd number of digits */ n /= 2; array->value = p = (char*)malloc (n+1); for (s1=string; n; s1 += 2, n--) *p++ = xtoi_2 (s1); *p = 0; } else { /* regular v3 quoted string */ for (n=0, s=string; *s; s++) { if (*s == '\\') { /* pair */ s++; if (*s == ',' || *s == '=' || *s == '+' || *s == '<' || *s == '>' || *s == '#' || *s == ';' || *s == '\\' || *s == '\"' || *s == ' ') n++; else if (hexdigitp (s) && hexdigitp (s+1)) { s++; n++; } else return NULL; /* invalid escape sequence */ } else if (*s == '\"') return NULL; /* invalid encoding */ else if (*s == ',' || *s == '=' || *s == '+' || *s == '<' || *s == '>' || *s == '#' || *s == ';' ) break; else n++; } array->value = p = (char*)malloc (n+1); for (s=string; n; s++, n--) { if (*s == '\\') { s++; if (hexdigitp (s)) { *p++ = xtoi_2 (s); s++; } else *p++ = *s; } else *p++ = *s; } *p = 0; } return s; } /* Parse a DN and return an array-ized one. This is not a validating parser and it does not support any old-stylish syntax; gpgme is expected to return only rfc2253 compatible strings. */ static Kleo::DN::Attribute::List parse_dn( const unsigned char * string ) { if ( !string ) return QValueVector(); QValueVector result; while (*string) { while (*string == ' ') string++; if (!*string) break; /* ready */ DnPair pair = { 0, 0 }; string = parse_dn_part (&pair, string); if (!string) goto failure; if ( pair.key && pair.value ) result.push_back( Kleo::DN::Attribute( QString::fromUtf8( pair.key ), QString::fromUtf8( pair.value ) ) ); free( pair.key ); free( pair.value ); while (*string == ' ') string++; if (*string && *string != ',' && *string != ';' && *string != '+') goto failure; /* invalid delimiter */ if (*string) string++; } return result; failure: return QValueVector(); } static QValueVector parse_dn( const QString & dn ) { return parse_dn( (const unsigned char*)dn.utf8().data() ); } static QString serialise( const QValueVector & dn ) { QStringList result; for ( QValueVector::const_iterator it = dn.begin() ; it != dn.end() ; ++it ) if ( !(*it).name().isEmpty() && !(*it).value().isEmpty() ) result.push_back( (*it).name().stripWhiteSpace() + '=' + (*it).value().stripWhiteSpace() ); return result.join( "," ); } static Kleo::DN::Attribute::List reorder_dn( const Kleo::DN::Attribute::List & dn ) { const QStringList & attrOrder = Kleo::DNAttributeMapper::instance()->attributeOrder(); Kleo::DN::Attribute::List unknownEntries; Kleo::DN::Attribute::List result; unknownEntries.reserve( dn.size() ); result.reserve( dn.size() ); // find all unknown entries in their order of appearance for ( Kleo::DN::const_iterator it = dn.begin(); it != dn.end(); ++it ) if ( attrOrder.find( (*it).name() ) == attrOrder.end() ) unknownEntries.push_back( *it ); // process the known attrs in the desired order for ( QStringList::const_iterator oit = attrOrder.begin() ; oit != attrOrder.end() ; ++oit ) if ( *oit == "_X_" ) { // insert the unknown attrs std::copy( unknownEntries.begin(), unknownEntries.end(), std::back_inserter( result ) ); unknownEntries.clear(); // don't produce dup's } else { for ( Kleo::DN::const_iterator dnit = dn.begin() ; dnit != dn.end() ; ++dnit ) if ( (*dnit).name() == *oit ) result.push_back( *dnit ); } return result; } // // // class DN // // Kleo::DN::DN() { d = new Private(); d->ref(); } Kleo::DN::DN( const QString & dn ) { d = new Private(); d->ref(); d->attributes = parse_dn( dn ); } Kleo::DN::DN( const char * utf8DN ) { d = new Private(); d->ref(); if ( utf8DN ) d->attributes = parse_dn( (const unsigned char*)utf8DN ); } Kleo::DN::DN( const DN & other ) : d( other.d ) { if ( d ) d->ref(); } Kleo::DN::~DN() { if ( d ) d->unref(); } const Kleo::DN & Kleo::DN::operator=( const DN & that ) { if ( this->d == that.d ) return *this; if ( that.d ) that.d->ref(); if ( this->d ) this->d->unref(); this->d = that.d; return *this; } QString Kleo::DN::prettyDN() const { if ( !d ) return QString::null; if ( d->reorderedAttributes.empty() ) d->reorderedAttributes = reorder_dn( d->attributes ); return serialise( d->reorderedAttributes ); } QString Kleo::DN::dn() const { return d ? serialise( d->attributes ) : QString::null ; } void Kleo::DN::detach() { if ( !d ) { d = new Kleo::DN::Private(); d->ref(); } else if ( d->refCount() > 1 ) { Kleo::DN::Private * d_save = d; d = new Kleo::DN::Private( *d ); d->ref(); d_save->unref(); } } void Kleo::DN::append( const Attribute & attr ) { detach(); d->attributes.push_back( attr ); d->reorderedAttributes.clear(); } QString Kleo::DN::operator[]( const QString & attr ) const { if ( !d ) return QString::null; const QString attrUpper = attr.upper(); for ( QValueVector::const_iterator it = d->attributes.begin() ; it != d->attributes.end() ; ++it ) if ( (*it).name() == attrUpper ) return (*it).value(); return QString::null; } static QValueVector empty; Kleo::DN::const_iterator Kleo::DN::begin() const { return d ? d->attributes.begin() : empty.begin() ; } Kleo::DN::const_iterator Kleo::DN::end() const { return d ? d->attributes.end() : empty.end() ; } ///////////////////// namespace { struct ltstr { bool operator()( const char * s1, const char * s2 ) const { return qstrcmp( s1, s2 ) < 0 ; } }; } static const char * defaultOrder[] = { "CN", "L", "_X_", "OU", "O", "C" }; std::pair attributeLabels[] = { #define MAKE_PAIR(x,y) std::pair( x, y ) MAKE_PAIR( "CN", I18N_NOOP("Common name") ), MAKE_PAIR( "SN", I18N_NOOP("Surname") ), MAKE_PAIR( "GN", I18N_NOOP("Given name") ), MAKE_PAIR( "L", I18N_NOOP("Location") ), MAKE_PAIR( "T", I18N_NOOP("Title") ), MAKE_PAIR( "OU", I18N_NOOP("Organizational unit") ), MAKE_PAIR( "O", I18N_NOOP("Organization") ), MAKE_PAIR( "PC", I18N_NOOP("Postal code") ), MAKE_PAIR( "C", I18N_NOOP("Country code") ), MAKE_PAIR( "SP", I18N_NOOP("State or province") ), MAKE_PAIR( "DC", I18N_NOOP("Domain component") ), MAKE_PAIR( "BC", I18N_NOOP("Business category") ), MAKE_PAIR( "EMAIL", I18N_NOOP("Email address") ), MAKE_PAIR( "MAIL", I18N_NOOP("Mail address") ), MAKE_PAIR( "MOBILE", I18N_NOOP("Mobile phone number") ), MAKE_PAIR( "TEL", I18N_NOOP("Telephone number") ), MAKE_PAIR( "FAX", I18N_NOOP("Fax number") ), MAKE_PAIR( "STREET", I18N_NOOP("Street address") ), MAKE_PAIR( "UID", I18N_NOOP("Unique ID") ) #undef MAKE_PAIR }; static const unsigned int numAttributeLabels = sizeof attributeLabels / sizeof *attributeLabels ; class Kleo::DNAttributeMapper::Private { public: Private(); std::map map; QStringList attributeOrder; }; Kleo::DNAttributeMapper::Private::Private() : map( attributeLabels, attributeLabels + numAttributeLabels ) {} Kleo::DNAttributeMapper::DNAttributeMapper() { d = new Private(); const KConfigGroup config( kapp->config(), "DN" ); d->attributeOrder = config.readListEntry( "AttributeOrder" ); if ( d->attributeOrder.empty() ) std::copy( defaultOrder, defaultOrder + sizeof defaultOrder / sizeof *defaultOrder, std::back_inserter( d->attributeOrder ) ); mSelf = this; } Kleo::DNAttributeMapper::~DNAttributeMapper() { mSelf = 0; delete d; d = 0; } Kleo::DNAttributeMapper * Kleo::DNAttributeMapper::mSelf = 0; const Kleo::DNAttributeMapper * Kleo::DNAttributeMapper::instance() { if ( !mSelf ) (void)new DNAttributeMapper(); return mSelf; } QString Kleo::DNAttributeMapper::name2label( const QString & s ) const { const std::map::const_iterator it = d->map.find( s.stripWhiteSpace().upper().latin1() ); if ( it == d->map.end() ) return QString::null; return i18n( it->second ); } QStringList Kleo::DNAttributeMapper::names() const { QStringList result; for ( std::map::const_iterator it = d->map.begin() ; it != d->map.end() ; ++it ) result.push_back( it->first ); return result; } const QStringList & Kleo::DNAttributeMapper::attributeOrder() const { return d->attributeOrder; } void Kleo::DNAttributeMapper::setAttributeOrder( const QStringList & order ) { d->attributeOrder = order; if ( order.empty() ) std::copy( defaultOrder, defaultOrder + sizeof defaultOrder / sizeof *defaultOrder, std::back_inserter( d->attributeOrder ) ); KConfigGroup config( kapp->config(), "DN" ); config.writeEntry( "AttributeOrder", order ); } Kleo::DNAttributeOrderConfigWidget * Kleo::DNAttributeMapper::configWidget( QWidget * parent, const char * name ) const { return new DNAttributeOrderConfigWidget( mSelf, parent, name ); } diff --git a/certmanager/lib/kleo/dn.h b/certmanager/lib/kleo/dn.h index 18c80ab1bf..f4bd78e8ec 100644 --- a/certmanager/lib/kleo/dn.h +++ b/certmanager/lib/kleo/dn.h @@ -1,139 +1,139 @@ /* dn.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_DN_H__ #define __KLEO_DN_H__ #include #include #include class QStringList; class QWidget; namespace Kleo { class DNAttributeOrderConfigWidget; } namespace Kleo { /** @short DN Attribute mapper */ class KDE_EXPORT DNAttributeMapper { DNAttributeMapper(); ~DNAttributeMapper(); public: static const DNAttributeMapper * instance(); QString name2label( const QString & s ) const; QStringList names() const; const QStringList & attributeOrder() const; void setAttributeOrder( const QStringList & order ); DNAttributeOrderConfigWidget * configWidget( QWidget * parent=0, const char * name=0 ) const; private: class Private; Private * d; static DNAttributeMapper * mSelf; }; /** @short DN parser and reorderer */ class KDE_EXPORT DN { public: class Attribute; typedef QValueVector AttributeList; typedef AttributeList::const_iterator const_iterator; DN(); DN( const QString & dn ); DN( const char * utf8DN ); DN( const DN & other ); ~DN(); const DN & operator=( const DN & other ); /** @return the DN in a reordered form, according to the settings in the [DN] group of the application's config file */ QString prettyDN() const; /** @return the DN in the original form */ QString dn() const; QString operator[]( const QString & attr ) const; void append( const Attribute & attr ); const_iterator begin() const; const_iterator end() const; private: void detach(); private: class Private; Private * d; }; class KDE_EXPORT DN::Attribute { public: typedef DN::AttributeList List; Attribute( const QString & name=QString::null, const QString & value=QString::null ) : mName( name.upper() ), mValue( value ) {} Attribute( const Attribute & other ) : mName( other.name() ), mValue( other.value() ) {} const Attribute & operator=( const Attribute & other ) { if ( this != &other ) { mName = other.name(); mValue = other.value(); } return *this; } const QString & name() const { return mName; } const QString & value() const { return mValue; } void setValue( const QString & value ) { mValue = value; } private: QString mName; QString mValue; }; } #endif // __KLEO_DN_H__ diff --git a/certmanager/lib/kleo/downloadjob.h b/certmanager/lib/kleo/downloadjob.h index 466733607e..006ab8ebd4 100644 --- a/certmanager/lib/kleo/downloadjob.h +++ b/certmanager/lib/kleo/downloadjob.h @@ -1,83 +1,83 @@ /* downloadjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_DOWNLOADJOB_H__ #define __KLEO_DOWNLOADJOB_H__ #include "job.h" #include namespace GpgME { class Error; } class QStringList; namespace Kleo { /** @short An abstract base class for asynchronous downloaders To use a DownloadJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the download with a call to start(). This call might fail, in which case the DownloadJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the DownloadJob will schedule it's own destruction by calling QObject::deleteLater(). */ class DownloadJob : public Job { Q_OBJECT protected: DownloadJob( QObject * parent, const char * name ); public: ~DownloadJob(); /** Starts the download operation. \a fingerprints is a list of fingerprints used to specify the list of keys downloaded. Empty patterns are ignored. If \a fingerprints is empty, contains only empty strings or anything other than fingerprints, the result is undefined. */ virtual GpgME::Error start( const QStringList & fingerprints ) = 0; signals: void result( const GpgME::Error & result, const QByteArray & keyData ); }; } #endif // __KLEO_DOWNLOADJOB_H__ diff --git a/certmanager/lib/kleo/encryptjob.h b/certmanager/lib/kleo/encryptjob.h index ac891637a6..02144656ff 100644 --- a/certmanager/lib/kleo/encryptjob.h +++ b/certmanager/lib/kleo/encryptjob.h @@ -1,92 +1,92 @@ /* encryptjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_ENCRYPTJOB_H__ #define __KLEO_ENCRYPTJOB_H__ #include "job.h" #include #include namespace GpgME { class Error; class Key; class EncryptionResult; } namespace Kleo { /** @short An abstract base class for asynchronous encrypters To use a EncryptJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the encryption with a call to start(). This call might fail, in which case the EncryptJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the EncryptJob will schedule it's own destruction by calling QObject::deleteLater(). */ class EncryptJob : public Job { Q_OBJECT protected: EncryptJob( QObject * parent, const char * name ); public: ~EncryptJob(); /** Starts the encryption operation. \a recipients is the a list of keys to encrypt \a plainText to. Empty (null) keys are ignored. If \a alwaysTrust is true, validity checking for the keys will not be performed, but full validity assumed for all keys without further checks. */ virtual GpgME::Error start( const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust=false ) = 0; virtual GpgME::EncryptionResult exec( const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust, QByteArray & cipherText ) = 0; signals: void result( const GpgME::EncryptionResult & result, const QByteArray & cipherText ); }; } #endif // __KLEO_ENCRYPTJOB_H__ diff --git a/certmanager/lib/kleo/enum.cpp b/certmanager/lib/kleo/enum.cpp index 47b27044c0..efa4cfaa3d 100644 --- a/certmanager/lib/kleo/enum.cpp +++ b/certmanager/lib/kleo/enum.cpp @@ -1,206 +1,206 @@ /* kleo/enum.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "enum.h" #include #include #include static const struct { Kleo::CryptoMessageFormat format; const char * displayName; const char * configName; } cryptoMessageFormats[] = { { Kleo::InlineOpenPGPFormat, I18N_NOOP("Inline OpenPGP (deprecated)"), "inline openpgp" }, { Kleo::OpenPGPMIMEFormat, I18N_NOOP("OpenPGP/MIME"), "openpgp/mime" }, { Kleo::SMIMEFormat, I18N_NOOP("S/MIME"), "s/mime" }, { Kleo::SMIMEOpaqueFormat, I18N_NOOP("S/MIME Opaque"), "s/mime opaque" }, }; static const unsigned int numCryptoMessageFormats = sizeof cryptoMessageFormats / sizeof *cryptoMessageFormats ; const char * Kleo::cryptoMessageFormatToString( Kleo::CryptoMessageFormat f ) { if ( f == AutoFormat ) return "auto"; for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i ) if ( f == cryptoMessageFormats[i].format ) return cryptoMessageFormats[i].configName; return 0; } QStringList Kleo::cryptoMessageFormatsToStringList( unsigned int f ) { QStringList result; for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i ) if ( f & cryptoMessageFormats[i].format ) result.push_back( cryptoMessageFormats[i].configName ); return result; } QString Kleo::cryptoMessageFormatToLabel( Kleo::CryptoMessageFormat f ) { if ( f == AutoFormat ) return i18n("Any"); for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i ) if ( f == cryptoMessageFormats[i].format ) return i18n( cryptoMessageFormats[i].displayName ); return QString::null; } Kleo::CryptoMessageFormat Kleo::stringToCryptoMessageFormat( const QString & s ) { const QString t = s.lower(); for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i ) if ( t == cryptoMessageFormats[i].configName ) return cryptoMessageFormats[i].format; return AutoFormat; } unsigned int Kleo::stringListToCryptoMessageFormats( const QStringList & sl ) { unsigned int result = 0; for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it ) result |= stringToCryptoMessageFormat( *it ); return result; } // For the config values used below, see also kaddressbook/editors/cryptowidget.cpp const char* Kleo::encryptionPreferenceToString( EncryptionPreference pref ) { switch( pref ) { case UnknownPreference: return 0; case NeverEncrypt: return "never"; case AlwaysEncrypt: return "always"; case AlwaysEncryptIfPossible: return "alwaysIfPossible"; case AlwaysAskForEncryption: return "askAlways"; case AskWheneverPossible: return "askWhenPossible"; } return 0; // keep the compiler happy } Kleo::EncryptionPreference Kleo::stringToEncryptionPreference( const QString& str ) { if ( str == "never" ) return NeverEncrypt; if ( str == "always" ) return AlwaysEncrypt; if ( str == "alwaysIfPossible" ) return AlwaysEncryptIfPossible; if ( str == "askAlways" ) return AlwaysAskForEncryption; if ( str == "askWhenPossible" ) return AskWheneverPossible; return UnknownPreference; } QString Kleo::encryptionPreferenceToLabel( EncryptionPreference pref ) { switch( pref ) { case NeverEncrypt: return i18n( "Never Encrypt" ); case AlwaysEncrypt: return i18n( "Always Encrypt" ); case AlwaysEncryptIfPossible: return i18n( "Always Encrypt If Possible" ); case AlwaysAskForEncryption: return i18n( "Ask" ); case AskWheneverPossible: return i18n( "Ask Whenever Possible" ); default: return i18n( "no specific preference", "" ); } } const char* Kleo::signingPreferenceToString( SigningPreference pref ) { switch( pref ) { case UnknownSigningPreference: return 0; case NeverSign: return "never"; case AlwaysSign: return "always"; case AlwaysSignIfPossible: return "alwaysIfPossible"; case AlwaysAskForSigning: return "askAlways"; case AskSigningWheneverPossible: return "askWhenPossible"; } return 0; // keep the compiler happy } Kleo::SigningPreference Kleo::stringToSigningPreference( const QString& str ) { if ( str == "never" ) return NeverSign; if ( str == "always" ) return AlwaysSign; if ( str == "alwaysIfPossible" ) return AlwaysSignIfPossible; if ( str == "askAlways" ) return AlwaysAskForSigning; if ( str == "askWhenPossible" ) return AskSigningWheneverPossible; return UnknownSigningPreference; } QString Kleo::signingPreferenceToLabel( SigningPreference pref ) { switch( pref ) { case NeverSign: return i18n( "Never Sign" ); case AlwaysSign: return i18n( "Always Sign" ); case AlwaysSignIfPossible: return i18n( "Always Sign If Possible" ); case AlwaysAskForSigning: return i18n( "Ask" ); case AskSigningWheneverPossible: return i18n( "Ask Whenever Possible" ); default: return i18n( "no specific preference", "" ); } } diff --git a/certmanager/lib/kleo/enum.h b/certmanager/lib/kleo/enum.h index 1ee5af3cc5..29f8e2a661 100644 --- a/certmanager/lib/kleo/enum.h +++ b/certmanager/lib/kleo/enum.h @@ -1,93 +1,93 @@ /* kleo/enum.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_ENUM_H__ #define __KLEO_ENUM_H__ #include class QString; class QStringList; namespace Kleo { enum CryptoMessageFormat { InlineOpenPGPFormat = 1, OpenPGPMIMEFormat = 2, SMIMEFormat = 4, SMIMEOpaqueFormat = 8, AnyOpenPGP = InlineOpenPGPFormat|OpenPGPMIMEFormat, AnySMIME = SMIMEOpaqueFormat|SMIMEFormat, AutoFormat = AnyOpenPGP|AnySMIME }; KDE_EXPORT QString cryptoMessageFormatToLabel( CryptoMessageFormat f ); KDE_EXPORT const char * cryptoMessageFormatToString( CryptoMessageFormat f ); KDE_EXPORT QStringList cryptoMessageFormatsToStringList( unsigned int f ); KDE_EXPORT CryptoMessageFormat stringToCryptoMessageFormat( const QString & s ); KDE_EXPORT unsigned int stringListToCryptoMessageFormats( const QStringList & sl ); enum Action { Conflict, DoIt, DontDoIt, Ask, AskOpportunistic, Impossible }; enum EncryptionPreference { UnknownPreference = 0, NeverEncrypt = 1, AlwaysEncrypt = 2, AlwaysEncryptIfPossible = 3, AlwaysAskForEncryption = 4, AskWheneverPossible = 5, MaxEncryptionPreference = AskWheneverPossible }; KDE_EXPORT QString encryptionPreferenceToLabel( EncryptionPreference pref ); KDE_EXPORT const char* encryptionPreferenceToString( EncryptionPreference pref ); KDE_EXPORT EncryptionPreference stringToEncryptionPreference( const QString& str ); enum SigningPreference { UnknownSigningPreference = 0, NeverSign = 1, AlwaysSign = 2, AlwaysSignIfPossible = 3, AlwaysAskForSigning = 4, AskSigningWheneverPossible = 5, MaxSigningPreference = AskSigningWheneverPossible }; KDE_EXPORT QString signingPreferenceToLabel( SigningPreference pref ) KDE_EXPORT; KDE_EXPORT const char* signingPreferenceToString( SigningPreference pref ) KDE_EXPORT; KDE_EXPORT SigningPreference stringToSigningPreference( const QString& str ); } #endif // __KLEO_CRYPTOBACKEND_H__ diff --git a/certmanager/lib/kleo/exportjob.h b/certmanager/lib/kleo/exportjob.h index e6ca770f5b..d6a0db185b 100644 --- a/certmanager/lib/kleo/exportjob.h +++ b/certmanager/lib/kleo/exportjob.h @@ -1,82 +1,82 @@ /* exportjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_EXPORTJOB_H__ #define __KLEO_EXPORTJOB_H__ #include "job.h" #include namespace GpgME { class Error; } class QStringList; namespace Kleo { /** @short An abstract base class for asynchronous exporters To use a ExportJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the export with a call to start(). This call might fail, in which case the ExportJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the ExportJob will schedule it's own destruction by calling QObject::deleteLater(). */ class ExportJob : public Job { Q_OBJECT protected: ExportJob( QObject * parent, const char * name ); public: ~ExportJob(); /** Starts the export operation. \a patterns is a list of patterns used to restrict the list of keys exported. Empty patterns are ignored. If \a patterns is empty or contains only empty strings, all available keys are exported. */ virtual GpgME::Error start( const QStringList & patterns ) = 0; signals: void result( const GpgME::Error & result, const QByteArray & keyData ); }; } #endif // __KLEO_EXPORTJOB_H__ diff --git a/certmanager/lib/kleo/hierarchicalkeylistjob.cpp b/certmanager/lib/kleo/hierarchicalkeylistjob.cpp index 996ece9c7d..a7a66b2fe8 100644 --- a/certmanager/lib/kleo/hierarchicalkeylistjob.cpp +++ b/certmanager/lib/kleo/hierarchicalkeylistjob.cpp @@ -1,158 +1,158 @@ /* hierarchicalkeylistjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "hierarchicalkeylistjob.h" #include "cryptobackend.h" #include "keylistjob.h" #include #include #include #include #include #include #include #include #include #include Kleo::HierarchicalKeyListJob::HierarchicalKeyListJob( const CryptoBackend::Protocol * protocol, bool remote, bool includeSigs, bool validating ) : KeyListJob( 0, "Kleo::HierarchicalKeyListJob" ), mProtocol( protocol ), mRemote( remote ), mIncludeSigs( includeSigs ), mValidating( validating ), mTruncated( false ), mIntermediateResult(), mJob( 0 ) { assert( protocol ); } Kleo::HierarchicalKeyListJob::~HierarchicalKeyListJob() { } GpgME::Error Kleo::HierarchicalKeyListJob::start( const QStringList & patterns, bool secretOnly ) { if ( secretOnly || patterns.empty() ) return gpg_err_make( GPG_ERR_SOURCE_GPGME, GPG_ERR_UNSUPPORTED_OPERATION ); qCopy( patterns.begin(), patterns.end(), std::inserter( mNextSet, mNextSet.begin() ) ); const GpgME::Error err = startAJob(); if ( err ) deleteLater(); return err; } GpgME::KeyListResult Kleo::HierarchicalKeyListJob::exec( const QStringList &, bool, std::vector & keys ) { keys.clear(); return GpgME::KeyListResult( gpg_err_make( GPG_ERR_SOURCE_GPGME, GPG_ERR_UNSUPPORTED_OPERATION ) ); } void Kleo::HierarchicalKeyListJob::slotNextKey( const GpgME::Key & key ) { if ( const char * chain_id = key.chainID() ) mNextSet.insert( chain_id ); if ( const char * fpr = key.primaryFingerprint() ) if ( mSentSet.find( fpr ) == mSentSet.end() ) { mSentSet.insert( fpr ); emit nextKey( key ); } } void Kleo::HierarchicalKeyListJob::slotCancel() { if ( mJob ) mJob->slotCancel(); mNextSet.clear(); } void Kleo::HierarchicalKeyListJob::slotResult( const GpgME::KeyListResult & res ) { mJob = 0; mIntermediateResult.mergeWith( res ); std::set tmp; std::set_difference( mNextSet.begin(), mNextSet.end(), mScheduledSet.begin(), mScheduledSet.end(), std::inserter( tmp, tmp.begin() ) ); mNextSet.clear(); std::set_difference( tmp.begin(), tmp.end(), mSentSet.begin(), mSentSet.end(), std::inserter( mNextSet, mNextSet.begin() ) ); if ( mIntermediateResult.error() || mNextSet.empty() ) { emit done(); emit result( mIntermediateResult ); deleteLater(); return; } if ( const GpgME::Error error = startAJob() ) { // error starting the job for next keys mIntermediateResult.mergeWith( GpgME::KeyListResult( error ) ); emit done(); emit result( mIntermediateResult ); deleteLater(); return; } #if 0 // FIXME const int current = mIt - mKeys.begin(); const int total = mKeys.size(); emit progress( i18n("progress info: \"%1 of %2\"","%1/%2").arg( current ).arg( total ), current, total ); #endif } GpgME::Error Kleo::HierarchicalKeyListJob::startAJob() { if ( mNextSet.empty() ) return 0; mJob = mProtocol->keyListJob( mRemote, mIncludeSigs, mValidating ); assert( mJob ); // FIXME: we need a way to generate errors ourselves, // but I don't like the dependency on gpg-error :/ connect( mJob, SIGNAL(nextKey(const GpgME::Key&)), SLOT(slotNextKey(const GpgME::Key&)) ); connect( mJob, SIGNAL(result(const GpgME::KeyListResult&)), SLOT(slotResult(const GpgME::KeyListResult&)) ); QStringList patterns; for ( std::set::const_iterator it = mNextSet.begin() ; it != mNextSet.end() ; ++it ) patterns.push_back( *it ); mScheduledSet.insert( mNextSet.begin(), mNextSet.end() ); mNextSet.clear(); return mJob->start( patterns, false ); } #include "hierarchicalkeylistjob.moc" diff --git a/certmanager/lib/kleo/hierarchicalkeylistjob.h b/certmanager/lib/kleo/hierarchicalkeylistjob.h index 134cfed1ab..a91ff6dc08 100644 --- a/certmanager/lib/kleo/hierarchicalkeylistjob.h +++ b/certmanager/lib/kleo/hierarchicalkeylistjob.h @@ -1,116 +1,116 @@ /* hierarchicalkeylistjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_HIERARCHICALKEYLISTJOB_H__ #define __KLEO_HIERARCHICALKEYLISTJOB_H__ #include #include #include #include #include #include #include namespace GpgME { class Error; class Key; } namespace Kleo { class KeyListJob; } namespace Kleo { /** @short A convenience job that additionally fetches all available issuers. To use a HierarchicalKeyListJob, pass it a CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the keylisting with a call to start(). This call might fail, in which case the HierarchicalKeyListJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the HierarchicalKeyListJob will schedule its own destruction by calling QObject::deleteLater(). */ class KDE_EXPORT HierarchicalKeyListJob : public KeyListJob { Q_OBJECT public: HierarchicalKeyListJob( const CryptoBackend::Protocol * protocol, bool remote=false, bool includeSigs=false, bool validating=false ); ~HierarchicalKeyListJob(); /** Starts the keylist operation. \a patterns is a list of patterns used to restrict the list of keys returned. Empty patterns are ignored. \a patterns must not be empty or contain only empty patterns; use the normal KeyListJob for a full listing. The \a secretOnly parameter is ignored by HierarchicalKeyListJob and must be set to false. */ GpgME::Error start( const QStringList & patterns, bool secretOnly=false ); GpgME::KeyListResult exec( const QStringList & patterns, bool secretOnly, std::vector & keys ); private slots: void slotResult( const GpgME::KeyListResult & ); void slotNextKey( const GpgME::Key & key ); /*! \reimp from Job */ void slotCancel(); private: GpgME::Error startAJob(); private: const CryptoBackend::Protocol * const mProtocol; const bool mRemote; const bool mIncludeSigs; const bool mValidating; bool mTruncated; std::set mSentSet; // keys already sent (prevent duplicates even if the backend should return them) std::set mScheduledSet; // keys already scheduled (by starting a job for them) std::set mNextSet; // keys to schedule for the next iteraton GpgME::KeyListResult mIntermediateResult; QGuardedPtr mJob; }; } #endif // __KLEO_HIERARCHICALKEYLISTJOB_H__ diff --git a/certmanager/lib/kleo/importjob.h b/certmanager/lib/kleo/importjob.h index 8e82eba4be..10aa903836 100644 --- a/certmanager/lib/kleo/importjob.h +++ b/certmanager/lib/kleo/importjob.h @@ -1,83 +1,83 @@ /* importjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_IMPORTJOB_H__ #define __KLEO_IMPORTJOB_H__ #include "job.h" #include namespace GpgME { class Error; class Key; class ImportResult; } namespace Kleo { /** @short An abstract base class for asynchronous importers To use a ImportJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the import with a call to start(). This call might fail, in which case the ImportJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the ImportJob will schedule it's own destruction by calling QObject::deleteLater(). */ class ImportJob : public Job { Q_OBJECT protected: ImportJob( QObject * parent, const char * name ); public: ~ImportJob(); /** Starts the importing operation. \a keyData contains the data to import from. */ virtual GpgME::Error start( const QByteArray & keyData ) = 0; virtual GpgME::ImportResult exec( const QByteArray & keyData ) = 0; signals: void result( const GpgME::ImportResult & result ); }; } #endif // __KLEO_IMPORTJOB_H__ diff --git a/certmanager/lib/kleo/job.cpp b/certmanager/lib/kleo/job.cpp index 9d1fbb265e..abccca7b38 100644 --- a/certmanager/lib/kleo/job.cpp +++ b/certmanager/lib/kleo/job.cpp @@ -1,108 +1,113 @@ /* job.cpp This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB + Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ +#ifdef HAVE_CONFIG_H #include +#endif #include "job.h" #include "keylistjob.h" #include "encryptjob.h" #include "decryptjob.h" #include "decryptverifyjob.h" #include "signjob.h" #include "signencryptjob.h" #include "verifydetachedjob.h" #include "verifyopaquejob.h" #include "keygenerationjob.h" #include "importjob.h" #include "exportjob.h" #include "downloadjob.h" #include "deletejob.h" #include "refreshkeysjob.h" +#include "specialjob.h" #include #include Kleo::Job::Job( QObject * parent, const char * name ) : QObject( parent, name ) { if ( qApp ) connect( qApp, SIGNAL(aboutToQuit()), SLOT(slotCancel()) ); } Kleo::Job::~Job() { } void Kleo::Job::showErrorDialog( QWidget *, const QString & ) const { kdDebug() << "Kleo::Job::showErrorDialog() should be reimplemented in Kleo::Job subclasses!" << endl; } #define make_job_subclass(x) \ Kleo::x::x( QObject * parent, const char * name ) : Job( parent, name ) {} \ Kleo::x::~x() {} make_job_subclass(KeyListJob) make_job_subclass(EncryptJob) make_job_subclass(DecryptJob) make_job_subclass(DecryptVerifyJob) make_job_subclass(SignJob) make_job_subclass(SignEncryptJob) make_job_subclass(VerifyDetachedJob) make_job_subclass(VerifyOpaqueJob) make_job_subclass(KeyGenerationJob) make_job_subclass(ImportJob) make_job_subclass(ExportJob) make_job_subclass(DownloadJob) make_job_subclass(DeleteJob) make_job_subclass(RefreshKeysJob) +make_job_subclass(SpecialJob) #undef make_job_subclass #include "job.moc" #include "keylistjob.moc" #include "encryptjob.moc" #include "decryptjob.moc" #include "decryptverifyjob.moc" #include "signjob.moc" #include "signencryptjob.moc" #include "verifydetachedjob.moc" #include "verifyopaquejob.moc" #include "keygenerationjob.moc" #include "importjob.moc" #include "exportjob.moc" #include "downloadjob.moc" #include "deletejob.moc" #include "refreshkeysjob.moc" +#include "specialjob.moc" diff --git a/certmanager/lib/kleo/job.h b/certmanager/lib/kleo/job.h index cc174efaa4..6b762a04b3 100644 --- a/certmanager/lib/kleo/job.h +++ b/certmanager/lib/kleo/job.h @@ -1,79 +1,79 @@ /* job.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_JOB_H__ #define __KLEO_JOB_H__ #include #include class QWidget; namespace Kleo { /** @short An abstract base class for asynchronous crypto operations During the operation, you might receive progress updates through the progress() signal as they arrive, but an implementation is free to not send progress information. You should show a busy progressbar until the first progress() signal is received. The done() signal is emitted _before_ the result() signals of subclasses and should be used to hide and/or reset progress bars, not to learn of the end of the operation. Use the result() signals for that. To cancel the operation, simply call slotCancel(). The result() signal of subclasses will still be emitted, though, and will carry the information that the operation was canceled. */ class Job : public QObject { Q_OBJECT protected: Job( QObject * parent, const char * name ); public: ~Job(); virtual void showErrorDialog( QWidget * parent=0, const QString & caption=QString::null ) const; public slots: virtual void slotCancel() = 0; signals: void progress( const QString & what, int current, int total ); void done(); }; } #endif // __KLEO_JOB_H__ diff --git a/certmanager/lib/kleo/kconfigbasedkeyfilter.cpp b/certmanager/lib/kleo/kconfigbasedkeyfilter.cpp index 3248097837..89d18e799b 100644 --- a/certmanager/lib/kleo/kconfigbasedkeyfilter.cpp +++ b/certmanager/lib/kleo/kconfigbasedkeyfilter.cpp @@ -1,251 +1,251 @@ /* kconfigbasedkeyfilter.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "kconfigbasedkeyfilter.h" #include #include static const struct { const char * name; GpgME::Key::OwnerTrust trust; GpgME::UserID::Validity validity; } ownerTrustAndValidityMap[] = { { "unknown", GpgME::Key::Unknown, GpgME::UserID::Unknown }, { "undefined", GpgME::Key::Undefined, GpgME::UserID::Undefined }, { "never", GpgME::Key::Never, GpgME::UserID::Never }, { "marginal", GpgME::Key::Marginal, GpgME::UserID::Marginal }, { "full", GpgME::Key::Full, GpgME::UserID::Full }, { "ultimate", GpgME::Key::Ultimate, GpgME::UserID::Ultimate }, }; static GpgME::Key::OwnerTrust map2OwnerTrust( const QString & s ) { for ( unsigned int i = 0 ; i < sizeof ownerTrustAndValidityMap / sizeof *ownerTrustAndValidityMap ; ++i ) if ( s.lower() == ownerTrustAndValidityMap[i].name ) return ownerTrustAndValidityMap[i].trust; return ownerTrustAndValidityMap[0].trust; } static GpgME::UserID::Validity map2Validity( const QString & s ) { for ( unsigned int i = 0 ; i < sizeof ownerTrustAndValidityMap / sizeof *ownerTrustAndValidityMap ; ++i ) if ( s.lower() == ownerTrustAndValidityMap[i].name ) return ownerTrustAndValidityMap[i].validity; return ownerTrustAndValidityMap[0].validity; } Kleo::KConfigBasedKeyFilter::KConfigBasedKeyFilter( const KConfigBase & config ) : KeyFilter(), mSpecificity( 0 ), mItalic( false ), mBold( false ), mStrikeOut( false ), mUseFullFont( false ), mRevoked( DoesNotMatter ), mExpired( DoesNotMatter ), mDisabled( DoesNotMatter ), mRoot( DoesNotMatter ), mCanEncrypt( DoesNotMatter ), mCanSign( DoesNotMatter ), mCanCertify( DoesNotMatter ), mCanAuthenticate( DoesNotMatter ), mHasSecret( DoesNotMatter ), mIsOpenPGP( DoesNotMatter ), mWasValidated( DoesNotMatter ), mOwnerTrust( LevelDoesNotMatter ), mOwnerTrustReferenceLevel( GpgME::Key::Unknown ), mValidity( LevelDoesNotMatter ), mValidityReferenceLevel( GpgME::UserID::Unknown ) { mFgColor = config.readColorEntry( "foreground-color" ); mBgColor = config.readColorEntry( "background-color" ); mName = config.readEntry( "name", i18n("") ); mIcon = config.readEntry( "icon" ); if ( config.hasKey( "font" ) ) { mUseFullFont = true; mFont = config.readFontEntry( "font" ); } else { mItalic = config.readBoolEntry( "font-italic", false ); mBold = config.readBoolEntry( "font-bold", false ); } mStrikeOut = config.readBoolEntry( "font-strikeout", false ); #ifdef SET #undef SET #endif #define SET(member,key) \ if ( config.hasKey( key ) ) { \ member = config.readBoolEntry( key ) ? Set : NotSet ; \ ++mSpecificity; \ } SET( mRevoked, "is-revoked" ); SET( mExpired, "is-expired" ); SET( mDisabled, "is-disabled" ); SET( mRoot, "is-root-certificate" ); SET( mCanEncrypt, "can-encrypt" ); SET( mCanSign, "can-sign" ); SET( mCanCertify, "can-certify" ); SET( mCanAuthenticate, "can-authenticate" ); SET( mHasSecret, "has-secret-key" ); SET( mIsOpenPGP, "is-openpgp-key" ); SET( mWasValidated, "was-validated" ); #undef SET static const struct { const char * prefix; LevelState state; } prefixMap[] = { { "is-", Is }, { "is-not-", IsNot }, { "is-at-least-", IsAtLeast }, { "is-at-most-", IsAtMost }, }; for ( unsigned int i = 0 ; i < sizeof prefixMap / sizeof *prefixMap ; ++i ) { const QString key = QString( prefixMap[i].prefix ) + "ownertrust"; if ( config.hasKey( key ) ) { mOwnerTrust = prefixMap[i].state; mOwnerTrustReferenceLevel = map2OwnerTrust( config.readEntry( key ) ); ++mSpecificity; break; } } for ( unsigned int i = 0 ; i < sizeof prefixMap / sizeof *prefixMap ; ++i ) { const QString key = QString( prefixMap[i].prefix ) + "validity"; if ( config.hasKey( key ) ) { mValidity = prefixMap[i].state; mValidityReferenceLevel = map2Validity( config.readEntry( key ) ); ++mSpecificity; break; } } } Kleo::KConfigBasedKeyFilter::~KConfigBasedKeyFilter() { } bool Kleo::KConfigBasedKeyFilter::matches( const GpgME::Key & key ) const { #ifdef MATCH #undef MATCH #endif #define MATCH(member,method) \ if ( member != DoesNotMatter && key.method() != bool( member == Set ) ) \ return false #define IS_MATCH(what) MATCH( m##what, is##what ) #define CAN_MATCH(what) MATCH( mCan##what, can##what ) IS_MATCH( Revoked ); IS_MATCH( Expired ); IS_MATCH( Disabled ); IS_MATCH( Root ); CAN_MATCH( Encrypt ); CAN_MATCH( Sign ); CAN_MATCH( Certify ); CAN_MATCH( Authenticate ); MATCH( mHasSecret, isSecret ); #undef MATCH if ( mIsOpenPGP != DoesNotMatter && bool( key.protocol() == GpgME::Context::OpenPGP ) != bool( mIsOpenPGP == Set ) ) return false; if ( mWasValidated != DoesNotMatter && bool( key.keyListMode() & GpgME::Context::Validate ) != bool( mWasValidated == Set ) ) return false; switch ( mOwnerTrust ) { default: case LevelDoesNotMatter: break; case Is: if ( key.ownerTrust() != mOwnerTrustReferenceLevel ) return false; break; case IsNot: if ( key.ownerTrust() == mOwnerTrustReferenceLevel ) return false; break; case IsAtLeast: if ( (int)key.ownerTrust() < (int)mOwnerTrustReferenceLevel ) return false; break; case IsAtMost: if ( (int)key.ownerTrust() > (int)mOwnerTrustReferenceLevel ) return false; break; } const GpgME::UserID uid = key.userID(0); switch ( mValidity ) { default: case LevelDoesNotMatter: break; case Is: if ( uid.validity() != mValidityReferenceLevel ) return false; break; case IsNot: if ( uid.validity() == mValidityReferenceLevel ) return false; break; case IsAtLeast: if ( (int)uid.validity() < (int)mValidityReferenceLevel ) return false; break; case IsAtMost: if ( (int)uid.validity() > (int)mValidityReferenceLevel ) return false; break; } return true; } static inline QFont resizedFont( QFont font, int pointSize, bool strike ) { font.setPointSize( pointSize ); if ( strike ) font.setStrikeOut( true ); return font; } static inline QFont adapt( QFont font, bool it, bool b, bool strike ) { if ( it ) font.setItalic( true ); if ( b ) font.setBold( true ); if ( strike ) font.setStrikeOut( true ); return font; } QFont Kleo::KConfigBasedKeyFilter::font( const QFont & f ) const { if ( mUseFullFont ) return resizedFont( mFont, f.pointSize(), mStrikeOut ); else return adapt( f, mItalic, mBold, mStrikeOut ); } diff --git a/certmanager/lib/kleo/kconfigbasedkeyfilter.h b/certmanager/lib/kleo/kconfigbasedkeyfilter.h index 7d0c034418..42c0830809 100644 --- a/certmanager/lib/kleo/kconfigbasedkeyfilter.h +++ b/certmanager/lib/kleo/kconfigbasedkeyfilter.h @@ -1,104 +1,104 @@ /* kconfigbasedkeyfilter.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KCONFIGBASEDKEYFILTER_H__ #define __KLEO_KCONFIGBASEDKEYFILTER_H__ #include "keyfilter.h" #include #include #include #include class KConfigBase; namespace Kleo { class KConfigBasedKeyFilter : public KeyFilter { public: explicit KConfigBasedKeyFilter( const KConfigBase & config ); ~KConfigBasedKeyFilter(); bool matches( const GpgME::Key & key ) const; unsigned int specificity() const { return mSpecificity; } QColor fgColor() const { return mFgColor; } QColor bgColor() const { return mBgColor; } QFont font( const QFont & ) const; QString name() const { return mName; } QString icon() const { return mIcon; } private: QColor mFgColor, mBgColor; QString mName; QString mIcon; unsigned int mSpecificity; bool mItalic; bool mBold; bool mStrikeOut; bool mUseFullFont; QFont mFont; enum TriState { DoesNotMatter = 0, Set = 1, NotSet = 2 }; TriState mRevoked; TriState mExpired; TriState mDisabled; TriState mRoot; TriState mCanEncrypt; TriState mCanSign; TriState mCanCertify; TriState mCanAuthenticate; TriState mHasSecret; TriState mIsOpenPGP; TriState mWasValidated; enum LevelState { LevelDoesNotMatter = 0, Is = 1, IsNot = 2, IsAtLeast = 3, IsAtMost = 4 }; LevelState mOwnerTrust; GpgME::Key::OwnerTrust mOwnerTrustReferenceLevel; LevelState mValidity; GpgME::UserID::Validity mValidityReferenceLevel; }; } #endif // __KLEO_KCONFIGBASEDKEYFILTER_H__ diff --git a/certmanager/lib/kleo/keyfilter.h b/certmanager/lib/kleo/keyfilter.h index 91b9921f3b..f10fba9bf4 100644 --- a/certmanager/lib/kleo/keyfilter.h +++ b/certmanager/lib/kleo/keyfilter.h @@ -1,68 +1,68 @@ /* keyfilter.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KEYFILTER_H__ #define __KLEO_KEYFILTER_H__ namespace GpgME { class Key; } class QFont; class QColor; class QString; namespace Kleo { /** @short An abstract base class key filters */ class KeyFilter { public: virtual ~KeyFilter() {} virtual bool matches( const GpgME::Key & key ) const = 0; virtual unsigned int specificity() const = 0; // not sure if we want these here, but for the time being, it's // the easiest way: virtual QColor fgColor() const = 0; virtual QColor bgColor() const = 0; virtual QFont font( const QFont & ) const = 0; virtual QString name() const = 0; virtual QString icon() const = 0; }; } #endif // __KLEO_KEYFILTER_H__ diff --git a/certmanager/lib/kleo/keyfiltermanager.cpp b/certmanager/lib/kleo/keyfiltermanager.cpp index 3a13613fa8..14932801c9 100644 --- a/certmanager/lib/kleo/keyfiltermanager.cpp +++ b/certmanager/lib/kleo/keyfiltermanager.cpp @@ -1,118 +1,118 @@ /* keyfiltermanager.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "keyfiltermanager.h" #include "kconfigbasedkeyfilter.h" #include "cryptobackendfactory.h" #include #include #include #include #include #include namespace { template struct Delete { void operator()( T * item ) { delete item; } }; } struct Kleo::KeyFilterManager::Private { void clear() { std::for_each( filters.begin(), filters.end(), Delete() ); filters.clear(); } QValueVector filters; }; Kleo::KeyFilterManager * Kleo::KeyFilterManager::mSelf = 0; Kleo::KeyFilterManager::KeyFilterManager( QObject * parent, const char * name ) : QObject( parent, name ), d( 0 ) { mSelf = this; d = new Private(); // ### DF: doesn't a KStaticDeleter work more reliably? if ( qApp ) connect( qApp, SIGNAL(aboutToQuit()), SLOT(deleteLater()) ); reload(); } Kleo::KeyFilterManager::~KeyFilterManager() { mSelf = 0; if ( d ) d->clear(); delete d; d = 0; } Kleo::KeyFilterManager * Kleo::KeyFilterManager::instance() { if ( !mSelf ) mSelf = new Kleo::KeyFilterManager(); return mSelf; } const Kleo::KeyFilter * Kleo::KeyFilterManager::filterMatching( const GpgME::Key & key ) const { for ( QValueVector::const_iterator it = d->filters.begin() ; it != d->filters.end() ; ++it ) if ( (*it)->matches( key ) ) return *it; return 0; } static inline bool by_increasing_specificity( const Kleo::KeyFilter * left, const Kleo::KeyFilter * right ) { return left->specificity() > right->specificity(); } void Kleo::KeyFilterManager::reload() { d->clear(); KConfig * config = Kleo::CryptoBackendFactory::instance()->configObject(); if ( !config ) return; const QStringList groups = config->groupList().grep( QRegExp( "^Key Filter #\\d+$" ) ); for ( QStringList::const_iterator it = groups.begin() ; it != groups.end() ; ++it ) { const KConfigGroup cfg( config, *it ); d->filters.push_back( new KConfigBasedKeyFilter( cfg ) ); } std::stable_sort( d->filters.begin(), d->filters.end(), by_increasing_specificity ); } #include "keyfiltermanager.moc" diff --git a/certmanager/lib/kleo/keyfiltermanager.h b/certmanager/lib/kleo/keyfiltermanager.h index 898ae016d0..25353d71aa 100644 --- a/certmanager/lib/kleo/keyfiltermanager.h +++ b/certmanager/lib/kleo/keyfiltermanager.h @@ -1,69 +1,69 @@ /* keyfiltermanager.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KEYFILTERMANAGER_H__ #define __KLEO_KEYFILTERMANAGER_H__ #include #include namespace GpgME { class Key; } namespace Kleo { class KeyFilter; } namespace Kleo { class KDE_EXPORT KeyFilterManager : public QObject { Q_OBJECT protected: KeyFilterManager( QObject * parent=0, const char * name=0 ); ~KeyFilterManager(); public: static KeyFilterManager * instance(); const KeyFilter * filterMatching( const GpgME::Key & key ) const; void reload(); private: class Private; Private * d; static KeyFilterManager * mSelf; }; } #endif // __KLEO_KEYFILTERMANAGER_H__ diff --git a/certmanager/lib/kleo/keygenerationjob.h b/certmanager/lib/kleo/keygenerationjob.h index d0ed092bd4..f78152c5c2 100644 --- a/certmanager/lib/kleo/keygenerationjob.h +++ b/certmanager/lib/kleo/keygenerationjob.h @@ -1,81 +1,81 @@ /* keygenerationjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KEYGENERATIONJOB_H__ #define __KLEO_KEYGENERATIONJOB_H__ #include "job.h" #include namespace GpgME { class Error; class KeyGenerationResult; } namespace Kleo { /** @short An abstract base class for asynchronous key generation To use a KeyGenerationJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the key generation with a call to start(). This call might fail, in which case the KeyGenerationJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the KeyGenerationJob will schedule it's own destruction by calling QObject::deleteLater(). */ class KeyGenerationJob : public Job { Q_OBJECT protected: KeyGenerationJob( QObject * parent, const char * name ); public: ~KeyGenerationJob(); /** Starts the key generation operation. \a parameters is a backend-specific string containing the paramaters of the key to create (length, capabilities, etc). */ virtual GpgME::Error start( const QString & parameters ) = 0; signals: void result( const GpgME::KeyGenerationResult & result, const QByteArray & pubKeyData ); }; } #endif // __KLEO_KEYGENERATIONJOB_H__ diff --git a/certmanager/lib/kleo/keylistjob.h b/certmanager/lib/kleo/keylistjob.h index 6ef747ac8a..c419ad47d7 100644 --- a/certmanager/lib/kleo/keylistjob.h +++ b/certmanager/lib/kleo/keylistjob.h @@ -1,96 +1,96 @@ /* keylistjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KEYLISTJOB_H__ #define __KLEO_KEYLISTJOB_H__ #include "job.h" #include namespace GpgME { class Error; class Key; class KeyListResult; } class QStringList; namespace Kleo { /** @short An abstract base class for asynchronous key listers To use a KeyListJob, first obtain an instance from the CryptoBackend implementation, connect the nextKey(), progress() and result() signals to suitable slots and then start the key listing with a call to start(). This call might fail, in which case the KeylistJob instance will have schedules it's own destruction with a call to QObject::deleteLater(). During keylisting, you will receive new key objects through the nextKey() signal as they arrive. After result() is emitted, the KeyListJob will schedule it's own destruction by calling QObject::deleteLater(). */ class KeyListJob : public Job { Q_OBJECT protected: KeyListJob( QObject * parent, const char * name ); public: ~KeyListJob(); /** Starts the keylist operation. \a pattern is a list of patterns used to restrict the list of keys returned. Empty patterns are ignored. If \a pattern is empty or contains only empty strings, all keys are returned (however, the backend is free to truncate the result and should do so; when this happens, it will be reported by the reult object). If \a secretOnly is true, only keys for which the secret key is also available are returned. Use this if you need to select a key for signing. */ virtual GpgME::Error start( const QStringList & patterns, bool secretOnly=false ) = 0; virtual GpgME::KeyListResult exec( const QStringList & patterns, bool secretOnly, std::vector & keys ) = 0; signals: void nextKey( const GpgME::Key & key ); void result( const GpgME::KeyListResult & result ); }; } #endif // __KLEO_KEYLISTJOB_H__ diff --git a/certmanager/lib/kleo/multideletejob.cpp b/certmanager/lib/kleo/multideletejob.cpp index 7ff9c5b071..32596e78f7 100644 --- a/certmanager/lib/kleo/multideletejob.cpp +++ b/certmanager/lib/kleo/multideletejob.cpp @@ -1,110 +1,110 @@ /* multideletejob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "multideletejob.h" #include "cryptobackend.h" #include "deletejob.h" #include #include #include #include #include #include Kleo::MultiDeleteJob::MultiDeleteJob( const CryptoBackend::Protocol * protocol ) : Job( 0, "Kleo::MultiDeleteJob" ), mProtocol( protocol ), mJob( 0 ) { assert( protocol ); } Kleo::MultiDeleteJob::~MultiDeleteJob() { } GpgME::Error Kleo::MultiDeleteJob::start( const std::vector & keys, bool allowSecretKeyDeletion ) { mKeys = keys; mAllowSecretKeyDeletion = allowSecretKeyDeletion; mIt = mKeys.begin(); const GpgME::Error err = startAJob(); if ( err ) deleteLater(); return err; } void Kleo::MultiDeleteJob::slotCancel() { if ( mJob ) mJob->slotCancel(); mIt = mKeys.end(); } void Kleo::MultiDeleteJob::slotResult( const GpgME::Error & err ) { mJob = 0; GpgME::Error error = err; if ( error || // error in last op mIt == mKeys.end() || // (shouldn't happen) ++mIt == mKeys.end() || // was the last key (error = startAJob()) ) { // error starting the job for the new key emit done(); emit result( error, error && mIt != mKeys.end() ? *mIt : GpgME::Key::null ); deleteLater(); return; } const int current = mIt - mKeys.begin(); const int total = mKeys.size(); emit progress( i18n("progress info: \"%1 of %2\"","%1/%2").arg( current ).arg( total ), current, total ); } GpgME::Error Kleo::MultiDeleteJob::startAJob() { if ( mIt == mKeys.end() ) return 0; mJob = mProtocol->deleteJob(); assert( mJob ); // FIXME: we need a way to generate errors ourselves, // but I don't like the dependency on gpg-error :/ connect( mJob, SIGNAL(result(const GpgME::Error&)), SLOT(slotResult(const GpgME::Error&)) ); return mJob->start( *mIt, mAllowSecretKeyDeletion ); } #include "multideletejob.moc" diff --git a/certmanager/lib/kleo/multideletejob.h b/certmanager/lib/kleo/multideletejob.h index 3f38929e04..5b995adaf9 100644 --- a/certmanager/lib/kleo/multideletejob.h +++ b/certmanager/lib/kleo/multideletejob.h @@ -1,101 +1,101 @@ /* multideletejob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_MULTIDELETEJOB_H__ #define __KLEO_MULTIDELETEJOB_H__ #include #include #include #include #include namespace GpgME { class Error; class Key; } namespace Kleo { class DeleteJob; } namespace Kleo { /** @short A convenience class bundling together multiple DeleteJobs. To use a MultiDeleteJob, pass it a CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the delete with a call to start(). This call might fail, in which case the MultiDeleteJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the MultiDeleteJob will schedule it's own destruction by calling QObject::deleteLater(). */ class KDE_EXPORT MultiDeleteJob : public Job { Q_OBJECT public: MultiDeleteJob( const CryptoBackend::Protocol * protocol ); ~MultiDeleteJob(); /** Starts the delete operation. \a keys is the list of keys to delete, \a allowSecretKeyDeletion specifies if a key may also be deleted if the secret key part is available, too. */ GpgME::Error start( const std::vector & keys, bool allowSecretKeyDeletion=false ); signals: void result( const GpgME::Error & result, const GpgME::Key & errorKey ); private slots: void slotResult( const GpgME::Error & ); /*! \reimp from Job */ void slotCancel(); private: GpgME::Error startAJob(); private: const CryptoBackend::Protocol * mProtocol; QGuardedPtr mJob; std::vector mKeys; std::vector::const_iterator mIt; bool mAllowSecretKeyDeletion; }; } #endif // __KLEO_MULTIDELETEJOB_H__ diff --git a/certmanager/lib/kleo/oidmap.h b/certmanager/lib/kleo/oidmap.h index 0d66d2e6f1..5962963329 100644 --- a/certmanager/lib/kleo/oidmap.h +++ b/certmanager/lib/kleo/oidmap.h @@ -1,57 +1,57 @@ /* oidmap.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_OIDMAP_H__ #define __KLEO_OIDMAP_H__ static struct { const char * name; const char * oid; } oidmap[] = { // keep them ordered by oid: { "SP", "ST" }, // hack to show the Sphinx-required/desired SP for // StateOrProvince, otherwise known as ST or even S { "NameDistinguisher", "0.2.262.1.10.7.20" }, { "EMAIL", "1.2.840.113549.1.9.1" }, { "SN", "2.5.4.4" }, { "SerialNumber", "2.5.4.5" }, { "T", "2.5.4.12" }, { "D", "2.5.4.13" }, { "BC", "2.5.4.15" }, { "ADDR", "2.5.4.16" }, { "PC", "2.5.4.17" }, { "GN", "2.5.4.42" }, { "Pseudo", "2.5.4.65" }, }; static const unsigned int numOidMaps = sizeof oidmap / sizeof *oidmap; #endif // __KLEO_OIDMAP_H__ diff --git a/certmanager/lib/kleo/refreshkeysjob.h b/certmanager/lib/kleo/refreshkeysjob.h index 8a57a653ff..dcf9cd516c 100644 --- a/certmanager/lib/kleo/refreshkeysjob.h +++ b/certmanager/lib/kleo/refreshkeysjob.h @@ -1,90 +1,90 @@ /* refreshkeysjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_REFRESHKEYSJOB_H__ #define __KLEO_REFRESHKEYSJOB_H__ #include "job.h" #include namespace GpgME { class Error; class Key; } class QStringList; namespace Kleo { /** @short An abstract base class for asynchronous key refreshers. To use a RefreshKeysJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the key refresh with a call to start(). This call might fail, in which case the RefreshKeysJob instance will have scheduled its own destruction with a call to QObject::deleteLater(). After result() is emitted, the KeyListJob will schedule it's own destruction by calling QObject::deleteLater(). */ class RefreshKeysJob : public Job { Q_OBJECT protected: RefreshKeysJob( QObject * parent, const char * name ); public: ~RefreshKeysJob(); /** Starts the keylist operation. \a pattern is a list of patterns used to restrict the list of keys returned. Empty patterns are ignored. If \a pattern is empty or contains only empty strings, all keys are returned (however, the backend is free to truncate the result and should do so; when this happens, it will be reported by the reult object). If \a secretOnly is true, only keys for which the secret key is also available are returned. Use this if you need to select a key for signing. */ virtual GpgME::Error start( const QStringList & patterns ) = 0; signals: void result( const GpgME::Error & error ); }; } #endif // __KLEO_REFRESHKEYSJOB_H__ diff --git a/certmanager/lib/kleo/signencryptjob.h b/certmanager/lib/kleo/signencryptjob.h index c276956e3e..42d3a179f8 100644 --- a/certmanager/lib/kleo/signencryptjob.h +++ b/certmanager/lib/kleo/signencryptjob.h @@ -1,103 +1,103 @@ /* signencryptjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_SIGNENCRYPTJOB_H__ #define __KLEO_SIGNENCRYPTJOB_H__ #include // for Context::SignatureMode (or should // we roll our own enum here?) #include "job.h" #include #include #include namespace GpgME { class Error; class Key; class SigningResult; class EncryptionResult; } namespace Kleo { /** @short An abstract base class for asynchronous combined signing and encrypting To use a SignEncryptJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the operation with a call to start(). This call might fail, in which case the SignEncryptJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the SignEncryptJob will schedule it's own destruction by calling QObject::deleteLater(). */ class SignEncryptJob : public Job { Q_OBJECT protected: SignEncryptJob( QObject * parent, const char * name ); public: ~SignEncryptJob(); /** Starts the combined signing and encrypting operation. \a signers is the list of keys to sign \a plainText with. \a recipients is a list of keys to encrypt the signed \a plainText to. In both lists, empty (null) keys are ignored. If \a alwaysTrust is true, validity checking for the \em recipient keys will not be performed, but full validity assumed for all \em recipient keys without further checks. */ virtual GpgME::Error start( const std::vector & signers, const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust=false ) = 0; virtual std::pair exec( const std::vector & signers, const std::vector & recipients, const QByteArray & plainText, bool alwaysTrust, QByteArray & cipherText ) = 0; signals: void result( const GpgME::SigningResult & signingresult, const GpgME::EncryptionResult & encryptionresult, const QByteArray & cipherText ); }; } #endif // __KLEO_SIGNENCRYPTJOB_H__ diff --git a/certmanager/lib/kleo/signjob.h b/certmanager/lib/kleo/signjob.h index 9a8cada10c..17ea3d9473 100644 --- a/certmanager/lib/kleo/signjob.h +++ b/certmanager/lib/kleo/signjob.h @@ -1,90 +1,90 @@ /* signjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_SIGNJOB_H__ #define __KLEO_SIGNJOB_H__ #include // for Context::SignatureMode (or should // we roll our own enum here?) #include "job.h" #include #include namespace GpgME { class Error; class Key; class SigningResult; } namespace Kleo { /** @short An abstract base class for asynchronous signing To use a SignJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the signing with a call to start(). This call might fail, in which case the SignJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the SignJob will schedule it's own destruction by calling QObject::deleteLater(). */ class SignJob : public Job { Q_OBJECT protected: SignJob( QObject * parent, const char * name ); public: ~SignJob(); /** Starts the signing operation. \a signers is the list of keys to sign \a plainText with. Empty (null) keys are ignored. */ virtual GpgME::Error start( const std::vector & signers, const QByteArray & plainText, GpgME::Context::SignatureMode mode ) = 0; virtual GpgME::SigningResult exec( const std::vector & signers, const QByteArray & plainText, GpgME::Context::SignatureMode mode, QByteArray & signature ) = 0; signals: void result( const GpgME::SigningResult & result, const QByteArray & signature ); }; } #endif // __KLEO_SIGNJOB_H__ diff --git a/kleopatra/lib/kleo/specialjob.h b/certmanager/lib/kleo/specialjob.h similarity index 100% rename from kleopatra/lib/kleo/specialjob.h rename to certmanager/lib/kleo/specialjob.h diff --git a/certmanager/lib/kleo/verifydetachedjob.h b/certmanager/lib/kleo/verifydetachedjob.h index 1096855d6f..f50fda546b 100644 --- a/certmanager/lib/kleo/verifydetachedjob.h +++ b/certmanager/lib/kleo/verifydetachedjob.h @@ -1,86 +1,86 @@ /* verifydetachedjob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_VERIFYDETACHEDJOB_H__ #define __KLEO_VERIFYDETACHEDJOB_H__ #include "job.h" #include namespace GpgME { class Error; class Key; class VerificationResult; } namespace Kleo { /** @short An abstract base class for asynchronous verification of detached signatures To use a VerifyDetachedJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the verification with a call to start(). This call might fail, in which case the VerifyDetachedJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the VerifyDetachedJob will schedule it's own destruction by calling QObject::deleteLater(). */ class VerifyDetachedJob : public Job { Q_OBJECT protected: VerifyDetachedJob( QObject * parent, const char * name ); public: ~VerifyDetachedJob(); /** Starts the verification operation. \a signature contains the signature data, while \a signedData contains the data over which the signature was made. */ virtual GpgME::Error start( const QByteArray & signature, const QByteArray & signedData ) = 0; virtual GpgME::VerificationResult exec( const QByteArray & signature, const QByteArray & signedData ) = 0; signals: void result( const GpgME::VerificationResult & result ); }; } #endif // __KLEO_VERIFYDETACHEDJOB_H__ diff --git a/certmanager/lib/kleo/verifyopaquejob.h b/certmanager/lib/kleo/verifyopaquejob.h index a73f71ef4d..b38b18de11 100644 --- a/certmanager/lib/kleo/verifyopaquejob.h +++ b/certmanager/lib/kleo/verifyopaquejob.h @@ -1,85 +1,85 @@ /* verifyopaquejob.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_VERIFYOPAQUEJOB_H__ #define __KLEO_VERIFYOPAQUEJOB_H__ #include "job.h" #include namespace GpgME { class Error; class Key; class VerificationResult; } namespace Kleo { /** @short An abstract base class for asynchronous verification of opaque signatures To use a VerifyOpaqueJob, first obtain an instance from the CryptoBackend implementation, connect the progress() and result() signals to suitable slots and then start the verification with a call to start(). This call might fail, in which case the VerifyOpaqueJob instance will have scheduled it's own destruction with a call to QObject::deleteLater(). After result() is emitted, the VerifyOpaqueJob will schedule it's own destruction by calling QObject::deleteLater(). */ class VerifyOpaqueJob : public Job { Q_OBJECT protected: VerifyOpaqueJob( QObject * parent, const char * name ); public: ~VerifyOpaqueJob(); /** Starts the verification operation. \a signature contains the signature data, while \a signedData contains the data over which the signature was made. */ virtual GpgME::Error start( const QByteArray & signedData ) = 0; /** Synchronous version of @ref start */ virtual GpgME::VerificationResult exec( const QByteArray & signedData, QByteArray & plainText ) = 0; signals: void result( const GpgME::VerificationResult & result, const QByteArray & plainText ); }; } #endif // __KLEO_VERIFYOPAQUEJOB_H__ diff --git a/certmanager/lib/libkleopatrarc.desktop b/certmanager/lib/libkleopatrarc.desktop index b724daaa3e..1e26c1ae51 100644 --- a/certmanager/lib/libkleopatrarc.desktop +++ b/certmanager/lib/libkleopatrarc.desktop @@ -1,180 +1,190 @@ [Key Filter #0] was-validated=false Name=Not Validated Key Name[bg]=Непроверен ключ Name[ca]=Clau no validada Name[cs]=Nevalidovaný klíč Name[da]=Ikke godkendt nøgle Name[de]=Ungeprüfter Schlüssel Name[es]=Clave no validada Name[et]=Võtme ehtsus kontrollimatu Name[fr]=Clé non validée +Name[he]=מפתח לא מוודא Name[hu]=Nem ellenőrzött kulcs Name[is]=Ekki gildur hnappur Name[it]=Chiave non validata Name[nl]=Geen gevalideerde sleutel Name[nn]=Ikkje-validert nøkkel Name[pl]=Niesprawdzony klucz Name[pt]=Chave Não Validada Name[pt_BR]=Chave Não Validada Name[ru]=Непроверенный ключ Name[sl]=Nepreverjen ključ Name[sr]=Неоверени кључ Name[sr@Latn]=Neovereni ključ Name[sv]=Nyckeln har inte validerats Name[ta]=செல்லுபடியாகாத விசை +Name[tr]=Geçerli Olmayan Anahtar Name[uk]=Неперевірений ключ Name[zh_CN]=未校验的密钥 [Key Filter #1] was-validated=true is-expired=true is-revoked=false foreground-color=255,0,0 Name=Expired Key Name[bg]=Изтекъл ключ Name[br]=Alc'hwez kabac'het Name[ca]=Clau expirada Name[cs]=Klíš s prošlou platností Name[da]=Udløbet nøgle Name[de]=Abgelaufener Schlüssel Name[es]=Clave caducada Name[et]=Aegunud võti Name[fr]=Clé expirée +Name[he]=מפתח לא תקף Name[hu]=Lejárt kulcs Name[is]=Útrunninn lykill Name[it]=Chiave scaduta Name[nl]=Verlopen sleutel Name[nn]=Forelda nøkkel Name[pl]=Klucz, który stracił ważność Name[pt]=Chave Expirada Name[pt_BR]=Chave Expirada Name[ru]=Утерявший силу ключ Name[sl]=Pretečen ključ Name[sr]=Истекли кључ Name[sr@Latn]=Istekli ključ Name[sv]=Utgången nyckel Name[ta]=காலாவதியான விசை +Name[tr]=Süresi Dolmuş Anahtar Name[uk]=Застарілий ключ Name[zh_CN]=过期密钥 [Key Filter #2] was-validated=true is-revoked=true Name=Revoked Key Name[bg]=Анулиран ключ Name[ca]=Clau revocada Name[cs]=Odvolaný klíč Name[da]=Fjernet nøgle Name[de]=Widerrufener Schlüssel Name[es]=Clave revocada Name[et]=Tühistatud võti Name[fr]=Clé révoquée +Name[he]=מפתח לא קביל Name[hu]=Visszavont kulcs Name[is]=Afturkallaður lykill Name[it]=Chiave revocata Name[nl]=Ingetrokken sleutel Name[nn]=Tilbakekalla nøkkel Name[pl]=Odwołany klucz Name[pt]=Chave Revogada Name[pt_BR]=Chave Revogada Name[ru]=Отозванный ключ Name[sl]=Preklican ključ Name[sr]=Опозвани кључ Name[sr@Latn]=Opozvani ključ Name[sv]=Återkallad nyckel Name[ta]=நீக்கிய விசை +Name[tr]=Geri Alınmış Anahtar Name[uk]=Анульований ключ Name[zh_CN]=吊销的密钥 [Key Filter #3] was-validated=true is-root-certificate=true is-validity=ultimate Name=Trusted Root Certificate Name[bg]=Надеждно удостоверение Name[ca]=Certificat arrel de confiança Name[cs]=Důvěryhodný kořenový certifikát Name[da]=Root-certifikat der stoles på Name[de]=Vertrauenswürdiges Stammzertifikat Name[es]=Certificado raíz de confianza Name[et]=Usaldusväärne juursertifikaat Name[fr]=Certificat racine de confiance Name[hu]=Megbízható gyökértanúsítvány Name[is]=Treyst rótarskilríki Name[it]=Certificato radice affidabile Name[nl]=Vertrouwd hoofdcertificaat Name[nn]=Tiltrudd rotsertifikat Name[pl]=Zaufany certyfikat bazowy Name[pt]=Certificado Raiz de Confiança Name[pt_BR]=Certificado Raiz Confiável Name[ru]=Доверяемый корневой сертификат Name[sl]=Zaupan korenski certifikat Name[sr]=Корени сертификат од поверења Name[sr@Latn]=Koreni sertifikat od poverenja Name[sv]=Pålitligt rotcertifikat Name[ta]=நம்பகமான மூல சான்றிதழ் +Name[tr]=Güvenilir Kök Sertifikası Name[uk]=Кореневий сертифікат з довірою Name[zh_CN]=可信任的根证书 [Key Filter #4] was-validated=true is-root-certificate=true is-not-validity=ultimate Name=Not Trusted Root Certificate Name[bg]=Ненадеждно удостоверение Name[ca]=Certificat arrel sense confiança Name[cs]=Nedůvěryhodný kořenový certifikát Name[da]=Root-certifikat der ikke stoles på Name[de]=Nicht vertrauenswürdiges Stammzertifikat Name[es]=Certificado raíz no de confianza Name[et]=Ebausaldusväärne juursertifikaat Name[fr]=Certificat racine non fiable Name[hu]=Nem megbízható gyökértanúsítvány Name[is]=Ekki traust rótarskilríki Name[it]=Certificato radice non affidabile Name[nl]=Niet vertrouwd hoofdcertificaat Name[nn]=Ikkje tiltrudd rotsertifikat Name[pl]=Nie zaufany certyfikat bazowy Name[pt]=Certificado Raiz Não de Confiança Name[pt_BR]=Certificado Raiz Não-Confiável Name[ru]=Не доверяемый корневой сертификат Name[sl]=Nezaupan korenski certifikat Name[sr]=Корени сертификат који није од поверења Name[sr@Latn]=Koreni sertifikat koji nije od poverenja Name[sv]=Opålitligt rotcertifikat Name[ta]=நம்பமுடியாத மூல சான்றிதழ் +Name[tr]=Güvenilmeyen Kök Sertifikası Name[uk]=Кореневий сертифікат без довіри Name[zh_CN]=未信任的根证书 [Key Filter #5] was-validated=true Name=Other Keys Name[bg]=Други ключове Name[br]=Alc'hwezioù all Name[ca]=Altres claus Name[cs]=Ostatní klíče Name[da]=Andre nøgler Name[de]=Andere Schlüssel Name[es]=Otras claves Name[et]=Muud võtmed Name[fr]=Autres clés Name[ga]=Eochracha Eile +Name[he]=מפתחות אחרים Name[hu]=Egyéb kulcsok Name[is]=Aðrir lyklar Name[it]=Altre chiavi Name[nl]=Andere sleutels Name[nn]=Andre nøklar Name[pa]=ਹੋਰ ਕੁੰਜੀਆਂ Name[pl]=Inne klucze Name[pt]=Outras Chaves Name[pt_BR]=Outras Chaves Name[ru]=Другие ключи Name[sl]=Drugi ključi Name[sr]=Други кључеви Name[sr@Latn]=Drugi ključevi Name[sv]=Andra nycklar Name[ta]=மற்ற விசைகள் +Name[tr]=Diğer Anahtarlar Name[uk]=Інші ключі Name[zh_CN]=其它密钥 diff --git a/certmanager/lib/pics/Makefile.am b/certmanager/lib/pics/Makefile.am index 0196f5c679..33704d1b27 100644 --- a/certmanager/lib/pics/Makefile.am +++ b/certmanager/lib/pics/Makefile.am @@ -1,4 +1,4 @@ picsdir = $(kde_datadir)/libkleopatra/pics -pics_DATA = key.png key_ok.png key_bad.png key_unknown.png +pics_DATA = key.png key_ok.png key_bad.png key_unknown.png chiasmus_chi.png KDE_ICON = gpg gpgsm diff --git a/kleopatra/lib/pics/chiasmus_chi.png b/certmanager/lib/pics/chiasmus_chi.png similarity index 100% rename from kleopatra/lib/pics/chiasmus_chi.png rename to certmanager/lib/pics/chiasmus_chi.png diff --git a/certmanager/lib/tests/gnupgviewer.h b/certmanager/lib/tests/gnupgviewer.h index fcb8376c9d..efba1760bb 100644 --- a/certmanager/lib/tests/gnupgviewer.h +++ b/certmanager/lib/tests/gnupgviewer.h @@ -1,64 +1,64 @@ /* gnupgviewer.h This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_TESTS_GNUPGVIEWER_H__ #define __KLEO_TESTS_GNUPGVIEWER_H__ #include #include namespace Kleo { class GnuPGProcessBase; } class KProcess; class QStringList; class GnuPGViewer : public QTextEdit { Q_OBJECT public: GnuPGViewer( QWidget * parent=0, const char * name=0 ); ~GnuPGViewer(); void setProcess( Kleo::GnuPGProcessBase * process ); private slots: void slotStdout( KProcess *, char *, int ); void slotStderr( KProcess *, char *, int ); void slotStatus( Kleo::GnuPGProcessBase *, const QString &, const QStringList & ); void slotProcessExited( KProcess * ); private: Kleo::GnuPGProcessBase * mProcess; QString mLastStdout, mLastStderr, mLastStatus; }; #endif // __KLEO_TESTS_GNUPGVIEWER_H__ diff --git a/certmanager/lib/tests/test_cryptoconfig.cpp b/certmanager/lib/tests/test_cryptoconfig.cpp index ebf3c5aa78..fab91cff11 100644 --- a/certmanager/lib/tests/test_cryptoconfig.cpp +++ b/certmanager/lib/tests/test_cryptoconfig.cpp @@ -1,361 +1,365 @@ /* test_cryptoconfig.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include #include #include #include #include using namespace std; #include #include int main( int argc, char** argv ) { KAboutData aboutData( "test_cryptoconfig", "CryptoConfig Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app( false, false ); Kleo::CryptoConfig * config = new QGpgMECryptoConfig(); // Dynamic querying of the options cout << "Components:" << endl; QStringList components = config->componentList(); for( QStringList::Iterator compit = components.begin(); compit != components.end(); ++compit ) { cout << "Component " << (*compit).local8Bit() << ":" << endl; const Kleo::CryptoConfigComponent* comp = config->component( *compit ); assert( comp ); QStringList groups = comp->groupList(); for( QStringList::Iterator groupit = groups.begin(); groupit != groups.end(); ++groupit ) { const Kleo::CryptoConfigGroup* group = comp->group( *groupit ); assert( group ); cout << " Group " << (*groupit).local8Bit() << ": descr=\"" << group->description().local8Bit() << "\"" << " level=" << group->level() << endl; QStringList entries = group->entryList(); for( QStringList::Iterator entryit = entries.begin(); entryit != entries.end(); ++entryit ) { const Kleo::CryptoConfigEntry* entry = group->entry( *entryit ); assert( entry ); cout << " Entry " << (*entryit).local8Bit() << ":" << " descr=\"" << entry->description().local8Bit() << "\"" << " " << ( entry->isSet() ? "is set" : "is not set" ); if ( !entry->isList() ) switch( entry->argType() ) { case Kleo::CryptoConfigEntry::ArgType_None: break; case Kleo::CryptoConfigEntry::ArgType_Int: cout << " int value=" << entry->intValue(); break; case Kleo::CryptoConfigEntry::ArgType_UInt: cout << " uint value=" << entry->uintValue(); break; case Kleo::CryptoConfigEntry::ArgType_LDAPURL: case Kleo::CryptoConfigEntry::ArgType_URL: cout << " URL value=" << entry->urlValue().prettyURL().local8Bit(); // fallthrough case Kleo::CryptoConfigEntry::ArgType_Path: // fallthrough + case Kleo::CryptoConfigEntry::ArgType_DirPath: + // fallthrough case Kleo::CryptoConfigEntry::ArgType_String: cout << " string value=" << entry->stringValue().local8Bit(); break; } else // lists { switch( entry->argType() ) { case Kleo::CryptoConfigEntry::ArgType_None: { cout << " set " << entry->numberOfTimesSet() << " times"; break; } case Kleo::CryptoConfigEntry::ArgType_Int: { assert( entry->isOptional() ); // empty lists must be allowed (see issue121) QValueList lst = entry->intValueList(); QString str; for( QValueList::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " int values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::ArgType_UInt: { assert( entry->isOptional() ); // empty lists must be allowed (see issue121) QValueList lst = entry->uintValueList(); QString str; for( QValueList::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " uint values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::ArgType_LDAPURL: case Kleo::CryptoConfigEntry::ArgType_URL: { assert( entry->isOptional() ); // empty lists must be allowed (see issue121) KURL::List urls = entry->urlValueList(); cout << " url values=" << urls.toStringList().join(" ").local8Bit() << "\n "; } // fallthrough case Kleo::CryptoConfigEntry::ArgType_Path: // fallthrough + case Kleo::CryptoConfigEntry::ArgType_DirPath: + // fallthrough case Kleo::CryptoConfigEntry::ArgType_String: { assert( entry->isOptional() ); // empty lists must be allowed (see issue121) QStringList lst = entry->stringValueList(); cout << " string values=" << lst.join(" ").local8Bit(); break; } } } cout << endl; } // ... } } { // Static querying of a single boolean option static const char* s_groupName = "Monitor"; static const char* s_entryName = "quiet"; Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); if ( entry ) { assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_None ); bool val = entry->boolValue(); cout << "quiet option initially: " << ( val ? "is set" : "is not set" ) << endl; entry->setBoolValue( !val ); assert( entry->isDirty() ); config->sync( true ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); assert( entry ); assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_None ); cout << "quiet option now: " << ( val ? "is set" : "is not set" ) << endl; assert( entry->boolValue() == !val ); // Set to default entry->resetToDefault(); assert( entry->boolValue() == false ); // that's the default assert( entry->isDirty() ); assert( !entry->isSet() ); config->sync( true ); config->clear(); // Check value entry = config->entry( "dirmngr", s_groupName, s_entryName ); assert( !entry->isDirty() ); assert( !entry->isSet() ); cout << "quiet option reset to default: " << ( entry->boolValue() ? "is set" : "is not set" ) << endl; assert( entry->boolValue() == false ); // Reset old value entry->setBoolValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "quiet option reset to initial: " << ( val ? "is set" : "is not set" ) << endl; } else cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl; } { // Static querying and setting of a single int option static const char* s_groupName = "LDAP"; static const char* s_entryName = "ldaptimeout"; Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); if ( entry ) { assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ); uint val = entry->uintValue(); cout << "LDAP timeout initially: " << val << " seconds." << endl; // Test setting the option directly, then querying again //system( "echo 'ldaptimeout:0:101' | gpgconf --change-options dirmngr" ); // Now let's do it with the C++ API instead entry->setUIntValue( 101 ); assert( entry->isDirty() ); config->sync( true ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); assert( entry ); assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ); cout << "LDAP timeout now: " << entry->uintValue() << " seconds." << endl; assert( entry->uintValue() == 101 ); // Set to default entry->resetToDefault(); assert( entry->uintValue() == 100 ); assert( entry->isDirty() ); assert( !entry->isSet() ); config->sync( true ); config->clear(); // Check value entry = config->entry( "dirmngr", s_groupName, s_entryName ); assert( !entry->isDirty() ); assert( !entry->isSet() ); cout << "LDAP timeout reset to default, " << entry->uintValue() << " seconds." << endl; assert( entry->uintValue() == 100 ); // Reset old value entry->setUIntValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "LDAP timeout reset to initial " << val << " seconds." << endl; } else cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl; } { // Static querying and setting of a single string option static const char* s_groupName = "Debug"; static const char* s_entryName = "log-file"; Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); if ( entry ) { assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path ); QString val = entry->stringValue(); cout << "Log-file initially: " << val.local8Bit() << endl; // Test setting the option, sync'ing, then querying again entry->setStringValue( "/tmp/test:%e5" ); assert( entry->isDirty() ); config->sync( true ); // Let's see how it prints it system( "gpgconf --list-options dirmngr | grep log-file" ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); assert( entry ); assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path ); cout << "Log-file now: " << entry->stringValue().local8Bit() << endl; assert( entry->stringValue() == "/tmp/test:%e5" ); // (or even with %e5 decoded) // Reset old value #if 0 QString arg( val ); if ( !arg.isEmpty() ) arg.prepend( '"' ); QCString sys; sys.sprintf( "echo 'log-file:%s' | gpgconf --change-options dirmngr", arg.local8Bit().data() ); system( sys.data() ); #endif entry->setStringValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "Log-file reset to initial " << val.local8Bit() << endl; } else cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl; } { // Static querying and setting of the LDAP URL list option static const char* s_groupName = "LDAP"; static const char* s_entryName = "LDAP Server"; Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); if ( entry ) { assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_LDAPURL ); assert( entry->isList() ); KURL::List val = entry->urlValueList(); cout << "URL list initially: " << val.toStringList().join(", ").local8Bit() << endl; // Test setting the option, sync'ing, then querying again KURL::List lst; // We use non-empty paths to workaround a bug in KURL (kdelibs-3.2) lst << KURL( "ldap://a:389/?b" ); // Test with query containing a litteral ':' (KURL supports this) // and a ' ' (KURL will escape it, see issue119) lst << KURL( "ldap://foo:389/?a:b c" ); lst << KURL( "ldap://server:389/?a%3db,c=DE" ); // the query contains a litteral ',' //cout << " trying to set: " << lst.toStringList().join(", ").local8Bit() << endl; assert( lst[0].query() == "?b" ); assert( lst[1].query() == "?a:b%20c" ); // see, the space got escaped entry->setURLValueList( lst ); assert( entry->isDirty() ); config->sync( true ); // Let's see how it prints it system( "gpgconf --list-options dirmngr | grep 'LDAP Server'" ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); assert( entry ); assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_LDAPURL ); assert( entry->isList() ); // Get raw a:b:c:d:e form QStringList asStringList = entry->stringValueList(); assert( asStringList.count() == 3 ); cout << "asStringList[0]=" << asStringList[0].local8Bit() << endl; cout << "asStringList[1]=" << asStringList[1].local8Bit() << endl; cout << "asStringList[2]=" << asStringList[2].local8Bit() << endl; assert( asStringList[0] == "a:389:::b" ); assert( asStringList[1] == "foo:389:::a%3ab c" ); // the space must be decoded (issue119) assert( asStringList[2] == "server:389:::a=b,c=DE" ); // all decoded // Get KURL form KURL::List newlst = entry->urlValueList(); cout << "URL list now: " << newlst.toStringList().join(", ").local8Bit() << endl; assert( newlst.count() == 3 ); //cout << "newlst[0]=" << newlst[0].url().local8Bit() << endl; //cout << "lst[0]=" << lst[0].url().local8Bit() << endl; assert( newlst[0] == lst[0] ); assert( newlst[1] == lst[1] ); assert( newlst[2].url() == "ldap://server:389/?a=b,c=DE" ); // != lst[2] due to the encoded = // Reset old value entry->setURLValueList( val ); assert( entry->isDirty() ); config->sync( true ); cout << "URL list reset to initial: " << val.toStringList().join(", ").local8Bit() << endl; } else cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl; } cout << "Done." << endl; } diff --git a/certmanager/lib/tests/test_gnupgprocessbase.cpp b/certmanager/lib/tests/test_gnupgprocessbase.cpp index dc71d08e56..37e961801f 100644 --- a/certmanager/lib/tests/test_gnupgprocessbase.cpp +++ b/certmanager/lib/tests/test_gnupgprocessbase.cpp @@ -1,143 +1,143 @@ /* gnupgviewer.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "gnupgviewer.h" #include #include #include #include #include #include #include GnuPGViewer::GnuPGViewer( QWidget * parent, const char * name ) : QTextEdit( parent, name ), mProcess( 0 ) { setTextFormat( LogText ); setMaxLogLines( 10000 ); } GnuPGViewer::~GnuPGViewer() { if ( mProcess ) mProcess->kill(); } void GnuPGViewer::setProcess( Kleo::GnuPGProcessBase * process ) { if ( !process ) return; mProcess = process; connect( mProcess, SIGNAL(processExited(KProcess*)), SLOT(slotProcessExited(KProcess*)) ); connect( mProcess, SIGNAL(receivedStdout(KProcess*,char*,int)), SLOT(slotStdout(KProcess*,char*,int)) ); connect( mProcess, SIGNAL(receivedStderr(KProcess*,char*,int)), SLOT(slotStderr(KProcess*,char*,int)) ); connect( mProcess, SIGNAL(status(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)), SLOT(slotStatus(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)) ); } static QStringList split( char * buffer, int buflen, QString & old ) { // when done right, this would need to use QTextCodec... const QString str = old + QString::fromLocal8Bit( buffer, buflen ); QStringList l = QStringList::split( '\n', str, true ); if ( l.empty() ) return l; if ( str.endsWith( "\n" ) ) { old = QString::null; } else { old = l.back(); l.pop_back(); } return l; } static QString escape( QString str ) { return str.replace( '&', "&" ).replace( '<', "<" ).replace( '>', ">" ); } void GnuPGViewer::slotStdout( KProcess *, char * buffer, int buflen ) { const QStringList l = split( buffer, buflen, mLastStdout ); for ( QStringList::const_iterator it = l.begin() ; it != l.end() ; ++it ) append( "stdout: " + escape( *it ) ); } void GnuPGViewer::slotStderr( KProcess *, char * buffer, int buflen ) { const QStringList l = split( buffer, buflen, mLastStderr ); for ( QStringList::const_iterator it = l.begin() ; it != l.end() ; ++it ) append( "stderr: " + escape( *it ) + "" ); } void GnuPGViewer::slotStatus( Kleo::GnuPGProcessBase *, const QString & type, const QStringList & args ) { append( "status: " + escape( type + ' ' + args.join( " " ) ) + "" ); } void GnuPGViewer::slotProcessExited( KProcess * proc ) { if ( !proc ) return; if ( proc->normalExit() ) append( QString( "Process exit: return code %1" ).arg ( proc->exitStatus() ) ); else append( "Process exit: killed" ); } int main( int argc, char** argv ) { if ( argc < 3 ) { kdDebug() << "Need at least two arguments" << endl; return 1; } KAboutData aboutData( "test_gnupgprocessbase", "GnuPGProcessBase Test", "0.1" ); KCmdLineArgs::init( &aboutData ); KApplication app; Kleo::GnuPGProcessBase gpg; for ( int i = 1 ; i < argc ; ++i ) gpg << argv[i]; gpg.setUseStatusFD( true ); GnuPGViewer * gv = new GnuPGViewer(); gv->setProcess( &gpg ); app.setMainWidget( gv ); gv->show(); gpg.start( KProcess::NotifyOnExit, KProcess::AllOutput ); return app.exec(); } #include "gnupgviewer.moc" diff --git a/certmanager/lib/tests/test_jobs.cpp b/certmanager/lib/tests/test_jobs.cpp index dd49abb017..22d9136d4d 100644 --- a/certmanager/lib/tests/test_jobs.cpp +++ b/certmanager/lib/tests/test_jobs.cpp @@ -1,108 +1,108 @@ /* test_jobs.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include static const char * protocol = 0; static void testSign() { const Kleo::CryptoBackend::Protocol * proto = protocol == "openpgp" ? Kleo::CryptoBackendFactory::instance()->openpgp() : Kleo::CryptoBackendFactory::instance()->smime() ; assert( proto ); kdDebug() << "Using protocol " << proto->name() << endl; std::vector signingKeys; std::auto_ptr listJob( proto->keyListJob( false, false, true ) ); // use validating keylisting if ( listJob.get() ) { // ##### Adjust this to your own identity listJob->exec( "faure@kde.org", true /*secret*/, signingKeys ); assert( !signingKeys.empty() ); } else { assert( 0 ); // job failed } Kleo::SignJob* job = proto->signJob( true, true ); QCString cText = "Hallo Leute\n"; // like gpgme's t-sign.c QByteArray plainText; plainText.duplicate( cText.data(), cText.length() ); // hrmpf... kdDebug() << k_funcinfo << "plainText=" << cText.data() << endl; kdDebug() << k_funcinfo << " signing with " << signingKeys[0].primaryFingerprint() << endl; QByteArray signature; const GpgME::SigningResult res = job->exec( signingKeys, plainText, GpgME::Context::Clearsigned, signature ); if ( res.error().isCanceled() ) { kdDebug() << "signing was canceled by user" << endl; return; } if ( res.error() ) { kdDebug() << "signing failed: " << res.error().asString() << endl; return; } kdDebug() << k_funcinfo << "signing resulted in signature=" << QCString( signature.data(), signature.size() + 1 ) << endl; } int main( int argc, char** argv ) { protocol = "openpgp"; if ( argc == 2 ) { protocol = argv[1]; argc = 1; // hide from KDE } KAboutData aboutData( "test_jobs", "Signing Job Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app; testSign(); } diff --git a/certmanager/lib/tests/test_keygen.cpp b/certmanager/lib/tests/test_keygen.cpp index 2949456174..9303b331cd 100644 --- a/certmanager/lib/tests/test_keygen.cpp +++ b/certmanager/lib/tests/test_keygen.cpp @@ -1,160 +1,160 @@ /* test_keygen.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "test_keygen.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const char * keyParams[] = { "Key-Type", "Key-Length", "Subkey-Type", "Subkey-Length", "Name-Real", "Name-Comment", "Name-Email", "Name-DN", "Expire-Date", "Passphrase" }; static const int numKeyParams = sizeof keyParams / sizeof *keyParams; static const char * protocol = 0; KeyGenerator::KeyGenerator( QWidget * parent, const char * name, WFlags ) : KDialogBase( parent, name, true, "KeyGenerationJob test", Close|User1, User1, true, KGuiItem( "Create" ) ) { QWidget * w = new QWidget( this ); setMainWidget( w ); QGridLayout * glay = new QGridLayout( w, numKeyParams+3, 2, marginHint(), spacingHint() ); int row = -1; ++row; glay->addMultiCellWidget( new QLabel( "", w ), row, row, 0, 1 ); for ( int i = 0 ; i < numKeyParams ; ++i ) { ++row; glay->addWidget( new QLabel( keyParams[i], w ), row, 0 ); glay->addWidget( mLineEdits[i] = new QLineEdit( w ), row, 1 ); } ++row; glay->addMultiCellWidget( new QLabel( "", w ), row, row, 0, 1 ); ++row; glay->setRowStretch( row, 1 ); glay->setColStretch( 1, 1 ); connect( this, SIGNAL(user1Clicked()), SLOT(slotStartKeyGeneration()) ); } KeyGenerator::~KeyGenerator() {} void KeyGenerator::slotStartKeyGeneration() { QString params = "\n"; for ( int i = 0 ; i < numKeyParams ; ++i ) if ( mLineEdits[i] && !mLineEdits[i]->text().stripWhiteSpace().isEmpty() ) params += keyParams[i] + ( ": " + mLineEdits[i]->text().stripWhiteSpace() ) + '\n'; params += "\n"; const Kleo::CryptoBackend::Protocol * proto = protocol == "openpgp" ? Kleo::CryptoBackendFactory::instance()->openpgp() : Kleo::CryptoBackendFactory::instance()->smime() ; if ( !proto ) proto = Kleo::CryptoBackendFactory::instance()->smime(); assert( proto ); kdDebug() << "Using protocol " << proto->name() << endl; Kleo::KeyGenerationJob * job = proto->keyGenerationJob(); assert( job ); connect( job, SIGNAL(result(const GpgME::KeyGenerationResult&,const QByteArray&)), SLOT(slotResult(const GpgME::KeyGenerationResult&,const QByteArray&)) ); const GpgME::Error err = job->start( params ); if ( err ) showError( err ); else (void)new Kleo::ProgressDialog( job, "Generating key", this ); } void KeyGenerator::showError( const GpgME::Error & err ) { KMessageBox::error( this, "Could not start key generation: " + QString::fromLocal8Bit( err.asString() ), "Key Generation Error" ); } void KeyGenerator::slotResult( const GpgME::KeyGenerationResult & res, const QByteArray & keyData ) { if ( res.error() ) showError( res.error() ); else KMessageBox::information( this, QString("Key generated successfully, %1 bytes long").arg( keyData.size() ), "Key Generation Finished" ); } int main( int argc, char** argv ) { if ( argc == 2 ) { protocol = argv[1]; argc = 1; // hide from KDE } KAboutData aboutData( "test_keygen", "KeyGenerationJob Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app; KeyGenerator * keygen = new KeyGenerator( 0, "KeyGenerator top-level" ); app.setMainWidget( keygen ); keygen->show(); return app.exec(); } #include "test_keygen.moc" diff --git a/certmanager/lib/tests/test_keygen.h b/certmanager/lib/tests/test_keygen.h index c3b3a3f136..0ba7138237 100644 --- a/certmanager/lib/tests/test_keygen.h +++ b/certmanager/lib/tests/test_keygen.h @@ -1,62 +1,62 @@ /* test_keygen.h This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_TEST_KEYGEN_H__ #define __KLEO_TEST_KEYGEN_H__ #include #include namespace GpgME { class Error; class KeyGenerationResult; } class QLineEdit; class KeyGenerator : public KDialogBase { Q_OBJECT public: KeyGenerator( QWidget * parent=0, const char * name=0, WFlags f=0 ); ~KeyGenerator(); public slots: void slotStartKeyGeneration(); void slotResult( const GpgME::KeyGenerationResult & res, const QByteArray & keyData ); private: void showError( const GpgME::Error & err ); private: QLineEdit * mLineEdits[20]; }; #endif // __KLEO_TEST_KEYGEN_H__ diff --git a/certmanager/lib/tests/test_keylister.cpp b/certmanager/lib/tests/test_keylister.cpp index dd1eb26365..9507221e77 100644 --- a/certmanager/lib/tests/test_keylister.cpp +++ b/certmanager/lib/tests/test_keylister.cpp @@ -1,146 +1,146 @@ /* test_keylister.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include #include "test_keylister.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { class TestColumnStrategy : public Kleo::KeyListView::ColumnStrategy { public: ~TestColumnStrategy() {} QString title( int col ) const; QString toolTip( const GpgME::Key & key, int col ) const; QString text( const GpgME::Key & key, int col ) const; }; QString TestColumnStrategy::title( int col ) const { switch ( col ) { case 0: return "Subject"; case 1: return "EMail"; case 2: return "Issuer"; case 3: return "Serial"; case 4: return "Protocol"; case 5: return "Validity"; default: return QString::null; } } QString TestColumnStrategy::toolTip( const GpgME::Key & key, int ) const { return "Fingerprint: " + QString::fromUtf8( key.primaryFingerprint() ); } QString TestColumnStrategy::text( const GpgME::Key & key, int col ) const { if ( key.isNull() ) return ""; switch ( col ) { case 0: return QString::fromUtf8( key.userID(0).id() ); case 1: return QString::fromUtf8( key.userID(0).email() ); case 2: return QString::fromUtf8( key.issuerName() ); case 3: return key.issuerSerial(); case 4: return key.protocolAsString(); case 5: return QChar( key.userID(0).validityAsString() ); default: return QString::null; } } } CertListView::CertListView( QWidget * parent, const char * name, WFlags f ) : Kleo::KeyListView( new TestColumnStrategy(), 0, parent, name, f ) { setHierarchical( true ); setRootIsDecorated( true ); } void CertListView::slotResult( const GpgME::KeyListResult & result ) { kdDebug() << "CertListView::slotResult()" << endl; if ( result.isNull() ) QMessageBox::information( this, "Key Listing Result", "KeyListResult is null!" ); else if ( result.error() ) QMessageBox::critical( this, "Key Listing Result", QString("KeyListResult Error: %1").arg( result.error().asString() ) ); else if ( result.isTruncated() ) QMessageBox::information( this, "Key Listing Result", "KeyListResult is truncated!" ); else QMessageBox::information( this, "Key Listing Result", "Key listing successful" ); } void CertListView::slotStart() { kdDebug() << "CertListView::slotStart()" << endl; Kleo::KeyListJob * job = Kleo::CryptoBackendFactory::instance()->smime()->keyListJob( false ); assert( job ); QObject::connect( job, SIGNAL(nextKey(const GpgME::Key&)), this, SLOT(slotAddKey(const GpgME::Key&)) ); QObject::connect( job, SIGNAL(result(const GpgME::KeyListResult&)), this, SLOT(slotResult(const GpgME::KeyListResult&)) ); #if 0 QStringList l; l << "Marc"; job->start( l, false ); #else job->start( QStringList(), false ); #endif } int main( int argc, char** argv ) { KAboutData aboutData( "test_keylister", "KeyLister Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app; CertListView * clv = new CertListView( 0, "CertListView top-level" ); app.setMainWidget( clv ); clv->show(); QTimer::singleShot( 5000, clv, SLOT(slotStart()) ); return app.exec(); } #include "test_keylister.moc" diff --git a/certmanager/lib/tests/test_keylister.h b/certmanager/lib/tests/test_keylister.h index b800355092..348ec262ff 100644 --- a/certmanager/lib/tests/test_keylister.h +++ b/certmanager/lib/tests/test_keylister.h @@ -1,52 +1,52 @@ /* test_keylister.h This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_TEST_KEYLISTER_H__ #define __KLEO_TEST_KEYLISTER_H__ #include namespace GpgME { class Key; class KeyListResult; } class CertListView : public Kleo::KeyListView { Q_OBJECT public: CertListView( QWidget * parent=0, const char * name=0, WFlags f=0 ); public slots: void slotResult( const GpgME::KeyListResult & result ); void slotStart(); }; #endif // __KLEO_TEST_KEYLISTER_H__ diff --git a/certmanager/lib/tests/test_keyselectiondialog.cpp b/certmanager/lib/tests/test_keyselectiondialog.cpp index 76797576b1..e6c85fca0b 100644 --- a/certmanager/lib/tests/test_keyselectiondialog.cpp +++ b/certmanager/lib/tests/test_keyselectiondialog.cpp @@ -1,67 +1,67 @@ /* test_keygen.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include #include #include #include #include #include #include #include #include #include int main( int argc, char ** argv ) { KAboutData aboutData( "test_keyselectiondialog", "KeySelectionDialog Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app; KGlobal::iconLoader()->addAppDir( "libkleopatra" ); Kleo::KeySelectionDialog dlg( "Kleo::KeySelectionDialog Test", "Please select a key:", std::vector(), Kleo::KeySelectionDialog::AllKeys, true, true ); if ( dlg.exec() == QDialog::Accepted ) { kdDebug() << "accepted; selected key: " << (dlg.selectedKey().userID(0).id() ? dlg.selectedKey().userID(0).id() : "") << "\nselected _keys_:" << endl; for ( std::vector::const_iterator it = dlg.selectedKeys().begin() ; it != dlg.selectedKeys().end() ; ++it ) kdDebug() << (it->userID(0).id() ? it->userID(0).id() : "") << endl; } else { kdDebug() << "rejected" << endl; } return 0; } diff --git a/certmanager/lib/ui/Makefile.am b/certmanager/lib/ui/Makefile.am index c3e049fa0b..80c6e96dd5 100644 --- a/certmanager/lib/ui/Makefile.am +++ b/certmanager/lib/ui/Makefile.am @@ -1,38 +1,40 @@ INCLUDES = -I$(top_srcdir)/libkdenetwork \ -I$(top_srcdir)/libkpgp \ -I$(top_srcdir)/certmanager/lib \ $(GPGME_CFLAGS) $(all_includes) noinst_LTLIBRARIES = libkleopatra_ui.la libkleopatra_ui_la_SOURCES = \ + kdhorizontalline.cpp \ progressbar.cpp \ progressdialog.cpp \ keylistview.cpp \ keyselectiondialog.cpp \ keyrequester.cpp \ passphrasedialog.cpp \ keyapprovaldialog.cpp \ backendconfigwidget.cpp \ dnattributeorderconfigwidget.cpp \ cryptoconfigmodule.cpp \ cryptoconfigdialog.cpp \ directoryserviceswidgetbase.ui \ directoryserviceswidget.cpp \ adddirectoryservicedialog.ui \ adddirectoryservicedialogimpl.cpp kleodir = $(includedir)/kleo kleo_HEADERS = \ + kdhorizontalline.h \ progressbar.h \ progressdialog.h \ keylistview.h \ keyselectiondialog.h \ keyrequester.h \ passphrasedialog.h \ keyapprovaldialog.h \ backendconfigwidget.h \ dnattributeorderconfigwidget.h METASOURCES = AUTO diff --git a/certmanager/lib/ui/adddirectoryservicedialogimpl.cpp b/certmanager/lib/ui/adddirectoryservicedialogimpl.cpp index 01d03de87c..973266b161 100644 --- a/certmanager/lib/ui/adddirectoryservicedialogimpl.cpp +++ b/certmanager/lib/ui/adddirectoryservicedialogimpl.cpp @@ -1,63 +1,63 @@ /* adddirectoryservicedialogimpl.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "adddirectoryservicedialogimpl.h" #include #include /* * Constructs a AddDirectoryServiceDialogImpl which is 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. */ AddDirectoryServiceDialogImpl::AddDirectoryServiceDialogImpl( QWidget* parent, const char* name, bool modal, WFlags fl ) : AddDirectoryServiceDialog( parent, name, modal, fl ) { portED->setValidator( new QIntValidator( 0, 65535, portED ) ); } /* * Destroys the object and frees any allocated resources */ AddDirectoryServiceDialogImpl::~AddDirectoryServiceDialogImpl() { // no need to delete child widgets, Qt does it all for us } #include "adddirectoryservicedialogimpl.moc" diff --git a/certmanager/lib/ui/adddirectoryservicedialogimpl.h b/certmanager/lib/ui/adddirectoryservicedialogimpl.h index 18c1a5596e..deee06439f 100644 --- a/certmanager/lib/ui/adddirectoryservicedialogimpl.h +++ b/certmanager/lib/ui/adddirectoryservicedialogimpl.h @@ -1,47 +1,47 @@ /* adddirectoryservicedialogimpl.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef ADDDIRECTORYSERVICEDIALOGIMPL_H #define ADDDIRECTORYSERVICEDIALOGIMPL_H #include "adddirectoryservicedialog.h" class AddDirectoryServiceDialogImpl : public AddDirectoryServiceDialog { Q_OBJECT public: AddDirectoryServiceDialogImpl( QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0 ); ~AddDirectoryServiceDialogImpl(); }; #endif // ADDDIRECTORYSERVICEDIALOGIMPL_H diff --git a/certmanager/lib/ui/backendconfigwidget.cpp b/certmanager/lib/ui/backendconfigwidget.cpp index aa1c393f94..c40890a430 100644 --- a/certmanager/lib/ui/backendconfigwidget.cpp +++ b/certmanager/lib/ui/backendconfigwidget.cpp @@ -1,326 +1,323 @@ /* -*- c++ -*- backendconfigwidget.cpp This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2002,2004 Klarlvdalens Datakonsult AB + Copyright (c) 2002,2004,2005 Klarlvdalens Datakonsult AB Copyright (c) 2002,2003 Marc Mutz Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "backendconfigwidget.h" #include "cryptoconfigdialog.h" #include "kleo/cryptobackendfactory.h" +#include "ui/keylistview.h" // for lvi_cast<> #include #include #include #include #include #include #include #include #include #include +#include #include namespace Kleo { class BackendListView; } class Kleo::BackendConfigWidget::Private { public: Kleo::BackendListView * listView; QPushButton * configureButton; QPushButton * rescanButton; Kleo::CryptoBackendFactory * backendFactory; }; namespace Kleo { class BackendListViewItem; class ProtocolCheckListItem; - enum ProtocolType { OpenPGP, SMIME }; } class Kleo::BackendListView : public KListView { public: BackendListView( BackendConfigWidget* parent, const char* name = 0 ) : KListView( parent, name ) {} /// return backend for currently selected (/current) item. Used by Configure button. const Kleo::CryptoBackend* currentBackend() const; /// return which protocol implementation was chosen (checked) for each type (used when saving) - const Kleo::CryptoBackend* chosenBackend( ProtocolType protocolType ); + const Kleo::CryptoBackend* chosenBackend( const char * protocol ); /// deselect all except one for a given protocol type (radiobutton-like exclusivity) - void deselectAll( ProtocolType protocolType, QCheckListItem* except ); + void deselectAll( const char * protocol, QCheckListItem* except ); void emitChanged() { static_cast( parentWidget() )->emitChanged( true ); } }; // Toplevel listviewitem for a given backend (e.g. "GpgME", "Kgpg/gpg v2") class Kleo::BackendListViewItem : public QListViewItem { public: BackendListViewItem( KListView* lv, QListViewItem *prev, const CryptoBackend *cryptoBackend ) : QListViewItem( lv, prev, cryptoBackend->displayName() ), mCryptoBackend( cryptoBackend ) {} const CryptoBackend *cryptoBackend() const { return mCryptoBackend; } - static const int RTTI = 20001; - virtual int rtti() const { return RTTI; } + enum { RTTI = 0x2EAE3BE0, RTTI_MASK = 0xFFFFFFFF }; + int rtti() const { return RTTI; } private: const CryptoBackend *mCryptoBackend; }; // Checklist item under a BackendListViewItem // (e.g. "GpgME supports protocol OpenPGP") class Kleo::ProtocolCheckListItem : public QCheckListItem { public: ProtocolCheckListItem( BackendListViewItem* blvi, - QListViewItem* prev, - ProtocolType protocolType, + QListViewItem* prev, const char * protocolName, const CryptoBackend::Protocol* protocol ) // can be 0 - : QCheckListItem( blvi, prev, itemText( protocolType, protocol ), + : QCheckListItem( blvi, prev, itemText( protocolName, protocol ), QCheckListItem::CheckBox ), - mProtocol( protocol ), mProtocolType( protocolType ) + mProtocol( protocol ), mProtocolName( protocolName ) {} - static const int RTTI = 20002; + enum { RTTI = 0x2EAE3BE1, RTTI_MASK = 0xFFFFFFFF }; virtual int rtti() const { return RTTI; } // can be 0 const CryptoBackend::Protocol* protocol() const { return mProtocol; } - ProtocolType protocolType() const { return mProtocolType; } + const char * protocolName() const { return mProtocolName; } protected: virtual void stateChange( bool b ) { BackendListView* lv = static_cast( listView() ); // "radio-button-like" behavior for the protocol checkboxes if ( b ) - lv->deselectAll( mProtocolType, this ); + lv->deselectAll( mProtocolName, this ); lv->emitChanged(); QCheckListItem::stateChange( b ); } private: // Helper for the constructor. - static QString itemText( ProtocolType protocolType, const CryptoBackend::Protocol* protocol ) { - // First one is the generic name (OpenPGP, SMIME) - QString protoTypeName = protocolType == OpenPGP ? i18n( "OpenPGP" ) : i18n( "S/MIME" ); + static QString itemText( const char * protocolName, const CryptoBackend::Protocol* protocol ) { + // First one is the generic name (find a nice one for OpenPGP, SMIME) + const QString protoName = qstricmp( protocolName, "openpgp" ) != 0 + ? qstricmp( protocolName, "smime" ) != 0 + ? QString::fromLatin1( protocolName ) + : i18n( "S/MIME" ) + : i18n( "OpenPGP" ); // second one is implementation name (gpg, gpgsm...) - QString impName = protocol ? protocol->displayName() : i18n( "failed" ); - return QString( "%1 (%2)" ).arg( protoTypeName ).arg( impName ); + const QString impName = protocol ? protocol->displayName() : i18n( "failed" ); + return i18n( "Items in Kleo::BackendConfigWidget listview (1: protocol; 2: implementation name)", + "%1 (%2)" ).arg( protoName, impName ); } const CryptoBackend::Protocol* mProtocol; // can be 0 - ProtocolType mProtocolType; + const char * mProtocolName; }; const Kleo::CryptoBackend* Kleo::BackendListView::currentBackend() const { - QListViewItem* curItem = currentItem(); + const QListViewItem* curItem = currentItem(); if ( !curItem ) // can't happen return 0; - if ( curItem->rtti() == Kleo::ProtocolCheckListItem::RTTI ) + if ( lvi_cast( curItem ) ) curItem = curItem->parent(); - if ( curItem && curItem->rtti() == Kleo::BackendListViewItem::RTTI ) - return static_cast( curItem )->cryptoBackend(); + if ( const Kleo::BackendListViewItem * blvi = lvi_cast( curItem ) ) + return blvi->cryptoBackend(); return 0; } // can't be const method due to QListViewItemIterator (why?) -const Kleo::CryptoBackend* Kleo::BackendListView::chosenBackend( ProtocolType protocolType ) +const Kleo::CryptoBackend* Kleo::BackendListView::chosenBackend( const char * protocolName ) { - QListViewItemIterator it( this /*, QListViewItemIterator::Checked doesn't work*/ ); - for ( ; it.current() ; ++it ) { - if( it.current()->rtti() == Kleo::ProtocolCheckListItem::RTTI ) { - Kleo::ProtocolCheckListItem* p = static_cast( it.current() ); - if ( p->isOn() && p->protocolType() == protocolType ) { + for ( QListViewItemIterator it( this /*, QListViewItemIterator::Checked doesn't work*/ ) ; + it.current() ; ++it ) + if ( ProtocolCheckListItem * p = lvi_cast( it.current() ) ) + if ( p->isOn() && qstricmp( p->protocolName(), protocolName ) == 0 ) { // OK that's the one. Now go up to the parent backend // (need to do that in the listview since Protocol doesn't know it) - QListViewItem* parItem = it.current()->parent(); - if ( parItem && parItem->rtti() == Kleo::BackendListViewItem::RTTI ) - return static_cast( parItem )->cryptoBackend(); + if ( const BackendListViewItem * parItem = lvi_cast( it.current()->parent() ) ) + return parItem->cryptoBackend(); } - } - } return 0; } -void Kleo::BackendListView::deselectAll( ProtocolType protocolType, QCheckListItem* except ) +void Kleo::BackendListView::deselectAll( const char * protocolName, QCheckListItem* except ) { - QListViewItemIterator it( this /*, QListViewItemIterator::Checked doesn't work*/ ); - for ( ; it.current() ; ++it ) { - if( it.current() != except && - it.current()->rtti() == Kleo::ProtocolCheckListItem::RTTI ) { - Kleo::ProtocolCheckListItem* p = static_cast( it.current() ); - if ( p->isOn() && p->protocolType() == protocolType ) + for ( QListViewItemIterator it( this /*, QListViewItemIterator::Checked doesn't work*/ ) ; + it.current() ; ++it ) { + if ( it.current() == except ) continue; + if ( ProtocolCheckListItem * p = lvi_cast( it.current() ) ) + if ( p->isOn() && qstricmp( p->protocolName(), protocolName ) == 0 ) p->setOn( false ); - } } } //// Kleo::BackendConfigWidget::BackendConfigWidget( CryptoBackendFactory * factory, QWidget * parent, const char * name, WFlags f ) : QWidget( parent, name, f ), d( 0 ) { assert( factory ); d = new Private(); d->backendFactory = factory; QHBoxLayout * hlay = new QHBoxLayout( this, 0, KDialog::spacingHint() ); d->listView = new BackendListView( this, "d->listView" ); d->listView->addColumn( i18n("Available Backends") ); d->listView->setAllColumnsShowFocus( true ); d->listView->setSorting( -1 ); d->listView->header()->setClickEnabled( false ); d->listView->setFullWidth( true ); hlay->addWidget( d->listView, 1 ); connect( d->listView, SIGNAL(selectionChanged(QListViewItem*)), SLOT(slotSelectionChanged(QListViewItem*)) ); QVBoxLayout * vlay = new QVBoxLayout( hlay ); // inherits spacing d->configureButton = new QPushButton( i18n("Confi&gure..."), this ); d->configureButton->setAutoDefault( false ); vlay->addWidget( d->configureButton ); connect( d->configureButton, SIGNAL(clicked()), SLOT(slotConfigureButtonClicked()) ); d->rescanButton = new QPushButton( i18n("Rescan"), this ); d->rescanButton->setAutoDefault( false ); vlay->addWidget( d->rescanButton ); connect( d->rescanButton, SIGNAL(clicked()), SLOT(slotRescanButtonClicked()) ); vlay->addStretch( 1 ); } Kleo::BackendConfigWidget::~BackendConfigWidget() { delete d; d = 0; } void Kleo::BackendConfigWidget::load() { d->listView->clear(); unsigned int backendCount = 0; // populate the plugin list: BackendListViewItem * top = 0; for ( unsigned int i = 0 ; const CryptoBackend * b = d->backendFactory->backend( i ) ; ++i ) { - const CryptoBackend::Protocol * openpgp = b->openpgp(); - const CryptoBackend::Protocol * smime = b->smime(); top = new Kleo::BackendListViewItem( d->listView, top, b ); + ProtocolCheckListItem * last = 0; - if ( openpgp ) { - last = new ProtocolCheckListItem( top, last, Kleo::OpenPGP, openpgp ); - last->setOn( openpgp == d->backendFactory->openpgp() ); - } else if ( b->supportsOpenPGP() ) { - last = new ProtocolCheckListItem( top, last, Kleo::OpenPGP, 0 ); - last->setOn( false ); - last->setEnabled( false ); - } - if ( smime ) { - last = new ProtocolCheckListItem( top, last, Kleo::SMIME, smime ); - last->setOn( smime == d->backendFactory->smime() ); - } else if ( b->supportsSMIME() ) { - last = new ProtocolCheckListItem( top, last, Kleo::SMIME, 0 ); - last->setOn( false ); - last->setEnabled( false ); + for ( int i = 0 ; const char * name = b->enumerateProtocols( i ) ; ++i ) { + const CryptoBackend::Protocol * protocol = b->protocol( name ); + + if ( protocol ) { + last = new ProtocolCheckListItem( top, last, name, protocol ); + last->setOn( protocol == d->backendFactory->protocol( name ) ); + } else if ( b->supportsProtocol( name ) ) { + last = new ProtocolCheckListItem( top, last, name, 0 ); + last->setOn( false ); + last->setEnabled( false ); + } } - top->setOpen( true ); + top->setOpen( true ); ++backendCount; } if ( backendCount ) { d->listView->setCurrentItem( d->listView->firstChild() ); d->listView->setSelected( d->listView->firstChild(), true ); } slotSelectionChanged( d->listView->firstChild() ); } void Kleo::BackendConfigWidget::slotSelectionChanged( QListViewItem * ) { const CryptoBackend* backend = d->listView->currentBackend(); + if ( backend && !backend->config() ) + kdDebug(5150) << "Backend w/o config object!" << endl; d->configureButton->setEnabled( backend && backend->config() ); } void Kleo::BackendConfigWidget::slotRescanButtonClicked() { QStringList reasons; d->backendFactory->scanForBackends( &reasons ); if ( !reasons.empty() ) KMessageBox::informationList( this, i18n("The following problems where encountered during scanning:"), reasons, i18n("Scan Results") ); load(); emit changed( true ); } void Kleo::BackendConfigWidget::slotConfigureButtonClicked() { const CryptoBackend* backend = d->listView->currentBackend(); if ( backend && backend->config() ) { - Kleo::CryptoConfigDialog dlg( backend->config() ); + Kleo::CryptoConfigDialog dlg( backend->config(), this ); int result = dlg.exec(); - if ( result == QDialog::Accepted ) - { + if ( result == QDialog::Accepted ) { // Tell other users of gpgconf (e.g. the s/mime page) that the gpgconf data might have changed kapp->dcopClient()->emitDCOPSignal( "KPIM::CryptoConfig", "changed()", QByteArray() ); + // and schedule a rescan, in case the updates make a backend valid + QTimer::singleShot( 0, this, SLOT(slotRescanButtonClicked()) ); } } else // shouldn't happen, button is disabled kdWarning(5150) << "Can't configure backend, no config object available" << endl; } void Kleo::BackendConfigWidget::save() const { - d->backendFactory->setSMIMEBackend( d->listView->chosenBackend( Kleo::SMIME ) ); - d->backendFactory->setOpenPGPBackend( d->listView->chosenBackend( Kleo::OpenPGP ) ); + for ( int i = 0 ; const char * name = d->backendFactory->enumerateProtocols( i ) ; ++i ) + d->backendFactory->setProtocolBackend( name, d->listView->chosenBackend( name ) ); } void Kleo::BackendConfigWidget::virtual_hook( int, void* ) {} #include "backendconfigwidget.moc" diff --git a/certmanager/lib/ui/backendconfigwidget.h b/certmanager/lib/ui/backendconfigwidget.h index 220a8ca0da..0e26655ce4 100644 --- a/certmanager/lib/ui/backendconfigwidget.h +++ b/certmanager/lib/ui/backendconfigwidget.h @@ -1,76 +1,76 @@ /* -*- c++ -*- backendconfigwidget.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2002,2004 Klarlvdalens Datakonsult AB Copyright (c) 2002,2003 Marc Mutz Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_UI_BACKENDCONFIGWIDGET_H__ #define __KLEO_UI_BACKENDCONFIGWIDGET_H__ #include #include namespace Kleo { class CryptoBackendFactory; } class QListViewItem; namespace Kleo { class KDE_EXPORT BackendConfigWidget : public QWidget { Q_OBJECT public: BackendConfigWidget( CryptoBackendFactory * factory, QWidget * parent=0, const char * name=0, WFlags f=0 ); ~BackendConfigWidget(); void load(); void save() const; void emitChanged( bool b ) { emit changed( b ); } signals: void changed( bool ); private slots: void slotSelectionChanged( QListViewItem * ); void slotRescanButtonClicked(); void slotConfigureButtonClicked(); private: class Private; Private * d; protected: virtual void virtual_hook( int, void* ); }; } #endif // __KLEO_UI_BACKENDCONFIGWIDGET_H__ diff --git a/certmanager/lib/ui/cryptoconfigdialog.cpp b/certmanager/lib/ui/cryptoconfigdialog.cpp index 9d9f71dc62..3fa0a97ca8 100644 --- a/certmanager/lib/ui/cryptoconfigdialog.cpp +++ b/certmanager/lib/ui/cryptoconfigdialog.cpp @@ -1,89 +1,89 @@ /* cryptoconfigdialog.h This file is part of kgpgcertmanager Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "cryptoconfigdialog.h" #include "cryptoconfigmodule.h" #include #include Kleo::CryptoConfigDialog::CryptoConfigDialog( Kleo::CryptoConfig* config, QWidget *parent, const char* name ) : KDialogBase( Swallow, // Remove the "whats's this" button since we have no support for it WStyle_Customize | WStyle_DialogBorder | WStyle_Maximize | WStyle_Title | WStyle_SysMenu, parent, name, true /*modal*/, i18n( "Configure" ), Default|Cancel|Apply|Ok|User1, Ok, true /*separator*/, KGuiItem( i18n( "&Reset" ), "undo" ) ) { mMainWidget = new CryptoConfigModule( config, this ); setMainWidget( mMainWidget ); connect( mMainWidget, SIGNAL( changed() ), SLOT( slotChanged() ) ); enableButton( Apply, false ); // Automatically assign accelerators KAcceleratorManager::manage( this ); } void Kleo::CryptoConfigDialog::slotOk() { slotApply(); accept(); } void Kleo::CryptoConfigDialog::slotCancel() { mMainWidget->cancel(); reject(); } void Kleo::CryptoConfigDialog::slotDefault() { mMainWidget->defaults(); slotChanged(); } void Kleo::CryptoConfigDialog::slotApply() { mMainWidget->save(); enableButton( Apply, false ); } void Kleo::CryptoConfigDialog::slotUser1() // reset { mMainWidget->reset(); enableButton( Apply, false ); } void Kleo::CryptoConfigDialog::slotChanged() { enableButton( Apply, true ); } #include "cryptoconfigdialog.moc" diff --git a/certmanager/lib/ui/cryptoconfigdialog.h b/certmanager/lib/ui/cryptoconfigdialog.h index 808a78f3b2..484c55ea48 100644 --- a/certmanager/lib/ui/cryptoconfigdialog.h +++ b/certmanager/lib/ui/cryptoconfigdialog.h @@ -1,69 +1,69 @@ /* cryptoconfigdialog.h This file is part of kgpgcertmanager Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef CRYPTOCONFIGDIALOG_H #define CRYPTOCONFIGDIALOG_H #include #include namespace Kleo { class CryptoConfig; class CryptoConfigModule; /** * Simple KDialogBase wrapper around CryptoConfigModule */ class KDE_EXPORT CryptoConfigDialog : public KDialogBase { Q_OBJECT public: CryptoConfigDialog( Kleo::CryptoConfig* config, QWidget *parent = 0, const char* name = 0 ); protected: virtual void slotOk(); virtual void slotCancel(); virtual void slotDefault(); virtual void slotApply(); virtual void slotUser1(); // reset public slots: void slotChanged(); private: CryptoConfigModule* mMainWidget; }; } #endif /* CRYPTOCONFIGDIALOG_H */ diff --git a/certmanager/lib/ui/cryptoconfigmodule.cpp b/certmanager/lib/ui/cryptoconfigmodule.cpp index 88353c38c8..6c2128de11 100644 --- a/certmanager/lib/ui/cryptoconfigmodule.cpp +++ b/certmanager/lib/ui/cryptoconfigmodule.cpp @@ -1,456 +1,572 @@ /* cryptoconfigmodule.cpp This file is part of kgpgcertmanager Copyright (c) 2004 Klar�vdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "cryptoconfigmodule.h" +#include "cryptoconfigmodule_p.h" #include "directoryserviceswidget.h" +#include "kdhorizontalline.h" + #include #include #include #include #include #include #include #include +#include #include #include #include #include +#include #include #include using namespace Kleo; inline QPixmap loadIcon( QString s ) { return KGlobal::instance()->iconLoader() ->loadIcon( s.replace( QRegExp( "[^a-zA-Z0-9_]" ), "_" ), KIcon::NoGroup, KIcon::SizeMedium ); } +static const KJanusWidget::Face determineJanusFace( const Kleo::CryptoConfig * config ) { + return config && config->componentList().size() < 2 + ? KJanusWidget::Plain + : KJanusWidget::IconList ; +} + Kleo::CryptoConfigModule::CryptoConfigModule( Kleo::CryptoConfig* config, QWidget * parent, const char * name ) - : KJanusWidget( parent, name, KJanusWidget::IconList ), mConfig( config ) + : KJanusWidget( parent, name, determineJanusFace( config ) ), mConfig( config ) { -// QVBoxLayout *vlay = new QVBoxLayout( this, 0, KDialog::spacingHint() ); -// mTabWidget = new QTabWidget( this ); -// vlay->addWidget( mTabWidget ); - - QStringList components = config->componentList(); + QWidget * vbox = 0; + if ( face() == Plain ) { + vbox = plainPage(); + QVBoxLayout * vlay = new QVBoxLayout( vbox, 0, KDialog::spacingHint() ); + vlay->setAutoAdd( true ); + } - for( QStringList::Iterator compit = components.begin(); compit != components.end(); ++compit ) { - //kdDebug(5150) << "Component " << (*compit).local8Bit() << ":" << endl; - Kleo::CryptoConfigComponent* comp = config->component( *compit ); + const QStringList components = config->componentList(); + for ( QStringList::const_iterator it = components.begin(); it != components.end(); ++it ) { + //kdDebug(5150) << "Component " << (*it).local8Bit() << ":" << endl; + Kleo::CryptoConfigComponent* comp = config->component( *it ); Q_ASSERT( comp ); - if ( !comp->groupList().isEmpty() ) { - QVBox* vbox = addVBoxPage( comp->description(), QString::null, loadIcon( *compit ) ); - CryptoConfigComponentGUI* compGUI = - new CryptoConfigComponentGUI( this, comp, vbox, (*compit).local8Bit() ); - // KJanusWidget doesn't seem to have iterators, so we store a copy... - mComponentGUIs.append( compGUI ); + if ( comp->groupList().empty() ) + continue; + if ( face() != Plain ) { + vbox = addVBoxPage( comp->description(), QString::null, loadIcon( comp->iconName() ) ); } + CryptoConfigComponentGUI* compGUI = + new CryptoConfigComponentGUI( this, comp, vbox, (*it).local8Bit() ); + // KJanusWidget doesn't seem to have iterators, so we store a copy... + mComponentGUIs.append( compGUI ); } } void Kleo::CryptoConfigModule::save() { bool changed = false; QValueList::Iterator it = mComponentGUIs.begin(); for( ; it != mComponentGUIs.end(); ++it ) { if ( (*it)->save() ) changed = true; } if ( changed ) mConfig->sync(true /*runtime*/); } void Kleo::CryptoConfigModule::reset() { QValueList::Iterator it = mComponentGUIs.begin(); for( ; it != mComponentGUIs.end(); ++it ) { (*it)->load(); } } void Kleo::CryptoConfigModule::defaults() { QValueList::Iterator it = mComponentGUIs.begin(); for( ; it != mComponentGUIs.end(); ++it ) { (*it)->defaults(); } } void Kleo::CryptoConfigModule::cancel() { mConfig->clear(); } //// Kleo::CryptoConfigComponentGUI::CryptoConfigComponentGUI( CryptoConfigModule* module, Kleo::CryptoConfigComponent* component, QWidget* parent, const char* name ) -#ifdef USE_TABS // Old idea, dead code - : QTabWidget( parent, name ), -#else : QWidget( parent, name ), -#endif mComponent( component ) { -#ifndef USE_TABS - QVBoxLayout *vlay = new QVBoxLayout( this, 0, KDialog::spacingHint() ); -#endif - - QStringList groups = mComponent->groupList(); - for( QStringList::Iterator groupit = groups.begin(); groupit != groups.end(); ++groupit ) { - Kleo::CryptoConfigGroup* group = mComponent->group( *groupit ); - Q_ASSERT( group ); - CryptoConfigGroupGUI* gg = new CryptoConfigGroupGUI( module, group, this ); -#ifdef USE_TABS - addTab( gg, group->description() ); -#else - vlay->addWidget( gg ); -#endif - mGroupGUIs.append( gg ); + QGridLayout * glay = new QGridLayout( this, 1, 3, 0, KDialog::spacingHint() ); + const QStringList groups = mComponent->groupList(); + if ( groups.size() > 1 ) { + glay->setColSpacing( 0, KDHorizontalLine::indentHint() ); + for ( QStringList::const_iterator it = groups.begin(), end = groups.end() ; it != end; ++it ) { + Kleo::CryptoConfigGroup* group = mComponent->group( *it ); + Q_ASSERT( group ); + if ( !group ) + continue; + KDHorizontalLine * hl = new KDHorizontalLine( group->description(), this ); + const int row = glay->numRows(); + glay->addMultiCellWidget( hl, row, row, 0, 2 ); + mGroupGUIs.append( new CryptoConfigGroupGUI( module, group, glay, this ) ); + } + } else if ( !groups.empty() ) { + mGroupGUIs.append( new CryptoConfigGroupGUI( module, mComponent->group( groups.front() ), glay, this ) ); } + glay->setRowStretch( glay->numRows(), 1 ); } bool Kleo::CryptoConfigComponentGUI::save() { bool changed = false; QValueList::Iterator it = mGroupGUIs.begin(); for( ; it != mGroupGUIs.end(); ++it ) { if ( (*it)->save() ) changed = true; } return changed; } void Kleo::CryptoConfigComponentGUI::load() { QValueList::Iterator it = mGroupGUIs.begin(); for( ; it != mGroupGUIs.end(); ++it ) (*it)->load(); } void Kleo::CryptoConfigComponentGUI::defaults() { QValueList::Iterator it = mGroupGUIs.begin(); for( ; it != mGroupGUIs.end(); ++it ) (*it)->defaults(); } //// Kleo::CryptoConfigGroupGUI::CryptoConfigGroupGUI( CryptoConfigModule* module, Kleo::CryptoConfigGroup* group, - QWidget* parent, const char* name ) - : QGroupBox( 1, Qt::Horizontal, // yeah that means a vertical layout... - group->description(), parent, name ), mGroup( group ) + QGridLayout * glay, QWidget* widget, const char* name ) + : QObject( module, name ), mGroup( group ) { - QStringList entries = mGroup->entryList(); - for( QStringList::Iterator entryit = entries.begin(); entryit != entries.end(); ++entryit ) { - Kleo::CryptoConfigEntry* entry = group->entry( *entryit ); + const int startRow = glay->numRows(); + const QStringList entries = mGroup->entryList(); + for( QStringList::const_iterator it = entries.begin(), end = entries.end() ; it != end; ++it ) { + Kleo::CryptoConfigEntry* entry = group->entry( *it ); Q_ASSERT( entry ); + if ( entry->level() > CryptoConfigEntry::Level_Advanced ) continue; CryptoConfigEntryGUI* entryGUI = - CryptoConfigEntryGUIFactory::createEntryGUI( module, entry, *entryit, this ); + CryptoConfigEntryGUIFactory::createEntryGUI( module, entry, *it, glay, widget ); if ( entryGUI ) { mEntryGUIs.append( entryGUI ); entryGUI->load(); } } + const int endRow = glay->numRows() - 1; + if ( endRow < startRow ) + return; + + const QString iconName = group->iconName(); + if ( iconName.isEmpty() ) + return; + + QLabel * l = new QLabel( widget ); + l->setPixmap( loadIcon( iconName ) ); + glay->addMultiCellWidget( l, startRow, endRow, 0, 0, Qt::AlignTop ); } bool Kleo::CryptoConfigGroupGUI::save() { bool changed = false; QValueList::Iterator it = mEntryGUIs.begin(); for( ; it != mEntryGUIs.end(); ++it ) { if ( (*it)->isChanged() ) { (*it)->save(); changed = true; } } return changed; } void Kleo::CryptoConfigGroupGUI::load() { QValueList::Iterator it = mEntryGUIs.begin(); for( ; it != mEntryGUIs.end(); ++it ) (*it)->load(); } void Kleo::CryptoConfigGroupGUI::defaults() { QValueList::Iterator it = mEntryGUIs.begin(); for( ; it != mEntryGUIs.end(); ++it ) (*it)->resetToDefault(); } //// -CryptoConfigEntryGUI* Kleo::CryptoConfigEntryGUIFactory::createEntryGUI( CryptoConfigModule* module, Kleo::CryptoConfigEntry* entry, const QString& entryName, QWidget* parent, const char* name ) +CryptoConfigEntryGUI* Kleo::CryptoConfigEntryGUIFactory::createEntryGUI( CryptoConfigModule* module, Kleo::CryptoConfigEntry* entry, const QString& entryName, QGridLayout * glay, QWidget* widget, const char* name ) { if ( entry->isList() ) { switch( entry->argType() ) { case Kleo::CryptoConfigEntry::ArgType_None: // A list of options with no arguments (e.g. -v -v -v) is shown as a spinbox - return new CryptoConfigEntrySpinBox( module, entry, entryName, parent, name ); + return new CryptoConfigEntrySpinBox( module, entry, entryName, glay, widget, name ); case Kleo::CryptoConfigEntry::ArgType_Int: case Kleo::CryptoConfigEntry::ArgType_UInt: // Let people type list of numbers (1,2,3....). Untested. - return new CryptoConfigEntryLineEdit( module, entry, entryName, parent, name ); + return new CryptoConfigEntryLineEdit( module, entry, entryName, glay, widget, name ); case Kleo::CryptoConfigEntry::ArgType_URL: case Kleo::CryptoConfigEntry::ArgType_Path: + case Kleo::CryptoConfigEntry::ArgType_DirPath: case Kleo::CryptoConfigEntry::ArgType_String: kdWarning(5150) << "No widget implemented for list of type " << entry->argType() << endl; return 0; // TODO when the need arises :) case Kleo::CryptoConfigEntry::ArgType_LDAPURL: - return new CryptoConfigEntryLDAPURL( module, entry, entryName, parent, name ); + return new CryptoConfigEntryLDAPURL( module, entry, entryName, glay, widget, name ); } + kdWarning(5150) << "No widget implemented for list of (unknown) type " << entry->argType() << endl; + return 0; } switch( entry->argType() ) { case Kleo::CryptoConfigEntry::ArgType_None: - return new CryptoConfigEntryCheckBox( module, entry, entryName, parent, name ); + return new CryptoConfigEntryCheckBox( module, entry, entryName, glay, widget, name ); case Kleo::CryptoConfigEntry::ArgType_Int: - // fallthrough case Kleo::CryptoConfigEntry::ArgType_UInt: - return new CryptoConfigEntrySpinBox( module, entry, entryName, parent, name ); - case Kleo::CryptoConfigEntry::ArgType_LDAPURL: - // TODO when the need arises + return new CryptoConfigEntrySpinBox( module, entry, entryName, glay, widget, name ); case Kleo::CryptoConfigEntry::ArgType_URL: - // fallthrough + return new CryptoConfigEntryURL( module, entry, entryName, glay, widget, name ); case Kleo::CryptoConfigEntry::ArgType_Path: - // fallthrough + return new CryptoConfigEntryPath( module, entry, entryName, glay, widget, name ); + case Kleo::CryptoConfigEntry::ArgType_DirPath: + return new CryptoConfigEntryDirPath( module, entry, entryName, glay, widget, name ); + case Kleo::CryptoConfigEntry::ArgType_LDAPURL: + kdWarning(5150) << "No widget implemented for type " << entry->argType() << endl; + return 0; // TODO when the need arises :) case Kleo::CryptoConfigEntry::ArgType_String: - return new CryptoConfigEntryLineEdit( module, entry, entryName, parent, name ); + return new CryptoConfigEntryLineEdit( module, entry, entryName, glay, widget, name ); } - kdWarning(5150) << "No widget implemented for list of (unknown) type " << entry->argType() << endl; + kdWarning(5150) << "No widget implemented for (unknown) type " << entry->argType() << endl; return 0; } //// Kleo::CryptoConfigEntryGUI::CryptoConfigEntryGUI( CryptoConfigModule* module, Kleo::CryptoConfigEntry* entry, const QString& entryName, - QWidget* parent, const char* name ) - : QHBox( parent, name ), mEntry( entry ), mName( entryName ), mChanged( false ) + const char* name ) + : QObject( module, name ), mEntry( entry ), mName( entryName ), mChanged( false ) { connect( this, SIGNAL( changed() ), module, SIGNAL( changed() ) ); } QString Kleo::CryptoConfigEntryGUI::description() const { QString descr = mEntry->description(); if ( descr.isEmpty() ) // shouldn't happen descr = QString( "<%1>" ).arg( mName ); return descr; } void Kleo::CryptoConfigEntryGUI::resetToDefault() { mEntry->resetToDefault(); load(); } //// Kleo::CryptoConfigEntryLineEdit::CryptoConfigEntryLineEdit( CryptoConfigModule* module, Kleo::CryptoConfigEntry* entry, const QString& entryName, - QWidget* parent, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, parent, name ) + QGridLayout * glay, QWidget* widget, const char* name ) + : CryptoConfigEntryGUI( module, entry, entryName, name ) { - setSpacing( KDialog::spacingHint() ); - QLabel* label = new QLabel( description(), this ); - mLineEdit = new KLineEdit( this ); + const int row = glay->numRows(); + mLineEdit = new KLineEdit( widget ); + glay->addWidget( new QLabel( mLineEdit, description(), widget ), row, 1 ); + glay->addWidget( mLineEdit, row, 2 ); connect( mLineEdit, SIGNAL( textChanged( const QString& ) ), SLOT( slotChanged() ) ); - label->setBuddy( mLineEdit ); - QWidget* stretch = new QWidget( this ); - setStretchFactor( stretch, 1 ); } void Kleo::CryptoConfigEntryLineEdit::doSave() { mEntry->setStringValue( mLineEdit->text() ); } void Kleo::CryptoConfigEntryLineEdit::doLoad() { mLineEdit->setText( mEntry->stringValue() ); } //// +Kleo::CryptoConfigEntryPath::CryptoConfigEntryPath( + CryptoConfigModule* module, + Kleo::CryptoConfigEntry* entry, const QString& entryName, + QGridLayout * glay, QWidget* widget, const char* name ) + : CryptoConfigEntryGUI( module, entry, entryName, name ) +{ + const int row = glay->numRows(); + mUrlRequester = new KURLRequester( widget ); + mUrlRequester->setMode( KFile::File | KFile::ExistingOnly | KFile::LocalOnly ); + glay->addWidget( new QLabel( mUrlRequester, description(), widget ), row, 1 ); + glay->addWidget( mUrlRequester, row, 2 ); + connect( mUrlRequester, SIGNAL( textChanged( const QString& ) ), SLOT( slotChanged() ) ); +} + +void Kleo::CryptoConfigEntryPath::doSave() +{ + KURL url; + url.setPath( mUrlRequester->url() ); + mEntry->setURLValue( url ); +} + +void Kleo::CryptoConfigEntryPath::doLoad() +{ + mUrlRequester->setURL( mEntry->urlValue().path() ); +} + +//// + +Kleo::CryptoConfigEntryDirPath::CryptoConfigEntryDirPath( + CryptoConfigModule* module, + Kleo::CryptoConfigEntry* entry, const QString& entryName, + QGridLayout * glay, QWidget* widget, const char* name ) + : CryptoConfigEntryGUI( module, entry, entryName, name ) +{ + const int row = glay->numRows(); + mUrlRequester = new KURLRequester( widget ); + mUrlRequester->setMode( KFile::Directory | KFile::ExistingOnly | KFile::LocalOnly ); + glay->addWidget( new QLabel( mUrlRequester, description(), widget ), row, 1 ); + glay->addWidget( mUrlRequester, row, 2 ); + connect( mUrlRequester, SIGNAL( textChanged( const QString& ) ), SLOT( slotChanged() ) ); +} + +void Kleo::CryptoConfigEntryDirPath::doSave() +{ + KURL url; + url.setPath( mUrlRequester->url() ); + mEntry->setURLValue( url ); + +} + +void Kleo::CryptoConfigEntryDirPath::doLoad() +{ + mUrlRequester->setURL( mEntry->urlValue().path() ); +} + +//// + +Kleo::CryptoConfigEntryURL::CryptoConfigEntryURL( + CryptoConfigModule* module, + Kleo::CryptoConfigEntry* entry, const QString& entryName, + QGridLayout * glay, QWidget* widget, const char* name ) + : CryptoConfigEntryGUI( module, entry, entryName, name ) +{ + const int row = glay->numRows(); + mUrlRequester = new KURLRequester( widget ); + mUrlRequester->setMode( KFile::File | KFile::ExistingOnly ); + glay->addWidget( new QLabel( mUrlRequester, description(), widget ), row, 1 ); + glay->addWidget( mUrlRequester, row, 2 ); + connect( mUrlRequester, SIGNAL( textChanged( const QString& ) ), SLOT( slotChanged() ) ); +} + +void Kleo::CryptoConfigEntryURL::doSave() +{ + mEntry->setURLValue( mUrlRequester->url() ); +} + +void Kleo::CryptoConfigEntryURL::doLoad() +{ + mUrlRequester->setURL( mEntry->urlValue().url() ); +} + +//// + Kleo::CryptoConfigEntrySpinBox::CryptoConfigEntrySpinBox( CryptoConfigModule* module, Kleo::CryptoConfigEntry* entry, const QString& entryName, - QWidget* parent, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, parent, name ) + QGridLayout * glay, QWidget* widget, const char* name ) + : CryptoConfigEntryGUI( module, entry, entryName, name ) { - setSpacing( KDialog::spacingHint() ); - QLabel* label = new QLabel( description(), this ); if ( entry->argType() == Kleo::CryptoConfigEntry::ArgType_None && entry->isList() ) { mKind = ListOfNone; } else if ( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ) { mKind = UInt; } else { Q_ASSERT( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Int ); mKind = Int; } - mNumInput = new KIntNumInput( this ); + const int row = glay->numRows(); + mNumInput = new KIntNumInput( widget ); + glay->addWidget( new QLabel( mNumInput, description(), widget ), row, 1 ); + glay->addWidget( mNumInput, row, 2 ); + if ( mKind == UInt || mKind == ListOfNone ) mNumInput->setMinValue( 0 ); connect( mNumInput, SIGNAL( valueChanged(int) ), SLOT( slotChanged() ) ); - label->setBuddy( mNumInput ); - - QWidget* stretch = new QWidget( this ); - setStretchFactor( stretch, 1 ); } void Kleo::CryptoConfigEntrySpinBox::doSave() { int value = mNumInput->value(); switch ( mKind ) { case ListOfNone: mEntry->setNumberOfTimesSet( value ); break; case UInt: mEntry->setUIntValue( value ); break; case Int: mEntry->setIntValue( value ); break; } } void Kleo::CryptoConfigEntrySpinBox::doLoad() { int value = 0; switch ( mKind ) { case ListOfNone: value = mEntry->numberOfTimesSet(); break; case UInt: value = mEntry->uintValue(); break; case Int: value = mEntry->intValue(); break; } mNumInput->setValue( value ); } //// Kleo::CryptoConfigEntryCheckBox::CryptoConfigEntryCheckBox( CryptoConfigModule* module, Kleo::CryptoConfigEntry* entry, const QString& entryName, - QWidget* parent, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, parent, name ) + QGridLayout * glay, QWidget* widget, const char* name ) + : CryptoConfigEntryGUI( module, entry, entryName, name ) { - mCheckBox = new QCheckBox( this); + const int row = glay->numRows(); + mCheckBox = new QCheckBox( widget ); + glay->addMultiCellWidget( mCheckBox, row, row, 1, 2 ); mCheckBox->setText( description() ); connect( mCheckBox, SIGNAL( toggled(bool) ), SLOT( slotChanged() ) ); } void Kleo::CryptoConfigEntryCheckBox::doSave() { mEntry->setBoolValue( mCheckBox->isChecked() ); } void Kleo::CryptoConfigEntryCheckBox::doLoad() { mCheckBox->setChecked( mEntry->boolValue() ); } Kleo::CryptoConfigEntryLDAPURL::CryptoConfigEntryLDAPURL( CryptoConfigModule* module, Kleo::CryptoConfigEntry* entry, const QString& entryName, - QWidget* parent, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, parent, name ) + QGridLayout * glay, QWidget* widget, const char* name ) + : CryptoConfigEntryGUI( module, entry, entryName, name ) { - setSpacing( KDialog::spacingHint() ); - QLabel* label = new QLabel( description(), this ); - mPushButton = new QPushButton( i18n( "Edit..." ), this ); - mLabel = new QLabel( this ); + mLabel = new QLabel( widget ); + mPushButton = new QPushButton( i18n( "Edit..." ), widget ); + + + const int row = glay->numRows(); + glay->addWidget( new QLabel( mPushButton, description(), widget ), row, 1 ); + QHBoxLayout * hlay = new QHBoxLayout; + glay->addLayout( hlay, row, 2 ); + hlay->addWidget( mLabel, 1 ); + hlay->addWidget( mPushButton ); + connect( mPushButton, SIGNAL( clicked() ), SLOT( slotOpenDialog() ) ); - label->setBuddy( mPushButton ); - QWidget* stretch = new QWidget( this ); - setStretchFactor( stretch, 1 ); } void Kleo::CryptoConfigEntryLDAPURL::doLoad() { setURLList( mEntry->urlValueList() ); } void Kleo::CryptoConfigEntryLDAPURL::doSave() { mEntry->setURLValueList( mURLList ); } void Kleo::CryptoConfigEntryLDAPURL::slotOpenDialog() { // I'm a bad boy and I do it all on the stack. Enough classes already :) // This is just a simple dialog around the directory-services-widget - KDialogBase dialog( this, 0, true /*modal*/, + KDialogBase dialog( mPushButton->parentWidget(), 0, true /*modal*/, i18n( "Configure LDAP Servers" ), KDialogBase::Default|KDialogBase::Cancel|KDialogBase::Ok, KDialogBase::Ok, true /*separator*/ ); DirectoryServicesWidget* dirserv = new DirectoryServicesWidget( mEntry, &dialog ); dirserv->load(); dialog.setMainWidget( dirserv ); connect( &dialog, SIGNAL( defaultClicked() ), dirserv, SLOT( defaults() ) ); if ( dialog.exec() ) { // Note that we just grab the urls from the dialog, we don't call its save method, // since the user hasn't confirmed the big config dialog yet. setURLList( dirserv->urlList() ); slotChanged(); } } void Kleo::CryptoConfigEntryLDAPURL::setURLList( const KURL::List& urlList ) { mURLList = urlList; if ( mURLList.isEmpty() ) mLabel->setText( i18n( "No server configured yet" ) ); else mLabel->setText( i18n( "1 server configured", "%n servers configured", mURLList.count() ) ); } #include "cryptoconfigmodule.moc" +#include "cryptoconfigmodule_p.moc" diff --git a/certmanager/lib/ui/cryptoconfigmodule.h b/certmanager/lib/ui/cryptoconfigmodule.h index 17b98d92e7..1858145947 100644 --- a/certmanager/lib/ui/cryptoconfigmodule.h +++ b/certmanager/lib/ui/cryptoconfigmodule.h @@ -1,241 +1,68 @@ /* cryptoconfigmodule.h - This file is part of kgpgcertmanager - Copyright (c) 2004 Klarlvdalens Datakonsult AB + This file is part of libkleopatra + Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef CRYPTOCONFIGMODULE_H #define CRYPTOCONFIGMODULE_H #include -#include -#include -#include -#include -#include -class KLineEdit; -class KIntNumInput; -class QPushButton; +#include namespace Kleo { class CryptoConfig; - class CryptoConfigComponent; - class CryptoConfigGroup; - class CryptoConfigEntry; class CryptoConfigComponentGUI; - class CryptoConfigGroupGUI; - class CryptoConfigEntryGUI; /** * Crypto Config Module widget, dynamically generated from CryptoConfig * It's a simple QWidget so that it can be embedded into a dialog or into a KCModule. */ class CryptoConfigModule : public KJanusWidget { Q_OBJECT public: CryptoConfigModule( Kleo::CryptoConfig* config, QWidget * parent=0, const char * name=0 ); void save(); void reset(); // i.e. reload current settings, discarding user input void defaults(); void cancel(); signals: void changed(); private: Kleo::CryptoConfig* mConfig; QValueList mComponentGUIs; }; - /** - * A widget corresponding to a component in the crypto config - */ - class CryptoConfigComponentGUI : public QWidget { - Q_OBJECT - - public: - CryptoConfigComponentGUI( CryptoConfigModule* module, Kleo::CryptoConfigComponent* component, - QWidget* parent, const char* name = 0 ); - - bool save(); - void load(); - void defaults(); - - private: - Kleo::CryptoConfigComponent* mComponent; - QValueList mGroupGUIs; - }; - - /** - * A widget corresponding to a group in the crypto config - */ - class CryptoConfigGroupGUI : public QGroupBox { - Q_OBJECT - - public: - CryptoConfigGroupGUI( CryptoConfigModule* module, Kleo::CryptoConfigGroup* group, - QWidget* parent, const char* name = 0 ); - - bool save(); - void load(); - void defaults(); - - private: - Kleo::CryptoConfigGroup* mGroup; - QValueList mEntryGUIs; - }; - - /** - * Factory for CryptoConfigEntryGUI instances - * Not a real factory, but can become one later. - */ - class CryptoConfigEntryGUIFactory { - public: - static CryptoConfigEntryGUI* createEntryGUI( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, const QString& entryName, - QWidget* parent, const char* name = 0 ); - }; - - /** - * Base class for the widget tied to an entry in the crypto config - */ - class CryptoConfigEntryGUI : public QHBox { - Q_OBJECT - public: - CryptoConfigEntryGUI( CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, - const QString& entryName, - QWidget* parent, const char* name = 0 ); - virtual ~CryptoConfigEntryGUI() {} - - void load() { doLoad(); mChanged = false; } - void save() { Q_ASSERT( mChanged ); doSave(); mChanged = false; } - void resetToDefault(); - - QString description() const; - bool isChanged() const { return mChanged; } - - signals: - void changed(); - - protected slots: - void slotChanged() { - mChanged = true; - emit changed(); - } - - protected: - virtual void doSave() = 0; - virtual void doLoad() = 0; - - Kleo::CryptoConfigEntry* mEntry; - QString mName; - bool mChanged; - }; - - /** - * A widget for a string entry in the crypto config - */ - class CryptoConfigEntryLineEdit : public CryptoConfigEntryGUI { - Q_OBJECT - - public: - CryptoConfigEntryLineEdit( CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, - const QString& entryName, - QWidget* parent, const char* name = 0 ); - - virtual void doSave(); - virtual void doLoad(); - private: - KLineEdit* mLineEdit; - }; - - /** - * A widget for an int/uint entry in the crypto config - */ - class CryptoConfigEntrySpinBox : public CryptoConfigEntryGUI { - Q_OBJECT - - public: - CryptoConfigEntrySpinBox( CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, - const QString& entryName, - QWidget* parent, const char* name = 0 ); - virtual void doSave(); - virtual void doLoad(); - private: - enum { Int, UInt, ListOfNone } mKind; - KIntNumInput* mNumInput; - }; - - /** - * A widget for a bool entry in the crypto config - */ - class CryptoConfigEntryCheckBox : public CryptoConfigEntryGUI { - Q_OBJECT - - public: - CryptoConfigEntryCheckBox( CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, - const QString& entryName, - QWidget* parent, const char* name = 0 ); - virtual void doSave(); - virtual void doLoad(); - private: - QCheckBox* mCheckBox; - }; - - /** - * A widget for a bool entry in the crypto config - */ - class CryptoConfigEntryLDAPURL : public CryptoConfigEntryGUI { - Q_OBJECT - - public: - CryptoConfigEntryLDAPURL( CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, - const QString& entryName, - QWidget* parent, const char* name = 0 ); - virtual void doSave(); - virtual void doLoad(); - private slots: - void slotOpenDialog(); - private: - void setURLList( const KURL::List& urlList ); - QLabel* mLabel; - QPushButton* mPushButton; - KURL::List mURLList; - }; } #endif diff --git a/kleopatra/lib/ui/cryptoconfigmodule_p.h b/certmanager/lib/ui/cryptoconfigmodule_p.h similarity index 100% rename from kleopatra/lib/ui/cryptoconfigmodule_p.h rename to certmanager/lib/ui/cryptoconfigmodule_p.h diff --git a/certmanager/lib/ui/directoryserviceswidget.cpp b/certmanager/lib/ui/directoryserviceswidget.cpp index c3c3b3ce1d..76c1b3ddab 100644 --- a/certmanager/lib/ui/directoryserviceswidget.cpp +++ b/certmanager/lib/ui/directoryserviceswidget.cpp @@ -1,308 +1,308 @@ /* directoryserviceswidget.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include #include "directoryserviceswidget.h" #include "adddirectoryservicedialogimpl.h" #include "cryptplugwrapper.h" #include #include #include #include #include #include #include #include using namespace Kleo; class QX500ListViewItem : public QListViewItem { public: QX500ListViewItem( QListView* lv, QListViewItem* prev, const QString& serverName, const QString& portNumber, const QString& dn, const QString& username, const QString& password ) : QListViewItem( lv, prev, serverName, portNumber, dn, username ) { setPassword( password ); } void setPassword( const QString& pass ) { mPassword = pass; setText( 4, pass.isEmpty() ? QString::null : QString::fromLatin1( "******" ) ); } const QString& password() const { return mPassword; } void setData( const QString& serverName, const QString& portNumber, const QString& dn, const QString& username, const QString& password ) { setText( 0, serverName ); setText( 1, portNumber ); setText( 2, dn ); setText( 3, username ); setPassword( password ); } void copyItem( QX500ListViewItem* item ) { for ( unsigned int i = 0; i < 4 ; ++i ) setText( i, item->text( i ) ); setPassword( item->password() ); } private: QString mPassword; }; Kleo::DirectoryServicesWidget::DirectoryServicesWidget( Kleo::CryptoConfigEntry* configEntry, QWidget* parent, const char* name, WFlags fl ) : DirectoryServicesWidgetBase( parent, name, fl ), mConfigEntry( configEntry ) { x500LV->setSorting( -1 ); // taken from kmail's configuredialog.cpp upButton->setIconSet( BarIconSet( "up", KIcon::SizeSmall ) ); upButton->setEnabled( false ); // b/c no item is selected yet downButton->setIconSet( BarIconSet( "down", KIcon::SizeSmall ) ); downButton->setEnabled( false ); // b/c no item is selected yet } /* * Destroys the object and frees any allocated resources */ DirectoryServicesWidget::~DirectoryServicesWidget() { // no need to delete child widgets, Qt does it all for us } /** Enables or disables the widgets in this dialog according to the capabilities of the current plugin passed as a parameter. */ void DirectoryServicesWidget::enableDisable( CryptPlugWrapper* cryptPlug ) // unused? { // disable the whole page if the plugin does not support the use // of directory services setEnabled( cryptPlug->hasFeature( Feature_CertificateDirectoryService ) || cryptPlug->hasFeature( Feature_CRLDirectoryService ) ); } /* * protected slot, connected to selectionChanged() */ void DirectoryServicesWidget::slotServiceChanged( QListViewItem* item ) { if( item ) removeServicePB->setEnabled( true ); else removeServicePB->setEnabled( false ); downButton->setEnabled( item && item->itemBelow() ); upButton->setEnabled( item && item->itemAbove() ); } /* * protected slot, connected to returnPressed/doubleClicked */ void DirectoryServicesWidget::slotServiceSelected( QListViewItem* item ) { AddDirectoryServiceDialogImpl* dlg = new AddDirectoryServiceDialogImpl( this ); dlg->serverNameED->setText( item->text( 0 ) ); dlg->portED->setText( item->text( 1 ) ); dlg->descriptionED->setText( item->text( 2 ) ); dlg->usernameED->setText( item->text( 3 ) ); QString pass = static_cast( item )->password(); dlg->passwordED->setText( pass ); if( dlg->exec() == QDialog::Accepted ) { item->setText( 0, dlg->serverNameED->text() ); item->setText( 1, dlg->portED->text() ); item->setText( 2, dlg->descriptionED->text() ); item->setText( 3, dlg->usernameED->text() ); static_cast( item )->setPassword( dlg->passwordED->text() ); emit changed(); } delete dlg; } /* * protected slot */ void DirectoryServicesWidget::slotAddService() { AddDirectoryServiceDialogImpl* dlg = new AddDirectoryServiceDialogImpl( this ); if( dlg->exec() == QDialog::Accepted ) { QX500ListViewItem *item = new QX500ListViewItem( x500LV, x500LV->lastItem(), dlg->serverNameED->text(), dlg->portED->text(), dlg->descriptionED->text(), dlg->usernameED->text(), dlg->passwordED->text() ); slotServiceChanged(item); emit changed(); } delete dlg; } /* * protected slot */ void DirectoryServicesWidget::slotDeleteService() { QListViewItem* item = x500LV->selectedItem(); Q_ASSERT( item ); if( !item ) return; else delete item; x500LV->triggerUpdate(); item = x500LV->currentItem(); x500LV->setCurrentItem( item ); // seems necessary... x500LV->setSelected( item, true ); emit changed(); } void DirectoryServicesWidget::setInitialServices( const KURL::List& urls ) { x500LV->clear(); for( KURL::List::const_iterator it = urls.begin(); it != urls.end(); ++it ) { QString dn = KURL::decode_string( (*it).query().mid( 1 ) ); // decode query and skip leading '?' (void)new QX500ListViewItem( x500LV, x500LV->lastItem(), (*it).host(), QString::number( (*it).port() ), dn, (*it).user(), (*it).pass()); } } KURL::List DirectoryServicesWidget::urlList() const { KURL::List lst; QListViewItemIterator it( x500LV ); for ( ; it.current() ; ++it ) { QListViewItem* item = it.current(); KURL url; url.setProtocol( "ldap" ); url.setHost( item->text( 0 ) ); url.setPort( item->text( 1 ).toInt() ); url.setPath( "/" ); // workaround KURL parsing bug url.setQuery( item->text( 2 ) ); url.setUser( item->text( 3 ) ); url.setPass( static_cast( item )->password() ); kdDebug() << url << endl; lst << url; } return lst; } void DirectoryServicesWidget::clear() { x500LV->clear(); emit changed(); } void DirectoryServicesWidget::load() { if ( mConfigEntry ) { setInitialServices( mConfigEntry->urlValueList() ); } } void DirectoryServicesWidget::save() { if ( mConfigEntry ) { mConfigEntry->setURLValueList( urlList() ); } } void DirectoryServicesWidget::defaults() { if ( mConfigEntry ) { // resetToDefault doesn't work since gpgconf doesn't know any defaults for this entry. //mConfigEntry->resetToDefault(); //load(); clear(); // the default is an empty list. } } static void swapItems( QX500ListViewItem *item, QX500ListViewItem *other ) { QString serverName = item->text( 0 ); QString portNumber = item->text( 1 ); QString dn = item->text( 2 ); QString username = item->text( 3 ); QString password = item->password(); item->copyItem( other ); other->setData( serverName, portNumber, dn, username, password ); } void Kleo::DirectoryServicesWidget::slotMoveUp() { QX500ListViewItem *item = static_cast( x500LV->selectedItem() ); if ( !item ) return; QX500ListViewItem *above = static_cast( item->itemAbove() ); if ( !above ) return; swapItems( item, above ); x500LV->setCurrentItem( above ); x500LV->setSelected( above, true ); emit changed(); } void Kleo::DirectoryServicesWidget::slotMoveDown() { QX500ListViewItem *item = static_cast( x500LV->selectedItem() ); if ( !item ) return; QX500ListViewItem *below = static_cast( item->itemBelow() ); if ( !below ) return; swapItems( item, below ); x500LV->setCurrentItem( below ); x500LV->setSelected( below, true ); emit changed(); } #include "directoryserviceswidget.moc" diff --git a/certmanager/lib/ui/directoryserviceswidget.h b/certmanager/lib/ui/directoryserviceswidget.h index bc33cca193..02e428c954 100644 --- a/certmanager/lib/ui/directoryserviceswidget.h +++ b/certmanager/lib/ui/directoryserviceswidget.h @@ -1,82 +1,82 @@ /* directoryserviceswidget.h This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef DIRECTORYSERVICESWIDGET_H #define DIRECTORYSERVICESWIDGET_H #include "directoryserviceswidgetbase.h" #include #include class CryptPlugWrapper; namespace Kleo { class CryptoConfigEntry; class KDE_EXPORT DirectoryServicesWidget : public DirectoryServicesWidgetBase { Q_OBJECT public: DirectoryServicesWidget( Kleo::CryptoConfigEntry* configEntry, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~DirectoryServicesWidget(); void load(); void save(); void enableDisable( CryptPlugWrapper* wrapper ); // unused? void setInitialServices( const KURL::List& urls ); KURL::List urlList() const; void clear(); public slots: void defaults(); signals: void changed(); protected slots: void slotServiceChanged( QListViewItem* ); void slotServiceSelected( QListViewItem* ); void slotAddService(); void slotDeleteService(); void slotMoveUp(); void slotMoveDown(); private: Kleo::CryptoConfigEntry* mConfigEntry; }; } #endif // DIRECTORYSERVICESWIDGET_H diff --git a/certmanager/lib/ui/dnattributeorderconfigwidget.cpp b/certmanager/lib/ui/dnattributeorderconfigwidget.cpp index 94bfc574ba..ad2ec69fe0 100644 --- a/certmanager/lib/ui/dnattributeorderconfigwidget.cpp +++ b/certmanager/lib/ui/dnattributeorderconfigwidget.cpp @@ -1,309 +1,309 @@ /* -*- c++ -*- dnattributeorderconfigwidget.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klar�vdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "dnattributeorderconfigwidget.h" #include "kleo/dn.h" #include #include #include #include #include #include #include #include #include #include #include #include #include struct Kleo::DNAttributeOrderConfigWidget::Private { enum { UUp=0, Up=1, Left=2, Right=3, Down=4, DDown=5 }; QListView * availableLV; QListView * currentLV; QToolButton * navTB[6]; QListViewItem * placeHolderItem; Kleo::DNAttributeMapper * mapper; }; static void prepare( QListView * lv ) { lv->setAllColumnsShowFocus( true ); lv->setResizeMode( QListView::LastColumn ); lv->header()->setClickEnabled( false ); lv->addColumn( QString::null ); lv->addColumn( i18n("Description") ); } Kleo::DNAttributeOrderConfigWidget::DNAttributeOrderConfigWidget( DNAttributeMapper * mapper, QWidget * parent, const char * name, WFlags f ) : QWidget( parent, name, f ), d( 0 ) { assert( mapper ); d = new Private(); d->mapper = mapper; QGridLayout * glay = new QGridLayout( this, 2, 3, 0, KDialog::spacingHint() ); glay->setColStretch( 0, 1 ); glay->setColStretch( 2, 1 ); int row = -1; ++row; glay->addWidget( new QLabel( i18n("Available attributes:"), this ), row, 0 ); glay->addWidget( new QLabel( i18n("Current attribute order:"), this ), row, 2 ); ++row; glay->setRowStretch( row, 1 ); d->availableLV = new QListView( this ); prepare( d->availableLV ); d->availableLV->setSorting( 0 ); glay->addWidget( d->availableLV, row, 0 ); d->currentLV = new QListView( this ); prepare( d->currentLV ); d->currentLV->setSorting( -1 ); glay->addWidget( d->currentLV, row, 2 ); connect( d->availableLV, SIGNAL(selectionChanged(QListViewItem*)), SLOT(slotAvailableSelectionChanged(QListViewItem*)) ); connect( d->currentLV, SIGNAL(selectionChanged(QListViewItem*)), SLOT(slotCurrentOrderSelectionChanged(QListViewItem*)) ); d->placeHolderItem = new QListViewItem( d->availableLV, "_X_", i18n("All others") ); // the up/down/left/right arrow cross: QGridLayout * xlay = new QGridLayout( 5, 3, 0, "xlay" ); xlay->setAlignment( AlignCenter ); static const struct { const char * icon; int row, col; const char * tooltip; const char * slot; } navButtons[] = { { "2uparrow", 0, 1, I18N_NOOP( "Move to top" ), SLOT(slotDoubleUpButtonClicked()) }, { "1uparrow", 1, 1, I18N_NOOP( "Move one up" ), SLOT(slotUpButtonClicked()) }, { "1leftarrow", 2, 0, I18N_NOOP( "Remove from current attribute order" ), SLOT(slotLeftButtonClicked()) }, { "1rightarrow", 2, 2, I18N_NOOP( "Add to current attribute order" ), SLOT(slotRightButtonClicked()) }, { "1downarrow", 3, 1, I18N_NOOP( "Move one down" ), SLOT(slotDownButtonClicked()) }, { "2downarrow", 4, 1, I18N_NOOP( "Move to bottom" ), SLOT(slotDoubleDownButtonClicked()) } }; for ( unsigned int i = 0 ; i < sizeof navButtons / sizeof *navButtons ; ++i ) { QToolButton * tb = d->navTB[i] = new QToolButton( this ); tb->setIconSet( SmallIconSet( navButtons[i].icon ) ); tb->setEnabled( false ); QToolTip::add( tb, i18n( navButtons[i].tooltip ) ); xlay->addWidget( tb, navButtons[i].row, navButtons[i].col ); connect( tb, SIGNAL(clicked()), navButtons[i].slot ); } glay->addLayout( xlay, row, 1 ); } Kleo::DNAttributeOrderConfigWidget::~DNAttributeOrderConfigWidget() { delete d; d = 0; } void Kleo::DNAttributeOrderConfigWidget::load() { // save the _X_ item: takePlaceHolderItem(); // clear the rest: d->availableLV->clear(); d->currentLV->clear(); const QStringList order = d->mapper->attributeOrder(); // fill the RHS listview: QListViewItem * last = 0; for ( QStringList::const_iterator it = order.begin() ; it != order.end() ; ++it ) { const QString attr = (*it).upper(); if ( attr == "_X_" ) { takePlaceHolderItem(); d->currentLV->insertItem( d->placeHolderItem ); d->placeHolderItem->moveItem( last ); last = d->placeHolderItem; } else last = new QListViewItem( d->currentLV, last, attr, d->mapper->name2label( attr ) ); } // fill the LHS listview with what's left: const QStringList all = Kleo::DNAttributeMapper::instance()->names(); for ( QStringList::const_iterator it = all.begin() ; it != all.end() ; ++it ) if ( order.find( *it ) == order.end() ) (void)new QListViewItem( d->availableLV, *it, d->mapper->name2label( *it ) ); if ( !d->placeHolderItem->listView() ) d->availableLV->insertItem( d->placeHolderItem ); } void Kleo::DNAttributeOrderConfigWidget::takePlaceHolderItem() { if ( QListView * lv = d->placeHolderItem->listView() ) lv->takeItem( d->placeHolderItem ); } void Kleo::DNAttributeOrderConfigWidget::save() const { QStringList order; for ( QListViewItemIterator it( d->currentLV ) ; it.current() ; ++it ) order.push_back( it.current()->text( 0 ) ); d->mapper->setAttributeOrder( order ); } void Kleo::DNAttributeOrderConfigWidget::defaults() { kdDebug() << "Sorry, not implemented: Kleo::DNAttributeOrderConfigWidget::defaults()" << endl; } void Kleo::DNAttributeOrderConfigWidget::slotAvailableSelectionChanged( QListViewItem * item ) { d->navTB[Private::Right]->setEnabled( item ); } void Kleo::DNAttributeOrderConfigWidget::slotCurrentOrderSelectionChanged( QListViewItem * item ) { enableDisableButtons( item ); } void Kleo::DNAttributeOrderConfigWidget::enableDisableButtons( QListViewItem * item ) { d->navTB[Private::UUp ]->setEnabled( item && item->itemAbove() ); d->navTB[Private::Up ]->setEnabled( item && item->itemAbove() ); d->navTB[Private::Left ]->setEnabled( item ); d->navTB[Private::Down ]->setEnabled( item && item->itemBelow() ); d->navTB[Private::DDown]->setEnabled( item && item->itemBelow() ); } void Kleo::DNAttributeOrderConfigWidget::slotUpButtonClicked() { QListViewItem * item = d->currentLV->selectedItem(); if ( !item ) return; QListViewItem * above = item->itemAbove(); if ( !above ) return; above->moveItem( item ); // moves "above" to after "item", ie. "item" one up enableDisableButtons( item ); emit changed(); } void Kleo::DNAttributeOrderConfigWidget::slotDoubleUpButtonClicked() { QListViewItem * item = d->currentLV->selectedItem(); if ( !item ) return; if ( item == d->currentLV->firstChild() ) return; d->currentLV->takeItem( item ); d->currentLV->insertItem( item ); d->currentLV->setSelected( item, true ); enableDisableButtons( item ); emit changed(); } void Kleo::DNAttributeOrderConfigWidget::slotDownButtonClicked() { QListViewItem * item = d->currentLV->selectedItem(); if ( !item ) return; QListViewItem * below = item->itemBelow(); if ( !below ) return; item->moveItem( below ); // moves "item" to after "below", ie. "item" one down enableDisableButtons( item ); emit changed(); } void Kleo::DNAttributeOrderConfigWidget::slotDoubleDownButtonClicked() { QListViewItem * item = d->currentLV->selectedItem(); if ( !item ) return; QListViewItem * last = d->currentLV->lastItem(); assert( last ); if ( item == last ) return; item->moveItem( last ); // moves "item" to after "last", ie. to the bottom enableDisableButtons( item ); emit changed(); } void Kleo::DNAttributeOrderConfigWidget::slotLeftButtonClicked() { QListViewItem * right = d->currentLV->selectedItem(); if ( !right ) return; QListViewItem * next = right->itemBelow(); if ( !next ) next = right->itemAbove(); d->currentLV->takeItem( right ); d->availableLV->insertItem( right ); if ( next ) d->currentLV->setSelected( next, true ); enableDisableButtons( next ); emit changed(); } void Kleo::DNAttributeOrderConfigWidget::slotRightButtonClicked() { QListViewItem * left = d->availableLV->selectedItem(); if ( !left ) return; QListViewItem * next = left->itemBelow(); if ( !next ) next = left->itemAbove(); d->availableLV->takeItem( left ); d->currentLV->insertItem( left ); if ( QListViewItem * right = d->currentLV->selectedItem() ) { if ( QListViewItem * above = right->itemAbove() ) left->moveItem( above ); // move new item immediately before old selected d->currentLV->setSelected( right, false ); } d->currentLV->setSelected( left, true ); enableDisableButtons( left ); d->navTB[Private::Right]->setEnabled( next ); if ( next ) d->availableLV->setSelected( next, true ); emit changed(); } void Kleo::DNAttributeOrderConfigWidget::virtual_hook( int, void* ) {} #include "dnattributeorderconfigwidget.moc" diff --git a/certmanager/lib/ui/dnattributeorderconfigwidget.h b/certmanager/lib/ui/dnattributeorderconfigwidget.h index d6ac2b3622..11299ab374 100644 --- a/certmanager/lib/ui/dnattributeorderconfigwidget.h +++ b/certmanager/lib/ui/dnattributeorderconfigwidget.h @@ -1,87 +1,87 @@ /* -*- c++ -*- dnattributeorderconfigwidget.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_UI_DNATTRIBUTEORDERCONFIGWIDGET_H__ #define __KLEO_UI_DNATTRIBUTEORDERCONFIGWIDGET_H__ #include #include namespace Kleo { class DNAttributeMapper; } class QListViewItem; namespace Kleo { class KDE_EXPORT DNAttributeOrderConfigWidget : public QWidget { Q_OBJECT public: /*! Use Kleo::DNAttributeMapper::instance()->configWidget( parent, name ) instead. */ DNAttributeOrderConfigWidget( DNAttributeMapper * mapper, QWidget * parent=0, const char * name=0, WFlags f=0 ); ~DNAttributeOrderConfigWidget(); void load(); void save() const; void defaults(); signals: void changed(); // // only boring stuff below... // private slots: void slotAvailableSelectionChanged( QListViewItem * ); void slotCurrentOrderSelectionChanged( QListViewItem * ); void slotDoubleUpButtonClicked(); void slotUpButtonClicked(); void slotDownButtonClicked(); void slotDoubleDownButtonClicked(); void slotLeftButtonClicked(); void slotRightButtonClicked(); private: void takePlaceHolderItem(); void enableDisableButtons( QListViewItem * ); private: class Private; Private * d; protected: virtual void virtual_hook( int, void* ); }; } #endif // __KLEO_UI_DNATTRIBUTEORDERCONFIGWIDGET_H__ diff --git a/kleopatra/lib/ui/kdhorizontalline.cpp b/certmanager/lib/ui/kdhorizontalline.cpp similarity index 100% rename from kleopatra/lib/ui/kdhorizontalline.cpp rename to certmanager/lib/ui/kdhorizontalline.cpp diff --git a/kleopatra/lib/ui/kdhorizontalline.h b/certmanager/lib/ui/kdhorizontalline.h similarity index 100% rename from kleopatra/lib/ui/kdhorizontalline.h rename to certmanager/lib/ui/kdhorizontalline.h diff --git a/certmanager/lib/ui/keyapprovaldialog.cpp b/certmanager/lib/ui/keyapprovaldialog.cpp index 6a7c5b7d13..7af85a0bbc 100644 --- a/certmanager/lib/ui/keyapprovaldialog.cpp +++ b/certmanager/lib/ui/keyapprovaldialog.cpp @@ -1,227 +1,227 @@ /* -*- c++ -*- keyapprovaldialog.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Based on kpgpui.h Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "keyapprovaldialog.h" #include "keyrequester.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include static Kleo::EncryptionPreference cb2pref( int i ) { switch ( i ) { default: case 0: return Kleo::UnknownPreference; case 1: return Kleo::NeverEncrypt; case 2: return Kleo::AlwaysEncrypt; case 3: return Kleo::AlwaysEncryptIfPossible; case 4: return Kleo::AlwaysAskForEncryption; case 5: return Kleo::AskWheneverPossible; } } static int pref2cb( Kleo::EncryptionPreference p ) { switch ( p ) { default: return 0; case Kleo::NeverEncrypt: return 1; case Kleo::AlwaysEncrypt: return 2; case Kleo::AlwaysEncryptIfPossible: return 3; case Kleo::AlwaysAskForEncryption: return 4; case Kleo::AskWheneverPossible: return 5; } } static QStringList preferencesStrings() { return QStringList() << i18n("") << i18n("Never Encrypt with This Key") << i18n("Always Encrypt with This Key") << i18n("Encrypt Whenever Encryption is Possible") << i18n("Always Ask") << i18n("Ask Whenever Encryption is Possible"); } struct Kleo::KeyApprovalDialog::Private { Private() : selfRequester( 0 ), prefsChanged( false ) {} Kleo::KeyRequester * selfRequester; QStringList addresses; std::vector requesters; std::vector preferences; bool prefsChanged; }; Kleo::KeyApprovalDialog::KeyApprovalDialog( const std::vector & recipients, const std::vector & sender, QWidget * parent, const char * name, bool modal ) : KDialogBase( parent, name, modal, i18n("Encryption Key Approval"), Ok|Cancel, Ok ), d( 0 ) { assert( !recipients.empty() ); d = new Private(); QFrame *page = makeMainWidget(); QVBoxLayout * vlay = new QVBoxLayout( page, 0, spacingHint() ); vlay->addWidget( new QLabel( i18n("The following keys will be used for encryption:"), page ) ); QScrollView * sv = new QScrollView( page ); sv->setResizePolicy( QScrollView::AutoOneFit ); vlay->addWidget( sv ); QWidget * view = new QWidget( sv->viewport() ); QGridLayout * glay = new QGridLayout( view, 3, 2, marginHint(), spacingHint() ); glay->setColStretch( 1, 1 ); sv->addChild( view ); int row = -1; if ( !sender.empty() ) { ++row; glay->addWidget( new QLabel( i18n("Your keys:"), view ), row, 0 ); d->selfRequester = new EncryptionKeyRequester( true, EncryptionKeyRequester::AllProtocols, view ); d->selfRequester->setKeys( sender ); glay->addWidget( d->selfRequester, row, 1 ); ++row; glay->addMultiCellWidget( new KSeparator( Horizontal, view ), row, row, 0, 1 ); } const QStringList prefs = preferencesStrings(); for ( std::vector::const_iterator it = recipients.begin() ; it != recipients.end() ; ++it ) { ++row; glay->addWidget( new QLabel( i18n("Recipient:"), view ), row, 0 ); glay->addWidget( new QLabel( it->address, view ), row, 1 ); d->addresses.push_back( it->address ); ++row; glay->addWidget( new QLabel( i18n("Encryption keys:"), view ), row, 0 ); KeyRequester * req = new EncryptionKeyRequester( true, EncryptionKeyRequester::AllProtocols, view ); req->setKeys( it->keys ); glay->addWidget( req, row, 1 ); d->requesters.push_back( req ); ++row; glay->addWidget( new QLabel( i18n("Encryption preference:"), view ), row, 0 ); QComboBox * cb = new QComboBox( false, view ); cb->insertStringList( prefs ); glay->addWidget( cb, row, 1 ); cb->setCurrentItem( pref2cb( it->pref ) ); connect( cb, SIGNAL(activated(int)), SLOT(slotPrefsChanged()) ); d->preferences.push_back( cb ); } // calculate the optimal width for the dialog const int dialogWidth = marginHint() + sv->frameWidth() + view->sizeHint().width() + sv->verticalScrollBar()->sizeHint().width() + sv->frameWidth() + marginHint() + 2; // calculate the optimal height for the dialog const int dialogHeight = marginHint() + fontMetrics().height() + spacingHint() + sv->frameWidth() + view->sizeHint().height() + sv->horizontalScrollBar()->sizeHint().height() + sv->frameWidth() + spacingHint() + actionButton( KDialogBase::Cancel )->sizeHint().height() + marginHint() + 2; // don't make the dialog too large const QRect desk = KGlobalSettings::desktopGeometry( this ); setInitialSize( QSize( kMin( dialogWidth, 3 * desk.width() / 4 ), kMin( dialogHeight, 7 * desk.height() / 8 ) ) ); } Kleo::KeyApprovalDialog::~KeyApprovalDialog() { delete d; d = 0; } std::vector Kleo::KeyApprovalDialog::senderKeys() const { return d->selfRequester ? d->selfRequester->keys() : std::vector() ; } std::vector Kleo::KeyApprovalDialog::items() const { assert( d->requesters.size() == d->addresses.size() ); assert( d->requesters.size() == d->preferences.size() ); std::vector result; result.reserve( d->requesters.size() ); QStringList::const_iterator ait = d->addresses.begin(); std::vector::const_iterator rit = d->requesters.begin(); std::vector::const_iterator cit = d->preferences.begin(); while ( ait != d->addresses.end() ) result.push_back( Item( *ait++, (*rit++)->keys(), cb2pref( (*cit++)->currentItem() ) ) ); return result; } bool Kleo::KeyApprovalDialog::preferencesChanged() const { return d->prefsChanged; } void Kleo::KeyApprovalDialog::slotPrefsChanged() { d->prefsChanged = true; } #include "keyapprovaldialog.moc" diff --git a/certmanager/lib/ui/keyapprovaldialog.h b/certmanager/lib/ui/keyapprovaldialog.h index caf6c9632a..224530a719 100644 --- a/certmanager/lib/ui/keyapprovaldialog.h +++ b/certmanager/lib/ui/keyapprovaldialog.h @@ -1,92 +1,92 @@ /* -*- c++ -*- keyselectiondialog.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Based on kpgpui.h Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KEYAPPROVALDIALOG_H__ #define __KLEO_KEYAPPROVALDIALOG_H__ #include #include #include #include // for EncryptPref #include #include namespace GpgME { class Key; } class QStringList; namespace Kleo { class KDE_EXPORT KeyApprovalDialog : public KDialogBase { Q_OBJECT public: struct Item { Item() : pref( UnknownPreference ) {} Item( const QString & a, const std::vector & k, EncryptionPreference p=UnknownPreference ) : address( a ), keys( k ), pref( p ) {} QString address; std::vector keys; EncryptionPreference pref; }; KeyApprovalDialog( const std::vector & recipients, const std::vector & sender, QWidget * parent=0, const char * name=0, bool modal=true ); ~KeyApprovalDialog(); std::vector items() const; std::vector senderKeys() const; bool preferencesChanged() const; private slots: void slotPrefsChanged(); private: class Private; Private * d; }; } // namespace Kleo #endif // __KLEO_KEYAPPROVALDIALOG_H__ diff --git a/certmanager/lib/ui/keylistview.cpp b/certmanager/lib/ui/keylistview.cpp index 2041ae9c42..98534a4b73 100644 --- a/certmanager/lib/ui/keylistview.cpp +++ b/certmanager/lib/ui/keylistview.cpp @@ -1,869 +1,869 @@ /* keylistview.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "keylistview.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const int updateDelayMilliSecs = 500; namespace { class ItemToolTip : public QToolTip { public: ItemToolTip( Kleo::KeyListView * parent ); protected: void maybeTip( const QPoint & p ); private: Kleo::KeyListView * mKeyListView; }; ItemToolTip::ItemToolTip( Kleo::KeyListView * parent ) : QToolTip( parent->viewport() ), mKeyListView( parent ) {} void ItemToolTip::maybeTip( const QPoint & p ) { if ( !mKeyListView ) return; const QListViewItem * item = mKeyListView->itemAt( p ); if ( !item ) return; const QRect itemRect = mKeyListView->itemRect( item ); if ( !itemRect.isValid() ) return; const int col = mKeyListView->header()->sectionAt( p.x() ); if ( col == -1 ) return; const QRect headerRect = mKeyListView->header()->sectionRect( col ); if ( !headerRect.isValid() ) return; const QRect cellRect( headerRect.left(), itemRect.top(), headerRect.width(), itemRect.height() ); QString tipStr; if ( const Kleo::KeyListViewItem * klvi = Kleo::lvi_cast( item ) ) tipStr = klvi->toolTip( col ); else tipStr = item->text( col ) ; if ( !tipStr.isEmpty() ) tip( cellRect, tipStr ); } } // anon namespace struct Kleo::KeyListView::Private { Private() : updateTimer( 0 ), itemToolTip( 0 ) {} std::vector keyBuffer; QTimer * updateTimer; QToolTip * itemToolTip; std::map itemMap; }; // a list of signals where we want to replace QListViewItem with // Kleo:KeyListViewItem: static const struct { const char * source; const char * target; } signalReplacements[] = { { SIGNAL(doubleClicked(QListViewItem*,const QPoint&,int)), SLOT(slotEmitDoubleClicked(QListViewItem*,const QPoint&,int)) }, { SIGNAL(returnPressed(QListViewItem*)), SLOT(slotEmitReturnPressed(QListViewItem*)) }, { SIGNAL(selectionChanged(QListViewItem*)), SLOT(slotEmitSelectionChanged(QListViewItem*)) }, { SIGNAL(contextMenu(KListView*, QListViewItem*,const QPoint&)), SLOT(slotEmitContextMenu(KListView*, QListViewItem*,const QPoint&)) }, }; static const int numSignalReplacements = sizeof signalReplacements / sizeof *signalReplacements; Kleo::KeyListView::KeyListView( const ColumnStrategy * columnStrategy, const DisplayStrategy * displayStrategy, QWidget * parent, const char * name, WFlags f ) : KListView( parent, name ), mColumnStrategy( columnStrategy ), mDisplayStrategy ( displayStrategy ), mHierarchical( false ) { setWFlags( f ); d = new Private(); d->updateTimer = new QTimer( this ); connect( d->updateTimer, SIGNAL(timeout()), SLOT(slotUpdateTimeout()) ); if ( !columnStrategy ) { kdWarning(5150) << "Kleo::KeyListView: need a column strategy to work with!" << endl; return; } const QFontMetrics fm = fontMetrics(); for ( int col = 0 ; !columnStrategy->title( col ).isEmpty() ; ++col ) { addColumn( columnStrategy->title( col ), columnStrategy->width( col, fm ) ); setColumnWidthMode( col, columnStrategy->widthMode( col ) ); } setAllColumnsShowFocus( true ); setShowToolTips( false ); // we do it instead... for ( int i = 0 ; i < numSignalReplacements ; ++i ) connect( this, signalReplacements[i].source, signalReplacements[i].target ); QToolTip::remove( this ); QToolTip::remove( viewport() ); // make double sure :) d->itemToolTip = new ItemToolTip( this ); } Kleo::KeyListView::~KeyListView() { d->updateTimer->stop(); // need to clear here, since in ~QListView, our children won't have // a valid listView() pointing to us anymore, and their dtors try to // unregister from us. clear(); assert( d->itemMap.size() == 0 ); // need to delete the tooltip ourselves, as ~QToolTip isn't virtual :o delete d->itemToolTip; d->itemToolTip = 0; delete d; d = 0; delete mColumnStrategy; mColumnStrategy = 0; delete mDisplayStrategy; mDisplayStrategy = 0; } void Kleo::KeyListView::insertItem( QListViewItem * qlvi ) { //kdDebug() << "Kleo::KeyListView::insertItem( " << qlvi << " )" << endl; KListView::insertItem( qlvi ); if ( KeyListViewItem * item = lvi_cast( qlvi ) ) registerItem( item ); } void Kleo::KeyListView::takeItem( QListViewItem * qlvi ) { //kdDebug() << "Kleo::KeyListView::takeItem( " << qlvi << " )" << endl; if ( KeyListViewItem * item = lvi_cast( qlvi ) ) deregisterItem( item ); KListView::takeItem( qlvi ); } void Kleo::KeyListView::setHierarchical( bool hier ) { if ( hier == mHierarchical ) return; mHierarchical = hier; if ( hier ) gatherScattered(); else scatterGathered( firstChild() ); } void Kleo::KeyListView::slotAddKey( const GpgME::Key & key ) { if ( key.isNull() ) return; d->keyBuffer.push_back( key ); if ( !d->updateTimer->isActive() ) d->updateTimer->start( updateDelayMilliSecs, true /* single-shot */ ); } void Kleo::KeyListView::slotUpdateTimeout() { if ( d->keyBuffer.empty() ) return; const bool wasUpdatesEnabled = viewport()->isUpdatesEnabled(); if ( wasUpdatesEnabled ) viewport()->setUpdatesEnabled( false ); kdDebug( 5150 ) << "Kleo::KeyListView::slotUpdateTimeout(): processing " << d->keyBuffer.size() << " items en block" << endl; if ( hierarchical() ) { for ( std::vector::const_iterator it = d->keyBuffer.begin() ; it != d->keyBuffer.end() ; ++it ) doHierarchicalInsert( *it ); gatherScattered(); } else { for ( std::vector::const_iterator it = d->keyBuffer.begin() ; it != d->keyBuffer.end() ; ++it ) (void)new KeyListViewItem( this, *it ); } if ( wasUpdatesEnabled ) viewport()->setUpdatesEnabled( true ); d->keyBuffer.clear(); } void Kleo::KeyListView::clear() { d->updateTimer->stop(); d->keyBuffer.clear(); KListView::clear(); } void Kleo::KeyListView::registerItem( KeyListViewItem * item ) { //kdDebug() << "registerItem( " << item << " )" << endl; if ( !item ) return; const QCString fpr = item->key().primaryFingerprint(); if ( !fpr.isEmpty() ) d->itemMap.insert( std::make_pair( fpr, item ) ); } void Kleo::KeyListView::deregisterItem( const KeyListViewItem * item ) { //kdDebug() << "deregisterItem( KeyLVI: " << item << " )" << endl; if ( !item ) return; std::map::iterator it = d->itemMap.find( item->key().primaryFingerprint() ); if ( it == d->itemMap.end() ) return; Q_ASSERT( it->second == item ); if ( it->second != item ) return; d->itemMap.erase( it ); } void Kleo::KeyListView::doHierarchicalInsert( const GpgME::Key & key ) { const QCString fpr = key.primaryFingerprint(); if ( fpr.isEmpty() ) return; KeyListViewItem * item = 0; if ( !key.isRoot() ) if ( KeyListViewItem * parent = itemByFingerprint( key.chainID() ) ) { item = new KeyListViewItem( parent, key ); parent->setOpen( true ); } if ( !item ) item = new KeyListViewItem( this, key ); // top-level (for now) d->itemMap.insert( std::make_pair( fpr, item ) ); } void Kleo::KeyListView::gatherScattered() { KeyListViewItem * item = firstChild(); while ( item ) { KeyListViewItem * cur = item; item = item->nextSibling(); if ( cur->key().isRoot() ) continue; if ( KeyListViewItem * parent = itemByFingerprint( cur->key().chainID() ) ) { // found a new parent... // ### todo: optimize by suppressing removing/adding the item to the itemMap... takeItem( cur ); parent->insertItem( cur ); parent->setOpen( true ); } } } void Kleo::KeyListView::scatterGathered( QListViewItem * start ) { QListViewItem * item = start; while ( item ) { QListViewItem * cur = item; item = item->nextSibling(); scatterGathered( cur->firstChild() ); assert( cur->childCount() == 0 ); // ### todo: optimize by suppressing removing/adding the item to the itemMap... if ( cur->parent() ) cur->parent()->takeItem( cur ); else takeItem( cur ); insertItem( cur ); } } Kleo::KeyListViewItem * Kleo::KeyListView::itemByFingerprint( const QCString & s ) const { if ( s.isEmpty() ) return 0; const std::map::const_iterator it = d->itemMap.find( s ); if ( it == d->itemMap.end() ) return 0; return it->second; } void Kleo::KeyListView::slotRefreshKey( const GpgME::Key & key ) { const char * fpr = key.primaryFingerprint(); if ( !fpr ) return; if ( KeyListViewItem * item = itemByFingerprint( fpr ) ) item->setKey ( key ); else // none found -> add it slotAddKey( key ); } // slots for the emission of covariant signals: void Kleo::KeyListView::slotEmitDoubleClicked( QListViewItem * item, const QPoint & p, int col ) { if ( !item || lvi_cast( item ) ) emit doubleClicked( static_cast( item ), p, col ); } void Kleo::KeyListView::slotEmitReturnPressed( QListViewItem * item ) { if ( !item || lvi_cast( item ) ) emit returnPressed( static_cast( item ) ); } void Kleo::KeyListView::slotEmitSelectionChanged( QListViewItem * item ) { if ( !item || lvi_cast( item ) ) emit selectionChanged( static_cast( item ) ); } void Kleo::KeyListView::slotEmitContextMenu( KListView*, QListViewItem * item, const QPoint & p ) { if ( !item || lvi_cast( item ) ) emit contextMenu( static_cast( item ), p ); } // // // KeyListViewItem // // Kleo::KeyListViewItem::KeyListViewItem( KeyListView * parent, const GpgME::Key & key ) : QListViewItem( parent ) { setKey( key ); } Kleo::KeyListViewItem::KeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::Key & key ) : QListViewItem( parent, after ) { setKey( key ); } Kleo::KeyListViewItem::KeyListViewItem( KeyListViewItem * parent, const GpgME::Key & key ) : QListViewItem( parent ) { setKey( key ); } Kleo::KeyListViewItem::KeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::Key & key ) : QListViewItem( parent, after ) { setKey( key ); } Kleo::KeyListViewItem::~KeyListViewItem() { // delete the children first... When children are deleted in the // QLVI dtor, they don't have listView() anymore, thus they don't // call deregister( this ), leading to stale entries in the // itemMap... while ( QListViewItem * item = firstChild() ) delete item; // better do this here, too, since deletion is top-down and thus // we're deleted when our parent item is no longer a // KeyListViewItem, but a mere QListViewItem, so our takeItem() // overload is gone by that time... if ( KeyListView * lv = listView() ) lv->deregisterItem( this ); } void Kleo::KeyListViewItem::setKey( const GpgME::Key & key ) { KeyListView * lv = listView(); if ( lv ) lv->deregisterItem( this ); mKey = key; if ( lv ) lv->registerItem( this ); // the ColumnStrategy operations might be very slow, so cache their // result here, where we're non-const :) const Kleo::KeyListView::ColumnStrategy * cs = lv ? lv->columnStrategy() : 0 ; if ( !cs ) return; const int numCols = lv ? lv->columns() : 0 ; for ( int i = 0 ; i < numCols ; ++i ) { setText( i, cs->text( key, i ) ); if ( const QPixmap * pix = cs->pixmap( key, i ) ) setPixmap( i, *pix ); } repaint(); } QString Kleo::KeyListViewItem::toolTip( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->toolTip( key(), col ) : QString::null ; } int Kleo::KeyListViewItem::compare( QListViewItem * item, int col, bool ascending ) const { if ( !item || item->rtti() != RTTI || !listView() || !listView()->columnStrategy() ) return QListViewItem::compare( item, col, ascending ); KeyListViewItem * that = static_cast( item ); return listView()->columnStrategy()->compare( this->key(), that->key(), col ); } void Kleo::KeyListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { const KeyListView::DisplayStrategy * ds = listView() ? listView()->displayStrategy() : 0 ; if ( !ds ) { QListViewItem::paintCell( p, cg, column, width, alignment ); return; } const QColor fg = ds->keyForeground( key(), cg.text() ); const QColor bg = ds->keyBackground( key(), cg.base() ); const QFont f = ds->keyFont( key(), p->font() ); QColorGroup _cg = cg; p->setFont( f ); _cg.setColor( QColorGroup::Text, fg ); _cg.setColor( QColorGroup::Base, bg ); QListViewItem::paintCell( p, _cg, column, width, alignment ); } void Kleo::KeyListViewItem::insertItem( QListViewItem * qlvi ) { //kdDebug() << "Kleo::KeyListViewItem::insertItem( " << qlvi << " )" << endl; QListViewItem::insertItem( qlvi ); if ( KeyListViewItem * item = lvi_cast( qlvi ) ) listView()->registerItem( item ); } void Kleo::KeyListViewItem::takeItem( QListViewItem * qlvi ) { //kdDebug() << "Kleo::KeyListViewItem::takeItem( " << qlvi << " )" << endl; if ( KeyListViewItem * item = lvi_cast( qlvi ) ) listView()->deregisterItem( item ); QListViewItem::takeItem( qlvi ); } // // // SubkeyKeyListViewItem // // Kleo::SubkeyKeyListViewItem::SubkeyKeyListViewItem( KeyListView * parent, const GpgME::Subkey & subkey ) : KeyListViewItem( parent, subkey.parent() ), mSubkey( subkey ) { } Kleo::SubkeyKeyListViewItem::SubkeyKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::Subkey & subkey ) : KeyListViewItem( parent, after, subkey.parent() ), mSubkey( subkey ) { } Kleo::SubkeyKeyListViewItem::SubkeyKeyListViewItem( KeyListViewItem * parent, const GpgME::Subkey & subkey ) : KeyListViewItem( parent, subkey.parent() ), mSubkey( subkey ) { } Kleo::SubkeyKeyListViewItem::SubkeyKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::Subkey & subkey ) : KeyListViewItem( parent, after, subkey.parent() ), mSubkey( subkey ) { } void Kleo::SubkeyKeyListViewItem::setSubkey( const GpgME::Subkey & subkey ) { mSubkey = subkey; setKey( subkey.parent() ); } QString Kleo::SubkeyKeyListViewItem::text( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->subkeyText( subkey(), col ) : QString::null ; } QString Kleo::SubkeyKeyListViewItem::toolTip( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->subkeyToolTip( subkey(), col ) : QString::null ; } const QPixmap * Kleo::SubkeyKeyListViewItem::pixmap( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->subkeyPixmap( subkey(), col ) : 0 ; } int Kleo::SubkeyKeyListViewItem::compare( QListViewItem * item, int col, bool ascending ) const { if ( !item || item->rtti() != RTTI || !listView() || !listView()->columnStrategy() ) return KeyListViewItem::compare( item, col, ascending ); SubkeyKeyListViewItem * that = static_cast( item ); return listView()->columnStrategy()->subkeyCompare( this->subkey(), that->subkey(), col ); } void Kleo::SubkeyKeyListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { const KeyListView::DisplayStrategy * ds = listView() ? listView()->displayStrategy() : 0 ; if ( !ds ) { QListViewItem::paintCell( p, cg, column, width, alignment ); return; } const QColor fg = ds->subkeyForeground( subkey(), cg.text() ); const QColor bg = ds->subkeyBackground( subkey(), cg.base() ); const QFont f = ds->subkeyFont( subkey(), p->font() ); QColorGroup _cg = cg; p->setFont( f ); _cg.setColor( QColorGroup::Text, fg ); _cg.setColor( QColorGroup::Base, bg ); QListViewItem::paintCell( p, _cg, column, width, alignment ); } // // // UserIDKeyListViewItem // // Kleo::UserIDKeyListViewItem::UserIDKeyListViewItem( KeyListView * parent, const GpgME::UserID & userID ) : KeyListViewItem( parent, userID.parent() ), mUserID( userID ) { } Kleo::UserIDKeyListViewItem::UserIDKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::UserID & userID ) : KeyListViewItem( parent, after, userID.parent() ), mUserID( userID ) { } Kleo::UserIDKeyListViewItem::UserIDKeyListViewItem( KeyListViewItem * parent, const GpgME::UserID & userID ) : KeyListViewItem( parent, userID.parent() ), mUserID( userID ) { } Kleo::UserIDKeyListViewItem::UserIDKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::UserID & userID ) : KeyListViewItem( parent, after, userID.parent() ), mUserID( userID ) { } void Kleo::UserIDKeyListViewItem::setUserID( const GpgME::UserID & userID ) { mUserID = userID; setKey( userID.parent() ); } QString Kleo::UserIDKeyListViewItem::text( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->userIDText( userID(), col ) : QString::null ; } QString Kleo::UserIDKeyListViewItem::toolTip( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->userIDToolTip( userID(), col ) : QString::null ; } const QPixmap * Kleo::UserIDKeyListViewItem::pixmap( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->userIDPixmap( userID(), col ) : 0 ; } int Kleo::UserIDKeyListViewItem::compare( QListViewItem * item, int col, bool ascending ) const { if ( !item || item->rtti() != RTTI || !listView() || !listView()->columnStrategy() ) return KeyListViewItem::compare( item, col, ascending ); UserIDKeyListViewItem * that = static_cast( item ); return listView()->columnStrategy()->userIDCompare( this->userID(), that->userID(), col ); } void Kleo::UserIDKeyListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { const KeyListView::DisplayStrategy * ds = listView() ? listView()->displayStrategy() : 0 ; if ( !ds ) { QListViewItem::paintCell( p, cg, column, width, alignment ); return; } const QColor fg = ds->useridForeground( userID(), cg.text() ); const QColor bg = ds->useridBackground( userID(), cg.base() ); const QFont f = ds->useridFont( userID(), p->font() ); QColorGroup _cg = cg; p->setFont( f ); _cg.setColor( QColorGroup::Text, fg ); _cg.setColor( QColorGroup::Base, bg ); QListViewItem::paintCell( p, _cg, column, width, alignment ); } // // // SignatureKeyListViewItem // // Kleo::SignatureKeyListViewItem::SignatureKeyListViewItem( KeyListView * parent, const GpgME::UserID::Signature & signature ) : KeyListViewItem( parent, signature.parent().parent() ), mSignature( signature ) { } Kleo::SignatureKeyListViewItem::SignatureKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::UserID::Signature & signature ) : KeyListViewItem( parent, after, signature.parent().parent() ), mSignature( signature ) { } Kleo::SignatureKeyListViewItem::SignatureKeyListViewItem( KeyListViewItem * parent, const GpgME::UserID::Signature & signature ) : KeyListViewItem( parent, signature.parent().parent() ), mSignature( signature ) { } Kleo::SignatureKeyListViewItem::SignatureKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::UserID::Signature & signature ) : KeyListViewItem( parent, after, signature.parent().parent() ), mSignature( signature ) { } void Kleo::SignatureKeyListViewItem::setSignature( const GpgME::UserID::Signature & signature ) { mSignature = signature; setKey( signature.parent().parent() ); } QString Kleo::SignatureKeyListViewItem::text( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->signatureText( signature(), col ) : QString::null ; } QString Kleo::SignatureKeyListViewItem::toolTip( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->signatureToolTip( signature(), col ) : QString::null ; } const QPixmap * Kleo::SignatureKeyListViewItem::pixmap( int col ) const { return listView() && listView()->columnStrategy() ? listView()->columnStrategy()->signaturePixmap( signature(), col ) : 0 ; } int Kleo::SignatureKeyListViewItem::compare( QListViewItem * item, int col, bool ascending ) const { if ( !item || item->rtti() != RTTI || !listView() || !listView()->columnStrategy() ) return KeyListViewItem::compare( item, col, ascending ); SignatureKeyListViewItem * that = static_cast( item ); return listView()->columnStrategy()->signatureCompare( this->signature(), that->signature(), col ); } void Kleo::SignatureKeyListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { const KeyListView::DisplayStrategy * ds = listView() ? listView()->displayStrategy() : 0 ; if ( !ds ) { QListViewItem::paintCell( p, cg, column, width, alignment ); return; } const QColor fg = ds->signatureForeground( signature(), cg.text() ); const QColor bg = ds->signatureBackground( signature(), cg.base() ); const QFont f = ds->signatureFont( signature(), p->font() ); QColorGroup _cg = cg; p->setFont( f ); _cg.setColor( QColorGroup::Text, fg ); _cg.setColor( QColorGroup::Base, bg ); QListViewItem::paintCell( p, _cg, column, width, alignment ); } // // // ColumnStrategy // // Kleo::KeyListView::ColumnStrategy::~ColumnStrategy() {} int Kleo::KeyListView::ColumnStrategy::compare( const GpgME::Key & key1, const GpgME::Key & key2, int col ) const { return QString::localeAwareCompare( text( key1, col ), text( key2, col ) ); } int Kleo::KeyListView::ColumnStrategy::width( int col, const QFontMetrics & fm ) const { return fm.width( title( col ) ) * 2; } int Kleo::KeyListView::ColumnStrategy::subkeyCompare( const GpgME::Subkey & sub1, const GpgME::Subkey & sub2, int col ) const { return QString::localeAwareCompare( subkeyText( sub1, col ), subkeyText( sub2, col ) ); } int Kleo::KeyListView::ColumnStrategy::userIDCompare( const GpgME::UserID & uid1, const GpgME::UserID & uid2, int col ) const { return QString::localeAwareCompare( userIDText( uid1, col ), userIDText( uid2, col ) ); } int Kleo::KeyListView::ColumnStrategy::signatureCompare( const GpgME::UserID::Signature & sig1, const GpgME::UserID::Signature & sig2, int col ) const { return QString::localeAwareCompare( signatureText( sig1, col ), signatureText( sig2, col ) ); } QString Kleo::KeyListView::ColumnStrategy::toolTip( const GpgME::Key & key, int col ) const { return text( key, col ); } QString Kleo::KeyListView::ColumnStrategy::subkeyToolTip( const GpgME::Subkey & sub, int col ) const { return subkeyText( sub, col ); } QString Kleo::KeyListView::ColumnStrategy::userIDToolTip( const GpgME::UserID & uid, int col ) const { return userIDText( uid, col ); } QString Kleo::KeyListView::ColumnStrategy::signatureToolTip( const GpgME::UserID::Signature & sig, int col ) const { return signatureText( sig, col ); } // // // DisplayStrategy // // Kleo::KeyListView::DisplayStrategy::~DisplayStrategy() {} //font QFont Kleo::KeyListView::DisplayStrategy::keyFont( const GpgME::Key &, const QFont & font ) const { return font; } QFont Kleo::KeyListView::DisplayStrategy::subkeyFont( const GpgME::Subkey &, const QFont & font ) const { return font; } QFont Kleo::KeyListView::DisplayStrategy::useridFont( const GpgME::UserID &, const QFont & font ) const { return font; } QFont Kleo::KeyListView::DisplayStrategy::signatureFont( const GpgME::UserID::Signature &, const QFont & font ) const { return font; } //foreground QColor Kleo::KeyListView::DisplayStrategy::keyForeground( const GpgME::Key &, const QColor & fg )const { return fg; } QColor Kleo::KeyListView::DisplayStrategy::subkeyForeground( const GpgME::Subkey &, const QColor & fg ) const { return fg; } QColor Kleo::KeyListView::DisplayStrategy::useridForeground( const GpgME::UserID &, const QColor & fg ) const { return fg; } QColor Kleo::KeyListView::DisplayStrategy::signatureForeground( const GpgME::UserID::Signature &, const QColor & fg ) const { return fg; } //background QColor Kleo::KeyListView::DisplayStrategy::keyBackground( const GpgME::Key &, const QColor & bg )const { return bg; } QColor Kleo::KeyListView::DisplayStrategy::subkeyBackground( const GpgME::Subkey &, const QColor & bg ) const { return bg; } QColor Kleo::KeyListView::DisplayStrategy::useridBackground( const GpgME::UserID &, const QColor & bg ) const { return bg; } QColor Kleo::KeyListView::DisplayStrategy::signatureBackground( const GpgME::UserID::Signature &, const QColor & bg ) const { return bg; } // // // Collection of covariant return reimplementations of QListView(Item) // members: // // Kleo::KeyListView * Kleo::KeyListViewItem::listView() const { return static_cast( QListViewItem::listView() ); } Kleo::KeyListViewItem * Kleo::KeyListViewItem::nextSibling() const { return static_cast( QListViewItem::nextSibling() ); } Kleo::KeyListViewItem * Kleo::KeyListView::firstChild() const { return static_cast( KListView::firstChild() ); } Kleo::KeyListViewItem * Kleo::KeyListView::selectedItem() const { return static_cast( KListView::selectedItem() ); } static void selectedItems( QPtrList & result, QListViewItem * start ) { for ( QListViewItem * item = start ; item ; item = item->nextSibling() ) { if ( item->isSelected() ) if ( Kleo::KeyListViewItem * i = Kleo::lvi_cast( item ) ) result.append( i ); selectedItems( result, item->firstChild() ); } } QPtrList Kleo::KeyListView::selectedItems() const { QPtrList result; ::selectedItems( result, firstChild() ); return result; } static bool hasSelection( QListViewItem * start ) { for ( QListViewItem * item = start ; item ; item = item->nextSibling() ) if ( item->isSelected() || hasSelection( item->firstChild() ) ) return true; return false; } bool Kleo::KeyListView::hasSelection() const { return ::hasSelection( firstChild() ); } #include "keylistview.moc" diff --git a/certmanager/lib/ui/keylistview.h b/certmanager/lib/ui/keylistview.h index a6607bfafd..3ef7087710 100644 --- a/certmanager/lib/ui/keylistview.h +++ b/certmanager/lib/ui/keylistview.h @@ -1,323 +1,323 @@ /* keylistview.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_KEYLISTVIEW_H__ #define __KLEO_KEYLISTVIEW_H__ #include #include #include class QPainter; class QColorGroup; class QFont; class QColor; namespace Kleo { // work around moc parser bug... #define TEMPLATE_TYPENAME(T) template TEMPLATE_TYPENAME(T) inline T * lvi_cast( QListViewItem * item ) { return item && (item->rtti() & T::RTTI_MASK) == T::RTTI ? static_cast( item ) : 0 ; } TEMPLATE_TYPENAME(T) inline const T * lvi_cast( const QListViewItem * item ) { return item && (item->rtti() & T::RTTI_MASK) == T::RTTI ? static_cast( item ) : 0 ; } #undef TEMPLATE_TYPENAME class KeyListView; class KDE_EXPORT KeyListViewItem : public QListViewItem { public: KeyListViewItem( KeyListView * parent, const GpgME::Key & key ); KeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::Key & key ); KeyListViewItem( KeyListViewItem * parent, const GpgME::Key & key ); KeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::Key & key ); ~KeyListViewItem(); void setKey( const GpgME::Key & key ); const GpgME::Key & key() const { return mKey; } enum { RTTI_MASK = 0xFFFFFFF0, RTTI = 0x2C1362E0 }; // // only boring stuff below: // virtual QString toolTip( int column ) const; /*! \reimp for covariant return */ KeyListView * listView() const; /*! \reimp for covariant return */ KeyListViewItem * nextSibling() const; /*! \reimp */ int compare( QListViewItem * other, int col, bool ascending ) const; /*! \reimp to allow for key() overload above */ QString key( int col, bool ascending ) const { return QListViewItem::key( col, ascending ); } /*! \reimp */ int rtti() const { return RTTI; } /*! \reimp */ void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); /*! \reimp */ void insertItem( QListViewItem * item ); /*! \reimp */ void takeItem( QListViewItem * item ); private: GpgME::Key mKey; }; class KDE_EXPORT SubkeyKeyListViewItem : public KeyListViewItem { public: SubkeyKeyListViewItem( KeyListView * parent, const GpgME::Subkey & subkey ); SubkeyKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::Subkey & subkey ); SubkeyKeyListViewItem( KeyListViewItem * parent, const GpgME::Subkey & subkey ); SubkeyKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::Subkey & subkey ); void setSubkey( const GpgME::Subkey & subkey ); const GpgME::Subkey & subkey() const { return mSubkey; } enum { RTTI = KeyListViewItem::RTTI + 1 }; // // only boring stuff below: // /*! \reimp */ QString toolTip( int col ) const; /*! \reimp */ QString text( int col ) const; /*! \reimp */ const QPixmap * pixmap( int col ) const; /*! \reimp */ int compare( QListViewItem * other, int col, bool ascending ) const; /*! \reimp */ int rtti() const { return RTTI; } /*! \reimp */ void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); private: GpgME::Subkey mSubkey; }; class KDE_EXPORT UserIDKeyListViewItem : public KeyListViewItem { public: UserIDKeyListViewItem( KeyListView * parent, const GpgME::UserID & userid ); UserIDKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::UserID & userid ); UserIDKeyListViewItem( KeyListViewItem * parent, const GpgME::UserID & userid ); UserIDKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::UserID & userid ); void setUserID( const GpgME::UserID & userid ); const GpgME::UserID userID() const { return mUserID; } enum { RTTI = KeyListViewItem::RTTI + 2 }; // // only boring stuff below: // /*! \reimp */ QString toolTip( int col ) const; /*! \reimp */ QString text( int col ) const; /*! \reimp */ const QPixmap * pixmap( int col ) const; /*! \reimp */ int compare( QListViewItem * other, int col, bool ascending ) const; /*! \reimp */ int rtti() const { return RTTI; } /*! \reimp */ void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); private: GpgME::UserID mUserID; }; class KDE_EXPORT SignatureKeyListViewItem : public KeyListViewItem { public: SignatureKeyListViewItem( KeyListView * parent, const GpgME::UserID::Signature & sig ); SignatureKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::UserID::Signature & sig ); SignatureKeyListViewItem( KeyListViewItem * parent, const GpgME::UserID::Signature & sig ); SignatureKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::UserID::Signature & sig ); void setSignature( const GpgME::UserID::Signature & sig ); const GpgME::UserID::Signature & signature() const { return mSignature; } enum { RTTI = KeyListViewItem::RTTI + 3 }; // // only boring stuff below: // /*! \reimp */ QString toolTip( int col ) const; /*! \reimp */ QString text( int col ) const; /*! \reimp */ const QPixmap * pixmap( int col ) const; /*! \reimp */ int compare( QListViewItem * other, int col, bool ascending ) const; /*! \reimp */ int rtti() const { return RTTI; } /*! \reimp */ void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); private: GpgME::UserID::Signature mSignature; }; class KDE_EXPORT KeyListView : public KListView { Q_OBJECT friend class KeyListViewItem; public: class KDE_EXPORT ColumnStrategy { public: virtual ~ColumnStrategy(); virtual QString title( int column ) const = 0; virtual int width( int column, const QFontMetrics & fm ) const; virtual QListView::WidthMode widthMode( int ) const { return QListView::Manual; } virtual QString text( const GpgME::Key & key, int column ) const = 0; virtual QString toolTip( const GpgME::Key & key, int column ) const; virtual const QPixmap * pixmap( const GpgME::Key &, int ) const { return 0; } virtual int compare( const GpgME::Key & key1, const GpgME::Key & key2, const int column ) const; virtual QString subkeyText( const GpgME::Subkey &, int ) const { return QString::null; } virtual QString subkeyToolTip( const GpgME::Subkey & subkey, int column ) const; virtual const QPixmap * subkeyPixmap( const GpgME::Subkey &, int ) const { return 0; } virtual int subkeyCompare( const GpgME::Subkey & subkey1, const GpgME::Subkey & subkey2, const int column ) const; virtual QString userIDText( const GpgME::UserID &, int ) const { return QString::null; } virtual QString userIDToolTip( const GpgME::UserID & userID, int column ) const; virtual const QPixmap * userIDPixmap( const GpgME::UserID &, int ) const { return 0; } virtual int userIDCompare( const GpgME::UserID & userID1, const GpgME::UserID & userID2, const int column ) const; virtual QString signatureText( const GpgME::UserID::Signature &, int ) const { return QString::null; } virtual QString signatureToolTip( const GpgME::UserID::Signature & sig, int column ) const; virtual const QPixmap * signaturePixmap( const GpgME::UserID::Signature &, int ) const { return 0; } virtual int signatureCompare( const GpgME::UserID::Signature & sig1, const GpgME::UserID::Signature & sig2, const int column ) const; }; class KDE_EXPORT DisplayStrategy { public: virtual ~DisplayStrategy(); //font virtual QFont keyFont( const GpgME::Key &, const QFont & ) const; virtual QFont subkeyFont( const GpgME::Subkey &, const QFont & ) const; virtual QFont useridFont( const GpgME::UserID &, const QFont & ) const; virtual QFont signatureFont( const GpgME::UserID::Signature & , const QFont & ) const; //foreground virtual QColor keyForeground( const GpgME::Key & , const QColor & ) const; virtual QColor subkeyForeground( const GpgME::Subkey &, const QColor & ) const; virtual QColor useridForeground( const GpgME::UserID &, const QColor & ) const; virtual QColor signatureForeground( const GpgME::UserID::Signature &, const QColor & ) const; //background virtual QColor keyBackground( const GpgME::Key &, const QColor & ) const; virtual QColor subkeyBackground( const GpgME::Subkey &, const QColor & ) const; virtual QColor useridBackground( const GpgME::UserID &, const QColor & ) const; virtual QColor signatureBackground( const GpgME::UserID::Signature &, const QColor & ) const; }; KeyListView( const ColumnStrategy * strategy, const DisplayStrategy * display=0, QWidget * parent=0, const char * name=0, WFlags f=0 ); ~KeyListView(); const ColumnStrategy * columnStrategy() const { return mColumnStrategy; } const DisplayStrategy * displayStrategy() const { return mDisplayStrategy; } bool hierarchical() const { return mHierarchical; } virtual void setHierarchical( bool hier ); void flushKeys() { slotUpdateTimeout(); } bool hasSelection() const; KeyListViewItem * itemByFingerprint( const QCString & ) const; signals: void doubleClicked( Kleo::KeyListViewItem*, const QPoint&, int ); void returnPressed( Kleo::KeyListViewItem* ); void selectionChanged( Kleo::KeyListViewItem* ); void contextMenu( Kleo::KeyListViewItem*, const QPoint& ); public slots: virtual void slotAddKey( const GpgME::Key & key ); virtual void slotRefreshKey( const GpgME::Key & key ); // // Only boring stuff below: // private slots: void slotEmitDoubleClicked( QListViewItem*, const QPoint&, int ); void slotEmitReturnPressed( QListViewItem* ); void slotEmitSelectionChanged( QListViewItem* ); void slotEmitContextMenu( KListView*, QListViewItem*, const QPoint& ); void slotUpdateTimeout(); public: /*! \reimp for covariant return */ KeyListViewItem * selectedItem() const; /*! \reimp */ QPtrList selectedItems() const; /*! \reimp for covariant return */ KeyListViewItem * firstChild() const; /*! \reimp */ void clear(); /*! \reimp */ void insertItem( QListViewItem * ); /*! \reimp */ void takeItem( QListViewItem * ); private: void doHierarchicalInsert( const GpgME::Key & ); void gatherScattered(); void scatterGathered( QListViewItem * ); void registerItem( KeyListViewItem * ); void deregisterItem( const KeyListViewItem * ); private: const ColumnStrategy * mColumnStrategy; const DisplayStrategy * mDisplayStrategy; bool mHierarchical; class Private; Private * d; }; } #endif // __KLEO_KEYLISTVIEW_H__ diff --git a/certmanager/lib/ui/keyrequester.cpp b/certmanager/lib/ui/keyrequester.cpp index 987b7b3803..d537affc5e 100644 --- a/certmanager/lib/ui/keyrequester.cpp +++ b/certmanager/lib/ui/keyrequester.cpp @@ -1,481 +1,481 @@ /* -*- c++ -*- keyrequester.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klar�vdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. Based on kpgpui.cpp Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details This file is part of KPGP, the KDE PGP/GnuPG support library. KPGP 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. 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 + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifdef HAVE_CONFIG_H #include #endif #include "keyrequester.h" #include "keyselectiondialog.h" #include #include #include // gpgme++ #include #include // KDE #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include #include Kleo::KeyRequester::KeyRequester( unsigned int allowedKeys, bool multipleKeys, QWidget * parent, const char * name ) : QWidget( parent, name ), mOpenPGPBackend( 0 ), mSMIMEBackend( 0 ), mMulti( multipleKeys ), mKeyUsage( allowedKeys ), mJobs( 0 ), d( 0 ) { init(); } Kleo::KeyRequester::KeyRequester( QWidget * parent, const char * name ) : QWidget( parent, name ), mOpenPGPBackend( 0 ), mSMIMEBackend( 0 ), mMulti( false ), mKeyUsage( 0 ), mJobs( 0 ), d( 0 ) { init(); } void Kleo::KeyRequester::init() { QHBoxLayout * hlay = new QHBoxLayout( this, 0, KDialog::spacingHint() ); // the label where the key id is to be displayed: mLabel = new QLabel( this ); mLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken ); // the button to unset any key: mEraseButton = new KPushButton( this ); mEraseButton->setAutoDefault( false ); mEraseButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) ); mEraseButton->setIconSet( SmallIconSet( QApplication::reverseLayout() ? "locationbar_erase" : "clear_left" ) ); QToolTip::add( mEraseButton, i18n("Clear") ); // the button to call the KeySelectionDialog: mDialogButton = new QPushButton( i18n("Change..."), this ); mDialogButton->setAutoDefault( false ); hlay->addWidget( mLabel, 1 ); hlay->addWidget( mEraseButton ); hlay->addWidget( mDialogButton ); connect( mEraseButton, SIGNAL(clicked()), SLOT(slotEraseButtonClicked()) ); connect( mDialogButton, SIGNAL(clicked()), SLOT(slotDialogButtonClicked()) ); setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ) ); setAllowedKeys( mKeyUsage ); } Kleo::KeyRequester::~KeyRequester() { } const std::vector & Kleo::KeyRequester::keys() const { return mKeys; } const GpgME::Key & Kleo::KeyRequester::key() const { if ( mKeys.empty() ) return GpgME::Key::null; else return mKeys.front(); } void Kleo::KeyRequester::setKeys( const std::vector & keys ) { mKeys.clear(); for ( std::vector::const_iterator it = keys.begin() ; it != keys.end() ; ++it ) if ( !it->isNull() ) mKeys.push_back( *it ); updateKeys(); } void Kleo::KeyRequester::setKey( const GpgME::Key & key ) { mKeys.clear(); if ( !key.isNull() ) mKeys.push_back( key ); updateKeys(); } QString Kleo::KeyRequester::fingerprint() const { if ( mKeys.empty() ) return QString::null; else return mKeys.front().primaryFingerprint(); } QStringList Kleo::KeyRequester::fingerprints() const { QStringList result; for ( std::vector::const_iterator it = mKeys.begin() ; it != mKeys.end() ; ++it ) if ( !it->isNull() ) if ( const char * fpr = it->primaryFingerprint() ) result.push_back( fpr ); return result; } void Kleo::KeyRequester::setFingerprint( const QString & fingerprint ) { startKeyListJob( fingerprint ); } void Kleo::KeyRequester::setFingerprints( const QStringList & fingerprints ) { startKeyListJob( fingerprints ); } void Kleo::KeyRequester::updateKeys() { if ( mKeys.empty() ) { mLabel->clear(); return; } if ( mKeys.size() > 1 ) setMultipleKeysEnabled( true ); QStringList labelTexts; QString toolTipText; for ( std::vector::const_iterator it = mKeys.begin() ; it != mKeys.end() ; ++it ) { if ( it->isNull() ) continue; const QString fpr = it->primaryFingerprint(); labelTexts.push_back( fpr.right(8) ); toolTipText += fpr.right(8) + ": "; if ( const char * uid = it->userID(0).id() ) if ( it->protocol() == GpgME::Context::OpenPGP ) toolTipText += QString::fromUtf8( uid ); else toolTipText += Kleo::DN( uid ).prettyDN(); else toolTipText += i18n(""); toolTipText += '\n'; } mLabel->setText( labelTexts.join(", ") ); QToolTip::remove( mLabel ); QToolTip::add( mLabel, toolTipText ); } #ifndef __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ #define __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ static void showKeyListError( QWidget * parent, const GpgME::Error & err ) { assert( err ); const QString msg = i18n( "

An error occurred while fetching " "the keys from the backend:

" "

%1

" ) .arg( QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n( "Key Listing Failed" ) ); } #endif // __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ void Kleo::KeyRequester::startKeyListJob( const QStringList & fingerprints ) { if ( !mSMIMEBackend && !mOpenPGPBackend ) return; mTmpKeys.clear(); mJobs = 0; unsigned int count = 0; for ( QStringList::const_iterator it = fingerprints.begin() ; it != fingerprints.end() ; ++it ) if ( !(*it).stripWhiteSpace().isEmpty() ) ++count; if ( !count ) { // don't fall into the trap that an empty pattern means // "return all keys" :) setKey( GpgME::Key::null ); return; } if ( mOpenPGPBackend ) { KeyListJob * job = mOpenPGPBackend->keyListJob( false ); // local, no sigs if ( !job ) { KMessageBox::error( this, i18n("The OpenPGP backend does not support listing keys. " "Check your installation."), i18n("Key Listing Failed") ); } else { connect( job, SIGNAL(result(const GpgME::KeyListResult&)), SLOT(slotKeyListResult(const GpgME::KeyListResult&)) ); connect( job, SIGNAL(nextKey(const GpgME::Key&)), SLOT(slotNextKey(const GpgME::Key&)) ); const GpgME::Error err = job->start( fingerprints, mKeyUsage & Kleo::KeySelectionDialog::SecretKeys && !( mKeyUsage & Kleo::KeySelectionDialog::PublicKeys ) ); if ( err ) showKeyListError( this, err ); else ++mJobs; } } if ( mSMIMEBackend ) { KeyListJob * job = mSMIMEBackend->keyListJob( false ); // local, no sigs if ( !job ) { KMessageBox::error( this, i18n("The S/MIME backend does not support listing keys. " "Check your installation."), i18n("Key Listing Failed") ); } else { connect( job, SIGNAL(result(const GpgME::KeyListResult&)), SLOT(slotKeyListResult(const GpgME::KeyListResult&)) ); connect( job, SIGNAL(nextKey(const GpgME::Key&)), SLOT(slotNextKey(const GpgME::Key&)) ); const GpgME::Error err = job->start( fingerprints, mKeyUsage & Kleo::KeySelectionDialog::SecretKeys && !( mKeyUsage & Kleo::KeySelectionDialog::PublicKeys ) ); if ( err ) showKeyListError( this, err ); else ++mJobs; } } if ( mJobs > 0 ) { mEraseButton->setEnabled( false ); mDialogButton->setEnabled( false ); } } void Kleo::KeyRequester::slotNextKey( const GpgME::Key & key ) { if ( !key.isNull() ) mTmpKeys.push_back( key ); } void Kleo::KeyRequester::slotKeyListResult( const GpgME::KeyListResult & res ) { if ( res.error() ) showKeyListError( this, res.error() ); if ( --mJobs <= 0 ) { mEraseButton->setEnabled( true ); mDialogButton->setEnabled( true ); setKeys( mTmpKeys ); mTmpKeys.clear(); } } void Kleo::KeyRequester::slotDialogButtonClicked() { KeySelectionDialog * dlg = mKeys.empty() - ? new KeySelectionDialog( mDialogCaption, mDialogMessage, mInitialQuery, mKeyUsage, mMulti ) - : new KeySelectionDialog( mDialogCaption, mDialogCaption, mKeys, mKeyUsage, mMulti ) ; + ? new KeySelectionDialog( mDialogCaption, mDialogMessage, mInitialQuery, mKeyUsage, mMulti, false, this ) + : new KeySelectionDialog( mDialogCaption, mDialogCaption, mKeys, mKeyUsage, mMulti, false, this ) ; if ( dlg->exec() == QDialog::Accepted ) { if ( mMulti ) setKeys( dlg->selectedKeys() ); else setKey( dlg->selectedKey() ); emit changed(); } delete dlg; } void Kleo::KeyRequester::slotEraseButtonClicked() { if ( !mKeys.empty() ) emit changed(); mKeys.clear(); updateKeys(); } void Kleo::KeyRequester::setDialogCaption( const QString & caption ) { mDialogCaption = caption; } void Kleo::KeyRequester::setDialogMessage( const QString & msg ) { mDialogMessage = msg; } bool Kleo::KeyRequester::isMultipleKeysEnabled() const { return mMulti; } void Kleo::KeyRequester::setMultipleKeysEnabled( bool multi ) { if ( multi == mMulti ) return; if ( !multi && !mKeys.empty() ) mKeys.erase( mKeys.begin() + 1, mKeys.end() ); mMulti = multi; updateKeys(); } unsigned int Kleo::KeyRequester::allowedKeys() const { return mKeyUsage; } void Kleo::KeyRequester::setAllowedKeys( unsigned int keyUsage ) { mKeyUsage = keyUsage; mOpenPGPBackend = 0; mSMIMEBackend = 0; if ( mKeyUsage & KeySelectionDialog::OpenPGPKeys ) mOpenPGPBackend = Kleo::CryptoBackendFactory::instance()->openpgp(); if ( mKeyUsage & KeySelectionDialog::SMIMEKeys ) mSMIMEBackend = Kleo::CryptoBackendFactory::instance()->smime(); if ( mOpenPGPBackend && !mSMIMEBackend ) { mDialogCaption = i18n("OpenPGP Key Selection"); mDialogMessage = i18n("Please select an OpenPGP key to use."); } else if ( !mOpenPGPBackend && mSMIMEBackend ) { mDialogCaption = i18n("S/MIME Key Selection"); mDialogMessage = i18n("Please select an S/MIME key to use."); } else { mDialogCaption = i18n("Key Selection"); mDialogMessage = i18n("Please select an (OpenPGP or S/MIME) key to use."); } } QPushButton * Kleo::KeyRequester::dialogButton() { return mDialogButton; } QPushButton * Kleo::KeyRequester::eraseButton() { return mEraseButton; } static inline unsigned int foo( bool openpgp, bool smime, bool trusted, bool valid ) { unsigned int result = 0; if ( openpgp ) result |= Kleo::KeySelectionDialog::OpenPGPKeys; if ( smime ) result |= Kleo::KeySelectionDialog::SMIMEKeys; if ( trusted ) result |= Kleo::KeySelectionDialog::TrustedKeys; if ( valid ) result |= Kleo::KeySelectionDialog::ValidKeys; return result; } static inline unsigned int encryptionKeyUsage( bool openpgp, bool smime, bool trusted, bool valid ) { return foo( openpgp, smime, trusted, valid ) | Kleo::KeySelectionDialog::EncryptionKeys | Kleo::KeySelectionDialog::PublicKeys; } static inline unsigned int signingKeyUsage( bool openpgp, bool smime, bool trusted, bool valid ) { return foo( openpgp, smime, trusted, valid ) | Kleo::KeySelectionDialog::SigningKeys | Kleo::KeySelectionDialog::SecretKeys; } Kleo::EncryptionKeyRequester::EncryptionKeyRequester( bool multi, unsigned int proto, QWidget * parent, const char * name, bool onlyTrusted, bool onlyValid ) : KeyRequester( encryptionKeyUsage( proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid ), multi, parent, name ) { } Kleo::EncryptionKeyRequester::EncryptionKeyRequester( QWidget * parent, const char * name ) : KeyRequester( 0, false, parent, name ) { } Kleo::EncryptionKeyRequester::~EncryptionKeyRequester() {} void Kleo::EncryptionKeyRequester::setAllowedKeys( unsigned int proto, bool onlyTrusted, bool onlyValid ) { KeyRequester::setAllowedKeys( encryptionKeyUsage( proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid ) ); } Kleo::SigningKeyRequester::SigningKeyRequester( bool multi, unsigned int proto, QWidget * parent, const char * name, bool onlyTrusted, bool onlyValid ) : KeyRequester( signingKeyUsage( proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid ), multi, parent, name ) { } Kleo::SigningKeyRequester::SigningKeyRequester( QWidget * parent, const char * name ) : KeyRequester( 0, false, parent, name ) { } Kleo::SigningKeyRequester::~SigningKeyRequester() {} void Kleo::SigningKeyRequester::setAllowedKeys( unsigned int proto, bool onlyTrusted, bool onlyValid ) { KeyRequester::setAllowedKeys( signingKeyUsage( proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid ) ); } void Kleo::KeyRequester::virtual_hook( int, void* ) {} void Kleo::EncryptionKeyRequester::virtual_hook( int id, void * data ) { KeyRequester::virtual_hook( id, data ); } void Kleo::SigningKeyRequester::virtual_hook( int id, void * data ) { KeyRequester::virtual_hook( id, data ); } #include "keyrequester.moc" diff --git a/certmanager/lib/ui/keyrequester.h b/certmanager/lib/ui/keyrequester.h index 393ccc3846..3de9c508bf 100644 --- a/certmanager/lib/ui/keyrequester.h +++ b/certmanager/lib/ui/keyrequester.h @@ -1,227 +1,227 @@ /* -*- c++ -*- keyrequester.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. Based on kpgpui.h Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details This file is part of KPGP, the KDE PGP/GnuPG support library. KPGP 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. 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 + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef __KLEO_UI_KEYREQUESTER_H__ #define __KLEO_UI_KEYREQUESTER_H__ #include #include #include #include namespace Kleo { class KeyListView; class KeyListViewItem; } namespace GpgME { class Key; class KeyListResult; } class QStringList; class QString; class QPushButton; class QLabel; namespace Kleo { /// Base class for SigningKeyRequester and EncryptionKeyRequester class KDE_EXPORT KeyRequester : public QWidget { Q_OBJECT public: KeyRequester( unsigned int allowedKeys, bool multipleKeys=false, QWidget * parent=0, const char * name=0 ); // Constructor for Qt Designer KeyRequester( QWidget * parent=0, const char * name=0 ); ~KeyRequester(); const GpgME::Key & key() const; /** Preferred method to set a key for non-multi-KeyRequesters. Doesn't start a backend KeyListJob. */ void setKey( const GpgME::Key & key ); const std::vector & keys() const; /** Preferred method to set a key for multi-KeyRequesters. Doesn't start a backend KeyListJob. */ void setKeys( const std::vector & keys ); QString fingerprint() const; /** Set the key by fingerprint. Starts a background KeyListJob to retrive the complete GpgME::Key object */ void setFingerprint( const QString & fingerprint ); QStringList fingerprints() const; /** Set the keys by fingerprint. Starts a background KeyListJob to retrive the complete GpgME::Key objects */ void setFingerprints( const QStringList & fingerprints ); QPushButton * eraseButton(); QPushButton * dialogButton(); void setDialogCaption( const QString & caption ); void setDialogMessage( const QString & message ); bool isMultipleKeysEnabled() const; void setMultipleKeysEnabled( bool enable ); unsigned int allowedKeys() const; void setAllowedKeys( unsigned int allowed ); void setInitialQuery( const QString & s ) { mInitialQuery = s; } const QString & initialQuery() const { return mInitialQuery; } signals: void changed(); private: void init(); void startKeyListJob( const QStringList & fingerprints ); void updateKeys(); private slots: void slotNextKey( const GpgME::Key & key ); void slotKeyListResult( const GpgME::KeyListResult & result ); void slotDialogButtonClicked(); void slotEraseButtonClicked(); private: const CryptoBackend::Protocol * mOpenPGPBackend; const CryptoBackend::Protocol * mSMIMEBackend; QLabel * mLabel; QPushButton * mEraseButton; QPushButton * mDialogButton; QString mDialogCaption, mDialogMessage, mInitialQuery; bool mMulti; unsigned int mKeyUsage; int mJobs; std::vector mKeys; std::vector mTmpKeys; private: class Private; Private * d; protected: virtual void virtual_hook( int, void* ); }; class KDE_EXPORT EncryptionKeyRequester : public KeyRequester { Q_OBJECT public: enum { OpenPGP = 1, SMIME = 2, AllProtocols = OpenPGP|SMIME }; /** * Preferred constructor */ EncryptionKeyRequester( bool multipleKeys=false, unsigned int proto=AllProtocols, QWidget * parent=0, const char * name=0, bool onlyTrusted=true, bool onlyValid=true ); /** * Constructor for Qt designer */ EncryptionKeyRequester( QWidget * parent=0, const char * name=0 ); ~EncryptionKeyRequester(); void setAllowedKeys( unsigned int proto, bool onlyTrusted=true, bool onlyValid=true ); private: class Private; Private * d; protected: virtual void virtual_hook( int, void* ); }; class KDE_EXPORT SigningKeyRequester : public KeyRequester { Q_OBJECT public: enum { OpenPGP = 1, SMIME = 2, AllProtocols = OpenPGP|SMIME }; /** * Preferred constructor * @param multipleKeys whether multiple keys can be selected * * @param proto the allowed protocols, OpenPGP and/or SMIME * @param onlyTrusted only show trusted keys * @param onlyValid only show valid keys */ SigningKeyRequester( bool multipleKeys=false, unsigned int proto=AllProtocols, QWidget * parent=0, const char * name=0, bool onlyTrusted=true, bool onlyValid=true ); /** * Constructor for Qt designer */ SigningKeyRequester( QWidget * parent=0, const char * name=0 ); ~SigningKeyRequester(); /* * Those parameters affect the parameters given to the key selection dialog. * @param proto the allowed protocols, OpenPGP and/or SMIME * @param onlyTrusted only show trusted keys * @param onlyValid only show valid keys */ void setAllowedKeys( unsigned int proto, bool onlyTrusted=true, bool onlyValid=true ); private: class Private; Private * d; protected: virtual void virtual_hook( int, void* ); }; } #endif // __KLEO_UI_KEYREQUESTER_H__ diff --git a/certmanager/lib/ui/keyselectiondialog.cpp b/certmanager/lib/ui/keyselectiondialog.cpp index 170aa2a3d5..b544711bba 100644 --- a/certmanager/lib/ui/keyselectiondialog.cpp +++ b/certmanager/lib/ui/keyselectiondialog.cpp @@ -1,773 +1,779 @@ /* -*- c++ -*- keyselectiondialog.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Based on kpgpui.cpp Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "keyselectiondialog.h" #include "keylistview.h" #include "progressdialog.h" #include #include #include // gpgme++ #include #include // KDE #include #include #include #include #include #include #include #include // Qt #include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include static bool checkKeyUsage( const GpgME::Key & key, unsigned int keyUsage ) { if ( keyUsage & Kleo::KeySelectionDialog::ValidKeys ) { if ( key.isInvalid() ) kdDebug() << "key is invalid - ignoring" << endl; if ( key.isExpired() ) { kdDebug() << "key is expired" << endl; return false; } else if ( key.isRevoked() ) { kdDebug() << "key is revoked" << endl; return false; } else if ( key.isDisabled() ) { kdDebug() << "key is disabled" << endl; return false; } } if ( keyUsage & Kleo::KeySelectionDialog::EncryptionKeys && !key.canEncrypt() ) { kdDebug() << "key can't encrypt" << endl; return false; } if ( keyUsage & Kleo::KeySelectionDialog::SigningKeys && !key.canSign() ) { kdDebug() << "key can't sign" << endl; return false; } if ( keyUsage & Kleo::KeySelectionDialog::CertificationKeys && !key.canCertify() ) { kdDebug() << "key can't certify" << endl; return false; } if ( keyUsage & Kleo::KeySelectionDialog::AuthenticationKeys && !key.canAuthenticate() ) { kdDebug() << "key can't authenticate" << endl; return false; } if ( keyUsage & Kleo::KeySelectionDialog::SecretKeys && !( keyUsage & Kleo::KeySelectionDialog::PublicKeys ) && !key.isSecret() ) { kdDebug() << "key isn't secret" << endl; return false; } if ( keyUsage & Kleo::KeySelectionDialog::TrustedKeys && key.protocol() == GpgME::Context::OpenPGP && // only check this for secret keys for now. // Seems validity isn't checked for secret keylistings... !key.isSecret() ) { std::vector uids = key.userIDs(); for ( std::vector::const_iterator it = uids.begin() ; it != uids.end() ; ++it ) if ( !it->isRevoked() && it->validity() >= GpgME::UserID::Marginal ) return true; kdDebug() << "key has no UIDs with validity >= Marginal" << endl; return false; } // X.509 keys are always trusted, else they won't be the keybox. // PENDING(marc) check that this ^ is correct return true; } static bool checkKeyUsage( const std::vector & keys, unsigned int keyUsage ) { for ( std::vector::const_iterator it = keys.begin() ; it != keys.end() ; ++it ) if ( !checkKeyUsage( *it, keyUsage ) ) return false; return true; } static inline QString time_t2string( time_t t ) { QDateTime dt; dt.setTime_t( t ); return dt.toString(); } namespace { class ColumnStrategy : public Kleo::KeyListView::ColumnStrategy { public: ColumnStrategy( unsigned int keyUsage ); QString title( int col ) const; int width( int col, const QFontMetrics & fm ) const; QString text( const GpgME::Key & key, int col ) const; QString toolTip( const GpgME::Key & key, int col ) const; const QPixmap * pixmap( const GpgME::Key & key, int col ) const; private: const QPixmap mKeyGoodPix, mKeyBadPix, mKeyUnknownPix, mKeyValidPix; const unsigned int mKeyUsage; }; ColumnStrategy::ColumnStrategy( unsigned int keyUsage ) : Kleo::KeyListView::ColumnStrategy(), mKeyGoodPix( UserIcon( "key_ok" ) ), mKeyBadPix( UserIcon( "key_bad" ) ), mKeyUnknownPix( UserIcon( "key_unknown" ) ), mKeyValidPix( UserIcon( "key" ) ), mKeyUsage( keyUsage ) { kdWarning( keyUsage == 0, 5150 ) << "KeySelectionDialog: keyUsage == 0. You want to use AllKeys instead." << endl; } QString ColumnStrategy::title( int col ) const { switch ( col ) { case 0: return i18n("Key ID"); case 1: return i18n("User ID"); default: return QString::null; } } int ColumnStrategy::width( int col, const QFontMetrics & fm ) const { if ( col == 0 ) { static const char hexchars[] = "0123456789ABCDEF"; int maxWidth = 0; for ( unsigned int i = 0 ; i < 16 ; ++i ) maxWidth = kMax( fm.width( QChar( hexchars[i] ) ), maxWidth ); return 8 * maxWidth + 2 * mKeyGoodPix.width(); } return Kleo::KeyListView::ColumnStrategy::width( col, fm ); } QString ColumnStrategy::text( const GpgME::Key & key, int col ) const { switch ( col ) { case 0: { if ( key.shortKeyID() ) return QString::fromUtf8( key.shortKeyID() ); else return i18n(""); } break; case 1: { const char * uid = key.userID(0).id(); if ( key.protocol() == GpgME::Context::OpenPGP ) return uid && *uid ? QString::fromUtf8( uid ) : QString::null ; else // CMS return Kleo::DN( uid ).prettyDN(); } break; default: return QString::null; } } QString ColumnStrategy::toolTip( const GpgME::Key & key, int ) const { const char * uid = key.userID(0).id(); const char * fpr = key.primaryFingerprint(); const char * issuer = key.issuerName(); const GpgME::Subkey subkey = key.subkey(0); const QString expiry = subkey.neverExpires() ? i18n("never") : time_t2string( subkey.expirationTime() ) ; const QString creation = time_t2string( subkey.creationTime() ); if ( key.protocol() == GpgME::Context::OpenPGP ) return i18n( "OpenPGP key for %1\n" "Created: %2\n" "Expiry: %3\n" "Fingerprint: %4" ) .arg( uid ? QString::fromUtf8( uid ) : i18n("unknown"), creation, expiry, fpr ? QString::fromLatin1( fpr ) : i18n("unknown") ); else return i18n( "S/MIME key for %1\n" "Created: %2\n" "Expiry: %3\n" "Fingerprint: %4\n" "Issuer: %5" ) .arg( uid ? Kleo::DN( uid ).prettyDN() : i18n("unknown"), creation, expiry, fpr ? QString::fromLatin1( fpr ) : i18n("unknown") ) .arg( issuer ? Kleo::DN( issuer ).prettyDN() : i18n("unknown") ); } const QPixmap * ColumnStrategy::pixmap( const GpgME::Key & key, int col ) const { if ( col != 0 ) return 0; // this key did not undergo a validating keylisting yet: if ( !( key.keyListMode() & GpgME::Context::Validate ) ) return &mKeyUnknownPix; if ( !checkKeyUsage( key, mKeyUsage ) ) return &mKeyBadPix; if ( key.protocol() == GpgME::Context::CMS ) return &mKeyGoodPix; switch ( key.userID(0).validity() ) { default: case GpgME::UserID::Unknown: case GpgME::UserID::Undefined: return &mKeyUnknownPix; case GpgME::UserID::Never: return &mKeyValidPix; case GpgME::UserID::Marginal: case GpgME::UserID::Full: case GpgME::UserID::Ultimate: return &mKeyGoodPix; } } } static const int sCheckSelectionDelay = 250; Kleo::KeySelectionDialog::KeySelectionDialog( const QString & title, const QString & text, const std::vector & selectedKeys, unsigned int keyUsage, bool extendedSelection, bool rememberChoice, QWidget * parent, const char * name, bool modal ) : KDialogBase( parent, name, modal, title, Default|Ok|Cancel, Ok ), mOpenPGPBackend( 0 ), mSMIMEBackend( 0 ), mRememberCB( 0 ), mSelectedKeys( selectedKeys ), mKeyUsage( keyUsage ), mCurrentContextMenuItem( 0 ) { init( rememberChoice, extendedSelection, text, QString::null ); } Kleo::KeySelectionDialog::KeySelectionDialog( const QString & title, const QString & text, const QString & initialQuery, unsigned int keyUsage, bool extendedSelection, bool rememberChoice, QWidget * parent, const char * name, bool modal ) : KDialogBase( parent, name, modal, title, Default|Ok|Cancel, Ok ), mOpenPGPBackend( 0 ), mSMIMEBackend( 0 ), mRememberCB( 0 ), mKeyUsage( keyUsage ), mSearchText( initialQuery ), mCurrentContextMenuItem( 0 ) { init( rememberChoice, extendedSelection, text, initialQuery ); } void Kleo::KeySelectionDialog::init( bool rememberChoice, bool extendedSelection, const QString & text, const QString & initialQuery ) { if ( mKeyUsage & OpenPGPKeys ) mOpenPGPBackend = Kleo::CryptoBackendFactory::instance()->openpgp(); if ( mKeyUsage & SMIMEKeys ) mSMIMEBackend = Kleo::CryptoBackendFactory::instance()->smime(); QSize dialogSize( 580, 400 ); if ( kapp ) { KWin::setIcons( winId(), kapp->icon(), kapp->miniIcon() ); KConfigGroup dialogConfig( KGlobal::config(), "Key Selection Dialog" ); dialogSize = dialogConfig.readSizeEntry( "Dialog size", &dialogSize ); } resize( dialogSize ); mCheckSelectionTimer = new QTimer( this ); mStartSearchTimer = new QTimer( this ); QFrame *page = makeMainWidget(); QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() ); if ( !text.isEmpty() ) topLayout->addWidget( new QLabel( text, page ) ); QHBoxLayout * hlay = new QHBoxLayout( topLayout ); // inherits spacing QLineEdit * le = new QLineEdit( page ); le->setText( initialQuery ); + QToolButton *clearButton = new QToolButton( page ); + clearButton->setIconSet( KGlobal::iconLoader()->loadIconSet( + KApplication::reverseLayout() ? "clear_left":"locationbar_erase", KIcon::Small, 0 ) ); + hlay->addWidget( clearButton ); hlay->addWidget( new QLabel( le, i18n("&Search for:"), page ) ); hlay->addWidget( le, 1 ); le->setFocus(); + connect( clearButton, SIGNAL( clicked() ), le, SLOT( clear() ) ); connect( le, SIGNAL(textChanged(const QString&)), this, SLOT(slotSearch(const QString&)) ); connect( mStartSearchTimer, SIGNAL(timeout()), SLOT(slotFilter()) ); mKeyListView = new KeyListView( new ColumnStrategy( mKeyUsage ), 0, page, "mKeyListView" ); mKeyListView->setResizeMode( QListView::LastColumn ); mKeyListView->setRootIsDecorated( true ); mKeyListView->setShowSortIndicator( true ); mKeyListView->setSorting( 1, true ); // sort by User ID mKeyListView->setShowToolTips( true ); if ( extendedSelection ) mKeyListView->setSelectionMode( QListView::Extended ); topLayout->addWidget( mKeyListView, 10 ); if ( rememberChoice ) { mRememberCB = new QCheckBox( i18n("&Remember choice"), page ); topLayout->addWidget( mRememberCB ); QWhatsThis::add( mRememberCB, i18n("

If you check this box your choice will " "be stored and you will not be asked again." "

") ); } connect( mCheckSelectionTimer, SIGNAL(timeout()), SLOT(slotCheckSelection()) ); connectSignals(); connect( mKeyListView, SIGNAL(doubleClicked(Kleo::KeyListViewItem*,const QPoint&,int)), SLOT(slotTryOk()) ); connect( mKeyListView, SIGNAL(contextMenu(Kleo::KeyListViewItem*,const QPoint&)), SLOT(slotRMB(Kleo::KeyListViewItem*,const QPoint&)) ); setButtonText( KDialogBase::Default, i18n("&Reread Keys") ); connect( this, SIGNAL(defaultClicked()), this, SLOT(slotRereadKeys()) ); slotRereadKeys(); } Kleo::KeySelectionDialog::~KeySelectionDialog() { KConfigGroup dialogConfig( KGlobal::config(), "Key Selection Dialog" ); dialogConfig.writeEntry( "Dialog size", size() ); dialogConfig.sync(); } void Kleo::KeySelectionDialog::connectSignals() { if ( mKeyListView->isMultiSelection() ) connect( mKeyListView, SIGNAL(selectionChanged()), SLOT(slotSelectionChanged()) ); else connect( mKeyListView, SIGNAL(selectionChanged(Kleo::KeyListViewItem*)), SLOT(slotCheckSelection(Kleo::KeyListViewItem*)) ); } void Kleo::KeySelectionDialog::disconnectSignals() { if ( mKeyListView->isMultiSelection() ) disconnect( mKeyListView, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged()) ); else disconnect( mKeyListView, SIGNAL(selectionChanged(Kleo::KeyListViewItem*)), this, SLOT(slotCheckSelection(Kleo::KeyListViewItem*)) ); } const GpgME::Key & Kleo::KeySelectionDialog::selectedKey() const { if ( mKeyListView->isMultiSelection() || !mKeyListView->selectedItem() ) return GpgME::Key::null; return mKeyListView->selectedItem()->key(); } QString Kleo::KeySelectionDialog::fingerprint() const { return selectedKey().primaryFingerprint(); } QStringList Kleo::KeySelectionDialog::fingerprints() const { QStringList result; for ( std::vector::const_iterator it = mSelectedKeys.begin() ; it != mSelectedKeys.end() ; ++it ) if ( const char * fpr = it->primaryFingerprint() ) result.push_back( fpr ); return result; } QStringList Kleo::KeySelectionDialog::pgpKeyFingerprints() const { QStringList result; for ( std::vector::const_iterator it = mSelectedKeys.begin() ; it != mSelectedKeys.end() ; ++it ) if ( it->protocol() == GpgME::Context::OpenPGP ) if ( const char * fpr = it->primaryFingerprint() ) result.push_back( fpr ); return result; } QStringList Kleo::KeySelectionDialog::smimeFingerprints() const { QStringList result; for ( std::vector::const_iterator it = mSelectedKeys.begin() ; it != mSelectedKeys.end() ; ++it ) if ( it->protocol() == GpgME::Context::CMS ) if ( const char * fpr = it->primaryFingerprint() ) result.push_back( fpr ); return result; } void Kleo::KeySelectionDialog::slotRereadKeys() { mKeyListView->clear(); mListJobCount = 0; mTruncated = 0; mSavedOffsetY = mKeyListView->contentsY(); disconnectSignals(); - this->setEnabled( false ); + mKeyListView->setEnabled( false ); // FIXME: save current selection if ( mOpenPGPBackend ) startKeyListJobForBackend( mOpenPGPBackend, std::vector(), false /*non-validating*/ ); if ( mSMIMEBackend ) startKeyListJobForBackend( mSMIMEBackend, std::vector(), false /*non-validating*/ ); if ( mListJobCount == 0 ) { - this->setEnabled( true ); + mKeyListView->setEnabled( true ); KMessageBox::information( this, i18n("No backends found for listing keys. " "Check your installation."), i18n("Key Listing Failed") ); connectSignals(); } } #ifndef __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ #define __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ static void showKeyListError( QWidget * parent, const GpgME::Error & err ) { assert( err ); const QString msg = i18n( "

An error occurred while fetching " "the keys from the backend:

" "

%1

" ) .arg( QString::fromLocal8Bit( err.asString() ) ); KMessageBox::error( parent, msg, i18n( "Key Listing Failed" ) ); } #endif // __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ namespace { struct ExtractFingerprint { QString operator()( const GpgME::Key & key ) { return key.primaryFingerprint(); } }; } void Kleo::KeySelectionDialog::startKeyListJobForBackend( const CryptoBackend::Protocol * backend, const std::vector & keys, bool validate ) { assert( backend ); KeyListJob * job = backend->keyListJob( false, false, validate ); // local, w/o sigs, validation as givem if ( !job ) return; connect( job, SIGNAL(result(const GpgME::KeyListResult&)), SLOT(slotKeyListResult(const GpgME::KeyListResult&)) ); connect( job, SIGNAL(nextKey(const GpgME::Key&)), mKeyListView, validate ? SLOT(slotRefreshKey(const GpgME::Key&)) : SLOT(slotAddKey(const GpgME::Key&)) ); QStringList fprs; std::transform( keys.begin(), keys.end(), std::back_inserter( fprs ), ExtractFingerprint() ); const GpgME::Error err = job->start( fprs, mKeyUsage & SecretKeys && !( mKeyUsage & PublicKeys ) ); if ( err ) return showKeyListError( this, err ); // FIXME: create a MultiProgressDialog: (void)new ProgressDialog( job, validate ? i18n( "Checking selected keys..." ) : i18n( "Fetching keys..." ), this ); ++mListJobCount; } static void selectKeys( Kleo::KeyListView * klv, const std::vector & selectedKeys ) { klv->clearSelection(); if ( selectedKeys.empty() ) return; for ( std::vector::const_iterator it = selectedKeys.begin() ; it != selectedKeys.end() ; ++it ) if ( Kleo::KeyListViewItem * item = klv->itemByFingerprint( it->primaryFingerprint() ) ) item->setSelected( true ); } void Kleo::KeySelectionDialog::slotKeyListResult( const GpgME::KeyListResult & res ) { if ( res.error() ) showKeyListError( this, res.error() ); else if ( res.isTruncated() ) ++mTruncated; if ( --mListJobCount > 0 ) return; // not yet finished... if ( mTruncated > 0 ) KMessageBox::information( this, i18n("One backend returned truncated output.
" "Not all available keys are shown
", "%n backends returned truncated output.
" "Not all available keys are shown
", mTruncated), i18n("Key List Result") ); mKeyListView->flushKeys(); - this->setEnabled( true ); + mKeyListView->setEnabled( true ); mListJobCount = mTruncated = 0; mKeysToCheck.clear(); selectKeys( mKeyListView, mSelectedKeys ); slotFilter(); connectSignals(); slotSelectionChanged(); // restore the saved position of the contents mKeyListView->setContentsPos( 0, mSavedOffsetY ); mSavedOffsetY = 0; } void Kleo::KeySelectionDialog::slotSelectionChanged() { kdDebug(5150) << "KeySelectionDialog::slotSelectionChanged()" << endl; // (re)start the check selection timer. Checking the selection is delayed // because else drag-selection doesn't work very good (checking key trust // is slow). mCheckSelectionTimer->start( sCheckSelectionDelay ); } namespace { struct AlreadyChecked { bool operator()( const GpgME::Key & key ) const { return key.keyListMode() & GpgME::Context::Validate ; } }; } void Kleo::KeySelectionDialog::slotCheckSelection( KeyListViewItem * item ) { kdDebug(5150) << "KeySelectionDialog::slotCheckSelection()\n"; mCheckSelectionTimer->stop(); mSelectedKeys.clear(); if ( !mKeyListView->isMultiSelection() ) { if ( item ) mSelectedKeys.push_back( item->key() ); } for ( KeyListViewItem * it = mKeyListView->firstChild() ; it ; it = it->nextSibling() ) if ( it->isSelected() ) mSelectedKeys.push_back( it->key() ); mKeysToCheck.clear(); std::remove_copy_if( mSelectedKeys.begin(), mSelectedKeys.end(), std::back_inserter( mKeysToCheck ), AlreadyChecked() ); if ( mKeysToCheck.empty() ) { enableButtonOK( !mSelectedKeys.empty() && checkKeyUsage( mSelectedKeys, mKeyUsage ) ); return; } // performed all fast checks - now for validating key listing: startValidatingKeyListing(); } void Kleo::KeySelectionDialog::startValidatingKeyListing() { if ( mKeysToCheck.empty() ) return; mListJobCount = 0; mTruncated = 0; mSavedOffsetY = mKeyListView->contentsY(); disconnectSignals(); - this->setEnabled( false ); + mKeyListView->setEnabled( false ); std::vector smime, openpgp; for ( std::vector::const_iterator it = mKeysToCheck.begin() ; it != mKeysToCheck.end() ; ++it ) if ( it->protocol() == GpgME::Context::OpenPGP ) openpgp.push_back( *it ); else smime.push_back( *it ); if ( !openpgp.empty() ) { assert( mOpenPGPBackend ); startKeyListJobForBackend( mOpenPGPBackend, openpgp, true /*validate*/ ); } if ( !smime.empty() ) { assert( mSMIMEBackend ); startKeyListJobForBackend( mSMIMEBackend, smime, true /*validate*/ ); } assert( mListJobCount > 0 ); } bool Kleo::KeySelectionDialog::rememberSelection() const { return mRememberCB && mRememberCB->isChecked() ; } void Kleo::KeySelectionDialog::slotRMB( Kleo::KeyListViewItem * item, const QPoint & p ) { if ( !item ) return; mCurrentContextMenuItem = item; QPopupMenu menu; menu.insertItem( i18n( "Recheck Key" ), this, SLOT(slotRecheckKey()) ); menu.exec( p ); } void Kleo::KeySelectionDialog::slotRecheckKey() { if ( !mCurrentContextMenuItem || mCurrentContextMenuItem->key().isNull() ) return; mKeysToCheck.clear(); mKeysToCheck.push_back( mCurrentContextMenuItem->key() ); } void Kleo::KeySelectionDialog::slotTryOk() { if ( actionButton( Ok )->isEnabled() ) slotOk(); } void Kleo::KeySelectionDialog::slotOk() { if ( mCheckSelectionTimer->isActive() ) slotCheckSelection(); mStartSearchTimer->stop(); accept(); } void Kleo::KeySelectionDialog::slotCancel() { mCheckSelectionTimer->stop(); mStartSearchTimer->stop(); reject(); } void Kleo::KeySelectionDialog::slotSearch( const QString & text ) { mSearchText = text.stripWhiteSpace().upper(); slotSearch(); } void Kleo::KeySelectionDialog::slotSearch() { mStartSearchTimer->start( sCheckSelectionDelay, true /*single-shot*/ ); } void Kleo::KeySelectionDialog::slotFilter() { if ( mSearchText.isEmpty() ) { showAllItems(); return; } // OK, so we need to filter: QRegExp keyIdRegExp( "(?:0x)?[A-F0-9]{1,8}", false /*case-insens.*/ ); if ( keyIdRegExp.exactMatch( mSearchText ) ) { if ( mSearchText.startsWith( "0X" ) ) // search for keyID only: filterByKeyID( mSearchText.mid( 2 ) ); else // search for UID and keyID: filterByKeyIDOrUID( mSearchText ); } else { // search in UID: filterByUID( mSearchText ); } } void Kleo::KeySelectionDialog::filterByKeyID( const QString & keyID ) { assert( keyID.length() <= 8 ); assert( !keyID.isEmpty() ); // regexp in slotFilter should prevent these if ( keyID.isEmpty() ) showAllItems(); else for ( KeyListViewItem * item = mKeyListView->firstChild() ; item ; item = item->nextSibling() ) item->setVisible( item->text( 0 ).upper().startsWith( keyID ) ); } static bool anyUIDMatches( const Kleo::KeyListViewItem * item, QRegExp & rx ) { if ( !item ) return false; const std::vector uids = item->key().userIDs(); for ( std::vector::const_iterator it = uids.begin() ; it != uids.end() ; ++it ) if ( it->id() && rx.search( QString::fromUtf8( it->id() ) ) >= 0 ) return true; return false; } void Kleo::KeySelectionDialog::filterByKeyIDOrUID( const QString & str ) { assert( !str.isEmpty() ); // match beginnings of words: QRegExp rx( "\\b" + QRegExp::escape( str ), false ); for ( KeyListViewItem * item = mKeyListView->firstChild() ; item ; item = item->nextSibling() ) item->setVisible( item->text( 0 ).upper().startsWith( str ) || anyUIDMatches( item, rx ) ); } void Kleo::KeySelectionDialog::filterByUID( const QString & str ) { assert( !str.isEmpty() ); // match beginnings of words: QRegExp rx( "\\b" + QRegExp::escape( str ), false ); for ( KeyListViewItem * item = mKeyListView->firstChild() ; item ; item = item->nextSibling() ) item->setVisible( anyUIDMatches( item, rx ) ); } void Kleo::KeySelectionDialog::showAllItems() { for ( KeyListViewItem * item = mKeyListView->firstChild() ; item ; item = item->nextSibling() ) item->setVisible( true ); } #include "keyselectiondialog.moc" diff --git a/certmanager/lib/ui/keyselectiondialog.h b/certmanager/lib/ui/keyselectiondialog.h index f44bd53f95..0f7607ebc9 100644 --- a/certmanager/lib/ui/keyselectiondialog.h +++ b/certmanager/lib/ui/keyselectiondialog.h @@ -1,168 +1,168 @@ /* -*- c++ -*- keyselectiondialog.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Based on kpgpui.h Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_UI_KEYSELECTIONDIALOG_H__ #define __KLEO_UI_KEYSELECTIONDIALOG_H__ #include #include #include #include #include class QCheckBox; class QPixmap; class QTimer; class QListViewItem; class QRegExp; class QPoint; namespace Kleo { class KeyListView; class KeyListViewItem; } namespace GpgME { class KeyListResult; } namespace Kleo { class KDE_EXPORT KeySelectionDialog : public KDialogBase { Q_OBJECT public: enum KeyUsage { PublicKeys = 1, SecretKeys = 2, EncryptionKeys = 4, SigningKeys = 8, ValidKeys = 16, TrustedKeys = 32, CertificationKeys = 64, AuthenticationKeys = 128, OpenPGPKeys = 256, SMIMEKeys = 512, AllKeys = PublicKeys | SecretKeys | OpenPGPKeys | SMIMEKeys, ValidTrustedEncryptionKeys = AllKeys | EncryptionKeys | ValidKeys | TrustedKeys }; KeySelectionDialog( const QString & title, const QString & text, const std::vector & selectedKeys=std::vector(), unsigned int keyUsage=AllKeys, bool extendedSelection=false, bool rememberChoice=false, QWidget * parent=0, const char * name=0, bool modal=true ); KeySelectionDialog( const QString & title, const QString & text, const QString & initialPattern, unsigned int keyUsage=AllKeys, bool extendedSelection=false, bool rememberChoice=false, QWidget * parent=0, const char * name=0, bool modal=true ); ~KeySelectionDialog(); /** Returns the key ID of the selected key in single selection mode. Otherwise it returns a null key. */ const GpgME::Key & selectedKey() const; QString fingerprint() const; /** Returns a list of selected key IDs. */ const std::vector & selectedKeys() const { return mSelectedKeys; } /// Return all the selected fingerprints QStringList fingerprints() const; /// Return the selected openpgp fingerprints QStringList pgpKeyFingerprints() const; /// Return the selected smime fingerprints QStringList smimeFingerprints() const; bool rememberSelection() const; private slots: void slotRereadKeys(); void slotKeyListResult( const GpgME::KeyListResult & ); void slotSelectionChanged(); void slotCheckSelection() { slotCheckSelection( 0 ); } void slotCheckSelection( Kleo::KeyListViewItem * ); void slotRMB( Kleo::KeyListViewItem *, const QPoint & ); void slotRecheckKey(); void slotTryOk(); void slotOk(); void slotCancel(); void slotSearch( const QString & text ); void slotSearch(); void slotFilter(); private: void filterByKeyID( const QString & keyID ); void filterByKeyIDOrUID( const QString & keyID ); void filterByUID( const QString & uid ); void showAllItems(); bool anyChildMatches( const Kleo::KeyListViewItem * item, QRegExp & rx ) const; void connectSignals(); void disconnectSignals(); void startKeyListJobForBackend( const Kleo::CryptoBackend::Protocol *, const std::vector &, bool ); void startValidatingKeyListing(); void init( bool, bool, const QString &, const QString & ); private: Kleo::KeyListView * mKeyListView; const Kleo::CryptoBackend::Protocol * mOpenPGPBackend; const Kleo::CryptoBackend::Protocol * mSMIMEBackend; QCheckBox * mRememberCB; std::vector mSelectedKeys, mKeysToCheck; unsigned int mKeyUsage; QTimer * mCheckSelectionTimer; QTimer * mStartSearchTimer; // cross-eventloop temporaries: QString mSearchText; Kleo::KeyListViewItem * mCurrentContextMenuItem; int mTruncated, mListJobCount, mSavedOffsetY; }; } #endif // __KLEO_UI_KEYSELECTIONDIALOG_H__ diff --git a/certmanager/lib/ui/passphrasedialog.cpp b/certmanager/lib/ui/passphrasedialog.cpp index 1312b778d3..5915387f5d 100644 --- a/certmanager/lib/ui/passphrasedialog.cpp +++ b/certmanager/lib/ui/passphrasedialog.cpp @@ -1,123 +1,123 @@ /* -*- c++ -*- passphrasedialog.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. Based on kpgpui.cpp Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details This file is part of KPGP, the KDE PGP/GnuPG support library. KPGP 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. 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 + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef HAVE_CONFIG_H #include #endif #include "passphrasedialog.h" #include #include #include #include #include #include struct Kleo::PassphraseDialog::Private { KPasswordEdit * lineedit; }; Kleo::PassphraseDialog::PassphraseDialog( const QString & msg, const QString & caption, QWidget * parent, const char * name, bool modal ) : KDialogBase( parent, name, modal, caption, Ok|Cancel, Ok ), d( 0 ) { d = new Private(); QWidget * w = new QWidget( this ); setMainWidget( w ); QHBoxLayout * hlay = new QHBoxLayout( w, 0, spacingHint() ); QLabel * label = new QLabel( w ); label->setPixmap( DesktopIcon( "pgp-keys", KIcon::SizeMedium ) ); hlay->addWidget( label, 0, AlignTop ); QVBoxLayout * vlay = new QVBoxLayout( hlay ); // inherits spacing vlay->addWidget( new QLabel( msg.isEmpty() ? i18n("Please enter your passphrase:") : msg, w ) ); d->lineedit = new KPasswordEdit( KPasswordEdit::OneStar, w, "d->lineedit" ); d->lineedit->setMinimumWidth( fontMetrics().width("*") * 20 ); d->lineedit->setFocus(); vlay->addWidget( d->lineedit ); connect( d->lineedit, SIGNAL(returnPressed()), SLOT(slotOk()) ); disableResize(); } Kleo::PassphraseDialog::~PassphraseDialog() { delete d; d = 0; } const char * Kleo::PassphraseDialog::passphrase() const { return d->lineedit->password(); } void Kleo::PassphraseDialog::slotOk() { const char * pass = passphrase(); emit finished( pass ? pass : "" ); KDialogBase::slotOk(); } void Kleo::PassphraseDialog::slotCancel() { emit canceled(); KDialogBase::slotCancel(); } void Kleo::PassphraseDialog::virtual_hook( int id, void * data ) { return KDialogBase::virtual_hook( id, data ); } #include "passphrasedialog.moc" diff --git a/certmanager/lib/ui/passphrasedialog.h b/certmanager/lib/ui/passphrasedialog.h index c36e3d0301..12a434e13a 100644 --- a/certmanager/lib/ui/passphrasedialog.h +++ b/certmanager/lib/ui/passphrasedialog.h @@ -1,91 +1,91 @@ /* -*- c++ -*- passphrasedialog.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. Based on kpgpui.h Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details This file is part of KPGP, the KDE PGP/GnuPG support library. KPGP 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. 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 + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef __KLEO_UI_PASSPHRASEDIALOG_H__ #define __KLEO_UI_PASSPHRASEDIALOG_H__ #include namespace Kleo { class PassphraseDialog : public KDialogBase { Q_OBJECT public: PassphraseDialog( const QString & description, const QString & caption=QString::null, QWidget * parent=0, const char * name=0, bool modal=true ); ~PassphraseDialog(); const char * passphrase() const; signals: /** emitted when the user clicks Ok. \a pass is never NULL. \c pass only valid inside slots connected to this signal. */ void finished( const char * pass ); /** emitted when the user clicks Cancel. */ void canceled(); protected slots: /*! \reimp */ void slotOk(); /*! \reimp */ void slotCancel(); private: class Private; Private * d; protected: /*! \reimp */ void virtual_hook( int, void* ); }; } // namespace Kleo #endif // __KLEO_UI_PASSPHRASEDIALOG_H__ diff --git a/certmanager/lib/ui/progressbar.cpp b/certmanager/lib/ui/progressbar.cpp index 70c04bc90d..96f51fa8a1 100644 --- a/certmanager/lib/ui/progressbar.cpp +++ b/certmanager/lib/ui/progressbar.cpp @@ -1,111 +1,111 @@ /* progressbar.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "config.h" #include "progressbar.h" #include #include static const int busyTimerTickInterval = 100; static const int busyTimerTickIncrement = 5; Kleo::ProgressBar::ProgressBar( QWidget * parent, const char * name, WFlags f ) : QProgressBar( 0, parent, name, f ), mRealProgress( -1 ) { mBusyTimer = new QTimer( this ); connect( mBusyTimer, SIGNAL(timeout()), SLOT(slotBusyTimerTick()) ); fixup( true ); } void Kleo::ProgressBar::slotProgress( const QString &, int cur, int tot ) { setProgress( cur, tot ); } void Kleo::ProgressBar::slotProgress( const QString &, int, int cur, int tot ) { setProgress( cur, tot ); } void Kleo::ProgressBar::setTotalSteps( int total ) { kdDebug() << "Kleo::ProgressBar::setTotalSteps( " << total << " )" << endl; if ( total == totalSteps() ) return; QProgressBar::setTotalSteps( 0 ); fixup( false ); } void Kleo::ProgressBar::setProgress( int p ) { kdDebug() << "Kleo::ProgressBar::setProgress( " << p << " )" << endl; mRealProgress = p; fixup( true ); } void Kleo::ProgressBar::reset() { mRealProgress = -1; fixup( true ); } void Kleo::ProgressBar::slotBusyTimerTick() { fixup( false ); if ( mBusyTimer->isActive() ) QProgressBar::setProgress( QProgressBar::progress() + busyTimerTickIncrement ); } void Kleo::ProgressBar::fixup( bool newValue ) { const int cur = QProgressBar::progress(); const int tot = QProgressBar::totalSteps(); kdDebug() << "Kleo::ProgressBar::startStopBusyTimer() cur = " << cur << "; tot = " << tot << "; real = " << mRealProgress << endl; if ( ( newValue && mRealProgress < 0 ) || ( !newValue && cur < 0 ) ) { kdDebug() << "(new value) switch to reset" << endl; mBusyTimer->stop(); if ( newValue ) QProgressBar::reset(); mRealProgress = -1; } else if ( tot == 0 ) { kdDebug() << "(new value) switch or stay in busy" << endl; if ( !mBusyTimer->isActive() ) { mBusyTimer->start( busyTimerTickInterval ); if ( newValue ) QProgressBar::setProgress( mRealProgress ); } } else { kdDebug() << "(new value) normal progress" << endl; mBusyTimer->stop(); if ( QProgressBar::progress() != mRealProgress ) QProgressBar::setProgress( mRealProgress ); } } #include "progressbar.moc" diff --git a/certmanager/lib/ui/progressbar.h b/certmanager/lib/ui/progressbar.h index 05f80eac8e..41d96796d5 100644 --- a/certmanager/lib/ui/progressbar.h +++ b/certmanager/lib/ui/progressbar.h @@ -1,74 +1,74 @@ /* progressbar.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_PROGRESSBAR_H__ #define __KLEO_PROGRESSBAR_H__ #include #include class QTimer; namespace Kleo { /** @short A QProgressBar with self-powered busy indicator */ class KDE_EXPORT ProgressBar : public QProgressBar { Q_OBJECT public: ProgressBar( QWidget * parent=0, const char * name=0, WFlags f=0 ); public slots: void slotProgress( const QString & message, int type, int current, int total ); void slotProgress( const QString & message, int current, int total ); /*! reimplementation to support self-powered busy indicator */ void setProgress( int progress ); /*! reimplementation to support self-powered busy indicator */ void setTotalSteps( int total ); /*! reimplementation to support self-powered busy indicator */ void reset(); /*! reimplementation to preserve visibility */ void setProgress( int cur, int tot ) { QProgressBar::setProgress( cur, tot ); } private slots: void slotBusyTimerTick(); private: void fixup( bool ); private: QTimer * mBusyTimer; int mRealProgress; }; } #endif // __KLEO_PROGRESSBAR_H__ diff --git a/certmanager/lib/ui/progressdialog.cpp b/certmanager/lib/ui/progressdialog.cpp index 2ba0d2ac3d..bb66aca173 100644 --- a/certmanager/lib/ui/progressdialog.cpp +++ b/certmanager/lib/ui/progressdialog.cpp @@ -1,98 +1,98 @@ /* progressdialog.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "progressdialog.h" #include "progressbar.h" #include #include #include #include #include Kleo::ProgressDialog::ProgressDialog( Job * job, const QString & baseText, QWidget * creator, const char * name, WFlags f ) : QProgressDialog( creator, name, false, f ), mBaseText( baseText ) { assert( job ); setBar( new ProgressBar( this, "replacement progressbar in Kleo::ProgressDialog" ) ); setMinimumDuration( 2000 /*ms*/ ); setAutoReset( false ); setAutoClose( false ); setLabelText( baseText ); setProgress( 0, 0 ); // activate busy indicator connect( job, SIGNAL(progress(const QString&,int,int)), SLOT(slotProgress(const QString&,int,int)) ); connect( job, SIGNAL(done()), SLOT(slotDone()) ); connect( this, SIGNAL(canceled()), job, SLOT(slotCancel()) ); QTimer::singleShot( minimumDuration(), this, SLOT(forceShow()) ); } Kleo::ProgressDialog::~ProgressDialog() { } void Kleo::ProgressDialog::setMinimumDuration( int ms ) { if ( 0 < ms && ms < minimumDuration() ) QTimer::singleShot( ms, this, SLOT(forceShow()) ); QProgressDialog::setMinimumDuration( ms ); } void Kleo::ProgressDialog::slotProgress( const QString & what, int current, int total ) { kdDebug(5150) << "Kleo::ProgressDialog::slotProgress( \"" << what << "\", " << current << ", " << total << " )" << endl; if ( mBaseText.isEmpty() ) setLabelText( what ); else if ( what.isEmpty() ) setLabelText( mBaseText ); else setLabelText( i18n( "%1: %2" ).arg( mBaseText, what ) ); setProgress( current, total ); } void Kleo::ProgressDialog::slotDone() { kdDebug(5150) << "Kleo::ProgressDialog::slotDone()" << endl; hide(); deleteLater(); } #include "progressdialog.moc" diff --git a/certmanager/lib/ui/progressdialog.h b/certmanager/lib/ui/progressdialog.h index 99078f7639..0b419aabba 100644 --- a/certmanager/lib/ui/progressdialog.h +++ b/certmanager/lib/ui/progressdialog.h @@ -1,66 +1,66 @@ /* progressdialog.h This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifndef __KLEO_PROGRESSDIALOG_H__ #define __KLEO_PROGRESSDIALOG_H__ #include #include #include namespace Kleo { class Job; /** @short A progress dialog for Kleo::Jobs */ class KDE_EXPORT ProgressDialog : public QProgressDialog { Q_OBJECT public: ProgressDialog( Job * job, const QString & baseText, QWidget * creator=0, const char * name=0, WFlags f=0 ); ~ProgressDialog(); public slots: /*! reimplementation */ void setMinimumDuration( int ms ); private slots: void slotProgress( const QString & what, int current, int total ); void slotDone(); private: QString mBaseText; }; } #endif // __KLEO_PROGRESSDIALOG_H__ diff --git a/certmanager/main.cpp b/certmanager/main.cpp index f734753169..37545502d1 100644 --- a/certmanager/main.cpp +++ b/certmanager/main.cpp @@ -1,84 +1,84 @@ /* main.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include #endif #include "aboutdata.h" #include "certmanager.h" #include #include #include #include #include #include #include int main( int argc, char** argv ) { AboutData aboutData; KCmdLineArgs::init(argc, argv, &aboutData); static const KCmdLineOptions options[] = { { "external" , I18N_NOOP("Search for external certificates initially"), 0 }, { "query " , I18N_NOOP("Initial query string"), 0 }, { "import-certificate ", I18N_NOOP("Name of certificate file to import"), 0 }, KCmdLineLastOption// End of options. }; KCmdLineArgs::addCmdLineOptions( options ); KApplication app; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); KGlobal::locale()->insertCatalogue( "libkleopatra" ); KGlobal::iconLoader()->addAppDir( "libkleopatra" ); if( !Kleo::CryptoBackendFactory::instance()->smime() ) { KMessageBox::error(0, i18n( "The crypto plugin could not be initialized.
" "Certificate Manager will terminate now.
") ); return -2; } CertManager* manager = new CertManager( args->isSet("external"), QString::fromLocal8Bit(args->getOption("query")), QString::fromLocal8Bit(args->getOption("import-certificate")) ); args->clear(); manager->show(); return app.exec(); } diff --git a/certmanager/storedtransferjob.cpp b/certmanager/storedtransferjob.cpp index d39ce123c3..589acd702b 100644 --- a/certmanager/storedtransferjob.cpp +++ b/certmanager/storedtransferjob.cpp @@ -1,98 +1,98 @@ /* Copyright (C) 2004 David Faure This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. */ #include "storedtransferjob.h" using namespace KIOext; #define KIO_ARGS QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream StoredTransferJob::StoredTransferJob(const KURL& url, int command, const QByteArray &packedArgs, const QByteArray &_staticData, bool showProgressInfo) : KIO::TransferJob( url, command, packedArgs, _staticData, showProgressInfo ), m_uploadOffset( 0 ) { connect( this, SIGNAL( data( KIO::Job *, const QByteArray & ) ), SLOT( slotData( KIO::Job *, const QByteArray & ) ) ); connect( this, SIGNAL( dataReq( KIO::Job *, QByteArray & ) ), SLOT( slotDataReq( KIO::Job *, QByteArray & ) ) ); } void StoredTransferJob::setData( const QByteArray& arr ) { Q_ASSERT( m_data.isNull() ); // check that we're only called once Q_ASSERT( m_uploadOffset == 0 ); // no upload started yet m_data = arr; } void StoredTransferJob::slotData( KIO::Job *, const QByteArray &data ) { // check for end-of-data marker: if ( data.size() == 0 ) return; unsigned int oldSize = m_data.size(); m_data.resize( oldSize + data.size(), QGArray::SpeedOptim ); memcpy( m_data.data() + oldSize, data.data(), data.size() ); } void StoredTransferJob::slotDataReq( KIO::Job *, QByteArray &data ) { // Inspired from kmail's KMKernel::byteArrayToRemoteFile // send the data in 64 KB chunks const int MAX_CHUNK_SIZE = 64*1024; int remainingBytes = m_data.size() - m_uploadOffset; if( remainingBytes > MAX_CHUNK_SIZE ) { // send MAX_CHUNK_SIZE bytes to the receiver (deep copy) data.duplicate( m_data.data() + m_uploadOffset, MAX_CHUNK_SIZE ); m_uploadOffset += MAX_CHUNK_SIZE; //kdDebug() << "Sending " << MAX_CHUNK_SIZE << " bytes (" // << remainingBytes - MAX_CHUNK_SIZE << " bytes remain)\n"; } else { // send the remaining bytes to the receiver (deep copy) data.duplicate( m_data.data() + m_uploadOffset, remainingBytes ); m_data = QByteArray(); m_uploadOffset = 0; //kdDebug() << "Sending " << remainingBytes << " bytes\n"; } } //// StoredTransferJob *KIOext::storedGet( const KURL& url, bool reload, bool showProgressInfo ) { // Send decoded path and encoded query KIO_ARGS << url; StoredTransferJob * job = new StoredTransferJob( url, KIO::CMD_GET, packedArgs, QByteArray(), showProgressInfo ); if (reload) job->addMetaData("cache", "reload"); return job; } StoredTransferJob *KIOext::put( const QByteArray& arr, const KURL& url, int permissions, bool overwrite, bool resume, bool showProgressInfo ) { KIO_ARGS << url << Q_INT8( overwrite ? 1 : 0 ) << Q_INT8( resume ? 1 : 0 ) << permissions; StoredTransferJob * job = new StoredTransferJob( url, KIO::CMD_PUT, packedArgs, QByteArray(), showProgressInfo ); job->setData( arr ); return job; } #include "storedtransferjob.moc" diff --git a/certmanager/storedtransferjob.h b/certmanager/storedtransferjob.h index db07c9b996..85b591c6b8 100644 --- a/certmanager/storedtransferjob.h +++ b/certmanager/storedtransferjob.h @@ -1,113 +1,113 @@ /* Copyright (C) 2004 David Faure This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. */ #ifndef STOREDTRANSFERJOB_H #define STOREDTRANSFERJOB_H #include // To be moved to KIO? namespace KIOext { /** * StoredTransferJob is a TransferJob (for downloading or uploading data) that * also stores a QByteArray with the data, making it simpler to use than the * standard TransferJob. * * For KIO::get it puts the data into the member QByteArray, so the user * of this class can get hold of the whole data at once by calling data() * when the result signal is emitted. * You should only use StoredTransferJob to download data if you cannot * process the data by chunks while it's being downloaded, since storing * everything in a QByteArray can potentially require a lot of memory. * * For KIO::put the user of this class simply provides the bytearray from * the start, and the job takes care of uploading it. * You should only use StoredTransferJob to upload data if you cannot * provide the in chunks while it's being uploaded, since storing * everything in a QByteArray can potentially require a lot of memory. * */ class StoredTransferJob : public KIO::TransferJob { Q_OBJECT public: /** * Do not create a StoredTransferJob. Use storedGet() or storedPut() * instead. * @param url the url to get or put * @param command the command to issue * @param packedArgs the arguments * @param _staticData additional data to transmit (e.g. in a HTTP Post) * @param showProgressInfo true to show progress information to the user */ StoredTransferJob(const KURL& url, int command, const QByteArray &packedArgs, const QByteArray &_staticData, bool showProgressInfo); /** * Set data to be uploaded. This is for put jobs. * Automatically called by KIOext::put(const QByteArray &, ...), do not call this yourself. */ void setData( const QByteArray& arr ); /** * Get hold of the downloaded data. This is for get jobs. * You're supposed to call this only from the slot connected to the result() signal. */ QByteArray data() const { return m_data; } private slots: void slotData( KIO::Job *job, const QByteArray &data ); void slotDataReq( KIO::Job *job, QByteArray &data ); private: QByteArray m_data; int m_uploadOffset; }; /** * Get (a.k.a. read), into a single QByteArray. * @see StoredTransferJob * * @param url the URL of the file * @param reload true to reload the file, false if it can be taken from the cache * @param showProgressInfo true to show progress information * @return the job handling the operation. */ StoredTransferJob *storedGet( const KURL& url, bool reload=false, bool showProgressInfo = true ); /** * Put (a.k.a. write) data from a single QByteArray. * @see StoredTransferJob * * @param url Where to write data. * @param permissions May be -1. In this case no special permission mode is set. * @param overwrite If true, any existing file will be overwritten. * @param resume true to resume, false otherwise * @param showProgressInfo true to show progress information * @return the job handling the operation. * @see multi_get() */ StoredTransferJob *put( const QByteArray& arr, const KURL& url, int permissions, bool overwrite, bool resume, bool showProgressInfo = true ); } // namespace #endif diff --git a/console/konsolekalendar/COPYING b/console/konsolekalendar/COPYING deleted file mode 100644 index 54754ab4ba..0000000000 --- a/console/konsolekalendar/COPYING +++ /dev/null @@ -1,341 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) 19yy - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) 19yy name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/console/konsolekalendar/Makefile.am b/console/konsolekalendar/Makefile.am deleted file mode 100644 index fdb9ae9139..0000000000 --- a/console/konsolekalendar/Makefile.am +++ /dev/null @@ -1,24 +0,0 @@ -SUBDIRS = pixmaps - -INCLUDES= -I$(top_srcdir)/libkcal \ - -I$(top_srcdir)/libemailfunctions \ - -I$(top_srcdir) $(all_includes) - -METASOURCES = AUTO - -bin_PROGRAMS = konsolekalendar - -konsolekalendar_SOURCES = konsolekalendarepoch.cpp konsolekalendardelete.cpp \ - konsolekalendarchange.cpp konsolekalendarvariables.cpp \ - konsolekalendaradd.cpp konsolekalendarexports.cpp konsolekalendar.cpp \ - main.cpp -konsolekalendar_LDADD = $(top_builddir)/libkcal/libkcal.la $(top_builddir)/libkdepim/libkdepim.la -konsolekalendar_LDFLAGS = $(all_libraries) $(KDE_RPATH) - -appsdir = $(kde_appsdir)/Utilities -xdg_apps_DATA = konsolekalendar.desktop - -messages: rc.cpp - $(XGETTEXT) *.cpp -o $(podir)/konsolekalendar.pot - -include $(top_srcdir)/admin/Doxyfile.am diff --git a/console/konsolekalendar/konsolekalendar.cpp b/console/konsolekalendar/konsolekalendar.cpp deleted file mode 100644 index 4e011a1420..0000000000 --- a/console/konsolekalendar/konsolekalendar.cpp +++ /dev/null @@ -1,463 +0,0 @@ -/******************************************************************************* - * konsolekalendar.cpp * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ -/** - * @file konsolekalendar.cpp - * Provides the KonsoleKalendar class definition. - * @author Tuukka Pasanen - * @author Allen Winter - */ -#include -#include -#include - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "konsolekalendar.h" -#include "konsolekalendaradd.h" -#include "konsolekalendarchange.h" -#include "konsolekalendardelete.h" -#include "konsolekalendarexports.h" - -using namespace KCal; -using namespace std; - -KonsoleKalendar::KonsoleKalendar( KonsoleKalendarVariables *variables ) -{ - m_variables = variables; - // m_Calendar = new ResourceCalendar; -} - -KonsoleKalendar::~KonsoleKalendar() -{ -} - -bool KonsoleKalendar::importCalendar() -{ - KonsoleKalendarAdd add( m_variables ); - - kdDebug() << "konsolecalendar.cpp::importCalendar() | importing now!" - << endl; - return( add.addImportedCalendar() ); -} - -bool KonsoleKalendar::createCalendar() -{ - bool status = false; - CalendarLocal newCalendar( QString::fromLatin1("UTC") ); - - if ( m_variables->isDryRun() ) { - cout << i18n( "Create Calendar : %1" ). - arg( m_variables->getCalendarFile() ).local8Bit() - << endl; - } else { - kdDebug() << "konsolekalendar.cpp::createCalendar() | " - << "Creating calendar file: " - << m_variables->getCalendarFile().local8Bit() - << endl; - - if ( m_variables->isVerbose() ) { - cout << i18n( "Create Calendar : %1" ). - arg( m_variables->getCalendarFile() ).local8Bit() - << endl; - } - - if ( newCalendar.save( m_variables->getCalendarFile() ) ) { - newCalendar.close(); - status = true; - } - } - return status; -} - -bool KonsoleKalendar::showInstance() -{ - bool status = true; - QFile f; - QString title; - Event::List *eventList; - Event *event; - - if ( m_variables->isDryRun() ) { - cout << i18n( "View Events :" ).local8Bit() - << endl; - printSpecs(); - } else { - - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "open export file" - << endl; - - if ( m_variables->isExportFile() ) { - f.setName( m_variables->getExportFile() ); - if ( !f.open( IO_WriteOnly ) ) { - status = false; - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "unable to open export file " - << m_variables->getExportFile() - << endl; - } - } else { - f.open( IO_WriteOnly, stdout ); - } - - if ( status ) { - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "opened successful" - << endl; - - if ( m_variables->isVerbose() ) { - cout << i18n( "View Event :" ).local8Bit() - << endl; - printSpecs(); - } - - QTextStream ts( &f ); - - if ( m_variables->getExportType() != ExportTypeHTML && - m_variables->getExportType() != ExportTypeMonthHTML ) { - - if ( m_variables->getAll() ) { - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "view all events sorted list" - << endl; - - Event::List sortedList = - m_variables->getCalendar()->events( EventSortStartDate ); - - QDate dt, firstdate, lastdate; - firstdate = sortedList.first()->dtStart().date(); - lastdate = sortedList.last()->dtStart().date(); - for ( dt = firstdate; - dt <= lastdate && status != false; - dt = dt.addDays(1) ) { - Event::List events = - m_variables->getCalendar()->events( dt, - EventSortStartDate, - SortDirectionAscending ); - status = printEventList( &ts, &events, dt ); - } - - } else if ( m_variables->isUID() ) { - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "view events by uid list" - << endl; - //TODO: support a list of UIDs - event = m_variables->getCalendar()->event( m_variables->getUID() ); - //If this UID represents a recurring Event, - //only the first day of the Event will be printed - status = printEvent ( &ts, event, event->dtStart().date() ); - - } else if ( m_variables->isNext() ) { - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "Show next activity in calendar" - << endl; - - QDateTime datetime = m_variables->getStartDateTime(); - datetime = datetime.addDays( 720 ); - - QDate dt; - for ( dt = m_variables->getStartDateTime().date(); - dt <= datetime.date() && status != false; - dt = dt.addDays(1) ) { - Event::List events = - m_variables->getCalendar()->events( dt, - EventSortStartDate, - SortDirectionAscending ); - status = printEventList( &ts, &events, dt ); - - // when we get next event we exit.. - if ( events.count() ) { - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "Next event" - << endl; - return true; - } - } - } else { - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "view raw events within date range list" - << endl; - - QDate dt; - for ( dt = m_variables->getStartDateTime().date(); - dt <= m_variables->getEndDateTime().date() && status != false; - dt = dt.addDays(1) ) { - Event::List events = - m_variables->getCalendar()->events( dt, - EventSortStartDate, - SortDirectionAscending ); - status = printEventList( &ts, &events, dt ); - } - } - } else { - QDate firstdate, lastdate; - if ( m_variables->getAll() ) { - // TODO: this is broken since the date on last() may not be last date - // (this is the case for me) - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "HTML view all events sorted list" - << endl; - eventList = - new Event::List ( m_variables->getCalendar()->rawEvents() ); - firstdate = eventList->first()->dtStart().date(); - lastdate = eventList->last()->dtStart().date(); - delete eventList; - } else if ( m_variables->isUID() ) { - // TODO - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "HTML view events by uid list" << endl; - cout << i18n("Sorry, export to HTML by UID is not supported yet") - .local8Bit() << endl; - return( false ); - } else { - kdDebug() << "konsolekalendar.cpp::showInstance() | " - << "HTML view raw events within date range list" - << endl; - firstdate = m_variables->getStartDateTime().date(); - lastdate = m_variables->getEndDateTime().date(); - } - - HTMLExportSettings htmlSettings( "Konsolekalendar" ); - - //TODO: get progname and url from the values set in main - htmlSettings.setCreditName( "KonsoleKalendar" ); - htmlSettings.setCreditURL( "http://pim.kde.org/components/konsolekalendar.php" ); - - htmlSettings.setExcludePrivate( true ); - htmlSettings.setExcludeConfidential( true ); - - htmlSettings.setEventView( false ); - htmlSettings.setMonthView( false ); - if ( m_variables->getExportType() == ExportTypeMonthHTML ) { - title = i18n( "Events:" ); - htmlSettings.setMonthView( true ); - } else { - if ( firstdate == lastdate ) { - title = i18n( "Events: %1" ) - .arg( firstdate.toString( Qt::TextDate ) ); - } else { - title = i18n( "Events: %1 - %2" ) - .arg( firstdate.toString( Qt::TextDate ) ) - .arg( lastdate.toString( Qt::TextDate ) ); - } - htmlSettings.setEventView( true ); - } - htmlSettings.setEventTitle( title ); - htmlSettings.setEventAttendees( true ); -// Not supporting Todos yet -// title = "To-Do List for " + firstdate.toString(Qt::TextDate); -// if ( firstdate != lastdate ) { -// title += " - " + lastdate.toString(Qt::TextDate); -// } - htmlSettings.setTodoListTitle( title ); - htmlSettings.setTodoView( false ); -// htmlSettings.setTaskCategories( false ); -// htmlSettings.setTaskAttendees( false ); -// htmlSettings.setTaskDueDate( true ); - - htmlSettings.setDateStart( QDateTime( firstdate ) ); - htmlSettings.setDateEnd( QDateTime( lastdate ) ) ; - - KCal::HtmlExport *Export; - if ( !m_variables->isCalendarResources() ) { - Export = new HtmlExport( m_variables->getCalendar(), &htmlSettings ); - } else { - Export = new HtmlExport( m_variables->getCalendarResources(), &htmlSettings ); - } - status = Export->save( &ts ); - delete Export; - } - f.close(); - } - } - return status; -} - -bool KonsoleKalendar::printEventList( QTextStream *ts, - Event::List *eventList, QDate date ) -{ - bool status = true; - - if ( eventList->count() ) { - Event *singleEvent; - Event::List::ConstIterator it; - - for ( it = eventList->begin(); - it != eventList->end() && status != false; - ++it ) { - singleEvent = *it; - - status = printEvent( ts, singleEvent, date ); - } - } - - return( status ); -} - -bool KonsoleKalendar::printEvent( QTextStream *ts, Event *event, QDate dt ) -{ - bool status = false; - bool sameDay = true; - KonsoleKalendarExports exports; - - if ( event ) { - switch ( m_variables->getExportType() ) { - - case ExportTypeCSV: - kdDebug() << "konsolekalendar.cpp::printEvent() | " - << "CSV export" - << endl; - status = exports.exportAsCSV( ts, event, dt ); - break; - - case ExportTypeTextShort: - kdDebug() - << "konsolekalendar.cpp::printEvent() | " - << "TEXT-SHORT export" - << endl; - if ( dt.daysTo( m_saveDate ) ) { - sameDay = false; - m_saveDate = dt; - } - status = exports.exportAsTxtShort( ts, event, dt, sameDay ); - break; - - case ExportTypeHTML: - // this is handled separately for now - break; - - default:// Default export-type is ExportTypeText - kdDebug() << "konsolekalendar.cpp::printEvent() | " - << "TEXT export" - << endl; - status = exports.exportAsTxt( ts, event, dt ); - break; - } - } - return( status ); -} - -bool KonsoleKalendar::addEvent() -{ - kdDebug() << "konsolecalendar.cpp::addEvent() | " - << "Create Adding" - << endl; - KonsoleKalendarAdd add( m_variables ); - kdDebug() << "konsolecalendar.cpp::addEvent() | " - << "Adding Event now!" - << endl; - return( add.addEvent() ); -} - -bool KonsoleKalendar::changeEvent() -{ - - kdDebug() << "konsolecalendar.cpp::changeEvent() | " - << "Create Changing" - << endl; - KonsoleKalendarChange change( m_variables ); - kdDebug() << "konsolecalendar.cpp::changeEvent() | " - << "Changing Event now!" - << endl; - return( change.changeEvent() ); -} - -bool KonsoleKalendar::deleteEvent() -{ - kdDebug() << "konsolecalendar.cpp::deleteEvent() | " - << "Create Deleting" - << endl; - KonsoleKalendarDelete del( m_variables ); - kdDebug() << "konsolecalendar.cpp::deleteEvent() | " - << "Deleting Event now!" - << endl; - return( del.deleteEvent() ); -} - -bool KonsoleKalendar::isEvent( QDateTime startdate, - QDateTime enddate, QString summary ) -{ - // Search for an event with specified start and end datetime stamp and summary - - Event *event; - Event::List::ConstIterator it; - - bool found = false; - - Event::List eventList( m_variables->getCalendar()-> - rawEventsForDate( startdate.date(), - EventSortStartDate, - SortDirectionAscending ) ); - for ( it = eventList.begin(); it != eventList.end(); ++it ) { - event = *it; - if ( event->dtEnd() == enddate && event->summary() == summary ) { - found = true; - break; - } - } - return found; -} - -void KonsoleKalendar::printSpecs() -{ - cout << i18n( " What: %1" ). - arg( m_variables->getSummary() ).local8Bit() - << endl; - - cout << i18n( " Begin: %1" ). - arg( m_variables->getStartDateTime().toString( Qt::TextDate ) ).local8Bit() - << endl; - - cout << i18n( " End: %1" ). - arg( m_variables->getEndDateTime().toString( Qt::TextDate ) ).local8Bit() - << endl; - - if ( m_variables->getFloating() == true ) { - cout << i18n( " No Time Associated with Event" ).local8Bit() - << endl; - } - - cout << i18n( " Desc: %1" ). - arg( m_variables->getDescription() ).local8Bit() - << endl; - - cout << i18n( " Location: %1" ). - arg( m_variables->getLocation() ).local8Bit() - << endl; -} diff --git a/console/konsolekalendar/konsolekalendar.h b/console/konsolekalendar/konsolekalendar.h deleted file mode 100644 index f41ed4ccb2..0000000000 --- a/console/konsolekalendar/konsolekalendar.h +++ /dev/null @@ -1,144 +0,0 @@ -/******************************************************************************* - * konsolekalendar.h * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ - -#ifndef _KONSOLEKALENDAR_H -#define _KONSOLEKALENDAR_H - -#include - -#include - -#include -#include -#include - -#include "konsolekalendarvariables.h" - -/** - * @file konsolekalendar.h - * Provides the KonsoleKalendar class definition. - */ - -namespace KCal -{ -/** - * The base class of the project. - * @author Tuukka Pasanen - */ - class KonsoleKalendar - { - public: - /** - * Constructs a KonsoleKalendar object from command line arguments. - */ - KonsoleKalendar( KonsoleKalendarVariables *variables ); - /** - * Destructor - */ - ~KonsoleKalendar(); - - /** - * Visualize what we need. - */ - bool showInstance(); - - /** - * Imports calendar file - */ - bool importCalendar(); - - /** - * Add event to calendar - */ - bool addEvent(); - - /** - * Change event - */ - bool changeEvent(); - - /** - * Delete event - */ - bool deleteEvent(); - - /** - * Detect if event already exists - * - * @param startdate Starting date - * @param enddate Ending date - * @param summary Which summary event should have have - */ - bool isEvent( QDateTime startdate, QDateTime enddate, QString summary ); - - /** - * Creates calendar file (If it doesn't exists) - */ - bool createCalendar(); - - private: - - /** - * Print event specs for dryrun and verbose options - */ - void printSpecs(); - - /** - * Prints event list in many formats - * - * @param eventlist which event we should print - * @param dt is the date to use when printing the event for recurring events - */ - bool printEventList( QTextStream *ts, Event::List *eventList, QDate dt ); - - /** - * Prints a single event in many formats - * - * @param event which we should print - * @param dt is the date to use when printing the event for recurring events - */ - bool printEvent( QTextStream *ts, Event *event, QDate dt ); - - /** - * Variables that changes stuff in programm - */ - KonsoleKalendarVariables *m_variables; - - /** - * Calendar file itself - */ - ResourceCalendar *m_Calendar; - - /** - * This is usefull if we like to have same day events to same system - */ - QDate m_saveDate; - - }; - -} -#endif diff --git a/console/konsolekalendar/konsolekalendaradd.cpp b/console/konsolekalendar/konsolekalendaradd.cpp deleted file mode 100644 index becbf29125..0000000000 --- a/console/konsolekalendar/konsolekalendaradd.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/******************************************************************************* - * konsolekalendaradd.cpp * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ -/** - * @file konsolekalendaradd.cpp - * Provides the KonsoleKalendarAdd class definition. - * @author Tuukka Pasanen - * @author Allen Winter - */ -#include -#include - -#include -#include - -#include -#include - -#include -#include -#include - -#include "konsolekalendaradd.h" - -using namespace KCal; -using namespace std; - -KonsoleKalendarAdd::KonsoleKalendarAdd( KonsoleKalendarVariables *vars ) -{ - m_variables = vars; -} - -KonsoleKalendarAdd::~KonsoleKalendarAdd() -{ -} - -/** - * Adds event to Calendar - */ - -bool KonsoleKalendarAdd::addEvent() -{ - bool status = true; - - kdDebug() << "konsolekalendaradd.cpp::addEvent()" << endl; - - if ( m_variables->isDryRun() ) { - cout << i18n( "Insert Event :" ).local8Bit() - << endl; - printSpecs(); - } else { - if ( m_variables->isVerbose() ) { - cout << i18n( "Insert Event :" ).local8Bit() - << endl; - printSpecs(); - } - - Event *event = new Event(); - - event->setDtStart( m_variables->getStartDateTime() ); - event->setDtEnd( m_variables->getEndDateTime() ); - event->setSummary( m_variables->getSummary() ); - event->setFloats( m_variables->getFloating() ); - event->setDescription( m_variables->getDescription() ); - event->setLocation( m_variables->getLocation() ); - - if ( m_variables->getCalendar()->addEvent( event ) ) { - cout << i18n( "Success: \"%1\" inserted" ). - arg( m_variables->getSummary() ).local8Bit() - << endl; - - if ( !m_variables->isCalendarResources() ) { - status = - m_variables->getCalendar()->save( m_variables->getCalendarFile() ); - } else { - m_variables->getCalendar()->save(); - } - - } else { - cout << i18n( "Failure: \"%1\" not inserted" ). - arg( m_variables->getSummary() ).local8Bit() - << endl; - status = false; - } - } - - kdDebug() << "konsolekalendaradd.cpp::addEvent() | Done " << endl; - return status; -} - -bool KonsoleKalendarAdd::addImportedCalendar() -{ - - if ( !m_variables->getCalendar()->load( m_variables->getImportFile() ) ) { - kdDebug() - << "konsolekalendaradd.cpp::importCalendar() | " - << "Can't import file: " - << m_variables->getImportFile() - << endl; - return false; - } else { - kdDebug() - << "konsolekalendaradd.cpp::importCalendar() | " - << "Successfully imported file: " - << m_variables->getImportFile() - << endl; - } - - if ( !m_variables->isCalendarResources() ) { - m_variables->getCalendar()->save( m_variables->getCalendarFile() ); - } else { - m_variables->getCalendar()->save(); - } - - return true; -} - -void KonsoleKalendarAdd::printSpecs() -{ - cout << i18n( " What: %1" ). - arg( m_variables->getSummary() ).local8Bit() - << endl; - - cout << i18n( " Begin: %1" ). - arg( m_variables->getStartDateTime().toString( Qt::TextDate ) ).local8Bit() - << endl; - - cout << i18n( " End: %1" ). - arg( m_variables->getEndDateTime().toString( Qt::TextDate ) ).local8Bit() - << endl; - - if ( m_variables->getFloating() == true ) { - cout << i18n( " No Time Associated with Event" ).local8Bit() - << endl; - } - - cout << i18n( " Desc: %1" ). - arg( m_variables->getDescription() ).local8Bit() - << endl; - - cout << i18n( " Location: %1" ). - arg( m_variables->getLocation() ).local8Bit() - << endl; -} diff --git a/console/konsolekalendar/konsolekalendaradd.h b/console/konsolekalendar/konsolekalendaradd.h deleted file mode 100644 index d1c9a29601..0000000000 --- a/console/konsolekalendar/konsolekalendaradd.h +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * konsolekalendaradd.h * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ - -#ifndef _KONSOLEKALENDARADD_H_ -#define _KONSOLEKALENDARADD_H_ - -#include "konsolekalendarvariables.h" - -/** - * @file konsolekalendaradd.h - * Provides the KonsoleKalendarAdd class definition. - */ - -namespace KCal -{ - /** - * Class to manage the Event insertion capability. - * @author Tuukka Pasanen - * @author Allen Winter - */ - class KonsoleKalendarAdd - { - public: - /** - * Constructs a KonsoleKalendarAdd object from command line arguments. - * @param vars is a KonsoleKalendarVariable object with Event information. - */ - KonsoleKalendarAdd( KonsoleKalendarVariables *vars ); - /** - * Destructor - */ - ~KonsoleKalendarAdd(); - - /** - * Add the Event. - */ - bool addEvent(); - - /** - * Imports calendar file to current Calendar. - */ - bool addImportedCalendar(); - - private: - - /** - * Print event specs for dryrun and verbose options - */ - void printSpecs(); - - /** - * Variable to how to make it - */ - KonsoleKalendarVariables *m_variables; - - }; - -} -#endif diff --git a/console/konsolekalendar/konsolekalendarchange.cpp b/console/konsolekalendar/konsolekalendarchange.cpp deleted file mode 100644 index b2970a662a..0000000000 --- a/console/konsolekalendar/konsolekalendarchange.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/******************************************************************************* - * konsolekalendarchange.cpp * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ -/** - * @file konsolekalendarchange.cpp - * Provides the KonsoleKalendarChange class definition. - * @author Tuukka Pasanen - * @author Allen Winter - */ -#include -#include - -#include -#include - -#include "konsolekalendarchange.h" - -using namespace KCal; -using namespace std; - -KonsoleKalendarChange::KonsoleKalendarChange( KonsoleKalendarVariables *vars ) -{ - m_variables = vars; -} - -KonsoleKalendarChange::~KonsoleKalendarChange() -{ -} - -bool KonsoleKalendarChange::changeEvent() -{ - bool status = false; - - kdDebug() << "konsolekalendarchange.cpp::changeEvent()" << endl; - - /* - * Retrieve event on the basis of the unique string ID - */ - Event *event = m_variables->getCalendar()->event( m_variables->getUID() ); - if ( event ) { - if ( m_variables->isDryRun() ) { - cout << i18n( "Change Event :" ).local8Bit() - << endl; - printSpecs( event ); - - cout << i18n( "To Event :" ).local8Bit() - << endl; - printSpecs(); - } else { - kdDebug() << "konsolekalendarchange.cpp:changeEvent() : " - << m_variables->getUID().local8Bit() - << endl; - - if ( m_variables->isVerbose() ) { - cout << i18n( "Change Event :" ).local8Bit() - << endl; - printSpecs( event ); - - cout << i18n( "To Event :" ).local8Bit() - << endl; - printSpecs(); - } - - if ( m_variables->isStartDateTime() ) { - event->setDtStart( m_variables->getStartDateTime() ); - } - - if ( m_variables->isEndDateTime() ) { - event->setDtEnd( m_variables->getEndDateTime() ); - } - - event->setFloats( m_variables->getFloating() ); - - if ( m_variables->isSummary() ) { - event->setSummary( m_variables->getSummary() ); - } - - if ( m_variables->isDescription() ) { - event->setDescription( m_variables->getDescription() ); - } - - if ( m_variables->isLocation() ) { - event->setLocation( m_variables->getLocation() ); - } - - if ( m_variables->getCalendar()->addEvent( event ) ) { - cout << i18n( "Success: \"%1\" changed" ) - .arg( event->summary() ).local8Bit() - << endl; - - if ( !m_variables->isCalendarResources() ) { - status = - m_variables->getCalendar()->save( m_variables->getCalendarFile() ); - } else { - m_variables->getCalendar()->save(); - status = true; - } - } else { - cout << i18n( "Failure: \"%1\" not changed" ) - .arg( event->summary() ).local8Bit() - << endl; - } - } - } - - kdDebug() << "konsolekalendarchange.cpp::changeEvent() | Done " << endl; - return status; -} - -void KonsoleKalendarChange::printSpecs( Event *event ) -{ - cout << i18n( " UID: %1" ). - arg( event->uid() ).local8Bit() - << endl; - - cout << i18n( " What: %1" ). - arg( event->summary() ).local8Bit() - << endl; - - cout << i18n( " Begin: %1" ). - arg( event->dtStart().toString( Qt::TextDate ) ).local8Bit() - << endl; - - cout << i18n( " End: %1" ). - arg( event->dtEnd().toString( Qt::TextDate ) ).local8Bit() - << endl; - - cout << i18n( " Desc: %1" ). - arg( event->description() ).local8Bit() - << endl; - - cout << i18n( " Location: %1" ). - arg( event->location() ).local8Bit() - << endl; -} - -void KonsoleKalendarChange::printSpecs() -{ - cout << i18n( " UID: %1" ). - arg( m_variables->getUID() ).local8Bit() - << endl; - - cout << i18n( " What: %1" ). - arg( m_variables->getSummary() ).local8Bit() - << endl; - - cout << i18n( " Begin: %1" ). - arg( m_variables->getStartDateTime().toString( Qt::TextDate ) ).local8Bit() - << endl; - - cout << i18n( " End: %1" ). - arg( m_variables->getEndDateTime().toString( Qt::TextDate ) ).local8Bit() - << endl; - - cout << i18n( " Desc: %1" ). - arg( m_variables->getDescription() ).local8Bit() - << endl; - - cout << i18n( " Location: %1" ). - arg( m_variables->getLocation() ).local8Bit() - << endl; -} diff --git a/console/konsolekalendar/konsolekalendarchange.h b/console/konsolekalendar/konsolekalendarchange.h deleted file mode 100644 index 80e8f8c2ea..0000000000 --- a/console/konsolekalendar/konsolekalendarchange.h +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * konsolekalendarchange.h * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ - -#ifndef _KONSOLEKALENDARCHANGE_H_ -#define _KONSOLEKALENDARCHANGE_H_ - -#include "konsolekalendarvariables.h" - -/** - * @file konsolekalendarchange.h - * Provides the KonsoleKalendarChange class definition. - */ - -namespace KCal -{ - /** - * Class to manage the Event modification capability. - * @author Tuukka Pasanen - * @author Allen Winter - */ - class KonsoleKalendarChange - { - public: - - /** - * Constructs a KonsoleKalendarChange object from command line arguments. - * @param vars is a KonsoleKalendarVariable object with Event information. - */ - KonsoleKalendarChange( KonsoleKalendarVariables *vars ); - /** - * Destructor - */ - ~KonsoleKalendarChange(); - - /** - * Modify the Event. - */ - bool changeEvent(); - - private: - - /** - * Print Event specs for dryrun and verbose options. - * @param event is the Event to print. - */ - void printSpecs( Event *event ); - /* - * Print Event specs as provided from the command line arguments. - */ - void printSpecs(); - - /** - * Variables are here - */ - KonsoleKalendarVariables *m_variables; - }; - -} -#endif diff --git a/console/konsolekalendar/konsolekalendardelete.cpp b/console/konsolekalendar/konsolekalendardelete.cpp deleted file mode 100644 index 1dd09a99cf..0000000000 --- a/console/konsolekalendar/konsolekalendardelete.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * konsolekalendardelete.cpp * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ -/** - * @file konsolekalendardelete.cpp - * Provides the KonsoleKalendarDelete class definition. - * @author Tuukka Pasanen - * @author Allen Winter - */ -#include -#include - -#include -#include - -#include "konsolekalendardelete.h" - -using namespace KCal; -using namespace std; - -KonsoleKalendarDelete::KonsoleKalendarDelete( KonsoleKalendarVariables *vars ) -{ - m_variables = vars; -} - -KonsoleKalendarDelete::~KonsoleKalendarDelete() -{ -} - -bool KonsoleKalendarDelete::deleteEvent() -{ - bool status = false; - - kdDebug() << "konsolekalendardelete.cpp::deleteEvent()" << endl; - - /* - * Retrieve event on the basis of the unique string ID - */ - Event *event = m_variables->getCalendar()->event( m_variables->getUID() ); - if ( event ) { - if ( m_variables->isDryRun() ) { - cout << i18n( "Delete Event :" ).local8Bit() - << endl; - printSpecs( event ); - } else { - kdDebug() << "konsolekalendardelete.cpp:deleteEvent() : " - << m_variables->getUID().local8Bit() - << endl; - - if ( m_variables->isVerbose() ) { - cout << i18n( "Delete Event :" ).local8Bit() - << endl; - printSpecs( event ); - } - - m_variables->getCalendar()->deleteEvent( event ); - cout << i18n( "Success: \"%1\" deleted" ) - .arg( event->summary() ).local8Bit() - << endl; - - if ( !m_variables->isCalendarResources() ) { - status = - m_variables->getCalendar()->save( m_variables->getCalendarFile() ); - } else { - m_variables->getCalendar()->save(); - status = true; - } - } - } - - kdDebug() << "konsolekalendardelete.cpp::deleteEvent() | Done " << endl; - return status; -} - -void KonsoleKalendarDelete::printSpecs( Event *event ) -{ - cout << i18n( " UID: %1" ). - arg( m_variables->getUID() ).local8Bit() - << endl; - - cout << i18n( " What: %1" ). - arg( event->summary() ).local8Bit() - << endl; - - cout << i18n( " Begin: %1" ). - arg( event->dtStart().toString( Qt::TextDate ) ).local8Bit() - << endl; - - cout << i18n( " End: %1" ). - arg( event->dtEnd().toString( Qt::TextDate ) ).local8Bit() - << endl; - - cout << i18n( " Desc: %1" ). - arg( event->description() ).local8Bit() - << endl; - - cout << i18n( " Location: %1" ). - arg( event->location() ).local8Bit() - << endl; -} diff --git a/console/konsolekalendar/konsolekalendardelete.h b/console/konsolekalendar/konsolekalendardelete.h deleted file mode 100644 index 2a01990f0a..0000000000 --- a/console/konsolekalendar/konsolekalendardelete.h +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * konsolekalendardelete.h * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ - -#ifndef _KONSOLEKALENDARDELETE_H_ -#define _KONSOLEKALENDARDELETE_H_ - -#include "konsolekalendarvariables.h" - -/** - * @file konsolekalendardelete.h - * Provides the KonsoleKalendarDelete class definition. - */ - -namespace KCal -{ - /** - * Class to manage the Event removal capability. - * @author Tuukka Pasanen - * @author Allen Winter - */ - class KonsoleKalendarDelete - { - public: - - /** - * Constructs a KonsoleKalendarDelete object from command line arguments. - */ - KonsoleKalendarDelete( KonsoleKalendarVariables *vars ); - /** - * Destructor - */ - ~KonsoleKalendarDelete(); - - /** - * Delete the Event. - */ - bool deleteEvent(); - - private: - - /** - * Print event specs for dryrun and verbose options. - */ - void printSpecs( Event *event ); - - /** - * What we need to delete - */ - KonsoleKalendarVariables *m_variables; - }; - -} -#endif diff --git a/console/konsolekalendar/konsolekalendarepoch.cpp b/console/konsolekalendar/konsolekalendarepoch.cpp deleted file mode 100644 index c070d25320..0000000000 --- a/console/konsolekalendar/konsolekalendarepoch.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/******************************************************************************* - * konsolekalendarepoch.cpp * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ -/** - * @file konsolekalendarepoch.cpp - * Provides the KonsoleKalendarEpoch class definition. - * @author Tuukka Pasanen - * @author Allen Winter - */ -#include -#include - -#include -#include "konsolekalendarepoch.h" - -using namespace KCal; -using namespace std; - -KonsoleKalendarEpoch::KonsoleKalendarEpoch() -{ -} - -KonsoleKalendarEpoch::~KonsoleKalendarEpoch() -{ -} - -// By "epoch" we mean the number of seconds since 00:00:00 UTC on January 1 1970 - -// Function to convert an epoch value into a QDateTime -QDateTime KonsoleKalendarEpoch::epoch2QDateTime( uint epoch ) -{ - QDateTime dt; - dt.setTime_t( epoch, Qt::UTC ); - return( dt ); -} - -// Function to convert a QDateTime value into an epoch -uint KonsoleKalendarEpoch::QDateTime2epoch( QDateTime dt ) -{ - // THIS FUNCTION CAN BE OFF BY 1 HOUR DUE TO DAYLIGHT SAVINGS TIME. - // SORRY QT DOESN'T HANDLE DAYLIGHT SAVINGS TIME. - - // Compute #seconds to subtract for local timezone difference from UTC. - int offset = QDateTime::currentDateTime( Qt::UTC ).toTime_t() - - QDateTime::currentDateTime( Qt::LocalTime ).toTime_t(); - return( dt.toTime_t() - offset ); -} - -#if defined (TEST) -// Pass -DTEST to the compile command to create the test program, e.g: -// cc -DTEST -I/usr/local/KDE/include konsolekalendarepoch.cpp -// -L/usr/local/KDE/lib -lqt-mt -pthread -main() -{ - uint epoch; - QDateTime dt; - - cout << endl; - cout << "NOTE: Some tests may be off by 1 hour (3600 secs) " - << "due to daylight savings time" - << endl << endl; - - // Test1 - epoch = 0; - dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); - cout << "TEST 1:" << endl; - cout << "epoch=" - << epoch - << " converts to " - << dt.toString( Qt::TextDate ) - << endl; - - epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); - cout << "date=" - << dt.toString( Qt::TextDate ) - << " converts to " - << "epoch=" - << epoch - << endl; - - // Test2 - epoch = 100000; - dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); - cout << "TEST 2:" << endl; - cout << "epoch=" - << epoch - << " converts to " - << dt.toString( Qt::TextDate ) - << endl; - - epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); - cout << "date=" - << dt.toString( Qt::TextDate ) - << " converts to " - << "epoch=" - << epoch - << endl; - - // Test3 - epoch = 10000000; - dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); - cout << "TEST 3:" << endl; - cout << "epoch=" - << epoch - << " converts to " - << dt.toString( Qt::TextDate ) - << endl; - - epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); - cout << "date=" - << dt.toString( Qt::TextDate ) - << " converts to " - << "epoch=" - << epoch - << endl; - - // Test4 - epoch = 1000000000; - dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); - cout << "TEST 4:" << endl; - cout << "epoch=" - << epoch - << " converts to " - << dt.toString( Qt::TextDate ) - << endl; - - epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); - cout << "date=" - << dt.toString( Qt::TextDate ) - << " converts to " - << "epoch=" - << epoch - << endl; - - // Test5 - epoch = 10000000000; - dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); - cout << "TEST 5:" << endl; - cout << "epoch=" - << epoch - << " converts to " - << dt.toString( Qt::TextDate ) - << endl; - - epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); - cout << "date=" - << dt.toString( Qt::TextDate ) - << " converts to " - << "epoch=" - << epoch - << endl; -} -#endif diff --git a/console/konsolekalendar/konsolekalendarepoch.h b/console/konsolekalendar/konsolekalendarepoch.h deleted file mode 100644 index e6db6d77e1..0000000000 --- a/console/konsolekalendar/konsolekalendarepoch.h +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * konsolekalendarepoch.h * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ - -#ifndef _KONSOLEKALENDAREPOCH_H_ -#define _KONSOLEKALENDAREPOCH_H_ - -#include - -/** - * @file konsolekalendarepoch.h - * Provides the KonsoleKalendarEpoch class definition. - */ - -namespace KCal -{ - /** - * Class for timestamps expressed as epochs. - * @author Allen Winter - */ - class KonsoleKalendarEpoch - { - public: - /** - * Constructor. - */ - KonsoleKalendarEpoch(); - /** - * Destructor - */ - ~KonsoleKalendarEpoch(); - - /** - * Converts epoch time to QDateTime format. - * @param epoch epoch time. - */ - static QDateTime epoch2QDateTime( uint epoch ); - - /** - * Converts QT DateTime to epoch format. - * @param dt is a QDateTime to convert to an epoch. - */ - static uint QDateTime2epoch( QDateTime dt ); - - }; - -} - -#endif diff --git a/console/konsolekalendar/konsolekalendarexports.cpp b/console/konsolekalendar/konsolekalendarexports.cpp deleted file mode 100644 index cad79964a4..0000000000 --- a/console/konsolekalendar/konsolekalendarexports.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/******************************************************************************* - * konsolekalendarexports.cpp * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ -/** - * @file konsolekalendarexports.cpp - * Provides the KonsoleKalendarExports class definition. - * @author Tuukka Pasanen - * @author Allen Winter - */ -#include -#include - -#include - -#include -#include - -#include -#include -#include - -#include "konsolekalendarexports.h" - -using namespace KCal; -using namespace std; - -KonsoleKalendarExports::KonsoleKalendarExports( KonsoleKalendarVariables *vars ) -{ - m_variables = vars; - m_firstEntry = true; -} - - -KonsoleKalendarExports::~KonsoleKalendarExports() -{ -} - -bool KonsoleKalendarExports::exportAsTxt( QTextStream *ts, - Event *event, QDate date ) -{ - - // Export "Text" Format: - // - // Date:\t(dddd yyyy-MM-dd) - // [\t(hh:mm) - (hh:mm)] - // Summary: - // \t - // Location: - // \t - // Description: - // \t - // UID: - // \t - // -------------------------------------------------- - - // Print Event Date (in user's prefered format) - *ts << i18n( "Date:" ) - << "\t" - << KGlobal::locale()->formatDate( date ) - << endl; - - // Print Event Starttime - Endtime, for Non-Floating Events Only - if ( !event->doesFloat() ) { - *ts << "\t" - << KGlobal::locale()->formatTime( event->dtStart().time() ) - << " - " - << KGlobal::locale()->formatTime( event->dtEnd().time() ); - } - *ts << endl; - - // Print Event Summary - *ts << i18n( "Summary:" ) - << endl; - if ( !event->summary().isEmpty() ) { - *ts << "\t" - << event->summary() - << endl; - } else { - *ts << "\t" - << i18n( "(no summary available)" ) - << endl; - } - - // Print Event Location - *ts << i18n( "Location:" ) - << endl; - if ( !event->location().isEmpty() ) { - *ts << "\t" - <location() - << endl; - } else { - *ts << "\t" - << i18n( "(no location available)" ) - << endl; - } - - // Print Event Description - *ts << i18n( "Description:" ) - << endl; - if ( !event->description().isEmpty() ) { - *ts << "\t" - << event->description() - << endl; - } else { - *ts << "\t" - << i18n( "(no description available)" ) - << endl; - } - - // Print Event UID - *ts << i18n( "UID:" ) - << endl - << "\t" - << event->uid() - << endl; - - // Print Line Separator - *ts << "--------------------------------------------------" - << endl; - - return true; -} - -bool KonsoleKalendarExports::exportAsTxtShort( QTextStream *ts, - Event *event, QDate date, - bool sameday ) -{ - - // Export "Text-Short" Format: - // - // [--------------------------------------------------] - // {(dddd yyyy-MM-dd)] - // [(hh:mm) - (hh:mm) | "\t"] - // \t[, ] - // \t\t - - if ( !sameday ) { - // If a new date, then Print the Event Date (in user's prefered format) - *ts << KGlobal::locale()->formatDate( date ) << ":" - << endl; - } - - // Print Event Starttime - Endtime - if ( !event->doesFloat() ) { - *ts << KGlobal::locale()->formatTime( event->dtStart().time() ) - << " - " - << KGlobal::locale()->formatTime( event->dtEnd().time() ); - } else { - *ts << i18n( "[all day]\t" ); - } - *ts << "\t"; - - // Print Event Summary - *ts << event->summary().replace( QChar( '\n' ), QChar( ' ' ) ); - - // Print Event Location - if ( !event->location().isEmpty() ) { - if ( !event->summary().isEmpty() ) { - *ts << ", "; - } - *ts << event->location().replace( QChar( '\n' ), QChar( ' ' ) ); - } - *ts << endl; - - // Print Event Description - if ( !event->description().isEmpty() ) { - *ts << "\t\t\t" - << event->description().replace( QChar( '\n' ), QChar( ' ' ) ) - << endl; - } - -// By user request, no longer print UIDs if export-type==short - - return true; -} - -QString KonsoleKalendarExports::processField( QString field, QString dquote ) -{ - // little function that processes a field for CSV compliance: - // 1. Replaces double quotes by a pair of consecutive double quotes - // 2. Surrounds field with double quotes - - QString double_dquote = dquote + dquote; - QString retField = dquote + field.replace( dquote, double_dquote ) + dquote; - return retField; -} - -#define pF( x ) processField( ( x ), dquote ) - -bool KonsoleKalendarExports::exportAsCSV( QTextStream *ts, - Event *event, QDate date ) -{ - - // Export "CSV" Format: - // - // startdate,starttime,enddate,endtime,summary,location,description,UID - - QString delim = i18n( "," ); // character to use as CSV field delimiter - QString dquote = i18n( "\"" ); // character to use to quote CSV fields - - if ( !event->doesFloat() ) { - *ts << pF( KGlobal::locale()->formatDate( date ) ) - << delim << pF( KGlobal::locale()->formatTime( event->dtStart().time() ) ) - << delim << pF( KGlobal::locale()->formatDate( date ) ) - << delim << pF( KGlobal::locale()->formatTime( event->dtEnd().time() ) ); - } else { - *ts << pF( KGlobal::locale()->formatDate( date ) ) - << delim << pF( "" ) - << delim << pF( KGlobal::locale()->formatDate( date ) ) - << delim << pF( "" ); - } - - *ts << delim << pF( event->summary().replace( QChar('\n'), QChar(' ') ) ) - << delim << pF( event->location().replace( QChar('\n'), QChar(' ') ) ) - << delim << pF( event->description().replace( QChar('\n'), QChar(' ') ) ) - << delim << pF( event->uid() ) - << endl; - - return true; -} diff --git a/console/konsolekalendar/konsolekalendarexports.h b/console/konsolekalendar/konsolekalendarexports.h deleted file mode 100644 index dc2f44ecaf..0000000000 --- a/console/konsolekalendar/konsolekalendarexports.h +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * konsolekalendarexports.h * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ - -#ifndef _KONSOLEKALENDAREXPORTS_H_ -#define _KONSOLEKALENDAREXPORTS_H_ - -#include - -#include "konsolekalendarvariables.h" - -/** - * @file konsolekalendarexports.h - * Provides the KonsoleKalendarExports class definition. - */ - -namespace KCal -{ - /** - * Class to manage the Export functionality. - * @author Tuukka Pasanen - * @author Allen Winter - */ - class KonsoleKalendarExports - { - public: - - /** - * Constructs a KonsoleKalendarChange object from command line arguments. - * @param vars is a KonsoleKalendarVariable object with Event information. - */ - KonsoleKalendarExports( KonsoleKalendarVariables *vars = 0 ); - /** - * Destructor - */ - ~KonsoleKalendarExports(); - - /** - * Export the Event in Text Mode. - * @param ts pointer to the output QTextStream. - * @param event pointer to the Event to export. - * @param date is the QDate to be exported for. - */ - bool exportAsTxt( QTextStream *ts, Event *event, QDate date ); - /** - * Export the Event in Short Text Mode. - * @param ts pointer to the output QTextStream. - * @param event pointer to the Event to export. - * @param date is the QDate to be exported for. - * @param sameday flags that this Event is on the same date as the - * previously exported Event. - */ - bool exportAsTxtShort( QTextStream *ts, Event *event, QDate date, - bool sameday ); - /** - * Export the Event in Comma-Separated Values (CSV) Mode. - * @param ts pointer to the output QTextStream. - * @param event pointer to the Event to export. - * @param date is the QDate to be exported for. - */ - bool exportAsCSV( QTextStream *ts, Event *event, QDate date ); - - private: - KonsoleKalendarVariables *m_variables; - bool m_firstEntry; - /** - * Processes a field for Comma-Separated Value (CSV) compliance: - * 1. Replaces double quotes by a pair of consecutive double quotes - * 2. Surrounds field with double quotes - * @param field is the field value to be processed. - * @param dquote is a QString containing the double quote character. - */ - QString processField( QString field, QString dquote ); - - }; - -} -#endif diff --git a/console/konsolekalendar/konsolekalendarvariables.cpp b/console/konsolekalendar/konsolekalendarvariables.cpp deleted file mode 100644 index 0b1364bc39..0000000000 --- a/console/konsolekalendar/konsolekalendarvariables.cpp +++ /dev/null @@ -1,472 +0,0 @@ -/******************************************************************************* - * konsolekalendarvariables.cpp * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ -/** - * @file konsolekalendarvariables.cpp - * Provides the KonsoleKalendarVariables class definition. - * @author Tuukka Pasanen - * @author Allen Winter - */ -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "konsolekalendarvariables.h" - -using namespace KCal; -using namespace std; - -KonsoleKalendarVariables::KonsoleKalendarVariables() -{ - m_TimeZoneId = ""; - m_bIsTimeZoneId = false; - m_bIsUID = false; - m_bIsStartDateTime = false; - m_bIsEndDateTime = false; - m_bNext = false; - m_bVerbose = false; - m_bDryRun = false; - m_bUseEvents = false; - m_bUseTodos = false; - m_bUseJournals = false; - m_bDescription = false; - m_description = ""; - m_bSummary = false; - m_summary = "Default summary"; - m_bFloating = true; - m_exportType = ExportTypeText; - m_bIsExportFile = false; - m_bIsDefault = false; - m_bIsCalendarResources = false; -} - -void KonsoleKalendarVariables::setTimeZoneId() -{ - m_bIsTimeZoneId = true; - m_TimeZoneId = KPimPrefs::timezone(); -} - -QString KonsoleKalendarVariables::getTimeZoneId() -{ - return m_TimeZoneId; -} - -bool KonsoleKalendarVariables::isTimeZoneId() -{ - return m_bIsTimeZoneId; -} - -KonsoleKalendarVariables::~KonsoleKalendarVariables() -{ - // delete m_resource; -} - -void KonsoleKalendarVariables::setUID( QString uid ) -{ - m_bIsUID = true; - m_UID = uid; -} - -QString KonsoleKalendarVariables::getUID() -{ - return m_UID; -} - -bool KonsoleKalendarVariables::isUID() -{ - return m_bIsUID; -} - -void KonsoleKalendarVariables::setStartDateTime( QDateTime start ) -{ - m_bIsStartDateTime = true; - m_startDateTime = start; -} - -QDateTime KonsoleKalendarVariables::getStartDateTime() -{ - return m_startDateTime; -} - -bool KonsoleKalendarVariables::isStartDateTime() -{ - return m_bIsStartDateTime; -} - -void KonsoleKalendarVariables::setEndDateTime( QDateTime end ) -{ - m_bIsEndDateTime = true; - m_endDateTime = end; -} - -QDateTime KonsoleKalendarVariables::getEndDateTime() -{ - return m_endDateTime; -} - -bool KonsoleKalendarVariables::isEndDateTime() -{ - return m_bIsEndDateTime; -} - -void KonsoleKalendarVariables::setNext( bool next ) -{ - m_bNext = next; -} - -bool KonsoleKalendarVariables::isNext() -{ - return m_bNext; -} - -void KonsoleKalendarVariables::setVerbose( bool verbose ) -{ - m_bVerbose = verbose; -} - -bool KonsoleKalendarVariables::isVerbose() -{ - return m_bVerbose; -} - -void KonsoleKalendarVariables::setDryRun( bool dryrun ) -{ - m_bDryRun = dryrun; -} - -bool KonsoleKalendarVariables::isDryRun() -{ - return m_bDryRun; -} - -void KonsoleKalendarVariables::setUseEvents( bool useEvents ) -{ - m_bUseEvents = useEvents; -} - -bool KonsoleKalendarVariables::getUseEvents() -{ - return( m_bUseEvents ); -} - -void KonsoleKalendarVariables::setUseTodos( bool useTodos ) -{ - m_bUseTodos = useTodos; -} - -bool KonsoleKalendarVariables::getUseTodos() -{ - return( m_bUseTodos ); -} - -void KonsoleKalendarVariables::setUseJournals( bool useJournals ) -{ - m_bUseJournals = useJournals; -} - -bool KonsoleKalendarVariables::getUseJournals() -{ - return( m_bUseJournals ); -} - -void KonsoleKalendarVariables::setCalendarFile( QString calendar ) -{ - m_calendar = calendar; -} - -QString KonsoleKalendarVariables::getCalendarFile() -{ - return m_calendar; -} - -void KonsoleKalendarVariables::setImportFile( QString calendar ) -{ - m_import = calendar; -} - -QString KonsoleKalendarVariables::getImportFile() -{ - return m_import; -} - -void KonsoleKalendarVariables::setCalendar( CalendarLocal *calendar ) -{ - m_calendarLocal = calendar; -} - -CalendarLocal *KonsoleKalendarVariables::getCalendar() -{ - return m_calendarLocal; -} - -void KonsoleKalendarVariables::setExportType( ExportType exportType ) -{ - m_exportType = exportType; -} - -ExportType KonsoleKalendarVariables::getExportType() -{ - return m_exportType; -} - -void KonsoleKalendarVariables::setExportFile( QString export_file ) -{ - m_exportFile = export_file; - m_bIsExportFile = true; -} - -bool KonsoleKalendarVariables::isExportFile() -{ - return m_bIsExportFile; -} - -QString KonsoleKalendarVariables::getExportFile() -{ - return m_exportFile; -} - -bool KonsoleKalendarVariables::isAll() -{ - return m_bAll; -} - -void KonsoleKalendarVariables::setAll( bool all ) -{ - m_bAll = all; -} - -bool KonsoleKalendarVariables::getAll() -{ - return m_bAll; -} - -void KonsoleKalendarVariables::setDefault( bool def ) -{ - m_bIsDefault = def; -} - -bool KonsoleKalendarVariables::isDefault() -{ - return m_bIsDefault; -} - -void KonsoleKalendarVariables::setDescription( QString description ) -{ - m_bDescription = true; - m_description = description; -} - -QString KonsoleKalendarVariables::getDescription() -{ - return m_description; -} - -bool KonsoleKalendarVariables::isDescription() -{ - return m_bDescription; -} - -void KonsoleKalendarVariables::setLocation( QString location ) -{ - m_bLocation = true; - m_location = location; -} - -QString KonsoleKalendarVariables::getLocation() -{ - return m_location; -} - -bool KonsoleKalendarVariables::isLocation() -{ - return m_bLocation; -} - -void KonsoleKalendarVariables::setSummary( QString summary ) -{ - m_bSummary = true; - m_summary = summary; -} - -QString KonsoleKalendarVariables::getSummary() -{ - return m_summary; -} - -bool KonsoleKalendarVariables::isSummary() -{ - return m_bSummary; -} - -void KonsoleKalendarVariables::setFloating( bool floating ) -{ - m_bFloating = floating; -} - -bool KonsoleKalendarVariables::getFloating() -{ - return m_bFloating; -} - -void KonsoleKalendarVariables::setDaysCount( int count ) -{ - m_daysCount = count; - m_bDaysCount = true; -} - -int KonsoleKalendarVariables::getDaysCount() -{ - return m_daysCount; -} - -bool KonsoleKalendarVariables::isDaysCount() -{ - return m_bDaysCount; -} - -bool KonsoleKalendarVariables::addCalendarResources( ResourceCalendar - *resource ) -{ - if ( m_resource ) { - // In current state we support only one calendar - // that's a fact and we have to live with that! - kdDebug() << "konsolekalendarvariables.cpp::addCalendarResources() | " - << "Add to calendar resource!" - << endl; - - CalendarResourceManager::ActiveIterator it; - CalendarResourceManager *manager = getCalendarResourceManager(); - QString fileName = NULL; - - for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) { - kdDebug() << "Resource name: " + (*it)->resourceName() - << endl; - - if ( !strcmp( (*it)->resourceName().local8Bit(), - getCalendarFile().local8Bit() ) ) { - kdDebug() << "konsolekalendarvariables.cpp::addCalendarResources() | " - << "We allready have this resource" - << endl; - return true; - } - - } - - manager->add( resource ); - - if ( isDefault() ) { - kdDebug() << "konsolekalendarvariables.cpp::addCalendarResources() | " - << "Make it default" - << endl; - manager->setStandardResource( resource ); - } - - } else { - kdDebug() << "konsolekalendarvariables.cpp::addCalendarResources() | " - << "Cannot add to calendar resources (Not created!)" - << endl; - return false; - } - - return true; -} - -bool KonsoleKalendarVariables::isCalendarResources() -{ - return m_bIsCalendarResources; -} - -void KonsoleKalendarVariables::setCalendarResources( CalendarResources - *resource ) -{ - m_resource = resource; - setCalendar( (CalendarLocal *) m_resource ); - m_bIsCalendarResources = true; -} - -CalendarResources *KonsoleKalendarVariables::getCalendarResources() -{ - return m_resource; -} - -CalendarResourceManager *KonsoleKalendarVariables::getCalendarResourceManager( ) -{ - return m_resource->resourceManager(); -} - -bool KonsoleKalendarVariables::loadCalendarResources( KConfig *config ) -{ - - if ( m_resource ) { - kdDebug() << "konsolekalendarvariables.cpp::loadCalendarResources() | " - << "loading resources" - << endl; - - CalendarResourceManager *manager = m_resource->resourceManager(); - - if ( manager->isEmpty() == true ) { - - config->setGroup( "General" ); - QString fileName = config->readPathEntry( "Active Calendar" ); - - QString resourceName; - if ( fileName.isEmpty() ) { - fileName = locateLocal( "appdata", "std.ics" ); - resourceName = i18n( "Default KOrganizer resource" ); - } else { - resourceName = i18n( "Active Calendar" ); - } - - kdDebug() << "konsolekalendarvariables.cpp::loadCalendarResources() | " - << "Using as default resource: '" - << fileName - << "'" - << endl; - - ResourceCalendar *defaultResource = new ResourceLocal( fileName ); - //defaultResource->setTimeZoneId); - defaultResource->setResourceName( resourceName ); - - manager->add( defaultResource ); - manager->setStandardResource( defaultResource ); - } - } - - return true; -} diff --git a/console/konsolekalendar/konsolekalendarvariables.h b/console/konsolekalendar/konsolekalendarvariables.h deleted file mode 100644 index cfc419a6ea..0000000000 --- a/console/konsolekalendar/konsolekalendarvariables.h +++ /dev/null @@ -1,467 +0,0 @@ -/******************************************************************************* - * konsolekalendarvariables.h * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ - -#ifndef _KONSOLEKALENDARVARIABLES_H_ -#define _KONSOLEKALENDARVARIABLES_H_ - -#include -#include -#include -#include -#include - -#include -#include - -/** - * @file konsolekalendarvariables.h - * Provides the KonsoleKalendarVariables class definition. - */ - -namespace KCal -{ - /** - * ExportType is the type of Export output - */ - enum ExportType - { - /** Export none */ - ExportTypeNone, - /** Export as text (default) */ - ExportTypeText, - /** Export as compact text */ - ExportTypeTextShort, - /** Export HTML for the specified time span */ - ExportTypeHTML, - /** Export HTML for the time span on month boundaries */ - ExportTypeMonthHTML, - /** Export XHTML (NOT AVAILABLE YET) */ - ExportTypeXHTML, - /** Export XML (NOT AVAILABLE YET) */ - ExportTypeXML, - /** Export Comma-Separated Values */ - ExportTypeCSV, - /** Export VCard (NOT AVAILABLE YET) */ - ExportTypeVCard - }; - - /** - * This class provides all the variables for the program. - * @author Tuukka Pasanen - * @author Allen Winter - */ - class KonsoleKalendarVariables - { - public: - /** - * Construct an empty KonsoleKalendarVariables object. - */ - KonsoleKalendarVariables(); - /** - * Destructor - */ - ~KonsoleKalendarVariables(); - - /** - * Set switch to use Events. - * @param useEvents if true, operation uses Events. - */ - void setUseEvents( bool useEvents ); - /** - * Get use Events switch. - * @return true if operation using Events is specified. - */ - bool getUseEvents(); - - /** - * Set switch to use Todos. - * @param useTodos if true, operation uses Todos. - */ - void setUseTodos( bool useTodos ); - /** - * Get use Todos switch. - * @return true if operation using Todos is specified. - */ - bool getUseTodos(); - - /** - * Set switch to use Journals. - * @param useJournals if true, operation uses Journals. - */ - void setUseJournals( bool useJournals ); - /** - * Get use Journals switch. - * @return true if operation using Journals is specified. - */ - bool getUseJournals(); - - /** - * Sets start date. - * @param start is the start date. - */ - void setStartDateTime( QDateTime start ); - - /** - * Get start date. - * @return start date. - */ - QDateTime getStartDateTime(); - - /** - * Is there start date? - * @return true if there is false is there isn't. - */ - bool isStartDateTime(); - - /** - * Sets end date. - * @param end is the enddate. - */ - void setEndDateTime( QDateTime end ); - - /** - * Get end date. - * @return end date. - */ - QDateTime getEndDateTime(); - - /** - * Is there end date? - * @return true if there is false is there isn't. - */ - bool isEndDateTime(); - - /** - * Sets the timezone from the user or system environment. - */ - void setTimeZoneId(); - - /** - * Get timezone id string. - * @return timezone id string. - */ - QString getTimeZoneId(); - - /** - * Is there a timezone set? - * @return true if there is false if there isn't. - */ - bool isTimeZoneId(); - - /** - * Sets the UID, the unique tag for VCard entry. - * @param uid unique tag for VCard entry. - */ - void setUID( QString uid ); - - /** - * Get UID, the unique tag for VCard entry. - * @return UID number. - */ - QString getUID(); - - /** - * Is there UID set? - * @return true there is UID false there isn't. - */ - bool isUID(); - - /** - * Show only next activity and exit. - * @param next true or false. - */ - void setNext( bool next ); - - /** - * Should we show only next activity and exit? - */ - bool isNext(); - - /** - * Should program be more verbose? - * @param verbose a flag to set verbosity. - */ - void setVerbose( bool verbose ); - - /** - * Should program be more verbose? - */ - bool isVerbose(); - - /** - * Should we only try to run it and do nothing? - * @param dryrun false no and true just test it. - */ - void setDryRun( bool dryrun ); - - /** - * Is this program only in testing mode? - * @return true yes false no. - */ - bool isDryRun(); - - /** - * Set calendar file (Kinda obsolete!) - * @param calendar Calendar files full path. - */ - void setCalendarFile( QString calendar ); - - /** - * Returns fullpath to calendar file. - * @return calendar file. - */ - QString getCalendarFile(); - - /** - * Set file to import active calendar. - * @param calendar Calendar file to import. - */ - void setImportFile( QString calendar ); - - /** - * Return import filename. - * @return File that should be imported. - */ - QString getImportFile(); - - /** - * Add description. - * @param description to event. - */ - void setDescription( QString description ); - - /** - * Return description. - * @return description of event. - */ - QString getDescription(); - - /** - * Is there an event description? - * @return true is there is description false there isn't. - */ - bool isDescription(); - - /** - * Add location information. - * @param location location where the event occurs. - */ - void setLocation( QString location ); - - /** - * Return location information. - * @return location where event is occurring. - */ - QString getLocation(); - - /** - * Is there event location information available? - * @return true is there is description false there isn't. - */ - bool isLocation(); - - /** - * Add summary. - * @param summary event summary. - */ - void setSummary( QString summary ); - - /** - * Get summary. - * @return summary. - */ - QString getSummary(); - - /** - * Is there an event summary? - * @return true there is false there isn't. - */ - bool isSummary(); - - /** - * View all option. - * @param all flag to view all Events. - */ - void setAll( bool all ); - /** - * Return all option. - */ - bool getAll(); - /** - * Is the all option set? - */ - bool isAll(); - - /** - * Set if Event is floating. - * @param floating if true then the Event is floating. - */ - void setFloating( bool floating ); - /** - * Return if Event is floating. - */ - bool getFloating(); - - /** - * Set is calendar default resource. - */ - void setDefault( bool def ); - - /** - * Return if calendar is default resource. - */ - bool isDefault(); - - /** - * Set calendar file for global use. - */ - - void setCalendar( CalendarLocal *calendar ); - - /** - * Get global calendar. - */ - - CalendarLocal *getCalendar(); - - /** - * Set output file. - */ - void setExportFile( QString export_file ); - - /** - * To what file we'll output. - */ - QString getExportFile(); - - /** - * Has an Export File been set? - */ - bool isExportFile(); - - /** - * Set export type that'll we use. - */ - void setExportType( ExportType exportType ); - - /** - * What export type to use. - */ - ExportType getExportType(); - - /** - * Do we use CalendarResources or LocalCalendar? - */ - bool isCalendarResources(); - - /** - * Add to Calendar Resources. - */ - CalendarResourceManager *getCalendarResourceManager(); - - /** - * Add to Calendar Resources. - */ - bool addCalendarResources( ResourceCalendar *cal ); - - /** - * Calendar resource is the new way. - */ - void setCalendarResources( CalendarResources *resource ); - - /** - * Calendar resource is the new way. - */ - CalendarResources *getCalendarResources(); - - /** - * Loads calendar resources. - */ - bool loadCalendarResources( KConfig *config ); - - /** - * Set how many day should be seen. - */ - - void setDaysCount( int count ); - - /** - * Is there some cound of days should be seen. - */ - bool isDaysCount(); - - /** - * Get how many day should be seen. - */ - - int getDaysCount(); - - private: - bool m_bIsTimeZoneId; - QString m_TimeZoneId; - QDateTime m_startDateTime; - QDateTime m_endDateTime; - bool m_bIsStartDateTime; - bool m_bIsEndDateTime; - QString m_calendar; - QString m_import; - QString m_description; - QString m_location; - QString m_summary; - QString m_export_file; - QString m_UID; - bool m_bUseEvents; - bool m_bUseTodos; - bool m_bUseJournals; - bool m_bSummary; - bool m_bNext; - bool m_bVerbose; - bool m_bDryRun; - bool m_bAll; - bool m_bDescription; - bool m_bLocation; - bool m_bFloating; - bool m_bDaysCount; - bool m_bIsUID; - int str_length; - ExportType m_exportType; - int m_daysCount; - QString m_exportFile; - bool m_bIsExportFile; - bool m_bIsDefault; - bool m_bIsCalendarResources; - // New resource stuff will over-ride old pne - CalendarResources *m_resource; - // We can use this from everywhere - CalendarLocal *m_calendarLocal; - Event::List m_eventList; - Todo::List m_todoList; - }; - -} - -#endif diff --git a/console/konsolekalendar/main.cpp b/console/konsolekalendar/main.cpp deleted file mode 100644 index f2198449b4..0000000000 --- a/console/konsolekalendar/main.cpp +++ /dev/null @@ -1,976 +0,0 @@ -/******************************************************************************* - * main.cpp * - * * - * KonsoleKalendar is a command line interface to KDE calendars * - * Copyright (C) 2002-2004 Tuukka Pasanen * - * Copyright (C) 2003-2005 Allen Winter * - * * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * - * * - ******************************************************************************/ -/** - * @file main.cpp - * KonsoleKalendar main program. - * @author Tuukka Pasanen - * @author Allen Winter - */ -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#if TIME_WITH_SYS_TIME -# include -# include -#else -# if HAVE_SYS_TIME_H -# include -# else -# include -# endif -#endif - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -#include -#include - -#include "konsolekalendar.h" -#include "konsolekalendarepoch.h" - -#include "konsolekalendarvariables.h" - -using namespace KCal; -using namespace std; - -static const char progName[] = "konsolekalendar"; -static const char progDisplay[] = "KonsoleKalendar"; -static const char progVersion[] = "1.3.5"; -static const char progDesc[] = "A command line interface to KDE calendars"; -static const char progURL[] = "pim.kde.org/components/konsolekalendar.php"; - - -static KCmdLineOptions options[] = -{ - { "verbose", - I18N_NOOP( "Print helpful runtime messages" ), 0 }, - { "dry-run", - I18N_NOOP( "Print what would have been done, but do not execute" ), 0 }, - { "file ", - I18N_NOOP( "Specify which calendar you want to use" ), 0 }, - - { ":", - I18N_NOOP( "Incidence types (these options can be combined):" ), 0 }, - { "event", - I18N_NOOP( " Operate for Events only (Default)" ), 0 }, - { "todo", - I18N_NOOP( " Operate for To-dos only [NOT WORKING YET]" ), 0 }, - { "journal", - I18N_NOOP( " Operate for Journals only [NOT WORKING YET]" ), 0 }, - - { ":", - I18N_NOOP( "Major operation modes:" ), 0 }, - { "view", - I18N_NOOP( " Print incidences in specified export format" ), 0 }, - { "add", - I18N_NOOP( " Insert an incidence into the calendar" ), 0 }, - { "change", - I18N_NOOP( " Modify an existing incidence" ), 0 }, - { "delete", - I18N_NOOP( " Remove an existing incidence" ), 0 }, - { "create", - I18N_NOOP( " Create new calendar file if one does not exist" ), 0 }, - { "import ", - I18N_NOOP( " Import this calendar to main calendar" ), 0 }, - { ":", - I18N_NOOP( "Operation modifiers:" ), 0 }, - { "all", - I18N_NOOP( " View all calendar entries" ), 0 }, - { "next", - I18N_NOOP( " View next activity in calendar" ), 0 }, - { "show-next ", - I18N_NOOP( " From start date show next # days' activities" ), 0 }, - { "uid ", - I18N_NOOP( " Incidence Unique-string identifier" ), 0 }, - { "date ", - I18N_NOOP( " Start from this day [YYYY-MM-DD]" ), 0 }, - { "time ", - I18N_NOOP( " Start from this time [HH:MM:SS]" ), 0 }, - { "end-date ", - I18N_NOOP( " End at this day [YYYY-MM-DD]" ), 0 }, - { "end-time ", - I18N_NOOP( " End at this time [HH:MM:SS]" ), 0 }, - { "epoch-start ", - I18N_NOOP( " Start from this time [secs since epoch]" ), 0 }, - { "epoch-end ", - I18N_NOOP( " End at this time [secs since epoch]" ), 0 }, - { "summary ", - I18N_NOOP( " Add summary to incidence (for add/change modes)" ), 0 }, - { "description ", - I18N_NOOP( "Add description to incidence (for add/change modes)" ), 0 }, - { "location ", - I18N_NOOP( " Add location to incidence (for add/change modes)" ), 0 }, - - { ":", I18N_NOOP( "Export options:" ), 0 }, - { "export-type ", - I18N_NOOP( "Export file type (Default: text)" ), 0 }, - { "export-file ", - I18N_NOOP( "Export to file (Default: stdout)" ), 0 }, - { "export-list", - I18N_NOOP( " Print list of export types supported and exit" ), 0 }, - - { "", - I18N_NOOP( "Examples:\n" - " konsolekalendar --view\n" - " konsolekalendar --add --date 2003-06-04 " - "--time 10:00 --end-time 12:00 \\\n" - " --summary \"Doctor Visit\" " - "--description \"Get My Head Examined\"\n" - " konsolekalendar --delete --uid KOrganizer-1740326.803" ), 0 }, - - { "", - I18N_NOOP( "For more information visit the program home page at:\n" - " http://pim.kde.org/components/konsolekalendar.php" ), 0 }, - - KCmdLineLastOption -}; - -int main( int argc, char *argv[] ) -{ - KAboutData aboutData( - progName, // internal program name - I18N_NOOP( progDisplay ), // displayable program name. - progVersion, // version string - I18N_NOOP( progDesc ), // short porgram description - KAboutData::License_GPL, // license type - "(c) 2002-2005, Tuukka Pasanen and Allen Winter", // copyright statement - 0, // any free form text - progURL, // program home page address - "bugs.kde.org" // bug report email address - ); - - aboutData.addAuthor( - "Tuukka Pasanen", // developer's name - I18N_NOOP( "Primary Author" ), // task or role - "illuusio@mailcity.com", // email address - 0 // home page or relevant link - ); - aboutData.addAuthor( - "Allen Winter", // developer's name - I18N_NOOP( "Author" ), // task or role - "winter@kde.org", // email address - 0 // home page or relevant link - ); - - - - // KCmdLineArgs::init() final 'true' argument indicates no commandline options - // for QApplication/KApplication (no KDE or Qt options) - KCmdLineArgs::init( argc, argv, &aboutData, true ); - KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. - - KInstance ins( progName ); - -// Replace the KApplication call below with the three lines above -// will make this a pure non-GUI application -// -- thanks for the info Stephan Kulow. - -// KApplication app( -// false, //do not allowstyles - disable the loading on plugin based styles -// false //GUI is not enabled - disable all GUI stuff -// ); - - KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); - - // Default values for start date/time (today at 07:00) - QDate startdate = QDate::currentDate(); - QTime starttime( 7, 0 ); - - // Default values for end date/time (today at 17:00) - QDate enddate = QDate::currentDate(); - QTime endtime( 17, 0 ); - - // Default values for switches - bool view = true; - bool add = false; - bool change = false; - bool del = false; - bool create = false; - bool calendarFile = false; - bool importFile = false; - - QString option; - - KonsoleKalendarVariables variables; - KonsoleKalendarEpoch epochs; - - variables.setFloating( false ); // by default, new events do NOT float - - if ( args->isSet( "verbose" ) ) { - variables.setVerbose( true ); - } - - if ( args->isSet( "dry-run" ) ) { - variables.setDryRun( true ); - } - - /* - * Switch on export list - */ - if ( args->isSet( "export-list" ) ) { - cout << endl; - cout << i18n( "%1 supports these export formats:" ). - arg( progDisplay ).local8Bit() - << endl; - cout << i18n( " %1 [Default]" ). - arg( "Text" ).local8Bit() - << endl; - cout << i18n( " %1 (like %2, but more compact)" ). - arg( "Short", "Text" ).local8Bit() - << endl; - cout << i18n( " %1" ). - arg( "HTML" ).local8Bit() - << endl; - cout << i18n( " %1 (like %2, but in a month view)" ). - arg( "HTMLmonth", "HTML" ).local8Bit() - << endl; - cout << i18n( " %1 (Comma-Separated Values)" ). - arg( "CSV" ).local8Bit() - << endl; - cout << endl; - return 0; - } - - /* - * Set incidence type(s) - */ - if ( args->isSet( "event" ) ) { - variables.setUseEvents( true ); - kdDebug() << "main | parse options | use Events" << endl; - } - if ( args->isSet( "todo" ) ) { - variables.setUseTodos( true ); - kdDebug() << "main | parse options | use To-dos" << endl; - cout << i18n( "Sorry, To-dos are not working yet." ).local8Bit() - << endl; - return 1; - } - if ( args->isSet( "journal" ) ) { - variables.setUseJournals( true ); - kdDebug() << "main | parse options | use Journals" << endl; - cout << i18n( "Sorry, Journals are not working yet." ).local8Bit() - << endl; - return 1; - } - // Use Events if no incidence type is specified on the command line - if ( !args->isSet( "event" ) && - !args->isSet( "todo" ) && - !args->isSet( "journal" ) ) { - variables.setUseEvents( true ); - kdDebug() << "main | parse options | use Events (Default)" << endl; - } - - /* - * Switch on exporting - */ - variables.setExportType( ExportTypeText ); - if ( args->isSet( "export-type" ) ) { - option = args->getOption( "export-type" ); - - if ( option.upper() == "HTML" ) { - kdDebug() << "main | export-type | Export to HTML" << endl; - variables.setExportType( ExportTypeHTML ); - } else if ( option.upper() == "HTMLMONTH" ) { - kdDebug() << "main | export-type | Export to HTML by Month" << endl; - variables.setExportType( ExportTypeMonthHTML ); - } else if ( option.upper() == "CSV" ) { - kdDebug() << "main | export-type | Export to CSV" << endl; - variables.setExportType( ExportTypeCSV ); - } else if ( option.upper() == "TEXT" ) { - kdDebug() << "main | export-type | Export to TEXT (default)" << endl; - variables.setExportType( ExportTypeText ); - } else if ( option.upper() == "SHORT" ) { - kdDebug() << "main | export-type | Export to TEXT-SHORT" << endl; - variables.setExportType( ExportTypeTextShort ); - } else { - cout << i18n( "Invalid Export Type Specified: %1" ). - arg( option ).local8Bit() - << endl; - return 1; - } - } - - /* - * Switch on export file name - */ - if ( args->isSet( "export-file" ) ) { - option = args->getOption( "export-file" ); - - kdDebug() << "main | parse options | " - << "Export File: " - << "(" << option << ")" - << endl; - - variables.setExportFile( option ); - } - - /* - * Switch on View (Print Entries). This is the default mode of operation. - */ - if ( args->isSet( "view" ) ) { - view = true; - - kdDebug() << "main | parse options | " - << "Mode: (Print incidences)" - << endl; - } - - /* - * Switch on Add (Insert Entry) - */ - if ( args->isSet( "add" ) ) { - view = false; - add = true; - - kdDebug() << "main | parse options | " - << "Mode: (Add incidence)" - << endl; - } - - /* - * Switch on Change (Modify Entry) - */ - if ( args->isSet( "change" ) ) { - view = false; - change = true; - - kdDebug() << "main | parse options | " - << "Mode: (Change incidence)" - << endl; - } - - /* - * Switch on Delete (Remove Entry) - */ - if ( args->isSet( "delete" ) ) { - view = false; - del = true; - - kdDebug() << "main | parse options | " - << "Mode: (Delete incidence)" - << endl; - } - - /* - * Switch on Create - */ - if ( args->isSet( "create" ) ) { - view = false; - create = true; - - kdDebug() << "main | parse options | " - << "Calendar File: (Create)" - << endl; - } - - /* - * If there is summary attached. - */ - if ( args->isSet( "summary" ) ) { - option = args->getOption( "summary" ); - - kdDebug() << "main | parse options | " - << "Summary: " - << "(" << option << ")" - << endl; - - variables.setSummary( option ); - } - - /* - * If there is description attached. - */ - if ( args->isSet( "description" ) ) { - option = args->getOption( "description" ); - - kdDebug() << "main | parse options | " - << "Description: " - << "(" << option << ")" - << endl; - - variables.setDescription( option ); - } - - /* - * If there is location information - */ - if ( args->isSet( "location" ) ) { - option = args->getOption( "location" ); - - kdDebug() << "main | parse options | " - << "Location: " - << "(" << option << ")" - << endl; - - variables.setLocation( option ); - } - - /* - * Show next happening and exit - */ - if ( args->isSet( "next" ) ) { - kdDebug() << "main | parse options | " - << "Show next incidence only" - << endl; - - variables.setNext( true ); - } - - /* - * Set incidence unique string identifier - */ - if ( args->isSet( "uid" ) ) { - option = args->getOption( "uid" ); - - kdDebug() << "main | parse options | " - << "incidence UID: " - << "(" << option << ")" - << endl; - - variables.setUID( option ); - } - - /* - * Set starting date for calendar - */ - if ( args->isSet( "date" ) ) { - option = args->getOption( "date" ); - - kdDebug() << "main | parse options | " - << "Start date before conversion: " - << "(" << option << ")" - << endl; - - startdate = QDate::fromString( option, Qt::ISODate ); - if ( !startdate.isValid() ) { - cout << i18n( "Invalid Start Date Specified: %1" ). - arg( option ).local8Bit() - << endl; - return 1; - } - kdDebug() << "main | parse options | " - << "Start date after conversion: " - << "(" << startdate.toString() << ")" - << endl; - } - - /* - * Set starting time - */ - if ( args->isSet( "time" ) ) { - option = args->getOption( "time" ); - - kdDebug() << "main | parse options | " - << "Start time before conversion : " - << "(" << option << ")" - << endl; - - if ( option.upper() != "FLOAT" ) { - starttime = QTime::fromString( option, Qt::ISODate ); - if ( !starttime.isValid() ) { - cout << i18n( "Invalid Start Time Specified: %1" ). - arg( option ).local8Bit() - << endl; - return 1; - } - kdDebug() << "main | parse options | " - << "Start time after conversion: " - << "(" << starttime.toString() << ")" - << endl; - } else { - variables.setFloating( true ); - kdDebug() << "main | parse options | " - << "Floating event time specified" - << endl; - } - } - - /* - * Set end date for calendar - */ - if ( args->isSet( "end-date" ) ) { - QString option = args->getOption( "end-date" ); - - kdDebug() << "main | parse options | " - << "End date before conversion: " - << "(" << option << ")" - << endl; - - enddate = QDate::fromString( option, Qt::ISODate ); - if ( !enddate.isValid() ) { - cout << i18n( "Invalid End Date Specified: %1" ). - arg( option ).local8Bit() - << endl; - return 1; - } - kdDebug() << "main | parse options | " - << "End date after conversion: " - << "(" << enddate.toString() << ")" - << endl; - } - - /* - * Show next # days and exit - */ - if ( args->isSet( "show-next" ) ) { - bool ok; - - option = args->getOption( "show-next" ); - kdDebug() << "main | parse options | " - << "Show " << option << " days ahead" - << endl; - variables.setDaysCount( option.toInt( &ok, 10 ) ); - - if ( !ok ) { - cout << i18n( "Invalid Date Count Specified: %1" ). - arg( option ).local8Bit() - << endl; - return 1; - } - - enddate = startdate; - enddate = enddate.addDays( variables.getDaysCount() ); - kdDebug() << "main | parse options | " - << "End date after conversion: " - << "(" << enddate.toString() << ")" - << endl; - } - - /* - * Set ending time - */ - if ( args->isSet( "end-time" ) ) { - option = args->getOption( "end-time" ); - - kdDebug() << "main | parse options | " - << "End time before conversion: " - << "(" << option << ")" - << endl; - - if ( option.upper() != "FLOAT" ) { - endtime = QTime::fromString( option, Qt::ISODate ); - if ( !endtime.isValid() ) { - cout << i18n( "Invalid End Time Specified: %1" ). - arg( option ).local8Bit() - << endl; - return 1; - } - - kdDebug() << "main | parse options | " - << "End time after conversion: " - << "(" << endtime.toString() << ")" - << endl; - } else { - variables.setFloating( true ); - kdDebug() << "main | parse options | " - << "Floating event time specified" - << endl; - } - } - - /* - * Set start date/time from epoch - */ - time_t epochstart = 0; - if ( args->isSet( "epoch-start" ) ) { - option = args->getOption( "epoch-start" ); - - kdDebug() << "main | parse options | " - << "Epoch start: " - << "(" << option << ")" - << endl; - - epochstart = ( time_t ) option.toULong( 0, 10 ); - } - - /* - * Set end date/time from epoch - */ - time_t epochend = 0; - if ( args->isSet( "epoch-end" ) ) { - option = args->getOption( "epoch-end" ); - - kdDebug() << "main | parse options | " - << "Epoch end: " - << "(" << option << ")" - << endl; - - epochend = ( time_t ) option.toULong( 0, 10 ); - } - - if ( args->isSet( "all" ) ) { - variables.setAll( true ); - } else { - variables.setAll( false ); - } - - if ( args->isSet( "import" ) ) { - view = false; - importFile = true; - option = args->getOption( "import" ); - variables.setImportFile( option ); - - kdDebug() << "main | parse options | " - << "importing file from: " - << "(" << option << ")" - << endl; - } - - KonsoleKalendar *konsolekalendar = new KonsoleKalendar( &variables ); - - if ( args->isSet( "file" ) ) { - calendarFile = true; - option = args->getOption( "file" ); - variables.setCalendarFile( option ); - - /* - * All modes need to know if the calendar file exists - * This must be done before we get to opening biz - */ - bool exists = QFile::exists( variables.getCalendarFile() ); - - if ( create ) { - - kdDebug() << "main | createcalendar | " - << "check if calendar file already exists" - << endl; - - if ( exists ) { - cout << i18n( "Calendar %1 already exists" ). - arg( variables.getCalendarFile() ).local8Bit() - << endl; - return 1; - } - if ( konsolekalendar->createCalendar() ) { - cout << i18n( "Calendar %1 successfully created" ). - arg( variables.getCalendarFile() ).local8Bit() - << endl; - return 0; - } else { - cout << i18n( "Unable to create calendar: %1" ). - arg( variables.getCalendarFile() ).local8Bit() - << endl; - return 1; - } - } - - if ( !exists ) { - cout << i18n( "Calendar file not found %1" ). - arg( option ).local8Bit() - << endl; - cout << i18n( "Try --create to create new calendar file" ).local8Bit() - << endl; - return 1; - } - } - - CalendarResources *calendarResource = NULL; - CalendarLocal *localCalendar = NULL; - - /* - * Should we use local calendar or resource? - */ - variables.setTimeZoneId(); - if ( args->isSet( "file" ) ) { - localCalendar = new CalendarLocal( variables.getTimeZoneId() ); - localCalendar->load( variables.getCalendarFile() ); - variables.setCalendar( localCalendar ); - } else { - calendarResource = new CalendarResources( variables.getTimeZoneId() ); - calendarResource->readConfig(); - calendarResource->load(); - variables.setCalendarResources( calendarResource ); - } - - /*************************************************************************** - * Glorious date/time checking and setting code * - ***************************************************************************/ - QDateTime startdatetime, enddatetime; - - // Handle case with either date or end-date unspecified - if ( !args->isSet( "end-date" ) && !args->isSet( "show-next" ) && - args->isSet( "date" ) ) { - enddate = startdate; - kdDebug() << "main | datetimestamp | " - << "setting enddate to startdate" - << endl; - } else if ( args->isSet( "end-date" ) && !args->isSet( "date" ) ) { - startdate = enddate; - kdDebug() << "main | datetimestamp | " - << "setting startdate to enddate" - << endl; - } - - // NOTE: If neither date nor end-date specified, then event will be today. - - // Case: - // End time (or epoch) unspecified, and start time (or epoch) IS specified. - // In this case, set the ending to 1 hour after starting. - if ( !args->isSet( "end-time" ) && !args->isSet( "epoch-end" ) ) { - if ( args->isSet( "time" ) ) { - endtime = starttime.addSecs( 60 * 60 ); // end is 1 hour after start - kdDebug() << "main | datetimestamp | " - << "setting endtime 1 hour after starttime" - << endl; - } else if ( args->isSet( "epoch-start" ) ) { - startdatetime = epochs.epoch2QDateTime( epochstart ); - enddatetime = startdatetime.addSecs( 60 * 60 ); - kdDebug() << "main | datetimestamp | " - << "setting endtime 1 hour after epochstart" - << endl; - } - } - - // Case: - // Time (or epoch) unspecified, and end-time (or epoch) IS specified. - // In this case, set the starting to 1 hour before ending. - if ( !args->isSet( "time" ) && !args->isSet( "epoch-start" ) ) { - if ( args->isSet( "end-time" ) ) { - starttime = endtime.addSecs( -60 * 60 ); // start is 1 hour before end - kdDebug() << "main | datetimestamp | " - << "setting starttime 1 hour before endtime" - << endl; - } else if ( args->isSet( "epoch-end" ) ) { - enddatetime = epochs.epoch2QDateTime( epochend ); - startdatetime = enddatetime.addSecs( -60 * 60 ); - kdDebug() << "main | datetimestamp | " - << "setting starttime 1 before after epochend" - << endl; - } - } - - // Case: - // Time (or epoch) unspecified, and end-time (or epoch) unspecified. - if ( !args->isSet( "time" ) && !args->isSet( "epoch-start" ) && - !args->isSet( "end-time" ) && !args->isSet( "epoch-end" ) ) { - // set default start date/time - startdatetime = QDateTime::QDateTime( startdate, starttime ); - kdDebug() << "main | datetimestamp | " - << "setting startdatetime from " - << "default startdate (today) and starttime" - << endl; - // set default end date/time - enddatetime = QDateTime::QDateTime( enddate, endtime ); - kdDebug() << "main | datetimestamp | " - << "setting enddatetime from " - << "default enddate (today) and endtime" - << endl; - } - - // Set startdatetime, enddatetime if still necessary - if ( startdatetime.isNull() ) { - startdatetime = QDateTime::QDateTime( startdate, starttime ); - kdDebug() << "main | datetimestamp | " - << "setting startdatetime from startdate and starttime" - << endl; - } - if ( enddatetime.isNull() ) { - enddatetime = QDateTime::QDateTime( enddate, endtime ); - kdDebug() << "main | datetimestamp | " - << "setting enddatetime from enddate and endtime" - << endl; - } - - // Float check for add mode: - // Events float if time AND end-time AND epoch times are UNspecified - if ( add ) { - if ( !args->isSet( "time" ) && !args->isSet( "end-time" ) && - !args->isSet( "epoch-start" ) && !args->isSet( "epoch-end" ) ) { - variables.setFloating( true ); - kdDebug() << "main | floatingcheck | " - << "turn-on floating event" - << endl; - } - } - - // Finally! Set the start/end date times - if ( !change ) { - variables.setStartDateTime( startdatetime ); - variables.setEndDateTime( enddatetime ); - } else { - // Do NOT set start/end datetimes in change mode, - // unless they were specified on commandline - if ( args->isSet( "time" ) || args->isSet( "epoch-start" ) || - args->isSet( "end-time" ) || args->isSet( "epoch-end" ) ) { - variables.setStartDateTime( startdatetime ); - variables.setEndDateTime( enddatetime ); - } - } - - // Some more debug prints - kdDebug() << "main | datetimestamp | StartDate=" - << startdatetime.toString( Qt::TextDate ) - << endl; - kdDebug() << "main | datetimestamp | EndDate=" - << enddatetime.toString( Qt::TextDate ) - << endl; - - /*************************************************************************** - * Sanity checks * - ***************************************************************************/ - - // Cannot combine modes - if ( create + view + add + change + del > 1 ) { - cout << i18n( - "Only 1 operation mode " - "(view, add, change, delete, create) " - "permitted at any one time" - ).local8Bit() << endl; - return 1; - } - - // Cannot have a ending before starting - if ( startdatetime > enddatetime ) { - cout << i18n( - "Ending Date/Time occurs before the Starting Date/Time" - ).local8Bit() << endl; - return 1; - } - - /*************************************************************************** - * And away we go with the real work... * - ***************************************************************************/ - - args->clear(); // Free up some memory. - - /* - * Set our application name for use in unique IDs and error messages, - * and product ID for incidence PRODID property - */ - QString prodId = "-//K Desktop Environment//NONSGML %1 %2//EN"; - CalFormat::setApplication( progDisplay, - prodId.arg( progDisplay ).arg( progVersion ) ); - - if ( importFile ) { - if ( konsolekalendar->importCalendar() ) { - cout << i18n( "Calendar %1 successfully imported" ). - arg( variables.getImportFile() ).local8Bit() - << endl; - return 0; - } else { - cout << i18n( "Unable to import calendar: %1" ). - arg( variables.getImportFile() ).local8Bit() - << endl; - return 1; - } - } - - if ( add ) { - if ( !konsolekalendar->isEvent( startdatetime, enddatetime, - variables.getSummary() ) ) { - kdDebug() << "main | modework | " - << "calling addEvent()" - << endl; - konsolekalendar->addEvent(); - } else { - cout << i18n( - "Attempting to insert an event that already exists" - ).local8Bit() << endl; - return 1; - } - } - - if ( change ) { - kdDebug() << "main | modework | " - << "calling changeEvent()" - << endl; - if ( !variables.isUID() ) { - cout << i18n( "Missing event UID: " - "use --uid command line option" ).local8Bit() - << endl; - return 1; - } - if ( konsolekalendar->changeEvent() != true ) { - cout << i18n( "No such event UID: change event failed" ).local8Bit() - << endl; - return 1; - } - kdDebug() << "main | modework | " - << "successful changeEvent()" - << endl; - } - - if ( del ) { - kdDebug() << "main | modework | " - << "calling deleteEvent()" - << endl; - if ( !variables.isUID() ) { - cout << i18n( "Missing event UID: " - "use --uid command line option" ).local8Bit() - << endl; - return 1; - } - if ( konsolekalendar->deleteEvent() != true ) { - cout << i18n( "No such event UID: delete event failed").local8Bit() - << endl; - return 1; - } - kdDebug() << "main | modework | " - << "successful deleteEvent()" - << endl; - } - - if ( view ) { - kdDebug() << "main | modework | " - << "calling showInstance() to view events" - << endl; - if ( !konsolekalendar->showInstance() ) { - cout << i18n( "Cannot open specified export file: %1" ). - arg( variables.getExportFile() ).local8Bit() - << endl; - return 1; - } - } - - delete konsolekalendar; - - if ( calendarFile ) { - localCalendar->close(); - delete localCalendar; - } else { - calendarResource->close(); - delete calendarResource; - } - - kdDebug() << "main | exiting" - << endl; - - return 0; -} diff --git a/doc/kjots/Makefile.am b/doc/kjots/Makefile.am deleted file mode 100644 index 085981d9b0..0000000000 --- a/doc/kjots/Makefile.am +++ /dev/null @@ -1,4 +0,0 @@ - -KDE_LANG = en -KDE_DOCS = AUTO - diff --git a/doc/kjots/index.docbook b/doc/kjots/index.docbook deleted file mode 100644 index 78e5620775..0000000000 --- a/doc/kjots/index.docbook +++ /dev/null @@ -1,552 +0,0 @@ - - - - - - -]> - - - -The &kjots; Handbook - - - -Matt -Johnston - -
matt.kde@caifex.org
-
-
- - -Christoph -Neerfield - -
Christoph.Neerfield@home.ivm.de
-
-Developer -
- - -Lauri -Watts - -
lauri@kde.org
-
-Reviewer -
- - -
- - -2000 -Matt Johnston - - -&FDLNotice; - -2004-10-17 -0.05.00 - -This handbook describes how to use &kjots; 0.5, a small -program which is handy for keeping miscellaneous -notes. - - -KDE -KJots -kdeutils -notes -organizer - - -
- - -Introduction - -&kjots; is a small program that helps you to write down some short -notes and organizes them for you. - - - - -Using &kjots; - -&kjots; has two basic items used to organize your notes - -Books and Pages. - -You can create a number of books in &kjots;, and each book can -contain a number of pages, where you actually type your notes. Each book -should be given a name (so you can find what you are looking for), as -should each page. Although you aren't forced to give a page a name, it -is sensible to do so. - - -Using Books - -To create a new book, use &Ctrl;&Shift; -N or the menu entry -FileNew -Book, and you will be prompted to enter a -name for the new book. - -The name of the new book should now appear in the left part of -the window. If you want the book to be in your -Bookmarks, use &Ctrl; -B or the menu entry -BookmarksAdd Bookmark -. You can even organize your bookmarks in separate folders -just as you probably do in &konqueror;. - -If you want to have your books in a different order, you can -simply drag and drop the book to the place where you want it to be. - - -Maybe you have noticed that there is no Save anywhere. -This is not an error, &kjots; saves your books and pages automatically, -so you will never lose that small note you write when you are on the phone -and need to write down something in a hurry. - -You can also export an entire book as a text file or as a html file, -using File Export book... -. You will be then prompted to enter a -location for the file to be saved. The format of an example saved book -is shown below: - -############ -# First page -############ -Remember to go to the shops! - -############# -# Useful code -############# -10 PRINT "HELLO WORLD" -20 GOTO 10 - -################ -# The third page -################ -This is the third page and is an example for KJots. - -Remember that the dialog where you are prompted for a filename is -a standard &kde; dialog. That means it is just as easy to store the file -on your local hard disk as it is to save it on a web server, ftp server -or USB memory stick. So you can export as html and save it on a webserver, -this way you always have your notes available to you. - - - -Using Pages - -Pages are where you actually write whatever you are going to -write. Once you have created a book, you can type text in the main text -box. - -To create additional pages, you can use &Ctrl; -N or the menu entry -FileNew Page -, which will create a new page. Similarly, the current page -can be removed using File -Delete Page. - -If you need to insert the current date and time while you are -writing a note, you can use &Ctrl;I -. - -So that you can get to the page you want to see, pages can (and -should) be given a name. This can be done in the way you are used to: -select the page you want to rename, wait a second and click it once more. -You are then able to rename the page. Of course there is also a keyboard -shortcut, you can use that at any time while writing a note. The shortcut -is: &Ctrl;M. - -An other way of renaming the page is by selecting a part of your note -and then press &Ctrl;T, -the selected text will instantly become the title of the page. - -If you want fast access to a particular page, you -can assign a keyboard shortcut to that page. Go to -SettingsConfigure Shortcuts... -. - - - - -Command Reference - - -The <guimenu>File</guimenu> Menu - - - - - -&Ctrl;N - -File -New Page... - -Creates a new Page. - - - - - -&Ctrl;&Shift;N - -File -New Book... - -Creates a new Book. - - - - -File -Export Page - -Saves the current page to a text file -or a html file. - - - - -File -Export Book - -Saves the current book to a text file -or a html file. - - - - -File -Delete Page - -Deletes the current page. - - - - -File -Delete Book - -Deletes the current book. - - - - - -&Ctrl;P - -File -Print - -Prints the current book or page. - - - - - -&Ctrl;Q - -File -Quit - -Quits &kjots;. - - - - - -The <guimenu>Edit</guimenu> Menu - - - - - -&Ctrl;X - -Edit -Cut - -Cuts the currently selected -text in the main textbox and places it on the clipboard. - - - - - -&Ctrl;C - -Edit -Copy - -Copies the currently selected -text in the main textbox and places it on the clipboard. - - - - - -&Ctrl;V - -Edit -Paste - -Pastes text from the clipboard -to the main textbox. - - - - - -&Ctrl;T - -Edit -Paste as Page Title - -Renames the page to the text on the -clipboard. - - - - - -&Ctrl;F - -Edit -Find... - -Searches for text in the main -textbox. Note that this only searches the current page. - - - - - - -F3 - -Edit -Find Next - -Searches for the next occurrence -of the search text (specified with Find). - - - - - -&Ctrl;R - -Edit -Replace... - -Replaces one bit of text with another, -only on the current page. - - - - - - -&Ctrl;M - -Edit -Rename... - -Gives the possibility to rename the -current page. - - - - - -&Ctrl;I - -Edit -Insert Date - -Inserts the date and time in the -current page. - - - - - -The <guimenu>Bookmarks</guimenu> Menu - - - - - -&Ctrl;B - -Bookmarks -Add bookmark - -Adds the current page to the list of -bookmarks. See Using Books. - - - - - -Bookmarks -Edit bookmarks - -Edits the bookmarks. Here you can -search bookmarks, make comments, organize them in different folders and -much more. - - - - - -Bookmarks -New Bookmark Folder - -Makes a new folder where you can store -your bookmarks. - - - - - - -The <guimenu>Settings</guimenu> Menu - - - - -Settings -Hide/Show Toolbar - -Toggles display of the toolbar below the -menu bar. - - - - -Settings -Configure Shortcuts... - -Choose shortcut keys for various -menu items. - - - - -Settings -Configure Toolbars... - -Choose which items are present in the -toolbar. - - - - -Settings -Configure KJots... - -Configure options for &kjots;, including -the font to use and the settings for autosaving. - - - - - - - -The <guimenu>Help</guimenu> Menu - -&help.menu.documentation; - - - - - - - -Credits and License - - -&kjots; - - -Program copyright 1997 Christoph Neerfeld Christoph.Neerfeld@home.ivm.de - - -Based on the jots program included in the tkgoodstuff package. -The tkgoodstuff package is -copyright 1995-96 Mark Crimmins markcrim@umich.edu - - - -Documentation copyright 2000 Matt Johnston matt.kde@caifex.org - - -Some parts taken from documentation copyright 1998 Christoph Neerfeld -Christoph.Neerfeld@home.ivm.de - -&underFDL; - -&underGPL; - - - - -Installation - - -How to obtain &kjots; - -&install.intro.documentation; - - - - -Requirements - -In order to successfully use &kjots;, you need &kde; 2.x. There are -no other requirements. - - - - -Compilation and Installation - -&install.compile.documentation; - - - - -Configuration - -&kjots; is a nice small program, and you don't have do do anything -before running it. - - - - - -&documentation.index; -
- - diff --git a/karm/Makefile.am b/karm/Makefile.am index 9a2cf24b48..4aa0e0ca4c 100644 --- a/karm/Makefile.am +++ b/karm/Makefile.am @@ -1,44 +1,67 @@ ############ Autoconf-generated variables ################### INCLUDES = -I$(top_srcdir)/libkcal -I$(top_srcdir)/kresources/remote -I$(top_srcdir) $(all_includes) bin_PROGRAMS = karm SUBDIRS = support pics test METASOURCES = AUTO COMPILE_BEFORE_karm = libkdepim kresources -karm_SOURCES = kaccelmenuwatch.cpp main.cpp desktoptracker.cpp \ +noinst_LTLIBRARIES = libkarm_shared.la + +libkarm_shared_la_SOURCES = kaccelmenuwatch.cpp desktoptracker.cpp \ edittaskdialog.cpp idletimedetector.cpp \ printdialog.cpp timekard.cpp karmutility.cpp ktimewidget.cpp \ karmstorage.cpp mainwindow.cpp preferences.cpp print.cpp \ task.cpp taskview.cpp tray.cpp \ csvexportdialog_base.ui csvexportdialog.cpp plannerparser.cpp \ karmdcopiface.skel -karm_LDADD = -lkdeprint $(top_builddir)/libkcal/libkcal.la \ +libkarm_shared_la_LIBADD = -lkdeprint $(top_builddir)/libkcal/libkcal.la \ $(top_builddir)/kresources/remote/libkcal_resourceremote.la \ $(top_builddir)/libkdepim/libkdepim.la $(LIBXSS) +karm_SOURCES = main.cpp +karm_LDADD = libkarm_shared.la karm_LDFLAGS = $(all_libraries) $(KDE_RPATH) noinst_HEADERS = desktoptracker.h edittaskdialog.h printdialog.h \ idletimedetector.h kaccelmenuwatch.h timekard.h \ karmutility.h ktimewidget.h karmstorage.h mainwindow.h \ preferences.h print.h task.h taskview.h toolicons.h \ tray.h version.h csvexportdialog.h plannerparser.h KDE_ICON = karm rcdir = $(kde_datadir)/karm rc_DATA = karmui.rc install-data-local: uninstall.desktop $(mkinstalldirs) $(DESTDIR)$(kde_appsdir)/Utilities $(INSTALL_DATA) $(srcdir)/uninstall.desktop $(DESTDIR)$(kde_appsdir)/Utilities/karm.desktop messages: rc.cpp $(XGETTEXT) *.cpp -o $(podir)/karm.pot srcdoc: kdoc -a -p -H -d $(HOME)/web/src/karm karm *.h -lkdecore -lkdeui -lqt -include $(top_srcdir)/doc/api/Doxyfile.am +DOXYGEN_REFERENCES = kdeui +include $(top_srcdir)/admin/Doxyfile.am + +######################################################################### +# KPART SECTION +######################################################################### +kde_module_LTLIBRARIES = libkarmpart.la + +# the Part's source, library search path, and link libraries +libkarmpart_la_SOURCES = karm_part.cpp +libkarmpart_la_LDFLAGS = -module -avoid-version -no-undefined $(KDE_PLUGIN) $(all_libraries) +libkarmpart_la_LIBADD = libkarm_shared.la $(LIB_KPARTS) + +# this is where the desktop file will go +partdesktopdir = $(kde_servicesdir) +partdesktop_DATA = karm_part.desktop + +# this is where the part's XML-GUI resource file goes +partrcdir = $(kde_datadir)/karmpart +partrc_DATA = karmui.rc diff --git a/karm/TODO b/karm/TODO index 61673dc92e..12df8f5c65 100644 --- a/karm/TODO +++ b/karm/TODO @@ -1,70 +1,90 @@ -* KarmWindow::makeMenus -> export KAction? -* KarmWindow::contextMenuRequest QPopupMenu should be static! -* put connect( ..contextMenu at the right place -* mainwindow: move tray signals into tray.cpp -* add mouse double-click action (start new timer, stop old) to "Configure +* KarmWindow::makeMenus -> export KAction? KarmWindow::contextMenuRequest +* QPopupMenu should be static! put connect( ..contextMenu at the right place +* mainwindow: move tray signals into tray.cpp add mouse double-click action +* (start new timer, stop old) to "Configure Shortcuts" dialog. -Mark - Sooner ... --------------------------- +Mark - Sooner ... -------------------------- + + * 2005-05-24: Modify test scripts for change in dcop iface. + + * 2005-05-24: Update docs for new dcop methods. * 2003-09-24: Generate man page (look for script mentioned on kde-devel). * 2004-01-27: BUG: if save fails (b/c of permission failure) KArm does not give any feecback and proceeds as if there was no error. * 2003-09-17: BUG: entering a negative time increments total session time (maybe only if session time is zero?) -Mark - Later ... --------------------------- +Mark - Later ... -------------------------- * 2004-06-14: In file exports, check if QT has a function to give you a platform-specific end of line character. Right now, it is hard coded to a "\n" * 2003-08-15: Implement comments: VTODO COMMENT or DESCRIPTION? - Make sure wrapping works according to iCalendar spec. - Handle multiple comments against same VEVENT. - Show in history report. * 2004-01-27: Write dcop interface so time cards can be exported to other systems. * 2003-09-24: Change menu entry from KArm to Time Clock. * 2003-08-15: Go over code and delete all cruft. In particular, take a look at taskview.cpp. * 2003-09-26: Add totals table across entire date range. * 2003-09-19: If task active, editing task stops timer. Necessary? * 2003-08-15: When loading an empty ics file, ask user if they want to import a task list from another file. If they say no, then pop up the new task dialog. (TaskView::load). - * 2003-09-03: Use file menu and delete storeage page in preferences. + * 2003-09-03: Use file menu and delete storage page in preferences. * 2003-08-15: Add ability to import tasks from an iCalendar file. - TaskView::load() * 2003-09-26: On timecard report, don't print rows for tasks with zero hours unless a child task has hours logged (that is, show full tree for every task with time logged). * 2003-10-13: New event: publish time card. Mark events that are published as read-only. Create plug-in framework so that when this event occurs, we export to a different backend. Write plugins for GnuCash and SQL-Ledger. Hmmm ... or just write a sql calendar resource? -Wishlist: ---------- -* activeTasks should be cleaned up -* if two timers are active, associate a percentage with them, optimaly the +Wishlist: -------------------------- +* activeTasks should be cleaned up if two timers are active, associate a +* percentage with them, optimaly the percentage should be configurable -* completed % per task -* don't display competed tasks -* context menu in headers for choosing if one wants to see some column or not +* completed % per task don't display competed tasks context menu in headers +* for choosing if one wants to see some column or not + +Design Notes -------------------------- + +- Taskview mediates access to KarmStorage. That is one overzealous ListView + subclass! + +- The original code was written with the expectation that the user would be + starting and stopping timers. This perspective loses relevance when you + want book time with an arbitrary start and stop time. This impacts method + names and the arguments passed. For example, see KarmStorage bookTime + versus changeTime. Duplicate code, different method signatures. + +- How do deal with keeping gui responsive while saving data. Really should be + asynchronous. Then we have to be careful with race conditions; for example, + if an external fires a DCOP event while the user is stopping a time and we + have a really slow remote resource. + +- Add the dcop method bookTime, I originally forgot to increment the total time + counter on the task. This is a bad design--a proper task class would provide + an interface to log a history event and would increment the total time for + me. diff --git a/karm/cr128-app-karm.png b/karm/cr128-app-karm.png deleted file mode 100644 index a6fd4ebc0b..0000000000 Binary files a/karm/cr128-app-karm.png and /dev/null differ diff --git a/karm/cr16-app-karm.png b/karm/cr16-app-karm.png deleted file mode 100644 index 787527ce20..0000000000 Binary files a/karm/cr16-app-karm.png and /dev/null differ diff --git a/karm/cr32-app-karm.png b/karm/cr32-app-karm.png deleted file mode 100644 index 4d63947e59..0000000000 Binary files a/karm/cr32-app-karm.png and /dev/null differ diff --git a/karm/cr48-app-karm.png b/karm/cr48-app-karm.png deleted file mode 100644 index 9398a9e963..0000000000 Binary files a/karm/cr48-app-karm.png and /dev/null differ diff --git a/karm/cr64-app-karm.png b/karm/cr64-app-karm.png deleted file mode 100644 index 796dddfe55..0000000000 Binary files a/karm/cr64-app-karm.png and /dev/null differ diff --git a/karm/csvexportdialog.cpp b/karm/csvexportdialog.cpp index b8f521d44e..4a5536d400 100644 --- a/karm/csvexportdialog.cpp +++ b/karm/csvexportdialog.cpp @@ -1,107 +1,107 @@ /* * Copyright (C) 2004 Mark Bucciarelli * * 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. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ #include #include #include #include #include #include #include #include #include #include #include "csvexportdialog.h" #include "reportcriteria.h" CSVExportDialog::CSVExportDialog( ReportCriteria::REPORTTYPE rt, QWidget *parent, const char *name ) : CSVExportDialogBase( parent, name ) { switch ( rt ) { case ReportCriteria::CSVTotalsExport: grpDateRange->setEnabled( false ); grpDateRange->hide(); rc.reportType = rt; break; case ReportCriteria::CSVHistoryExport: grpDateRange->setEnabled( true ); rc.reportType = rt; break; default: break; } // If decimal symbol is a comma, then default field seperator to semi-colon. // In France and Germany, one-and-a-half is written as 1,5 not 1.5 QString d = KGlobal::locale()->decimalSymbol(); if ( "," == d ) CSVExportDialogBase::radioSemicolon->setChecked(true); else CSVExportDialogBase::radioComma->setChecked(true); } void CSVExportDialog::enableExportButton() { btnExport->setEnabled( !urlExportTo->lineEdit()->text().isEmpty() ); } void CSVExportDialog::enableTasksToExportQuestion() { return; //grpTasksToExport->setEnabled( true ); } ReportCriteria CSVExportDialog::reportCriteria() { rc.url = urlExportTo->url(); rc.from = dtFrom->date(); rc.to = dtTo->date(); // Hard code to true for now as the CSV export of totals does not support // this choice currenly and I'm trying to minimize pre-3.3 hacking at the // moment. rc.allTasks = true; QString t = grpTimeFormat->selected()->name(); rc.decimalMinutes = ( t == i18n( "radioDecimal" ) ); QString d = grpDelimiter->selected()->name(); if ( d == "radioComma" ) rc.delimiter = ","; else if ( d == "radioTab" ) rc.delimiter = "\t"; else if ( d == "radioSemicolon" ) rc.delimiter = ";"; else if ( d == "radioSpace" ) rc.delimiter = " "; else if ( d == "radioOther" ) rc.delimiter = txtOther->text(); else { kdDebug(5970) << "*** CSVExportDialog::reportCriteria: Unexpected delimiter choice '" << d << "'--defaulting to a tab" << endl; rc.delimiter = "\t"; } rc.quote = cboQuote->currentText(); return rc; } #include "csvexportdialog.moc" diff --git a/karm/csvexportdialog.h b/karm/csvexportdialog.h index 502c27ec9d..eae6bd4abb 100644 --- a/karm/csvexportdialog.h +++ b/karm/csvexportdialog.h @@ -1,64 +1,64 @@ /* * Copyright (C) 2004 Mark Bucciarelli * * 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. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ #ifndef CSVEXPORTDIALOG_H #define CSVEXPORTDIALOG_H #include "csvexportdialog_base.h" #include "reportcriteria.h" class CSVExportDialog : public CSVExportDialogBase { Q_OBJECT public: CSVExportDialog( ReportCriteria::REPORTTYPE rt, QWidget *parent = 0, const char *name = 0 ); /** Enable the "Tasks to export" question in the dialog. Since Karm does not have the concept of a single root task, when the user requests a report on a top-level task, it is impossible to know if they want all tasks or just the currently selected top-level task. Stubbed for 3.3 release as CSV export of totals doesn't suppor this option. */ void enableTasksToExportQuestion(); /** Return an object that encapsulates the choices the user has made. */ ReportCriteria reportCriteria(); private slots: /** Enable export button if export url entered. */ void enableExportButton(); private: ReportCriteria rc; }; #endif diff --git a/karm/desktoptracker.cpp b/karm/desktoptracker.cpp index c225555e81..a84a8fdde5 100644 --- a/karm/desktoptracker.cpp +++ b/karm/desktoptracker.cpp @@ -1,131 +1,131 @@ #include // std::find #include #include #include "desktoptracker.h" // TODO: Put in config dialog const int minimumInterval = 5; // seconds DesktopTracker::DesktopTracker () { // Setup desktop change handling connect( &kWinModule, SIGNAL( currentDesktopChanged(int) ), this, SLOT( handleDesktopChange(int) )); _desktopCount = kWinModule.numberOfDesktops(); _previousDesktop = kWinModule.currentDesktop()-1; // TODO: removed? fixed by Lubos? // currentDesktop will return 0 if no window manager is started if( _previousDesktop < 0 ) _previousDesktop = 0; _timer = new QTimer(this); connect( _timer, SIGNAL( timeout() ), this, SLOT( changeTimers() ) ); } void DesktopTracker::handleDesktopChange( int desktop ) { _desktop = desktop; // If user changes back and forth between desktops rapidly and frequently, // the data file can get huge fast if logging is turned on. Then saving // get's slower, etc. There's no benefit in saving a lot of start/stop // events that are very small. Wait a bit to make sure the user is settled. - if ( !_timer->start( minimumInterval * 1000, TRUE ) ) changeTimers(); + if ( !_timer->start( minimumInterval * 1000, true ) ) changeTimers(); } void DesktopTracker::changeTimers() { _desktop--; // desktopTracker starts with 0 for desktop 1 // notify start all tasks setup for running on desktop TaskVector::iterator it; // stop trackers for _previousDesktop TaskVector tv = desktopTracker[_previousDesktop]; for (it = tv.begin(); it != tv.end(); ++it) { emit leftActiveDesktop(*it); } // start trackers for desktop tv = desktopTracker[_desktop]; for (it = tv.begin(); it != tv.end(); ++it) { emit reachedtActiveDesktop(*it); } _previousDesktop = _desktop; // emit updateButtons(); } void DesktopTracker::startTracking() { int currentDesktop = kWinModule.currentDesktop() -1; // TODO: removed? fixed by Lubos? // currentDesktop will return 0 if no window manager is started if ( currentDesktop < 0 ) currentDesktop = 0; TaskVector &tv = desktopTracker[ currentDesktop ]; TaskVector::iterator tit = tv.begin(); while(tit!=tv.end()) { emit reachedtActiveDesktop(*tit); tit++; } } void DesktopTracker::registerForDesktops( Task* task, DesktopList desktopList) { // if no desktop is marked, disable auto tracking for this task if (desktopList.size()==0) { for (int i=0; ibegin(), v->end(), task); if (tit != v->end()) desktopTracker[i].erase(tit); // if the task was priviously tracking this desktop then // emit a signal that is not tracking it any more if( i == kWinModule.currentDesktop() -1) emit leftActiveDesktop(task); } return; } // If desktop contains entries then configure desktopTracker // If a desktop was disabled, it will not be stopped automatically. // If enabled: Start it now. if (desktopList.size()>0) { for (int i=0; i, Jesper Pedersen * * * 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. + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include // i18n #include #include "edittaskdialog.h" #include "ktimewidget.h" #include "kdebug.h" EditTaskDialog::EditTaskDialog( QString caption, bool editDlg, DesktopList* desktopList) : KDialogBase(0, "EditTaskDialog", true, caption, Ok|Cancel, Ok, true ), origTime( 0 ), origSession( 0 ) { QWidget *page = new QWidget( this ); setMainWidget(page); KWinModule kwinmodule(0, KWinModule::INFO_DESKTOP); QVBoxLayout *lay1 = new QVBoxLayout(page); QHBoxLayout *lay2 = new QHBoxLayout(); lay1->addLayout(lay2); // The name of the widget QLabel *label = new QLabel( i18n("Task &name:"), page, "name" ); lay2->addWidget( label ); lay2->addSpacing(5); _name = new QLineEdit( page, "lineedit" ); _name->setMinimumWidth(fontMetrics().maxWidth()*15); lay2->addWidget( _name ); label->setBuddy( _name ); // The "Edit Absolut" radio button lay1->addSpacing(10);lay1->addStretch(1); _absoluteRB = new QRadioButton( i18n( "Edit &absolute" ), page, "_absoluteRB" ); lay1->addWidget( _absoluteRB ); connect( _absoluteRB, SIGNAL( clicked() ), this, SLOT( slotAbsolutePressed() ) ); // Absolute times QHBoxLayout *lay5 = new QHBoxLayout(); lay1->addLayout(lay5); lay5->addSpacing(20); QGridLayout *lay3 = new QGridLayout( 2, 2, -1, "lay3" ); lay5->addLayout(lay3); _sessionLA = new QLabel( i18n("&Session time: "), page, "session time" ); // Time _timeLA = new QLabel( i18n("&Time:"), page, "time" ); lay3->addWidget( _timeLA, 0, 0 ); _timeLA->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)0, 0, 0, _timeLA->sizePolicy().hasHeightForWidth()) ); // Based on measuring pixels in a screenshot, it looks like the fontmetrics // call includes the ampersand when calculating the width. To be sure // things will line up (no matter what language or widget style), set all // three date entry label controls to the same width. _timeLA->setMinimumWidth( fontMetrics().width( _sessionLA->text() ) ); _timeTW = new KArmTimeWidget( page, "_timeTW" ); lay3->addWidget( _timeTW, 0, 1 ); _timeLA->setBuddy( _timeTW ); // Session lay3->addWidget( _sessionLA, 1, 0 ); _sessionTW = new KArmTimeWidget( page, "_sessionTW" ); lay3->addWidget( _sessionTW, 1, 1 ); _sessionLA->setBuddy( _sessionTW ); _sessionLA->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)0, 0, 0, _sessionLA->sizePolicy().hasHeightForWidth()) ); _sessionLA->setMinimumWidth( fontMetrics().width( _sessionLA->text() ) ); // The "Edit relative" radio button lay1->addSpacing(10); lay1->addStretch(1); _relativeRB = new QRadioButton( i18n( "Edit &relative (apply to both time and" " session time)" ), page, "_relativeRB" ); lay1->addWidget( _relativeRB ); connect( _relativeRB, SIGNAL( clicked() ), this, SLOT(slotRelativePressed()) ); // The relative times QHBoxLayout *lay4 = new QHBoxLayout(); lay1->addLayout( lay4 ); lay4->addSpacing(20); _operator = new QComboBox(page); _operator->insertItem( QString::fromLatin1( "+" ) ); _operator->insertItem( QString::fromLatin1( "-" ) ); _operator->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)0, 0, 0, _operator->sizePolicy().hasHeightForWidth()) ); //kdDebug() << "text width=" << fontMetrics().width( _sessionLA->text() ) << endl; _operator->setMinimumWidth( fontMetrics().width( _sessionLA->text() ) ); lay4->addWidget( _operator ); _diffTW = new KArmTimeWidget( page, "_sessionAddTW" ); lay4->addWidget( _diffTW ); desktopCount = kwinmodule.numberOfDesktops(); // If desktopList contains higher numbered desktops than desktopCount then // delete those from desktopList. This may be the case if the user has // configured virtual desktops. The values in desktopList are sorted. if ( (desktopList != 0) && (desktopList->size() > 0) ) { DesktopList::iterator rit = desktopList->begin(); while (*rit < desktopCount && rit!=desktopList->end()) { ++rit; } desktopList->erase(rit, desktopList->end()); } // The "Choose Desktop" checkbox lay1->addSpacing(10); lay1->addStretch(1); _desktopCB = new QCheckBox(i18n("A&uto tracking"), page); _desktopCB->setEnabled(true); lay1->addWidget(_desktopCB); QGroupBox* groupBox; { int lines = (int)(desktopCount/2); if (lines*2 != desktopCount) lines++; groupBox = new QButtonGroup( lines, QGroupBox::Horizontal, i18n("In Desktop"), page, "_desktopsGB"); } lay1->addWidget(groupBox); QHBoxLayout *lay6 = new QHBoxLayout(); lay1->addLayout(lay6); for (int i=0; isetText(kwinmodule.desktopName(i+1)); _deskBox[i]->setChecked(false); lay6->addWidget(_deskBox[i]); } // check specified Desktop Check Boxes bool enableDesktops = false; if ( (desktopList != 0) && (desktopList->size() > 0) ) { DesktopList::iterator it = desktopList->begin(); while (it != desktopList->end()) { _deskBox[*it]->setChecked(true); it++; } enableDesktops = true; } // if some desktops were specified, then enable the parent box _desktopCB->setChecked(enableDesktops); for (int i=0; isetEnabled(enableDesktops); connect(_desktopCB, SIGNAL(clicked()), this, SLOT(slotAutoTrackingPressed())); lay1->addStretch(1); if ( editDlg ) { // This is an edit dialog. _operator->setFocus(); } else { // This is an initial dialog _name->setFocus(); } slotRelativePressed(); // Whats this help. QWhatsThis::add( _name, i18n( "Enter the name of the task here. " "This name is for your eyes only.")); QWhatsThis::add( _absoluteRB, i18n( "Use this option to set the time spent on this task " "to an absolute value.\n\nFor example, if you have " "worked exactly four hours on this task during the current " "session, you would set the Session time to 4 hr." ) ); QWhatsThis::add( _relativeRB, i18n( "Use this option to change the time spent on this task " "relative to its current value.\n\nFor example, if you worked " "on this task for one hour without the timer running, you " "would add 1 hr." ) ); QWhatsThis::add( _timeTW, i18n( "This is the time the task has been " "running since all times were reset.")); QWhatsThis::add( _sessionTW, i18n( "This is the time the task has been running this " "session.")); QWhatsThis::add( _diffTW, i18n( "Specify how much time to add or subtract " "to the overall and session time")); QWhatsThis::add( _desktopCB, i18n( "Use this option to automatically start the timer " "on this task when you switch to the specified desktop(s)." ) ); QWhatsThis::add( groupBox, i18n( "Select the desktop(s) that will automatically start the " "timer on this task." ) ); } void EditTaskDialog::slotAbsolutePressed() { _relativeRB->setChecked( false ); _absoluteRB->setChecked( true ); _operator->setEnabled( false ); _diffTW->setEnabled( false ); _timeLA->setEnabled( true ); _sessionLA->setEnabled( true ); _timeTW->setEnabled( true ); _sessionTW->setEnabled( true ); } void EditTaskDialog::slotRelativePressed() { _relativeRB->setChecked( true ); _absoluteRB->setChecked( false ); _operator->setEnabled( true ); _diffTW->setEnabled( true ); _timeLA->setEnabled( false ); _sessionLA->setEnabled( false ); _timeTW->setEnabled( false ); _sessionTW->setEnabled( false ); } void EditTaskDialog::slotAutoTrackingPressed() { bool checked = _desktopCB->isChecked(); for (unsigned int i=0; i<_deskBox.size(); i++) _deskBox[i]->setEnabled(checked); if (!checked) // uncheck all desktop boxes for (int i=0; isetChecked(false); } void EditTaskDialog::setTask( const QString &name, long time, long session ) { _name->setText( name ); _timeTW->setTime( time / 60, time % 60 ); _sessionTW->setTime( session / 60, session % 60 ); origTime = time; origSession = session; } QString EditTaskDialog::taskName() const { return( _name->text() ); } void EditTaskDialog::status(long *time, long *timeDiff, long *session, long *sessionDiff, DesktopList *desktopList) const { if ( _absoluteRB->isChecked() ) { *time = _timeTW->time(); *session = _sessionTW->time(); } else { int diff = _diffTW->time(); if ( _operator->currentItem() == 1) { diff = -diff; } *time = origTime + diff; *session = origSession + diff; } *timeDiff = *time - origTime; *sessionDiff = *session - origSession; for (unsigned int i=0; i<_deskBox.size(); i++) { if (_deskBox[i]->isChecked()) desktopList->push_back(i); } } #include "edittaskdialog.moc" diff --git a/karm/edittaskdialog.h b/karm/edittaskdialog.h index 79079eeeaf..0954d8b5df 100644 --- a/karm/edittaskdialog.h +++ b/karm/edittaskdialog.h @@ -1,89 +1,89 @@ /* * karm * This file only: Copyright (C) 1999 Espen Sand, espensa@online.no * * 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. + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef KARM_EDIT_TASK_DIALOG_H #define KARM_EDIT_TASK_DIALOG_H #include #include #include #include "desktoplist.h" class QComboBox; class QLabel; class QLineEdit; class QRadioButton; class QString; class KArmTimeWidget; /** * Dialog to add a new task or edit an existing task. */ class EditTaskDialog : public KDialogBase { Q_OBJECT public: EditTaskDialog(QString caption, bool editDlg, DesktopList* desktopList=0); void setTask(const QString &name, long time, long sessionTime); QString taskName() const; // return user choices void status( long *time, long *timeDiff, long *session, long *sessionDiff, DesktopList *desktopList) const; private slots: void slotAbsolutePressed(); void slotRelativePressed(); void slotAutoTrackingPressed(); private: QLineEdit* _name; KArmTimeWidget* _timeTW; KArmTimeWidget* _sessionTW; KArmTimeWidget* _diffTW; QComboBox* _operator; std::vector _deskBox; // we only need an array, but ISO forbids // passing an array as a function argument long origTime; long origSession; QRadioButton *_absoluteRB; QRadioButton *_relativeRB; QCheckBox *_desktopCB; int desktopCount; QLabel* _timeLA; QLabel* _sessionLA; }; #endif // KARM_EDIT_TASK_DIALOG diff --git a/ktimetracker/hi128-app-karm.png b/karm/hi128-app-karm.png similarity index 100% rename from ktimetracker/hi128-app-karm.png rename to karm/hi128-app-karm.png diff --git a/ktimetracker/hi16-app-karm.png b/karm/hi16-app-karm.png similarity index 100% rename from ktimetracker/hi16-app-karm.png rename to karm/hi16-app-karm.png diff --git a/ktimetracker/hi22-app-karm.png b/karm/hi22-app-karm.png similarity index 100% rename from ktimetracker/hi22-app-karm.png rename to karm/hi22-app-karm.png diff --git a/ktimetracker/hi32-app-karm.png b/karm/hi32-app-karm.png similarity index 100% rename from ktimetracker/hi32-app-karm.png rename to karm/hi32-app-karm.png diff --git a/ktimetracker/hi48-app-karm.png b/karm/hi48-app-karm.png similarity index 100% rename from ktimetracker/hi48-app-karm.png rename to karm/hi48-app-karm.png diff --git a/ktimetracker/hi64-app-karm.png b/karm/hi64-app-karm.png similarity index 100% rename from ktimetracker/hi64-app-karm.png rename to karm/hi64-app-karm.png diff --git a/karm/idletimedetector.h b/karm/idletimedetector.h index 8713429d44..e2d0e56c2e 100644 --- a/karm/idletimedetector.h +++ b/karm/idletimedetector.h @@ -1,101 +1,101 @@ #ifndef KARM_IDLE_TIME_DETECTOR_H #define KARM_IDLE_TIME_DETECTOR_H #include #include "config.h" // HAVE_LIBXSS class QTimer; #ifdef HAVE_LIBXSS #include #include #include #include #endif // HAVE_LIBXSS // Seconds per minutes - useful for speeding debugging up! const int secsPerMinute = 60; // Minutes between each idle overrun test. const int testInterval= secsPerMinute * 1000; /** * Keep track of how long the computer has been idle. */ class IdleTimeDetector :public QObject { Q_OBJECT public: /** Initializes and idle test timer @param maxIdle minutes before the idle timer will go off. **/ IdleTimeDetector(int maxIdle); /** Returns true if it is possible to do idle detection. Idle detection relys on a feature in the X server, which might not always be present. **/ bool isIdleDetectionPossible(); signals: /** Tells the listener to extract time from current timing. The time to extract is due to the idle time since the dialog wass shown, and until the user answers the dialog. @param minutes Minutes to extract. **/ void extractTime(int minutes); /** Tells the listener to stop timing **/ void stopAllTimers(); public slots: /** Sets the maximum allowed idle. @param maxIdle Maximum allowed idle time in minutes **/ void setMaxIdle(int maxIdle); /** Starts detecting idle time **/ void startIdleDetection(); /** Stops detecting idle time. **/ void stopIdleDetection(); /** Sets whether idle detection should be done at all - @param on If true idle detection is done based on @see + @param on If true idle detection is done based on startIdleDetection and @ref stopIdleDetection **/ void toggleOverAllIdleDetection(bool on); protected: #ifdef HAVE_LIBXSS void informOverrun(int idle); #endif // HAVE_LIBXSS protected slots: void check(); private: #ifdef HAVE_LIBXSS XScreenSaverInfo *_mit_info; #endif bool _idleDetectionPossible; bool _overAllIdleDetect; // Based on preferences. int _maxIdle; QTimer *_timer; }; #endif // KARM_IDLE_TIME_DETECTOR_H diff --git a/ktimetracker/karm_part.cpp b/karm/karm_part.cpp similarity index 100% rename from ktimetracker/karm_part.cpp rename to karm/karm_part.cpp diff --git a/ktimetracker/karm_part.desktop b/karm/karm_part.desktop similarity index 100% rename from ktimetracker/karm_part.desktop rename to karm/karm_part.desktop diff --git a/ktimetracker/karm_part.h b/karm/karm_part.h similarity index 100% rename from ktimetracker/karm_part.h rename to karm/karm_part.h diff --git a/karm/karmdcopiface.h b/karm/karmdcopiface.h index 2d71055176..1135c81e6a 100644 --- a/karm/karmdcopiface.h +++ b/karm/karmdcopiface.h @@ -1,44 +1,132 @@ /* * This file only: * Copyright (C) 2004 Mark Bucciarelli * * 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. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. */ #ifndef KARM_DCOP_IFAC_H #define KARM_DCOP_IFAC_H #include +/** Define DCOP interface to karm. Methods implemented in MainWindow */ class KarmDCOPIface : virtual public DCOPObject { K_DCOP k_dcop: /** Return karm version. */ virtual QString version() const = 0; - /** Return UID of todo found, empty string if no match. */ - virtual QString hastodo( const QString& taskname ) const = 0; + /** Return id of task found, empty string if no match. */ + virtual QString taskIdFromName( const QString& taskName ) const = 0; - /** Add a top-level todo. Return UID of new To-do. */ - virtual QString addtodo( const QString& todoname ) = 0; + /** + * Add a new top-level task. + * + * A top-level task is one that has no parent tasks. + * + * @param taskName Name of new task. + * + * @return 0 on success, error number on failure. + */ + virtual int addTask( const QString& taskName ) = 0; + + /** + * Set percent complete to a task + * + * @param taskName Name of new task. + * @param perCent percent, e.g. 99 + * + * @return "" on success, error msg on failure. + */ + virtual QString setPerCentComplete( const QString& taskName, int perCent ) = 0; + + /** + * Add time to a task. + * + * The GUI will be non-responsive until this method returns. + * + * @return 0 on success, error number on failure. + * + * @param taskId Unique ID of task to add time to + * + * @param iso8601StartDateTime Date and time the booking starts, in extended + * ISO-8601 format; for example, YYYY-MM-DDTHH:MI:SS format (see + * Qt::ISODate). No timezone support--time is interpreted as the local time. + * If just the date is passed in (i.e., YYYY-MM-DD) , then the time is set to + * noon. + * + * @param durationInMinutes The amount of time to book against the taskId. + * + */ + virtual int bookTime( const QString& taskId, const QString& iso8601StartDateTime, + long durationInMinutes ) = 0; + + /** + * Return error string associated with karm error number. + * + * @param karmErrorNumber An integer error number. + * + * @return String associated with error number. These strings are + * internationalized. An unknown error number produces an empty string as + * the return value. + * + */ + virtual QString getError( int karmErrorNumber ) const = 0; + + /** + * Total time currently associated with a task. + * + * A task has two counters: the total session time and the total time. Note + * that th euser can reset both counters. + * + * @param taskId Unique ID of task to lookup bookings for. + */ + virtual int totalMinutesForTaskId( const QString& taskId ) = 0; + + /** Start timer for all tasks with the summary taskname. */ + // may conflict with unitaskmode + virtual QString starttimerfor( const QString& taskname ) = 0; + + /** Stop timer for all tasks with the summary taskname. */ + // may conflict with unitaskmode + virtual QString stoptimerfor( const QString& taskname ) = 0; + + /** delete the current item */ + virtual QString deletetodo() = 0; + + /** set if prompted on deleting a task */ + virtual QString setpromptdelete( bool prompt ) = 0; + + /** get if prompted on deleting a task */ + virtual bool getpromptdelete() = 0; + + /** export csv history or totals file */ + virtual QString exportcsvfile( QString filename, QString from, QString to, int type = 0, bool decimalMinutes=true, bool allTasks=true, QString delimiter=";", QString quote="'" ) = 0; + + /** import planner project file */ + virtual QString importplannerfile( QString filename ) = 0; + + /** save your tasks */ + virtual bool save() = 0; /** Graceful shutdown. */ virtual void quit() = 0; }; #endif // KARM_DCOP_IFAC_H diff --git a/ktimetracker/karmerrors.h b/karm/karmerrors.h similarity index 100% rename from ktimetracker/karmerrors.h rename to karm/karmerrors.h diff --git a/karm/karmstorage.cpp b/karm/karmstorage.cpp index 857fa6d9e2..a49994cb5f 100644 --- a/karm/karmstorage.cpp +++ b/karm/karmstorage.cpp @@ -1,1211 +1,1196 @@ /* * This file only: * Copyright (C) 2003, 2004 Mark Bucciarelli * * 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. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ #include #include #include #include #include #include #include #include #include #include #include #include "incidence.h" #include "kapplication.h" // kapp #include #include #include // i18n #include #include #include #include #include #include #include #include #include #include #include #include #include //#include //#include //#include //#include #include "karmstorage.h" #include "preferences.h" #include "task.h" #include "reportcriteria.h" using namespace std; KarmStorage *KarmStorage::_instance = 0; static long linenr; // how many lines written by printTaskHistory so far KarmStorage *KarmStorage::instance() { if (_instance == 0) _instance = new KarmStorage(); return _instance; } KarmStorage::KarmStorage() { _calendar = 0; } -QString KarmStorage::load (TaskView* view, const Preferences* preferences) +QString KarmStorage::load (TaskView* view, const Preferences* preferences, QString fileName ) +// loads data from filename into view. If no filename is given, filename from preferences is used. +// filename might be of use if this program is run as embedded konqueror plugin. { // When I tried raising an exception from this method, the compiler // complained that exceptions are not allowed. Not sure how apps // typically handle error conditions in KDE, but I'll return the error // as a string (empty is no error). -- Mark, Aug 8, 2003 // Use KDE_CXXFLAGS=$(USE_EXCEPTIONS) in Makefile.am if you want to use // exceptions (David Faure) QString err; KEMailSettings settings; + if ( fileName.isEmpty() ) fileName = preferences->iCalFile(); // If same file, don't reload - if ( preferences->iCalFile() == _icalfile ) return err; + if ( fileName == _icalfile ) return err; // If file doesn't exist, create a blank one to avoid ResourceLocal load // error. We make it user and group read/write, others read. This is // masked by the users umask. (See man creat) if ( ! remoteResource( _icalfile ) ) { int handle; handle = open ( - QFile::encodeName( preferences->iCalFile() ), + QFile::encodeName( fileName ), O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH ); if (handle != -1) close(handle); } - if ( _calendar) closeStorage(view); - else _calendar = new KCal::CalendarResources( QString::fromLatin1("UTC") ); + if ( _calendar) + closeStorage(view); // Create local file resource and add to resources - _icalfile = preferences->iCalFile(); + _icalfile = fileName; - KCal::ResourceCalendar *l; + KCal::ResourceCached *resource; if ( remoteResource( _icalfile ) ) { - KURL download = KURL( _icalfile ); - KURL upload = KURL( _icalfile ); - l = new KCal::ResourceRemote( upload, download ); + KURL url( _icalfile ); + resource = new KCal::ResourceRemote( url, url ); // same url for upload and download } else { - l = new KCal::ResourceLocal( _icalfile ); + resource = new KCal::ResourceLocal( _icalfile ); } + _calendar = resource; - QObject::connect (l, SIGNAL(resourceChanged(ResourceCalendar *)), + QObject::connect (_calendar, SIGNAL(resourceChanged(ResourceCalendar *)), view, SLOT(iCalFileModified(ResourceCalendar *))); - l->setTimeZoneId( KPimPrefs::timezone() ); - l->setResourceName( QString::fromLatin1("KArm") ); - l->open(); - l->load(); - - KCal::CalendarResourceManager *m = _calendar->resourceManager(); - m->add(l); - m->setStandardResource(l); + _calendar->setTimeZoneId( KPimPrefs::timezone() ); + _calendar->setResourceName( QString::fromLatin1("KArm") ); + _calendar->open(); + _calendar->load(); // Claim ownership of iCalendar file if no one else has. - KCal::Person owner = _calendar->getOwner(); + KCal::Person owner = resource->getOwner(); if ( owner.isEmpty() ) { - _calendar->setOwner( KCal::Person( + resource->setOwner( KCal::Person( settings.getSetting( KEMailSettings::RealName ), settings.getSetting( KEMailSettings::EmailAddress ) ) ); } // Build task view from iCal data if (!err) { KCal::Todo::List todoList; KCal::Todo::List::ConstIterator todo; QDict< Task > map; // Build dictionary to look up Task object from Todo uid. Each task is a // QListViewItem, and is initially added with the view as the parent. todoList = _calendar->rawTodos(); kdDebug(5970) << "KarmStorage::load " << "rawTodo count (includes completed todos) =" << todoList.count() << endl; for( todo = todoList.begin(); todo != todoList.end(); ++todo ) { // Initially, if a task was complete, it was removed from the view. // However, this increased the complexity of reporting on task history. // // For example, if a task is complete yet has time logged to it during // the date range specified on the history report, we have to figure out // how that task fits into the task hierarchy. Currently, this // structure is held in memory by the structure in the list view. // // I considered creating a second tree that held the full structure of // all complete and incomplete tasks. But this seemed to much of a // change with an impending beta release and a full todo list. // // Hence this "solution". Include completed tasks, but mark them as // inactive in the view. // //if ((*todo)->isCompleted()) continue; Task* task = new Task(*todo, view); map.insert( (*todo)->uid(), task ); view->setRootIsDecorated(true); - if ((*todo)->isCompleted()) - { - task->setEnabled(false); - task->setOpen(false); - } - else - task->setOpen(true); + task->setPixmapProgress(); } // Load each task under it's parent task. for( todo = todoList.begin(); todo != todoList.end(); ++todo ) { Task* task = map.find( (*todo)->uid() ); // No relatedTo incident just means this is a top-level task. if ( (*todo)->relatedTo() ) { Task* newParent = map.find( (*todo)->relatedToUid() ); // Complete the loading but return a message if ( !newParent ) err = i18n("Error loading \"%1\": could not find parent (uid=%2)") .arg(task->name()) .arg((*todo)->relatedToUid()); if (!err) task->move( newParent); } } kdDebug(5970) << "KarmStorage::load - loaded " << view->count() << " tasks from " << _icalfile << endl; } return err; } QString KarmStorage::buildTaskView(KCal::ResourceCalendar *rc, TaskView *view) // makes *view contain the tasks out of *rc. { QString err; KCal::Todo::List todoList; KCal::Todo::List::ConstIterator todo; QDict< Task > map; // 1. delete old tasks while (view->item_at_index(0)) view->item_at_index(0)->cut(); // 1. insert tasks form rc into taskview // 1.1. Build dictionary to look up Task object from Todo uid. Each task is a // QListViewItem, and is initially added with the view as the parent. todoList = rc->rawTodos(); for( todo = todoList.begin(); todo != todoList.end(); ++todo ) { Task* task = new Task(*todo, view); map.insert( (*todo)->uid(), task ); view->setRootIsDecorated(true); - if ((*todo)->isCompleted()) - { - task->setEnabled(false); - task->setOpen(false); - } - else - task->setOpen(true); + task->setPixmapProgress(); } // 1.1. Load each task under it's parent task. for( todo = todoList.begin(); todo != todoList.end(); ++todo ) { Task* task = map.find( (*todo)->uid() ); // No relatedTo incident just means this is a top-level task. if ( (*todo)->relatedTo() ) { Task* newParent = map.find( (*todo)->relatedToUid() ); // Complete the loading but return a message if ( !newParent ) err = i18n("Error loading \"%1\": could not find parent (uid=%2)") .arg(task->name()) .arg((*todo)->relatedToUid()); if (!err) task->move( newParent); } } return err; } void KarmStorage::closeStorage(TaskView* view) { if ( _calendar ) { - _calendar->close(); - - KCal::CalendarResourceManager *m = _calendar->resourceManager(); - m->remove( m->standardResource() ); + delete _calendar; + _calendar = 0; view->clear(); } } QString KarmStorage::save(TaskView* taskview) { - QString err=""; + kdDebug(5970) << "entering KarmStorage::save" << endl; + QString err; QPtrStack< KCal::Todo > parents; for (Task* task=taskview->first_child(); task; task = task->nextSibling()) { - writeTaskAsTodo(task, 1, parents ); + err=writeTaskAsTodo(task, 1, parents ); } - if ( !_calendar->save( - _calendar->requestSaveTicket( _calendar->resourceManager()->standardResource() ) - ) - ) + if ( !saveCalendar() ) { err="Could not save"; } - kdDebug(5970) - << "KarmStorage::save : wrote " - << taskview->count() << " tasks to " << _icalfile << endl; + if ( err.isEmpty() ) + { + kdDebug(5970) + << "KarmStorage::save : wrote " + << taskview->count() << " tasks to " << _icalfile << endl; + } + else + { + kdWarning(5970) << "KarmStorage::save : " << err << endl; + } + return err; } -void KarmStorage::writeTaskAsTodo(Task* task, const int level, +QString KarmStorage::writeTaskAsTodo(Task* task, const int level, QPtrStack< KCal::Todo >& parents ) { + QString err; KCal::Todo* todo; todo = _calendar->todo(task->uid()); + if ( !todo ) + { + kdDebug(5970) << "Could not get todo from calendar" << endl; + return "Could not get todo from calendar"; + } task->asTodo(todo); if ( !parents.isEmpty() ) todo->setRelatedTo( parents.top() ); parents.push( todo ); - for (Task* nextTask = task->firstChild(); nextTask; - nextTask = nextTask->nextSibling() ) + for ( Task* nextTask = task->firstChild(); nextTask; + nextTask = nextTask->nextSibling() ) { - writeTaskAsTodo(nextTask, level+1, parents ); + err = writeTaskAsTodo(nextTask, level+1, parents ); } parents.pop(); + return err; } bool KarmStorage::isEmpty() { KCal::Todo::List todoList; todoList = _calendar->rawTodos(); return todoList.empty(); } bool KarmStorage::isNewStorage(const Preferences* preferences) const { if ( !_icalfile.isNull() ) return preferences->iCalFile() != _icalfile; else return false; } //---------------------------------------------------------------------------- // Routines that handle legacy flat file format. // These only stored total and session times. // QString KarmStorage::loadFromFlatFile(TaskView* taskview, const QString& filename) { QString err; kdDebug(5970) << "KarmStorage::loadFromFlatFile: " << filename << endl; QFile f(filename); if( !f.exists() ) err = i18n("File \"%1\" not found.").arg(filename); if (!err) { if( !f.open( IO_ReadOnly ) ) err = i18n("Could not open \"%1\".").arg(filename); } if (!err) { QString line; QPtrStack stack; Task *task; QTextStream stream(&f); while( !stream.atEnd() ) { // lukas: this breaks for non-latin1 chars!!! // if ( file.readLine( line, T_LINESIZE ) == 0 ) // break; line = stream.readLine(); kdDebug(5970) << "DEBUG: line: " << line << "\n"; if (line.isNull()) break; long minutes; int level; QString name; DesktopList desktopList; if (!parseLine(line, &minutes, &name, &level, &desktopList)) continue; unsigned int stackLevel = stack.count(); for (unsigned int i = level; i<=stackLevel ; i++) { stack.pop(); } if (level == 1) { kdDebug(5970) << "KarmStorage::loadFromFlatFile - toplevel task: " << name << " min: " << minutes << "\n"; task = new Task(name, minutes, 0, desktopList, taskview); task->setUid(addTask(task, 0)); } else { Task *parent = stack.top(); kdDebug(5970) << "KarmStorage::loadFromFlatFile - task: " << name << " min: " << minutes << " parent" << parent->name() << "\n"; task = new Task(name, minutes, 0, desktopList, parent); task->setUid(addTask(task, parent)); // Legacy File Format (!): parent->changeTimes(0, -minutes); taskview->setRootIsDecorated(true); parent->setOpen(true); } if (!task->uid().isNull()) stack.push(task); else delete task; } f.close(); } return err; } QString KarmStorage::loadFromFlatFileCumulative(TaskView* taskview, const QString& filename) { QString err = loadFromFlatFile(taskview, filename); if (!err) { for (Task* task = taskview->first_child(); task; task = task->nextSibling()) { adjustFromLegacyFileFormat(task); } } return err; } bool KarmStorage::parseLine(QString line, long *time, QString *name, int *level, DesktopList* desktopList) { if (line.find('#') == 0) { // A comment line return false; } int index = line.find('\t'); if (index == -1) { // This doesn't seem like a valid record return false; } QString levelStr = line.left(index); QString rest = line.remove(0,index+1); index = rest.find('\t'); if (index == -1) { // This doesn't seem like a valid record return false; } QString timeStr = rest.left(index); rest = rest.remove(0,index+1); bool ok; index = rest.find('\t'); // check for optional desktops string if (index >= 0) { *name = rest.left(index); QString deskLine = rest.remove(0,index+1); // now transform the ds string (e.g. "3", or "1,4,5") into // an DesktopList QString ds; int d; int commaIdx = deskLine.find(','); while (commaIdx >= 0) { ds = deskLine.left(commaIdx); d = ds.toInt(&ok); if (!ok) return false; desktopList->push_back(d); deskLine.remove(0,commaIdx+1); commaIdx = deskLine.find(','); } d = deskLine.toInt(&ok); if (!ok) return false; desktopList->push_back(d); } else { *name = rest.remove(0,index+1); } *time = timeStr.toLong(&ok); if (!ok) { // the time field was not a number return false; } *level = levelStr.toInt(&ok); if (!ok) { // the time field was not a number return false; } return true; } void KarmStorage::adjustFromLegacyFileFormat(Task* task) { // unless the parent is the listView if ( task->parent() ) task->parent()->changeTimes(-task->sessionTime(), -task->time()); // traverse depth first - // as soon as we're in a leaf, we'll substract it's time from the parent // then, while descending back we'll do the same for each node untill // we reach the root for ( Task* subtask = task->firstChild(); subtask; subtask = subtask->nextSibling() ) adjustFromLegacyFileFormat(subtask); } //---------------------------------------------------------------------------- // Routines that handle Comma-Separated Values export file format. // QString KarmStorage::exportcsvFile( TaskView *taskview, const ReportCriteria &rc ) { QString delim = rc.delimiter; QString dquote = rc.quote; QString double_dquote = dquote + dquote; bool to_quote = true; QString err; Task* task; int maxdepth=0; kdDebug(5970) << "KarmStorage::exportcsvFile: " << rc.url << endl; QString title = i18n("Export Progress"); KProgressDialog dialog( taskview, 0, title ); dialog.setAutoClose( true ); dialog.setAllowCancel( true ); dialog.progressBar()->setTotalSteps( 2 * taskview->count() ); // The default dialog was not displaying all the text in the title bar. int width = taskview->fontMetrics().width(title) * 3; QSize dialogsize; dialogsize.setWidth(width); dialog.setInitialSize( dialogsize, true ); if ( taskview->count() > 1 ) dialog.show(); QString retval; // Find max task depth int tasknr = 0; while ( tasknr < taskview->count() && !dialog.wasCancelled() ) { dialog.progressBar()->advance( 1 ); if ( tasknr % 15 == 0 ) kapp->processEvents(); // repainting is slow if ( taskview->item_at_index(tasknr)->depth() > maxdepth ) maxdepth = taskview->item_at_index(tasknr)->depth(); tasknr++; } // Export to file tasknr = 0; while ( tasknr < taskview->count() && !dialog.wasCancelled() ) { task = taskview->item_at_index( tasknr ); dialog.progressBar()->advance( 1 ); if ( tasknr % 15 == 0 ) kapp->processEvents(); // indent the task in the csv-file: for ( int i=0; i < task->depth(); ++i ) retval += delim; /* // CSV compliance // Surround the field with quotes if the field contains // a comma (delim) or a double quote if (task->name().contains(delim) || task->name().contains(dquote)) - to_quote = TRUE; + to_quote = true; else - to_quote = FALSE; + to_quote = false; */ to_quote = true; if (to_quote) retval += dquote; // Double quotes replaced by a pair of consecutive double quotes retval += task->name().replace( dquote, double_dquote ); if (to_quote) retval += dquote; // maybe other tasks are more indented, so to align the columns: for ( int i = 0; i < maxdepth - task->depth(); ++i ) retval += delim; retval += delim + formatTime( task->sessionTime(), rc.decimalMinutes ) + delim + formatTime( task->time(), rc.decimalMinutes ) + delim + formatTime( task->totalSessionTime(), rc.decimalMinutes ) + delim + formatTime( task->totalTime(), rc.decimalMinutes ) + "\n"; tasknr++; } // save, either locally or remote if ((rc.url.isLocalFile()) || (!rc.url.url().contains("/"))) { QString filename=rc.url.path(); if (filename.isEmpty()) filename=rc.url.url(); QFile f( filename ); if( !f.open( IO_WriteOnly ) ) { err = i18n( "Could not open \"%1\"." ).arg( filename ); } if (!err) { QTextStream stream(&f); // Export to file stream << retval; f.close(); } } else // use remote file { KTempFile tmpFile; if ( tmpFile.status() != 0 ) err = QString::fromLatin1( "Unable to get temporary file" ); else { QTextStream *stream=tmpFile.textStream(); *stream << retval; tmpFile.close(); if (!KIO::NetAccess::upload( tmpFile.name(), rc.url, 0 )) err=QString::fromLatin1("Could not upload"); } } return err; } //---------------------------------------------------------------------------- // Routines that handle logging KArm history // // // public routines: // QString KarmStorage::addTask(const Task* task, const Task* parent) { KCal::Todo* todo; QString uid; todo = new KCal::Todo(); if ( _calendar->addTodo( todo ) ) { task->asTodo( todo ); if (parent) todo->setRelatedTo(_calendar->todo(parent->uid())); uid = todo->uid(); } + else + { + // Most likely a lock could not be pulled, although there are other + // possiblities (like a really confused resource manager). + uid = ""; + } return uid; } bool KarmStorage::removeTask(Task* task) { // delete history KCal::Event::List eventList = _calendar->rawEvents(); for(KCal::Event::List::iterator i = eventList.begin(); i != eventList.end(); ++i) { //kdDebug(5970) << "KarmStorage::removeTask: " // << (*i)->uid() << " - relatedToUid() " // << (*i)->relatedToUid() // << ", relatedTo() = " << (*i)->relatedTo() <relatedToUid() == task->uid() || ( (*i)->relatedTo() && (*i)->relatedTo()->uid() == task->uid())) { _calendar->deleteEvent(*i); } } // delete todo KCal::Todo *todo = _calendar->todo(task->uid()); _calendar->deleteTodo(todo); // Save entire file - _calendar->save(_calendar->requestSaveTicket - (_calendar->resourceManager()->standardResource())); + saveCalendar(); return true; } void KarmStorage::addComment(const Task* task, const QString& comment) { KCal::Todo* todo; todo = _calendar->todo(task->uid()); // Do this to avoid compiler warnings about comment not being used. once we // transition to using the addComment method, we need this second param. QString s = comment; // TODO: Use libkcal comments // todo->addComment(comment); // temporary todo->setDescription(task->comment()); - _calendar->save(_calendar->requestSaveTicket - ( _calendar->resourceManager()->standardResource() )); + saveCalendar(); } long KarmStorage::printTaskHistory ( const Task *task, const QMap &taskdaytotals, QMap &daytotals, const QDate &from, const QDate &to, const int level, vector &matrix, const ReportCriteria &rc) // to>=from is precondition { long ownline=linenr++; // the how many-th instance of this function is this long colrectot=0; // colum where to write the task's total recursive time vector cell; // each line of the matrix is stored in an array of cells, one containing the recursive total long add; // total recursive time of all subtasks QString delim = rc.delimiter; QString dquote = rc.quote; QString double_dquote = dquote + dquote; bool to_quote = true; const QString cr = QString::fromLatin1("\n"); QString buf; QString daytaskkey, daykey; QDate day; long sum; if ( !task ) return 0; day = from; sum = 0; while (day <= to) { // write the time in seconds for the given task for the given day to s daykey = day.toString(QString::fromLatin1("yyyyMMdd")); daytaskkey = QString::fromLatin1("%1_%2") .arg(daykey) .arg(task->uid()); if (taskdaytotals.contains(daytaskkey)) { cell.push_back(QString::fromLatin1("%1") .arg(formatTime(taskdaytotals[daytaskkey]/60, rc.decimalMinutes))); sum += taskdaytotals[daytaskkey]; // in seconds if (daytotals.contains(daykey)) daytotals.replace(daykey, daytotals[daykey]+taskdaytotals[daytaskkey]); else daytotals.insert(daykey, taskdaytotals[daytaskkey]); } cell.push_back(delim); day = day.addDays(1); } // Total for task cell.push_back(QString::fromLatin1("%1").arg(formatTime(sum/60, rc.decimalMinutes))); // room for the recursive total time (that cannot be calculated now) cell.push_back(delim); colrectot = cell.size(); cell.push_back("???"); cell.push_back(delim); // Task name for ( int i = level + 1; i > 0; i-- ) cell.push_back(delim); /* // CSV compliance // Surround the field with quotes if the field contains // a comma (delim) or a double quote to_quote = task->name().contains(delim) || task->name().contains(dquote); */ to_quote = true; if ( to_quote) cell.push_back(dquote); // Double quotes replaced by a pair of consecutive double quotes cell.push_back(task->name().replace( dquote, double_dquote )); if ( to_quote) cell.push_back(dquote); cell.push_back(cr); add=0; for (Task* subTask = task->firstChild(); subTask; subTask = subTask->nextSibling()) { add += printTaskHistory( subTask, taskdaytotals, daytotals, from, to , level+1, matrix, rc ); } cell[colrectot]=(QString::fromLatin1("%1").arg(formatTime((add+sum)/60, rc.decimalMinutes ))); for (unsigned int i=0; i < cell.size(); i++) matrix[ownline]+=cell[i]; return add+sum; } QString KarmStorage::report( TaskView *taskview, const ReportCriteria &rc ) { QString err; if ( rc.reportType == ReportCriteria::CSVHistoryExport ) err = exportcsvHistory( taskview, rc.from, rc.to, rc ); else if ( rc.reportType == ReportCriteria::CSVTotalsExport ) err = exportcsvFile( taskview, rc ); else // hmmmm ... assert(0)? ; return err; } // export history report as csv, all tasks X all dates in one block QString KarmStorage::exportcsvHistory ( TaskView *taskview, const QDate &from, const QDate &to, const ReportCriteria &rc) { QString delim = rc.delimiter; const QString cr = QString::fromLatin1("\n"); QString err; // below taken from timekard.cpp QString retval; QString taskhdr, totalhdr; QString line, buf; long sum; QValueList events; QValueList::iterator event; QMap taskdaytotals; QMap daytotals; QString daytaskkey, daykey; QDate day; QDate dayheading; // parameter-plausi if ( from > to ) { err = QString::fromLatin1 ( "'to' has to be a date later than or equal to 'from'."); } // header retval += i18n("Task History\n"); retval += i18n("From %1 to %2") .arg(KGlobal::locale()->formatDate(from)) .arg(KGlobal::locale()->formatDate(to)); retval += cr; retval += i18n("Printed on: %1") .arg(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime())); retval += cr; day=from; events = taskview->getHistory(from, to); taskdaytotals.clear(); daytotals.clear(); // Build lookup dictionary used to output data in table cells. keys are // in this format: YYYYMMDD_NNNNNN, where Y = year, M = month, d = day and // NNNNN = the VTODO uid. The value is the total seconds logged against // that task on that day. Note the UID is the todo id, not the event id, // so times are accumulated for each task. for (event = events.begin(); event != events.end(); ++event) { daykey = (*event).start().date().toString(QString::fromLatin1("yyyyMMdd")); daytaskkey = QString(QString::fromLatin1("%1_%2")) .arg(daykey) .arg((*event).todoUid()); if (taskdaytotals.contains(daytaskkey)) taskdaytotals.replace(daytaskkey, taskdaytotals[daytaskkey] + (*event).duration()); else taskdaytotals.insert(daytaskkey, (*event).duration()); } // day headings dayheading = from; while ( dayheading <= to ) { // Use ISO 8601 format for date. retval += dayheading.toString(QString::fromLatin1("yyyy-MM-dd")); retval += delim; dayheading=dayheading.addDays(1); } retval += i18n("Sum") + delim + i18n("Total Sum") + delim + i18n("Task Hierarchy"); retval += cr; retval += line; // the tasks vector matrix; linenr=0; for (int i=0; i<=taskview->count()+1; i++) matrix.push_back(""); if (events.empty()) { retval += i18n(" No hours logged."); } else { if ( rc.allTasks ) { for ( Task* task= taskview->item_at_index(0); task; task= task->nextSibling() ) { printTaskHistory( task, taskdaytotals, daytotals, from, to, 0, matrix, rc ); } } else { printTaskHistory( taskview->current_item(), taskdaytotals, daytotals, from, to, 0, matrix, rc ); } for (unsigned int i=0; istartTime().secsTo(QDateTime::currentDateTime()); changeTime(task, delta); } +bool KarmStorage::bookTime(const Task* task, + const QDateTime& startDateTime, + const long durationInSeconds) +{ + // Ignores preferences setting re: logging history. + KCal::Event* e; + QDateTime end; + + e = baseEvent( task ); + e->setDtStart( startDateTime ); + e->setDtEnd( startDateTime.addSecs( durationInSeconds ) ); + + // Use a custom property to keep a record of negative durations + e->setCustomProperty( kapp->instanceName(), + QCString("duration"), + QString::number(durationInSeconds)); + + return _calendar->addEvent(e); +} + void KarmStorage::changeTime(const Task* task, const long deltaSeconds) { KCal::Event* e; QDateTime end; // Don't write events (with timer start/stop duration) if user has turned // this off in the settings dialog. if ( ! task->taskView()->preferences()->logging() ) return; e = baseEvent(task); // Don't use duration, as ICalFormatImpl::writeIncidence never writes a // duration, even though it looks like it's used in event.cpp. end = task->startTime(); if ( deltaSeconds > 0 ) end = task->startTime().addSecs(deltaSeconds); e->setDtEnd(end); // Use a custom property to keep a record of negative durations e->setCustomProperty( kapp->instanceName(), QCString("duration"), QString::number(deltaSeconds)); _calendar->addEvent(e); // This saves the entire iCal file each time, which isn't efficient but // ensures no data loss. A faster implementation would be to append events // to a file, and then when KArm closes, append the data in this file to the // iCal file. // // Meanwhile, we simply use a timer to delay the full-saving until the GUI // has updated, for better user feedback. Feel free to get rid of this // if/when implementing the faster saving (DF). task->taskView()->scheduleSave(); } KCal::Event* KarmStorage::baseEvent(const Task * task) { KCal::Event* e; QStringList categories; e = new KCal::Event; e->setSummary(task->name()); // Can't use setRelatedToUid()--no error, but no RelatedTo written to disk e->setRelatedTo(_calendar->todo(task->uid())); // Debugging: some events where not getting a related-to field written. assert(e->relatedTo()->uid() == task->uid()); // Have to turn this off to get datetimes in date fields. e->setFloats(false); e->setDtStart(task->startTime()); // So someone can filter this mess out of their calendar display categories.append(i18n("KArm")); e->setCategories(categories); return e; } HistoryEvent::HistoryEvent(QString uid, QString name, long duration, QDateTime start, QDateTime stop, QString todoUid) { _uid = uid; _name = name; _duration = duration; _start = start; _stop = stop; _todoUid = todoUid; } QValueList KarmStorage::getHistory(const QDate& from, const QDate& to) { QValueList retval; QStringList processed; KCal::Event::List events; KCal::Event::List::iterator event; QString duration; for(QDate d = from; d <= to; d = d.addDays(1)) { - events = _calendar->events(d); + events = _calendar->rawEventsForDate( d ); for (event = events.begin(); event != events.end(); ++event) { // KArm events have the custom property X-KDE-Karm-duration if (! processed.contains( (*event)->uid())) { // If an event spans multiple days, CalendarLocal::rawEventsForDate // will return the same event on both days. To avoid double-counting // such events, we (arbitrarily) attribute the hours from both days on // the first day. This mis-reports the actual time spent, but it is // an easy fix for a (hopefully) rare situation. processed.append( (*event)->uid()); duration = (*event)->customProperty(kapp->instanceName(), QCString("duration")); if ( ! duration.isNull() ) { if ( (*event)->relatedTo() && ! (*event)->relatedTo()->uid().isEmpty() ) { retval.append(HistoryEvent( (*event)->uid(), (*event)->summary(), duration.toLong(), (*event)->dtStart(), (*event)->dtEnd(), (*event)->relatedTo()->uid() )); } else // Something is screwy with the ics file, as this KArm history event // does not have a todo related to it. Could have been deleted // manually? We'll continue with report on with report ... kdDebug(5970) << "KarmStorage::getHistory(): " << "The event " << (*event)->uid() << " is not related to a todo. Dropped." << endl; } } } } return retval; } bool KarmStorage::remoteResource( const QString& file ) const { QString f = file.lower(); bool rval = f.startsWith( "http://" ) || f.startsWith( "ftp://" ); kdDebug(5970) << "KarmStorage::remoteResource( " << file << " ) returns " << rval << endl; return rval; } -/* - * Obsolete methods for writing to flat file format. - * Aug 8, 2003, Mark - * -void KarmStorage::saveToFileFormat() +bool KarmStorage::saveCalendar() { - //QFile f(_preferences->saveFile()); - QFile f(_preferences->flatFile()); - - if ( !f.open( IO_WriteOnly | IO_Truncate ) ) { - QString msg = i18n( "There was an error trying to save your data file.\n" - "Time accumulated during this session will not be saved!\n"); - KMessageBox::error(0, msg ); - return; - } - const char * comment = "# TaskView save data\n"; - - f.writeBlock(comment, strlen(comment)); //comment - f.flush(); + kdDebug(5970) << "KarmStorage::saveCalendar" << endl; - QTextStream stream(&f); - for (Task* child = firstChild(); - child; - child = child->nextSibling()) - writeTaskToFile(&stream, child, 1); + KABC::Lock *lock = _calendar->lock(); + if ( !lock || !lock->lock() ) + return false; - f.close(); - kdDebug(5970) << "Saved data to file " << f.name() << endl; -} -void KarmStorage::writeTaskToFile( QTextStream *strm, Task *task, - int level) -{ - //lukas: correct version for non-latin1 users - QString _line = QString::fromLatin1("%1\t%2\t%3").arg(level). - arg(task->time()).arg(task->name()); - - DesktopList d = task->getDesktops(); - int dsize = d.size(); - if (dsize>0) { - _line += '\t'; - for (int i=0; isave() ) { + lock->unlock(); + return true; } - *strm << _line << "\n"; - for ( Task* child= task->firstChild(); - child; - child=child->nextSibling()) { - writeTaskToFile(strm, child, level+1); - } + lock->unlock(); + return false; } - -*/ diff --git a/karm/karmstorage.h b/karm/karmstorage.h index 5a7e8caba3..8e92d1a478 100644 --- a/karm/karmstorage.h +++ b/karm/karmstorage.h @@ -1,350 +1,371 @@ /* * This file only: * Copyright (C) 2003 Mark Bucciarelli * * 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. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ #ifndef KARM_STORAGE_H #define KARM_STORAGE_H #include #include #include "journal.h" #include "reportcriteria.h" #include "desktoplist.h" #include #include #include "resourcecalendar.h" #include class QDateTime; class Preferences; class Task; class TaskView; class HistoryEvent; class KCal::Todo; /** * Singleton to store/retrieve KArm data to/from persistent storage. * * The storage is an iCalendar file. Also included are methods to * import KArm data from the two legacy file formats. * * All logic that deals with getting and saving data should go here. The * storage logic has changed at least twice already in KArm's history, and * chances are good it will change again (for example, allowing KOrganizer and * KArm to access the same iCalendar file simultaneously). * * Prior to KDE 3.2, KArm just stored totals for each task--a session total * and a task total. The session total was reset to zero each time KArm * started up or after the user reset the session times to zero. With the * release of KDE 3.2, KArm now stores these task totals as well as logging * the history of each start/stop event; that is, every time you start a timer * and then stop a timer on a task, KArm records this as an iCalendar event. * * @short Logic that gets and stores KArm data to disk. * @author Mark Bucciarelli */ class KarmStorage { public: /* * Return reference to storage singleton. * - * The constructors are made private, so in order to create this class - * you must use this function. + * The constructors are private, so this must be used to create a + * KarmStorage instance. */ static KarmStorage *instance(); /* * Load the list view with tasks read from iCalendar file. * * Parses iCalendar file, builds list view items in the proper * hierarchy, and loads them into the list view widget. * * If the file name passed in is the same as the last file name that was * loaded, this method does nothing. * * This method considers any of the following conditions errors: * * @li the iCalendar file does not exist * @li the iCalendar file is not readable * @li the list group currently has list items * @li an iCalendar todo has no related to attribute * @li a todo is related to another todo which does not exist * * @param taskview The list group used in the TaskView * @param preferences The current KArm preferences. + * @param fileName Override preferences' filename * * @return empty string if success, error message if error. * */ - QString load(TaskView* taskview, const Preferences* preferences); + QString load(TaskView* taskview, const Preferences* preferences, QString fileName="" ); QString buildTaskView(KCal::ResourceCalendar *rc, TaskView *view); /* Close calendar and clear view. Release lock if holding one. */ void closeStorage(TaskView* view); /* * Save all tasks and their totals to an iCalendar file. * * All tasks must have an associated VTODO object already created in the * calendar file; that is, the task->uid() must refer to a valid VTODO in * the calender. * Delivers empty string if successful, else error msg. * * @param taskview The list group used in the TaskView */ QString save(TaskView* taskview); /** * Read tasks and their total times from a text file (legacy storage). * * This reads from one of the two legacy file formats. In this version, * the parent task times do not include the sum of all their children's * times. * * The format of the file is zero or more lines of: * 1 task id (a number) * time in minutes * string task name * [string] desktops, in which to count. e.g. "1,2,5" (optional) */ QString loadFromFlatFile(TaskView* taskview, const QString& filename); /** * Reads tasks and their total times from text file (legacy). * * This is the older legacy format, where the task totals included the * children totals. * * @see loadFromFlatFile */ QString loadFromFlatFileCumulative(TaskView* taskview, const QString& filename); /** Output a report based on contents of ReportCriteria. */ QString report( TaskView *taskview, const ReportCriteria &rc ); /* * Log the change in a task's time. * * We create an iCalendar event to store each change. The event start * date is set to the current datetime. If time is added to the task, the * task end date is set to start time + delta. If the time is negative, * the end date is set to the start time. * * In both cases (postive or negative delta), we create a custom iCalendar * property that stores the delta (in seconds). This property is called * X-KDE-karm-duration. * * Note that the KArm UI allows the user to change both the session and * the total task time, and this routine does not account for all posibile * cases. For example, it is possible for the user to do something crazy * like add 10 minutes to the session time and subtract 50 minutes from * the total time. Although this change violates a basic law of physics, * it is allowed. * * For now, you should pass in the change to the total task time. * Eventually, the UI should be changed. * * @param task The task the change is for. * @param delta Change in task time, in seconds. Can be negative. */ void changeTime(const Task* task, const long deltaSeconds); + /** + * Book time to a task. + * + * Creates an iCalendar event and adds it to the calendar. Does not write + * calender to disk, just adds event to calendar in memory. However, the + * resource framework does try to get a lock on the file. After a + * succesful lock, the calendar marks this incidence as modified and then + * releases the lock. + * + * @param task Task + * @param startDateTime Date and time the booking starts. + * @param durationInSeconds Duration of time to book, in seconds. + * + * @return true if event was added, false if not (if, for example, the + * attempted file lock failed). + */ + bool bookTime(const Task* task, const QDateTime& startDateTime, + long durationInSeconds); + /** * Log a change to a task name. * * For iCalendar storage, there is no need to log an Event for this event, * since unique id's are used to link Events to Todos. No matter how many * times you change a task's name, the uid stays the same. * * @param task The task * @param oldname The old name of the task. The new name is in the task * object already. */ - void setName(const Task* /*task*/, const QString& /*oldname*/) {} + void setName(const Task* task, const QString& oldname) { Q_UNUSED(task); Q_UNUSED(oldname); } /** * Log the event that a timer has started for a task. * * For the iCalendar storage, there is no need to log anything for this * event. We log an event when the timer is stopped. * * @param task The task the timer was started for. */ - void startTimer(const Task* /*task*/) {} + void startTimer(const Task* task) { Q_UNUSED(task); } /** * Log the event that the timer has stopped for this task. * * The task stores the last time a timer was started, so we log a new iCal * Event with the start and end times for this task. * @see KarmStorage::changeTime * * @param task The task the timer was stopped for. */ void stopTimer(const Task* task); /** * Log a new comment for this task. * * iCal allows multiple comment tags. So we just add a new comment to the * todo for this task and write the calendar. * * @param task The task that gets the comment * @param comment The comment */ void addComment(const Task* task, const QString& comment); /** * Remove this task from iCalendar file. * * Removes task as well as all event history for this task. * * @param task The task to be removed. * @return true if change was saved, false otherwise */ bool removeTask(Task* task); /** * Add this task from iCalendar file. * * Create a new KCal::Todo object and load with task information. If * parent is not zero, then set the RELATED-TO attribute for this Todo. * * @param task The task to be removed. * @param parent The parent of this task. Must have a uid() that is in * the existing calendar. If zero, this task is considered a root task. * @return The unique ID for the new VTODO. Return an null QString if * there was an error creating the new calendar object. */ QString addTask(const Task* task, const Task* parent); /** * Check if the iCalendar file currently loaded has any Todos in it. * * @return true if iCalendar file has any todos */ bool isEmpty(); /** * Check if iCalendar file name in the preferences has changed since the * last call to load. If there is no calendar file currently loaded, * return false. * * @param preferences Set of KArm preferences. * * @return true if a previous file has been loaded and the iCalendar file * specified in the preferences is different. */ bool isNewStorage(const Preferences* preferences) const; /** Return a list of start/stop events for the given date range. */ QValueList getHistory(const QDate& from, const QDate& to); private: static KarmStorage *_instance; - KCal::CalendarResources *_calendar; + KCal::ResourceCalendar *_calendar; QString _icalfile; KarmStorage(); void adjustFromLegacyFileFormat(Task* task); bool parseLine(QString line, long *time, QString *name, int *level, DesktopList* desktopList); - void writeTaskAsTodo + QString writeTaskAsTodo (Task* task, const int level, QPtrStack< KCal::Todo >& parents); + bool saveCalendar(); KCal::Event* baseEvent(const Task*); bool remoteResource( const QString& file ) const; /** * Writes all tasks and their totals to a Comma-Separated Values file. * * The format of this file is zero or more lines of: * taskName,subtaskName,..,sessionTime,time,totalSessionTime,totalTime * the number of subtasks is determined at runtime. */ QString exportcsvFile( TaskView *taskview, const ReportCriteria &rc ); /** * Write task history to file as comma-delimited data. */ QString exportcsvHistory ( TaskView* taskview, const QDate& from, const QDate& to, const ReportCriteria &rc ); long printTaskHistory ( const Task *task, const QMap& taskdaytotals, QMap& daytotals, const QDate& from, const QDate& to, const int level, std::vector &matrix, const ReportCriteria &rc ); }; /** * One start/stop event that has been logged. * * When a task is running and the user stops it, KArm logs this event and * saves it in the history. This class represents such an event read from * storage, and abstracts it from the specific storage used. */ class HistoryEvent { public: /** Needed to be used in a value list. */ HistoryEvent() {} HistoryEvent(QString uid, QString name, long duration, QDateTime start, QDateTime stop, QString todoUid); QString uid() {return _uid; } QString name() {return _name; } /** In seconds. */ long duration() {return _duration; } QDateTime start() {return _start; } QDateTime stop() { return _stop; } QString todoUid() {return _todoUid; } private: QString _uid; QString _todoUid; QString _name; long _duration; QDateTime _start; QDateTime _stop; }; #endif // KARM_STORAGE_H diff --git a/karm/karmui.rc b/karm/karmui.rc index 74a48e46ee..d47608edb6 100644 --- a/karm/karmui.rc +++ b/karm/karmui.rc @@ -1,72 +1,81 @@ &File &Import/Export &Clock &Task + + + + + &Settings + Main Toolbar + + + diff --git a/karm/mainwindow.cpp b/karm/mainwindow.cpp index 898e172264..79427f2a48 100644 --- a/karm/mainwindow.cpp +++ b/karm/mainwindow.cpp @@ -1,488 +1,721 @@ /* * Top Level window for KArm. * Distributed under the GPL. */ #include #include "kaccelmenuwatch.h" #include #include #include #include // kapp #include #include #include #include #include // i18n #include #include // statusBar() #include #include #include #include #include +#include "karmerrors.h" #include "karmutility.h" #include "mainwindow.h" #include "preferences.h" #include "print.h" #include "task.h" #include "taskview.h" #include "timekard.h" #include "tray.h" #include "version.h" MainWindow::MainWindow( const QString &icsfile ) : DCOPObject ( "KarmDCOPIface" ), - KMainWindow(0), + KParts::MainWindow(), _accel ( new KAccel( this ) ), _watcher ( new KAccelMenuWatch( _accel, this ) ), _totalSum ( 0 ), _sessionSum( 0 ) { _taskView = new TaskView( this, 0, icsfile ); setCentralWidget( _taskView ); // status bar startStatusBar(); // setup PreferenceDialog. _preferences = Preferences::instance(); // popup menus makeMenus(); _watcher->updateMenus(); // connections connect( _taskView, SIGNAL( totalTimesChanged( long, long ) ), this, SLOT( updateTime( long, long ) ) ); connect( _taskView, SIGNAL( selectionChanged ( QListViewItem * )), this, SLOT(slotSelectionChanged())); connect( _taskView, SIGNAL( updateButtons() ), this, SLOT(slotSelectionChanged())); loadGeometry(); // Setup context menu request handling connect( _taskView, SIGNAL( contextMenuRequested( QListViewItem*, const QPoint&, int )), this, SLOT( contextMenuRequest( QListViewItem*, const QPoint&, int ))); _tray = new KarmTray( this ); connect( _tray, SIGNAL( quitSelected() ), SLOT( quit() ) ); connect( _taskView, SIGNAL( timersActive() ), _tray, SLOT( startClock() ) ); connect( _taskView, SIGNAL( timersActive() ), this, SLOT( enableStopAll() )); connect( _taskView, SIGNAL( timersInactive() ), _tray, SLOT( stopClock() ) ); connect( _taskView, SIGNAL( timersInactive() ), this, SLOT( disableStopAll())); connect( _taskView, SIGNAL( tasksChanged( QPtrList ) ), _tray, SLOT( updateToolTip( QPtrList ) )); _taskView->load(); // Everything that uses Preferences has been created now, we can let it // emit its signals _preferences->emitSignals(); slotSelectionChanged(); // Register with DCOP if ( !kapp->dcopClient()->isRegistered() ) { kapp->dcopClient()->registerAs( "karm" ); kapp->dcopClient()->setDefaultObject( objId() ); } + + // Set up DCOP error messages + m_error[ KARM_ERR_GENERIC_SAVE_FAILED ] = + i18n( "Save failed, most likely because the file could not be locked." ); + m_error[ KARM_ERR_COULD_NOT_MODIFY_RESOURCE ] = + i18n( "Could not modify calendar resource." ); + m_error[ KARM_ERR_MEMORY_EXHAUSTED ] = + i18n( "Out of memory--could not create object." ); + m_error[ KARM_ERR_UID_NOT_FOUND ] = + i18n( "UID not found." ); + m_error[ KARM_ERR_INVALID_DATE ] = + i18n( "Invalidate date--format is YYYY-MM-DD." ); + m_error[ KARM_ERR_INVALID_TIME ] = + i18n( "Invalid time--format is YYYY-MM-DDTHH:MM:SS." ); + m_error[ KARM_ERR_INVALID_DURATION ] = + i18n( "Invalid task duration--must be greater than zero." ); } void MainWindow::slotSelectionChanged() { Task* item= _taskView->current_item(); actionDelete->setEnabled(item); actionEdit->setEnabled(item); - actionStart->setEnabled(item && !item->isRunning()); + actionStart->setEnabled(item && !item->isRunning() && !item->isComplete()); actionStop->setEnabled(item && item->isRunning()); + actionMarkAsComplete->setEnabled(item && !item->isComplete()); + actionMarkAsIncomplete->setEnabled(item && item->isComplete()); } // This is _old_ code, but shows how to enable/disable add comment menu item. // We'll need this kind of logic when comments are implemented. //void MainWindow::timeLoggingChanged(bool on) //{ // actionAddComment->setEnabled( on ); //} -void MainWindow::save() +bool MainWindow::save() { - kdDebug(5970) << i18n("Saving time data to disk.") << endl; + kdDebug(5970) << "Saving time data to disk." << endl; QString err=_taskView->save(); // untranslated error msg. if (err.isEmpty()) statusBar()->message(i18n("Successfully saved tasks and history"),1807); else statusBar()->message(i18n(err.ascii()),7707); // no msgbox since save is called when exiting saveGeometry(); + return true; } void MainWindow::exportcsvHistory() { - kdDebug(5970) << i18n("Exporting History to disk.") << endl; + kdDebug(5970) << "Exporting History to disk." << endl; QString err=_taskView->exportcsvHistory(); if (err.isEmpty()) statusBar()->message(i18n("Successfully exported History to CSV-file"),1807); - else KMessageBox::error(this, i18n(err.ascii())); + else KMessageBox::error(this, err.ascii()); saveGeometry(); } void MainWindow::quit() { kapp->quit(); } MainWindow::~MainWindow() { - kdDebug(5970) << i18n("MainWindow::~MainWindows: Quitting karm.") << endl; + kdDebug(5970) << "MainWindow::~MainWindows: Quitting karm." << endl; _taskView->stopAllTimers(); save(); _taskView->closeStorage(); } void MainWindow::enableStopAll() { actionStopAll->setEnabled(true); } void MainWindow::disableStopAll() { actionStopAll->setEnabled(false); } /** * Calculate the sum of the session time and the total time for all * toplevel tasks and put it in the statusbar. */ void MainWindow::updateTime( long sessionDiff, long totalDiff ) { _sessionSum += sessionDiff; _totalSum += totalDiff; updateStatusBar(); } void MainWindow::updateStatusBar( ) { QString time; time = formatTime( _sessionSum ); statusBar()->changeItem( i18n("Session: %1").arg(time), 0 ); time = formatTime( _totalSum ); statusBar()->changeItem( i18n("Total: %1" ).arg(time), 1); } void MainWindow::startStatusBar() { statusBar()->insertItem( i18n("Session"), 0, 0, true ); statusBar()->insertItem( i18n("Total" ), 1, 0, true ); } void MainWindow::saveProperties( KConfig* cfg ) { _taskView->stopAllTimers(); _taskView->save(); cfg->writeEntry( "WindowShown", isVisible()); } void MainWindow::readProperties( KConfig* cfg ) { if( cfg->readBoolEntry( "WindowShown", true )) show(); } void MainWindow::keyBindings() { KKeyDialog::configure( actionCollection(), this ); } void MainWindow::startNewSession() { _taskView->startNewSession(); } void MainWindow::resetAllTimes() { if ( KMessageBox::warningContinueCancel( this, i18n( "Do you really want to reset the time to zero for all tasks?" ), i18n( "Confirmation Required" ), KGuiItem( i18n( "Reset All Times" ) ) ) == KMessageBox::Continue ) _taskView->resetTimeForAllTasks(); } void MainWindow::makeMenus() { KAction *actionKeyBindings, *actionNew, *actionNewSub; (void) KStdAction::quit( this, SLOT( quit() ), actionCollection()); (void) KStdAction::print( this, SLOT( print() ), actionCollection()); actionKeyBindings = KStdAction::keyBindings( this, SLOT( keyBindings() ), actionCollection() ); actionPreferences = KStdAction::preferences(_preferences, SLOT(showDialog()), actionCollection() ); (void) KStdAction::save( this, SLOT( save() ), actionCollection() ); KAction* actionStartNewSession = new KAction( i18n("Start &New Session"), 0, this, SLOT( startNewSession() ), actionCollection(), "start_new_session"); KAction* actionResetAll = new KAction( i18n("&Reset All Times"), 0, this, SLOT( resetAllTimes() ), actionCollection(), "reset_all_times"); actionStart = new KAction( i18n("&Start"), QString::fromLatin1("1rightarrow"), Key_S, _taskView, SLOT( startCurrentTimer() ), actionCollection(), "start"); actionStop = new KAction( i18n("S&top"), QString::fromLatin1("stop"), 0, _taskView, SLOT( stopCurrentTimer() ), actionCollection(), "stop"); actionStopAll = new KAction( i18n("Stop &All Timers"), Key_Escape, _taskView, SLOT( stopAllTimers() ), actionCollection(), "stopAll"); actionStopAll->setEnabled(false); actionNew = new KAction( i18n("&New..."), QString::fromLatin1("filenew"), CTRL+Key_N, _taskView, SLOT( newTask() ), actionCollection(), "new_task"); actionNewSub = new KAction( i18n("New &Subtask..."), QString::fromLatin1("kmultiple"), CTRL+ALT+Key_N, _taskView, SLOT( newSubTask() ), actionCollection(), "new_sub_task"); actionDelete = new KAction( i18n("&Delete"), QString::fromLatin1("editdelete"), Key_Delete, _taskView, SLOT( deleteTask() ), actionCollection(), "delete_task"); actionEdit = new KAction( i18n("&Edit..."), QString::fromLatin1("edit"), CTRL + Key_E, _taskView, SLOT( editTask() ), actionCollection(), "edit_task"); // actionAddComment = new KAction( i18n("&Add Comment..."), // QString::fromLatin1("document"), // CTRL+ALT+Key_E, // _taskView, // SLOT( addCommentToTask() ), // actionCollection(), // "add_comment_to_task"); actionMarkAsComplete = new KAction( i18n("&Mark as Complete"), QString::fromLatin1("document"), CTRL+Key_M, _taskView, SLOT( markTaskAsComplete() ), actionCollection(), "mark_as_complete"); + actionMarkAsIncomplete = new KAction( i18n("&Mark as Incomplete"), + QString::fromLatin1("document"), + CTRL+Key_M, + _taskView, + SLOT( markTaskAsIncomplete() ), + actionCollection(), + "mark_as_incomplete"); actionClipTotals = new KAction( i18n("&Copy Totals to Clipboard"), QString::fromLatin1("klipper"), CTRL+Key_C, _taskView, SLOT( clipTotals() ), actionCollection(), "clip_totals"); actionClipHistory = new KAction( i18n("Copy &History to Clipboard"), QString::fromLatin1("klipper"), CTRL+ALT+Key_C, _taskView, SLOT( clipHistory() ), actionCollection(), "clip_history"); new KAction( i18n("Import &Legacy Flat File..."), 0, _taskView, SLOT(loadFromFlatFile()), actionCollection(), "import_flatfile"); new KAction( i18n("&Export to CSV File..."), 0, _taskView, SLOT(exportcsvFile()), actionCollection(), "export_csvfile"); new KAction( i18n("Export &History to CSV File..."), 0, this, SLOT(exportcsvHistory()), actionCollection(), "export_csvhistory"); new KAction( i18n("Import Tasks From &Planner..."), 0, _taskView, SLOT(importPlanner()), actionCollection(), "import_planner"); /* new KAction( i18n("Import E&vents"), 0, _taskView, SLOT( loadFromKOrgEvents() ), actionCollection(), "import_korg_events"); */ - createGUI( QString::fromLatin1("karmui.rc") ); + setXMLFile( QString::fromLatin1("karmui.rc") ); + createGUI( 0 ); - // Tool tops must be set after the createGUI. + // Tool tips must be set after the createGUI. actionKeyBindings->setToolTip( i18n("Configure key bindings") ); actionKeyBindings->setWhatsThis( i18n("This will let you configure key" "bindings which is specific to karm") ); actionStartNewSession->setToolTip( i18n("Start a new session") ); actionStartNewSession->setWhatsThis( i18n("This will reset the session time " "to 0 for all tasks, to start a " "new session, without affecting " "the totals.") ); actionResetAll->setToolTip( i18n("Reset all times") ); actionResetAll->setWhatsThis( i18n("This will reset the session and total " "time to 0 for all tasks, to restart from " "scratch.") ); actionStart->setToolTip( i18n("Start timing for selected task") ); actionStart->setWhatsThis( i18n("This will start timing for the selected " "task.\n" "It is even possible to time several tasks " "simultaneously.\n\n" "You may also start timing of a tasks by " "double clicking the left mouse " "button on a given task. This will, however, " "stop timing of other tasks.")); actionStop->setToolTip( i18n("Stop timing of the selected task") ); actionStop->setWhatsThis( i18n("Stop timing of the selected task") ); actionStopAll->setToolTip( i18n("Stop all of the active timers") ); actionStopAll->setWhatsThis( i18n("Stop all of the active timers") ); actionNew->setToolTip( i18n("Create new top level task") ); actionNew->setWhatsThis( i18n("This will create a new top level task.") ); actionDelete->setToolTip( i18n("Delete selected task") ); actionDelete->setWhatsThis( i18n("This will delete the selected task and " "all its subtasks.") ); actionEdit->setToolTip( i18n("Edit name or times for selected task") ); actionEdit->setWhatsThis( i18n("This will bring up a dialog box where you " "may edit the parameters for the selected " "task.")); //actionAddComment->setToolTip( i18n("Add a comment to a task") ); //actionAddComment->setWhatsThis( i18n("This will bring up a dialog box where " // "you can add a comment to a task. The " // "comment can for instance add information on what you " // "are currently doing. The comment will " // "be logged in the log file.")); actionClipTotals->setToolTip(i18n("Copy task totals to clipboard")); actionClipHistory->setToolTip(i18n("Copy time card history to clipboard.")); slotSelectionChanged(); } void MainWindow::print() { MyPrinter printer(_taskView); printer.print(); } void MainWindow::loadGeometry() { if (initialGeometrySet()) setAutoSaveSettings(); else { KConfig &config = *kapp->config(); config.setGroup( QString::fromLatin1("Main Window Geometry") ); int w = config.readNumEntry( QString::fromLatin1("Width"), 100 ); int h = config.readNumEntry( QString::fromLatin1("Height"), 100 ); w = QMAX( w, sizeHint().width() ); h = QMAX( h, sizeHint().height() ); resize(w, h); } } void MainWindow::saveGeometry() { KConfig &config = *KGlobal::config(); config.setGroup( QString::fromLatin1("Main Window Geometry")); config.writeEntry( QString::fromLatin1("Width"), width()); config.writeEntry( QString::fromLatin1("Height"), height()); config.sync(); } bool MainWindow::queryClose() { if ( !kapp->sessionSaving() ) { hide(); return false; } return KMainWindow::queryClose(); } void MainWindow::contextMenuRequest( QListViewItem*, const QPoint& point, int ) { QPopupMenu* pop = dynamic_cast( factory()->container( i18n( "task_popup" ), this ) ); if ( pop ) pop->popup( point ); } //---------------------------------------------------------------------------- // // D C O P I N T E R F A C E // //---------------------------------------------------------------------------- QString MainWindow::version() const { return KARM_VERSION; } -QString MainWindow::hastodo( const QString &taskname ) const +QString MainWindow::deletetodo() +{ + _taskView->deleteTask(); + return ""; +} + +bool MainWindow::getpromptdelete() +{ + return _preferences->promptDelete(); +} + +QString MainWindow::setpromptdelete( bool prompt ) +{ + _preferences->setPromptDelete( prompt ); + return ""; +} + +QString MainWindow::taskIdFromName( const QString &taskname ) const { QString rval = ""; Task* task = _taskView->first_child(); while ( rval.isEmpty() && task ) { - rval = _hastodo( task, taskname ); + rval = _hasTask( task, taskname ); task = task->nextSibling(); } return rval; } -QString MainWindow::_hastodo( Task* task, const QString &taskname ) const +int MainWindow::addTask( const QString& taskname ) +{ + DesktopList desktopList; + QString uid = _taskView->addTask( taskname, 0, 0, desktopList ); + kdDebug(5970) << "MainWindow::addTask( " << taskname << " ) returns " << uid << endl; + if ( uid.length() > 0 ) return 0; + else + { + // We can't really tell what happened, b/c the resource framework only + // returns a boolean. + return KARM_ERR_GENERIC_SAVE_FAILED; + } +} + +QString MainWindow::setPerCentComplete( const QString& taskName, int perCent ) +{ + int index; + QString err="no such task"; + for (int i=0; i<_taskView->count(); i++) + { + if ((_taskView->item_at_index(i)->name()==taskName)) + { + index=i; + if (err==QString::null) err="task name is abigious"; + if (err=="no such task") err=QString::null; + } + } + if (err==QString::null) + { + _taskView->item_at_index(index)->setPercentComplete( perCent, _taskView->storage() ); + } + return err; +} + +int MainWindow::bookTime +( const QString& taskId, const QString& datetime, long minutes ) +{ + int rval = 0; + QDate startDate; + QTime startTime; + QDateTime startDateTime; + Task *task, *t; + + if ( minutes <= 0 ) rval = KARM_ERR_INVALID_DURATION; + + // Find task + task = _taskView->first_child(); + t = NULL; + while ( !t && task ) + { + t = _hasUid( task, taskId ); + task = task->nextSibling(); + } + if ( t == NULL ) rval = KARM_ERR_UID_NOT_FOUND; + + // Parse datetime + if ( !rval ) + { + startDate = QDate::fromString( datetime, Qt::ISODate ); + if ( datetime.length() > 10 ) // "YYYY-MM-DD".length() = 10 + { + startTime = QTime::fromString( datetime, Qt::ISODate ); + } + else startTime = QTime( 12, 0 ); + if ( startDate.isValid() && startTime.isValid() ) + { + startDateTime = QDateTime( startDate, startTime ); + } + else rval = KARM_ERR_INVALID_DATE; + + } + + // Update task totals (session and total) and save to disk + if ( !rval ) + { + t->changeTotalTimes( t->sessionTime() + minutes, t->totalTime() + minutes ); + if ( ! _taskView->storage()->bookTime( t, startDateTime, minutes * 60 ) ) + { + rval = KARM_ERR_GENERIC_SAVE_FAILED; + } + } + + return rval; +} + +// There was something really bad going on with DCOP when I used a particular +// argument name; if I recall correctly, the argument name was errno. +QString MainWindow::getError( int mkb ) const +{ + if ( mkb <= KARM_MAX_ERROR_NO ) return m_error[ mkb ]; + else return i18n( "Invalid error number: %1" ).arg( mkb ); +} + +int MainWindow::totalMinutesForTaskId( const QString& taskId ) +{ + int rval = 0; + Task *task, *t; + + kdDebug(5970) << "MainWindow::totalTimeForTask( " << taskId << " )" << endl; + + // Find task + task = _taskView->first_child(); + t = NULL; + while ( !t && task ) + { + t = _hasUid( task, taskId ); + task = task->nextSibling(); + } + if ( t != NULL ) + { + rval = t->totalTime(); + kdDebug(5970) << "MainWindow::totalTimeForTask - task found: rval = " << rval << endl; + } + else + { + kdDebug(5970) << "MainWindow::totalTimeForTask - task not found" << endl; + rval = KARM_ERR_UID_NOT_FOUND; + } + + return rval; +} + +QString MainWindow::_hasTask( Task* task, const QString &taskname ) const { QString rval = ""; if ( task->name() == taskname ) { rval = task->uid(); } else { Task* nexttask = task->firstChild(); while ( rval.isEmpty() && nexttask ) { - rval = _hastodo( nexttask, taskname ); + rval = _hasTask( nexttask, taskname ); nexttask = nexttask->nextSibling(); } } return rval; } -QString MainWindow::addtodo( const QString& taskname ) +Task* MainWindow::_hasUid( Task* task, const QString &uid ) const { - DesktopList desktopList; - return _taskView->addTask( taskname, 0, 0, desktopList ); + Task *rval = NULL; + + //kdDebug(5970) << "MainWindow::_hasUid( " << task << ", " << uid << " )" << endl; + + if ( task->uid() == uid ) rval = task; + else + { + Task* nexttask = task->firstChild(); + while ( !rval && nexttask ) + { + rval = _hasUid( nexttask, uid ); + nexttask = nexttask->nextSibling(); + } + } + return rval; +} +QString MainWindow::starttimerfor( const QString& taskname ) +{ + int index; + QString err="no such task"; + for (int i=0; i<_taskView->count(); i++) + { + if ((_taskView->item_at_index(i)->name()==taskname)) + { + index=i; + if (err==QString::null) err="task name is abigious"; + if (err=="no such task") err=QString::null; + } + } + if (err==QString::null) _taskView->startTimerFor( _taskView->item_at_index(index) ); + return err; +} + +QString MainWindow::stoptimerfor( const QString& taskname ) +{ + int index; + QString err="no such task"; + for (int i=0; i<_taskView->count(); i++) + { + if ((_taskView->item_at_index(i)->name()==taskname)) + { + index=i; + if (err==QString::null) err="task name is abigious"; + if (err=="no such task") err=QString::null; + } + } + if (err==QString::null) _taskView->stopTimerFor( _taskView->item_at_index(index) ); + return err; +} + +QString MainWindow::exportcsvfile( QString filename, QString from, QString to, int type, bool decimalMinutes, bool allTasks, QString delimiter, QString quote ) +{ + ReportCriteria rc; + rc.allTasks=allTasks; + rc.decimalMinutes=decimalMinutes; + rc.delimiter=delimiter; + rc.from=QDate::fromString( from ); + rc.quote=quote; + rc.reportType=(ReportCriteria::REPORTTYPE) type; + rc.to=QDate::fromString( to ); + rc.url=filename; + return _taskView->report( rc ); +} + +QString MainWindow::importplannerfile( QString fileName ) +{ + return _taskView->importPlanner(fileName); } + #include "mainwindow.moc" diff --git a/karm/mainwindow.h b/karm/mainwindow.h index 9b0fd5dd14..1899e11da4 100644 --- a/karm/mainwindow.h +++ b/karm/mainwindow.h @@ -1,91 +1,114 @@ #ifndef KARM_MAIN_WINDOW_H #define KARM_MAIN_WINDOW_H -#include +#include + +#include "karmerrors.h" #include +#include "reportcriteria.h" class KAccel; class KAccelMenuWatch; -class KDialogBase; class KarmTray; class QListViewItem; class QPoint; class QString; class Preferences; class PrintDialog; class Task; class TaskView; /** * Main window to tie the application together. */ -class MainWindow : public KMainWindow, virtual public KarmDCOPIface +class MainWindow : public KParts::MainWindow, virtual public KarmDCOPIface { Q_OBJECT private: - KAccel *_accel; - KAccelMenuWatch *_watcher; - TaskView *_taskView; - long _totalSum; - long _sessionSum; - Preferences *_preferences; - KarmTray *_tray; + void makeMenus(); + QString _hasTask( Task* task, const QString &taskname ) const; + Task* _hasUid( Task* task, const QString &uid ) const; + + KAccel* _accel; + KAccelMenuWatch* _watcher; + TaskView* _taskView; + long _totalSum; + long _sessionSum; + Preferences* _preferences; + KarmTray* _tray; + KAction* actionStart; + KAction* actionStop; + KAction* actionStopAll; + KAction* actionDelete; + KAction* actionEdit; + KAction* actionMarkAsComplete; + KAction* actionMarkAsIncomplete; + KAction* actionPreferences; + KAction* actionClipTotals; + KAction* actionClipHistory; + QString m_error[ KARM_MAX_ERROR_NO + 1 ]; + + friend class KarmTray; + + //private: + + //KDialogBase *dialog; + + public: MainWindow( const QString &icsfile = "" ); virtual ~MainWindow(); // DCOP QString version() const; - QString hastodo( const QString &storage ) const; - QString addtodo( const QString &storage ); + QString taskIdFromName( const QString &taskName ) const; + /** @reimp from KarmDCOPIface::addTask */ + int addTask( const QString &storage ); + /** @reimp from KarmDCOPIface::setPerCentComplete */ + QString setPerCentComplete( const QString& taskName, int PerCent ); + /** @reimp from KarmDCOPIface::bookTime */ + int bookTime( const QString& taskId, const QString& iso8601StartDateTime, long durationInMinutes ); + /** @reimp from KarmDCOPIface::getError */ + QString getError( int karmErrorNumber ) const; + int totalMinutesForTaskId( const QString& taskId ); + QString starttimerfor( const QString &taskname ); + QString stoptimerfor( const QString &taskname ); + QString deletetodo(); + bool getpromptdelete(); + QString setpromptdelete( bool prompt ); + QString exportcsvfile( QString filename, QString from, QString to, int type, bool decimalMinutes, bool allTasks, QString delimiter, QString quote ); + QString importplannerfile( QString filename ); public slots: void quit(); protected slots: void keyBindings(); void startNewSession(); void resetAllTimes(); void updateTime( long, long ); void updateStatusBar(); - void save(); + bool save(); void exportcsvHistory(); void print(); void slotSelectionChanged(); void contextMenuRequest( QListViewItem*, const QPoint&, int ); void enableStopAll(); void disableStopAll(); // void timeLoggingChanged( bool on ); protected: void startStatusBar(); virtual void saveProperties( KConfig* ); virtual void readProperties( KConfig* ); void saveGeometry(); void loadGeometry(); bool queryClose(); - private: - void makeMenus(); - QString _hastodo( Task* task, const QString &taskname ) const; - - KDialogBase *dialog; - KAction* actionStart; - KAction* actionStop; - KAction* actionStopAll; - KAction* actionDelete; - KAction* actionEdit; -// KAction* actionAddComment; - KAction* actionMarkAsComplete; - KAction* actionPreferences; - KAction* actionClipTotals; - KAction* actionClipHistory; - - friend class KarmTray; }; #endif // KARM_MAIN_WINDOW_H diff --git a/karm/pics/Makefile.am b/karm/pics/Makefile.am index 5e8f466d9f..c57c57a184 100644 --- a/karm/pics/Makefile.am +++ b/karm/pics/Makefile.am @@ -1,9 +1,10 @@ pics_DATA = filedel.xpm clock.xpm clockedit.xpm empty-watch.xpm\ watch-0.xpm watch-1.xpm watch-2.xpm watch-3.xpm \ watch-4.xpm watch-5.xpm watch-6.xpm watch-7.xpm \ active-icon-0.xpm active-icon-1.xpm active-icon-2.xpm \ active-icon-3.xpm active-icon-4.xpm active-icon-5.xpm \ - active-icon-6.xpm active-icon-7.xpm + active-icon-6.xpm active-icon-7.xpm \ + task-complete.xpm task-incomplete.xpm picsdir = $(kde_datadir)/karm/pics diff --git a/ktimetracker/pics/task-complete.xpm b/karm/pics/task-complete.xpm similarity index 100% rename from ktimetracker/pics/task-complete.xpm rename to karm/pics/task-complete.xpm diff --git a/ktimetracker/pics/task-incomplete.xpm b/karm/pics/task-incomplete.xpm similarity index 100% rename from ktimetracker/pics/task-incomplete.xpm rename to karm/pics/task-incomplete.xpm diff --git a/karm/plannerparser.cpp b/karm/plannerparser.cpp index dcdc7426b4..21e0c4f768 100644 --- a/karm/plannerparser.cpp +++ b/karm/plannerparser.cpp @@ -1,100 +1,100 @@ // // C++ Implementation: plannerparser // // Description: /* this class is here to import tasks from a planner project file to karm. the import shall not be limited to karm (kPlaTo sends greetings) it imports planner's top-level-tasks on the same level-depth as current_item. if there is no current_item, planner's top-level-tasks will become top-level-tasks in karm. it imports as well the level-depth of each task, as its name, as its percent-complete. test cases: - deleting all tasks away, then import! - having started with an empty ics, import! - with current_item being a top-level-task, import! - with current_item being a subtask, import! Author: Thorsten Staerk , (C) 2004 Copyright: See COPYING file that comes with this distribution */ #include "plannerparser.h" PlannerParser::PlannerParser(TaskView * tv) // if there is a task one level above current_item, make it the father of all imported tasks. Set level accordingly. // import as well if there a no task in the taskview as if there are. // if there are, put the top-level tasks of planner on the same level as current_item. // So you have the chance as well to have the planner tasks at top-level as at a whatever-so-deep sublevel. { kdDebug() << "entering constructor to import planner tasks" << endl; _taskView=tv; level=0; if (_taskView->current_item()) if (_taskView->current_item()->parent()) { task = _taskView->current_item()->parent(); level=1; } } bool PlannerParser::startDocument() { withInTasks=false; // becomes true as soon as parsing occurres - return TRUE; + return true; } bool PlannerParser::startElement( const QString&, const QString&, const QString& qName, const QXmlAttributes& att ) { kdDebug() << "entering startElement" << endl; QString taskName; int taskComplete=0; // only s within are processed if (qName == QString::fromLatin1("tasks")) withInTasks=true; if ((qName == QString::fromLatin1("task")) && (withInTasks)) { // find out name and percent-complete for (int i=0; i0) { parentTask=task; task = new Task(taskName, 0, 0, dl, parentTask); task->setUid(_taskView->storage()->addTask(task, parentTask)); } else { task = new Task(taskName, 0, 0, dl, _taskView); kdDebug() << "added" << taskName << endl; task->setUid(_taskView->storage()->addTask(task, 0)); } task->setPercentComplete(taskComplete, _taskView->storage()); } - return TRUE; + return true; } bool PlannerParser::endElement( const QString&, const QString&, const QString& qName) { // only s within increased level, so only decrease for s within if (withInTasks) { if (qName=="task") if (level-->=0) task=task->parent(); if (qName=="tasks") withInTasks=false; } - return TRUE; + return true; } diff --git a/karm/preferences.cpp b/karm/preferences.cpp index f2e2a95a24..d02db1cdc6 100644 --- a/karm/preferences.cpp +++ b/karm/preferences.cpp @@ -1,332 +1,333 @@ #undef Unsorted // for --enable-final #include #include #include #include #include #include // kapp #include #include #include #include #include // lineEdit() #include // i18n #include #include #include "preferences.h" Preferences *Preferences::_instance = 0; Preferences::Preferences( const QString& icsFile ) : KDialogBase( IconList, i18n("Preferences"), Ok|Cancel, Ok ) { setIconListAllVisible( true ); makeBehaviorPage(); makeDisplayPage(); makeStoragePage(); load(); // command-line option overrides what is stored in if ( ! icsFile.isEmpty() ) _iCalFileV = icsFile; } Preferences *Preferences::instance( const QString &icsfile ) { if (_instance == 0) { _instance = new Preferences( icsfile ); } return _instance; } void Preferences::makeBehaviorPage() { QPixmap icon = SmallIcon( "kcmsystem", KIcon::SizeMedium); QFrame* behaviorPage = addPage( i18n("Behavior"), i18n("Behavior Settings"), icon ); QVBoxLayout* topLevel = new QVBoxLayout( behaviorPage, 0, spacingHint() ); QGridLayout* layout = new QGridLayout( topLevel, 2, 2 ); layout->setColStretch( 1, 1 ); _doIdleDetectionW = new QCheckBox ( i18n("Detect desktop as idle after"), behaviorPage, "_doIdleDetectionW"); _idleDetectValueW = new QSpinBox (1,60*24, 1, behaviorPage, "_idleDetectValueW"); _idleDetectValueW->setSuffix(i18n(" min")); _promptDeleteW = new QCheckBox ( i18n( "Prompt before deleting tasks" ), behaviorPage, "_promptDeleteW" ); layout->addWidget(_doIdleDetectionW, 0, 0 ); layout->addWidget(_idleDetectValueW, 0, 1 ); layout->addWidget(_promptDeleteW, 1, 0 ); topLevel->addStretch(); connect( _doIdleDetectionW, SIGNAL( clicked() ), this, SLOT( idleDetectCheckBoxChanged() )); } void Preferences::makeDisplayPage() { QPixmap icon = SmallIcon( "viewmag", KIcon::SizeMedium ); QFrame* displayPage = addPage( i18n("Display"), i18n("Display Settings"), icon ); QVBoxLayout* topLevel = new QVBoxLayout( displayPage, 0, spacingHint() ); QGridLayout* layout = new QGridLayout( topLevel, 5, 2 ); layout->setColStretch( 1, 1 ); QLabel* _displayColumnsLabelW = new QLabel( i18n("Columns displayed:"), displayPage ); _displaySessionW = new QCheckBox ( i18n("Session time"), displayPage, "_displaySessionW"); _displayTimeW = new QCheckBox ( i18n("Cumulative task time"), displayPage, "_displayTimeW"); _displayTotalSessionW = new QCheckBox( i18n("Total session time"), displayPage, "_displayTotalSessionW"); _displayTotalTimeW = new QCheckBox ( i18n("Total task time"), displayPage, "_displayTotalTimeW"); layout->addMultiCellWidget( _displayColumnsLabelW, 0, 0, 0, 1 ); layout->addWidget(_displaySessionW, 1, 1 ); layout->addWidget(_displayTimeW, 2, 1 ); layout->addWidget(_displayTotalSessionW, 3, 1 ); layout->addWidget(_displayTotalTimeW, 4, 1 ); topLevel->addStretch(); } void Preferences::makeStoragePage() { QPixmap icon = SmallIcon( "kfm", KIcon::SizeMedium ); QFrame* storagePage = addPage( i18n("Storage"), i18n("Storage Settings"), icon ); QVBoxLayout* topLevel = new QVBoxLayout( storagePage, 0, spacingHint() ); QGridLayout* layout = new QGridLayout( topLevel, 4, 2 ); layout->setColStretch( 1, 1 ); // autosave _doAutoSaveW = new QCheckBox ( i18n("Save tasks every"), storagePage, "_doAutoSaveW" ); _autoSaveValueW = new QSpinBox(1, 60*24, 1, storagePage, "_autoSaveValueW"); _autoSaveValueW->setSuffix(i18n(" min")); // iCalendar QLabel* _iCalFileLabel = new QLabel( i18n("iCalendar file:"), storagePage); _iCalFileW = new KURLRequester(storagePage, "_iCalFileW"); _iCalFileW->setFilter(QString::fromLatin1("*.ics")); _iCalFileW->setMode(KFile::File); // Log time? _loggingW = new QCheckBox ( i18n("Log history"), storagePage, "_loggingW" ); // add widgets to layout layout->addWidget(_doAutoSaveW, 0, 0); layout->addWidget(_autoSaveValueW, 0, 1); layout->addWidget(_iCalFileLabel, 1, 0 ); layout->addWidget(_iCalFileW, 1, 1 ); layout->addWidget(_loggingW, 2, 0 ); topLevel->addStretch(); // checkboxes disable file selection controls connect( _doAutoSaveW, SIGNAL( clicked() ), this, SLOT( autoSaveCheckBoxChanged() )); } void Preferences::disableIdleDetection() { _doIdleDetectionW->setEnabled(false); } //--------------------------------------------------------------------------- // SLOTS //--------------------------------------------------------------------------- void Preferences::showDialog() { // set all widgets _iCalFileW->lineEdit()->setText(_iCalFileV); _doIdleDetectionW->setChecked(_doIdleDetectionV); _idleDetectValueW->setValue(_idleDetectValueV); _doAutoSaveW->setChecked(_doAutoSaveV); _autoSaveValueW->setValue(_autoSaveValueV); _loggingW->setChecked(_loggingV); _promptDeleteW->setChecked(_promptDeleteV); _displaySessionW->setChecked(_displayColumnV[0]); _displayTimeW->setChecked(_displayColumnV[1]); _displayTotalSessionW->setChecked(_displayColumnV[2]); _displayTotalTimeW->setChecked(_displayColumnV[3]); // adapt visibility of preference items according // to settings idleDetectCheckBoxChanged(); autoSaveCheckBoxChanged(); show(); } void Preferences::slotOk() { // storage _iCalFileV = _iCalFileW->lineEdit()->text(); _doIdleDetectionV = _doIdleDetectionW->isChecked(); _idleDetectValueV = _idleDetectValueW->value(); _doAutoSaveV = _doAutoSaveW->isChecked(); _autoSaveValueV = _autoSaveValueW->value(); _loggingV = _loggingW->isChecked(); // behavior _promptDeleteV = _promptDeleteW->isChecked(); // display _displayColumnV[0] = _displaySessionW->isChecked(); _displayColumnV[1] = _displayTimeW->isChecked(); _displayColumnV[2] = _displayTotalSessionW->isChecked(); _displayColumnV[3] = _displayTotalTimeW->isChecked(); emitSignals(); save(); KDialogBase::slotOk(); } void Preferences::slotCancel() { KDialogBase::slotCancel(); } void Preferences::idleDetectCheckBoxChanged() { _idleDetectValueW->setEnabled(_doIdleDetectionW->isChecked()); } void Preferences::autoSaveCheckBoxChanged() { _autoSaveValueW->setEnabled(_doAutoSaveW->isChecked()); } void Preferences::emitSignals() { emit iCalFile( _iCalFileV ); emit detectIdleness( _doIdleDetectionV ); emit idlenessTimeout( _idleDetectValueV ); emit autoSave( _doAutoSaveV ); emit autoSavePeriod( _autoSaveValueV ); emit setupChanged(); } -QString Preferences::iCalFile() const { return _iCalFileV; } -QString Preferences::activeCalendarFile() const { return _iCalFileV; } -bool Preferences::detectIdleness() const { return _doIdleDetectionV; } -int Preferences::idlenessTimeout() const { return _idleDetectValueV; } -bool Preferences::autoSave() const { return _doAutoSaveV; } -int Preferences::autoSavePeriod() const { return _autoSaveValueV; } -bool Preferences::logging() const { return _loggingV; } -bool Preferences::promptDelete() const { return _promptDeleteV; } -bool Preferences::displayColumn(int n) const { return _displayColumnV[n]; } -QString Preferences::userRealName() const { return _userRealName; } +QString Preferences::iCalFile() const { return _iCalFileV; } +QString Preferences::activeCalendarFile() const { return _iCalFileV; } +bool Preferences::detectIdleness() const { return _doIdleDetectionV; } +int Preferences::idlenessTimeout() const { return _idleDetectValueV; } +bool Preferences::autoSave() const { return _doAutoSaveV; } +int Preferences::autoSavePeriod() const { return _autoSaveValueV; } +bool Preferences::logging() const { return _loggingV; } +bool Preferences::promptDelete() const { return _promptDeleteV; } +QString Preferences::setPromptDelete(bool prompt) { _promptDeleteV=prompt; return ""; } +bool Preferences::displayColumn(int n) const { return _displayColumnV[n]; } +QString Preferences::userRealName() const { return _userRealName; } //--------------------------------------------------------------------------- // Load and Save //--------------------------------------------------------------------------- void Preferences::load() { KConfig &config = *kapp->config(); config.setGroup( QString::fromLatin1("Idle detection") ); _doIdleDetectionV = config.readBoolEntry( QString::fromLatin1("enabled"), true ); _idleDetectValueV = config.readNumEntry(QString::fromLatin1("period"), 15); config.setGroup( QString::fromLatin1("Saving") ); _iCalFileV = config.readPathEntry ( QString::fromLatin1("ical file"), locateLocal( "appdata", QString::fromLatin1( "karm.ics"))); _doAutoSaveV = config.readBoolEntry ( QString::fromLatin1("auto save"), true); _autoSaveValueV = config.readNumEntry ( QString::fromLatin1("auto save period"), 5); _promptDeleteV = config.readBoolEntry ( QString::fromLatin1("prompt delete"), true); _loggingV = config.readBoolEntry ( QString::fromLatin1("logging"), true); _displayColumnV[0] = config.readBoolEntry ( QString::fromLatin1("display session time"), true); _displayColumnV[1] = config.readBoolEntry ( QString::fromLatin1("display time"), true); _displayColumnV[2] = config.readBoolEntry ( QString::fromLatin1("display total session time"), true); _displayColumnV[3] = config.readBoolEntry ( QString::fromLatin1("display total time"), true); KEMailSettings settings; _userRealName = settings.getSetting( KEMailSettings::RealName ); } void Preferences::save() { KConfig &config = *KGlobal::config(); config.setGroup( QString::fromLatin1("Idle detection")); config.writeEntry( QString::fromLatin1("enabled"), _doIdleDetectionV); config.writeEntry( QString::fromLatin1("period"), _idleDetectValueV); config.setGroup( QString::fromLatin1("Saving")); config.writePathEntry( QString::fromLatin1("ical file"), _iCalFileV); config.writeEntry( QString::fromLatin1("auto save"), _doAutoSaveV); config.writeEntry( QString::fromLatin1("logging"), _loggingV); config.writeEntry( QString::fromLatin1("auto save period"), _autoSaveValueV); config.writeEntry( QString::fromLatin1("prompt delete"), _promptDeleteV); config.writeEntry( QString::fromLatin1("display session time"), _displayColumnV[0]); config.writeEntry( QString::fromLatin1("display time"), _displayColumnV[1]); config.writeEntry( QString::fromLatin1("display total session time"), _displayColumnV[2]); config.writeEntry( QString::fromLatin1("display total time"), _displayColumnV[3]); config.sync(); } // HACK: this entire config dialog should be upgraded to KConfigXT bool Preferences::readBoolEntry( const QString& key ) { KConfig &config = *KGlobal::config(); return config.readBoolEntry ( key, true ); } void Preferences::writeEntry( const QString &key, bool value) { KConfig &config = *KGlobal::config(); config.writeEntry( key, value ); config.sync(); } void Preferences::deleteEntry( const QString &key ) { KConfig &config = *KGlobal::config(); config.deleteEntry( key ); config.sync(); } #include "preferences.moc" diff --git a/karm/preferences.h b/karm/preferences.h index 263fe137ab..e917d70bbf 100644 --- a/karm/preferences.h +++ b/karm/preferences.h @@ -1,89 +1,90 @@ #ifndef KARM_PREFERENCES_H #define KARM_PREFERENCES_H #include class QCheckBox; class QLabel; class QSpinBox; class QString; class KURLRequester; /** * Provide an interface to the configuration options for the program. */ class Preferences :public KDialogBase { Q_OBJECT public: static Preferences *instance( const QString& icsfile = "" ); void disableIdleDetection(); // Retrive information about settings bool detectIdleness() const; int idlenessTimeout() const; QString iCalFile() const; QString activeCalendarFile() const; bool autoSave() const; bool logging() const; int autoSavePeriod() const; bool promptDelete() const; + QString setPromptDelete( bool prompt ); bool displayColumn(int n) const; QString userRealName() const; void emitSignals(); bool readBoolEntry( const QString& uid ); void writeEntry( const QString &key, bool value ); void deleteEntry( const QString &key ); public slots: void showDialog(); void load(); void save(); signals: void detectIdleness(bool on); void idlenessTimeout(int minutes); void iCalFile(QString); void autoSave(bool on); void autoSavePeriod(int minutes); void setupChanged(); protected slots: virtual void slotOk(); virtual void slotCancel(); void idleDetectCheckBoxChanged(); void autoSaveCheckBoxChanged(); private: void makeDisplayPage(); void makeBehaviorPage(); void makeStoragePage(); Preferences( const QString& icsfile = "" ); static Preferences *_instance; bool _unsavedChanges; // Widgets QCheckBox *_doIdleDetectionW, *_doAutoSaveW, *_promptDeleteW; QCheckBox *_displayTimeW, *_displaySessionW, *_displayTotalTimeW, *_displayTotalSessionW; QCheckBox *_loggingW; QLabel *_idleDetectLabelW, *_displayColumnsLabelW; QSpinBox *_idleDetectValueW, *_autoSaveValueW; KURLRequester *_iCalFileW ; // Values bool _doIdleDetectionV, _doAutoSaveV, _promptDeleteV, _loggingV; bool _displayColumnV[4]; int _idleDetectValueV, _autoSaveValueV; QString _iCalFileV; /** real name of the user, used during ICAL saving */ QString _userRealName; }; #endif // KARM_PREFERENCES_H diff --git a/karm/print.cpp b/karm/print.cpp index 37147cf85d..ff00a3bc3a 100644 --- a/karm/print.cpp +++ b/karm/print.cpp @@ -1,166 +1,166 @@ // #include #include #include #include #include #include // i18n #include "karmutility.h" // formatTime() #include "print.h" #include "task.h" #include "taskview.h" const int levelIndent = 10; MyPrinter::MyPrinter(const TaskView *taskView) { _taskView = taskView; } void MyPrinter::print() { // FIXME: make a better caption for the printingdialog if (setup(0L, i18n("Print Times"))) { // setup QPainter painter(this); QPaintDeviceMetrics deviceMetrics(this); QFontMetrics metrics = painter.fontMetrics(); pageHeight = deviceMetrics.height(); int pageWidth = deviceMetrics.width(); xMargin = margins().width(); yMargin = margins().height(); yoff = yMargin; lineHeight = metrics.height(); // Calculate the totals // Note the totals are only calculated at the top most levels, as the // totals are increased together with its children. int totalTotal = 0; int sessionTotal = 0; for (Task* task = _taskView->first_child(); task; task = static_cast(task->nextSibling())) { totalTotal += task->totalTime(); sessionTotal += task->totalSessionTime(); } // Calculate the needed width for each of the fields timeWidth = QMAX(metrics.width(i18n("Total")), metrics.width(formatTime(totalTotal))); sessionTimeWidth = QMAX(metrics.width(i18n("Session")), metrics.width(formatTime(sessionTotal))); nameFieldWidth = pageWidth - xMargin - timeWidth - sessionTimeWidth - 2*5; int maxReqNameFieldWidth= metrics.width(i18n("Task Name ")); for ( Task* task = _taskView->first_child(); task; task = static_cast(task->nextSibling())) { int width = calculateReqNameWidth(task, metrics, 0); maxReqNameFieldWidth = QMAX(maxReqNameFieldWidth, width); } nameFieldWidth = QMIN(nameFieldWidth, maxReqNameFieldWidth); int realPageWidth = nameFieldWidth + timeWidth + sessionTimeWidth + 2*5; // Print the header QFont origFont, newFont; origFont = painter.font(); newFont = origFont; newFont.setPixelSize( static_cast(origFont.pixelSize() * 1.5) ); painter.setFont(newFont); int height = metrics.height(); QString now = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime()); - painter.drawText(xMargin, yoff, pageWidth*2, height*2, + painter.drawText(xMargin, yoff, pageWidth, height, QPainter::AlignCenter, i18n("KArm - %1").arg(now)); painter.setFont(origFont); yoff += height + 10; // Print the second header. printLine(i18n("Total"), i18n("Session"), i18n("Task Name"), painter, 0); yoff += 4; painter.drawLine(xMargin, yoff, xMargin + realPageWidth, yoff); yoff += 2; // Now print the actual content for ( Task* task = _taskView->first_child(); task; task = static_cast(task->nextSibling()) ) { printTask(task, painter, 0); } yoff += 4; painter.drawLine(xMargin, yoff, xMargin + realPageWidth, yoff); yoff += 2; // Print the Totals printLine( formatTime( totalTotal ), formatTime( sessionTotal ), QString(), painter, 0); } } int MyPrinter::calculateReqNameWidth( Task* task, QFontMetrics &metrics, int level) { int width = metrics.width(task->name()) + level * levelIndent; for ( Task* subTask = task->firstChild(); subTask; subTask = subTask->nextSibling() ) { int subTaskWidth = calculateReqNameWidth(subTask, metrics, level+1); width = QMAX(width, subTaskWidth); } return width; } void MyPrinter::printTask(Task *task, QPainter &painter, int level) { QString time = formatTime(task->totalTime()); QString sessionTime = formatTime(task->totalSessionTime()); QString name = task->name(); printLine(time, sessionTime, name, painter, level); for ( Task* subTask = task->firstChild(); subTask; subTask = subTask->nextSibling()) { printTask(subTask, painter, level+1); } } void MyPrinter::printLine( QString total, QString session, QString name, QPainter &painter, int level ) { int xoff = xMargin + 10 * level; painter.drawText( xoff, yoff, nameFieldWidth, lineHeight, QPainter::AlignLeft, name); xoff = xMargin + nameFieldWidth; painter.drawText( xoff, yoff, sessionTimeWidth, lineHeight, QPainter::AlignRight, session); xoff += sessionTimeWidth+ 5; painter.drawText( xoff, yoff, timeWidth, lineHeight, QPainter::AlignRight, total); xoff += timeWidth+5; yoff += lineHeight; if (yoff + 2* lineHeight > pageHeight) { newPage(); yoff = yMargin; } } diff --git a/karm/printdialog.cpp b/karm/printdialog.cpp index 243873c010..51603a8c55 100644 --- a/karm/printdialog.cpp +++ b/karm/printdialog.cpp @@ -1,93 +1,117 @@ /* - * This file only: + * This file only: * Copyright (C) 2003 Mark Bucciarelli * * 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 + * with this program; if not, write to the * Free Software Foundation, Inc. - * 59 Temple Place - Suite 330 - * Boston, MA 02111-1307 USA. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include // i18n #include #include "printdialog.h" #include PrintDialog::PrintDialog() : KDialogBase(0, "PrintDialog", true, i18n("Print Dialog"), Ok|Cancel, Ok, true ) { - QWidget *page = new QWidget( this ); + QWidget *page = new QWidget( this ); setMainWidget(page); int year, month; - QVBoxLayout *layout = new QVBoxLayout(page); - + QVBoxLayout *layout = new QVBoxLayout(page, KDialog::spacingHint()); layout->addSpacing(10); layout->addStretch(1); - + // Date Range - QGroupBox *rangeGroup = new QGroupBox(1, Horizontal, i18n("Date Range"), + QGroupBox *rangeGroup = new QGroupBox(1, Horizontal, i18n("Date Range"), page); layout->addWidget(rangeGroup); QWidget *rangeWidget = new QWidget(rangeGroup); QHBoxLayout *rangeLayout = new QHBoxLayout(rangeWidget, 0, spacingHint()); rangeLayout->addWidget(new QLabel(i18n("From:"), rangeWidget)); _from = new KDateEdit(rangeWidget); // Default from date to beginning of the month year = QDate::currentDate().year(); month = QDate::currentDate().month(); _from->setDate(QDate(year, month, 1)); rangeLayout->addWidget(_from); rangeLayout->addWidget(new QLabel(i18n("To:"), rangeWidget)); _to = new KDateEdit(rangeWidget); rangeLayout->addWidget(_to); layout->addSpacing(10); layout->addStretch(1); + _allTasks = new QComboBox( page ); + _allTasks->insertItem( i18n( "Selected Task" ) ); + _allTasks->insertItem( i18n( "All Tasks" ) ); + layout->addWidget( _allTasks ); + + _perWeek = new QCheckBox( i18n( "Summarize per week" ), page ); + layout->addWidget( _perWeek ); + _totalsOnly = new QCheckBox( i18n( "Totals Only" ), page ); + layout->addWidget( _totalsOnly ); + layout->addSpacing(10); layout->addStretch(1); } QDate PrintDialog::from() const { return _from->date(); } QDate PrintDialog::to() const { return _to->date(); } +bool PrintDialog::perWeek() const +{ + return _perWeek->isChecked(); +} + +bool PrintDialog::allTasks() const +{ + return _allTasks->currentItem() == 1; +} + +bool PrintDialog::totalsOnly() const +{ + return _totalsOnly->isChecked(); +} + #include "printdialog.moc" diff --git a/karm/printdialog.h b/karm/printdialog.h index f081319dbb..6c2c4c581f 100644 --- a/karm/printdialog.h +++ b/karm/printdialog.h @@ -1,49 +1,61 @@ /* - * This file only: + * This file only: * Copyright (C) 2003 Mark Bucciarelli * * 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 + * with this program; if not, write to the * Free Software Foundation, Inc. - * 59 Temple Place - Suite 330 - * Boston, MA 02111-1307 USA. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ #ifndef KARM_PRINT_DIALOG_H #define KARM_PRINT_DIALOG_H #include #include class QCheckBox; class KDateEdit; class PrintDialog : public KDialogBase { Q_OBJECT public: PrintDialog(); /* Return the from date entered. */ QDate from() const; /* Return the to date entered. */ QDate to() const; - - private: + + /* Whether to summarize per week */ + bool perWeek() const; + + /* Whether to print all tasks */ + bool allTasks() const; + + /* Whether to print totals only, instead of per-day columns */ + bool totalsOnly() const; + +private: KDateEdit *_from, *_to; + QCheckBox *_perWeek; + QComboBox *_allTasks; + QCheckBox *_totalsOnly; }; #endif // KARM_PRINT_DIALOG_H diff --git a/karm/reportcriteria.h b/karm/reportcriteria.h index 919328e9c8..66b5b8a02b 100644 --- a/karm/reportcriteria.h +++ b/karm/reportcriteria.h @@ -1,91 +1,91 @@ /* * Copyright (C) 2004 Mark Bucciarelli * * 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. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ #ifndef REPORTCRITERIA_H #define REPORTCRITERIA_H #include #include class QString; /** Stores entries from export dialog. Keeps details (like CSV export dialog control names) out of the TaskView class, which contains the slot triggered by the export action. The dialog and the report logic can change all they want and the TaskView logic can stay the same. */ class ReportCriteria { public: /** The different report types. */ enum REPORTTYPE { CSVTotalsExport = 0, CSVHistoryExport = 1 }; /** The type of report we are running. */ REPORTTYPE reportType; /** For reports that write to a file, the filename to write to. */ KURL url; /** For history reports, the lower bound of the date range to report on. */ QDate from; /** For history reports, the upper bound of the date range to report on. */ QDate to; /** True if the report should contain all tasks in Karm. Defaults to true. */ bool allTasks; /** True if the durations should be output in decimal hours. Otherwise, output durations as HH24:MI */ bool decimalMinutes; /** The delimiter to use when outputting comma-seperated value reports. */ QString delimiter; /** The quote to use for text fields when outputting comma-seperated reports. */ QString quote; }; #endif diff --git a/karm/task.cpp b/karm/task.cpp index 8fe1e9b965..3312f0bc1a 100644 --- a/karm/task.cpp +++ b/karm/task.cpp @@ -1,446 +1,457 @@ #include #include #include #include #include #include "kapplication.h" // kapp #include "kdebug.h" #include "event.h" #include "karmutility.h" #include "task.h" #include "taskview.h" #include "preferences.h" const int gSecondsPerMinute = 60; QPtrVector *Task::icons = 0; Task::Task( const QString& taskName, long minutes, long sessionTime, DesktopList desktops, TaskView *parent) : QObject(), QListViewItem(parent) -{ +{ init(taskName, minutes, sessionTime, desktops, 0); } Task::Task( const QString& taskName, long minutes, long sessionTime, DesktopList desktops, Task *parent) : QObject(), QListViewItem(parent) { init(taskName, minutes, sessionTime, desktops, 0); } Task::Task( KCal::Todo* todo, TaskView* parent ) : QObject(), QListViewItem( parent ) { long minutes = 0; QString name; long sessionTime = 0; int percent_complete = 0; DesktopList desktops; parseIncidence(todo, minutes, sessionTime, name, desktops, percent_complete); init(name, minutes, sessionTime, desktops, percent_complete); } void Task::init( const QString& taskName, long minutes, long sessionTime, DesktopList desktops, int percent_complete) { // If our parent is the taskview then connect our totalTimesChanged // signal to its receiver if ( ! parent() ) connect( this, SIGNAL( totalTimesChanged ( long, long ) ), listView(), SLOT( taskTotalTimesChanged( long, long) )); connect( this, SIGNAL( deletingTask( Task* ) ), listView(), SLOT( deletingTask( Task* ) )); if (icons == 0) { icons = new QPtrVector(8); + KIconLoader* kil = new KIconLoader("karm"); // always load icons from the KArm application for (int i=0; i<8; i++) { QPixmap *icon = new QPixmap(); QString name; name.sprintf("watch-%d.xpm",i); - *icon = UserIcon(name); + *icon = kil->loadIcon( name, KIcon::User ); icons->insert(i,icon); } } - //kdDebug(5970) << "Task::init(" << taskName << ", " << minutes << ", " - // << sessionTime << ", desktops)" << endl; - _removing = false; _name = taskName.stripWhiteSpace(); _lastStart = QDateTime::currentDateTime(); _totalTime = _time = minutes; _totalSessionTime = _sessionTime = sessionTime; _timer = new QTimer(this); _desktops = desktops; connect(_timer, SIGNAL(timeout()), this, SLOT(updateActiveIcon())); setPixmap(1, UserIcon(QString::fromLatin1("empty-watch.xpm"))); _currentPic = 0; _percentcomplete = percent_complete; update(); changeParentTotalTimes( _sessionTime, _time); } Task::~Task() { emit deletingTask(this); delete _timer; } void Task::setRunning( bool on, KarmStorage* storage ) { if ( on ) { + if (isComplete()) return; // don't start if its marked complete if (!_timer->isActive()) { _timer->start(1000); storage->startTimer(this); _currentPic=7; _lastStart = QDateTime::currentDateTime(); updateActiveIcon(); } } else { if (_timer->isActive()) { _timer->stop(); if ( ! _removing ) { storage->stopTimer(this); setPixmap(1, UserIcon(QString::fromLatin1("empty-watch.xpm"))); } } } } void Task::setUid(QString uid) { _uid = uid; } bool Task::isRunning() const { return _timer->isActive(); } void Task::setName( const QString& name, KarmStorage* storage ) { kdDebug(5970) << "Task:setName: " << name << endl; QString oldname = _name; if ( oldname != name ) { _name = name; storage->setName(this, oldname); update(); } } void Task::setPercentComplete(const int percent, KarmStorage *storage) { kdDebug(5970) << "Task::setPercentComplete(" << percent << ", storage): " << _uid << endl; - if (isRunning()) setRunning(false, storage); - - setEnabled(false); - setOpen(false); - if (!percent) _percentcomplete = 0; else if (percent > 100) _percentcomplete = 100; else if (percent < 0) _percentcomplete = 0; else _percentcomplete = percent; + if (isRunning() && _percentcomplete==100) setRunning(false, storage); + + setPixmapProgress(); + // When parent marked as complete, mark all children as complete as well. // Complete tasks are not displayed in the task view, so if a parent is // marked as complete and some of the children are not, then we get an error // message. KArm actually keep chugging along in this case and displays the // child tasks just fine, so an alternative solution is to remove that error // message (from KarmStorage::load). But I think it makes more sense that // if you mark a parent task as complete, then all children should be // complete as well. // // This behavior is consistent with KOrganizer (as of 2003-09-24). if (_percentcomplete == 100) { for (Task* child= this->firstChild(); child; child = child->nextSibling()) child->setPercentComplete(_percentcomplete, storage); } } +void Task::setPixmapProgress() +{ + QPixmap* icon = new QPixmap(); + if (_percentcomplete >= 100) + *icon = UserIcon("task-complete.xpm"); + else + *icon = UserIcon("task-incomplete.xpm"); + setPixmap(0, *icon); +} + bool Task::isComplete() { return _percentcomplete == 100; } void Task::removeFromView() { for (Task* child= this->firstChild(); child; child= child->nextSibling()) child->removeFromView(); delete this; } void Task::setDesktopList ( DesktopList desktopList ) { _desktops = desktopList; } void Task::changeTime( long minutes, KarmStorage* storage ) { changeTimes( minutes, minutes, storage); } void Task::changeTimes( long minutesSession, long minutes, KarmStorage* storage) { if( minutesSession != 0 || minutes != 0) { _sessionTime += minutesSession; _time += minutes; if ( storage ) storage->changeTime(this, minutes * gSecondsPerMinute); changeTotalTimes( minutesSession, minutes ); } } void Task::changeTotalTimes( long minutesSession, long minutes ) { - //kdDebug(5970) - // << "Task::changeTotalTimes(" << minutesSession << ", " - // << minutes << ") for " << name() << endl; + kdDebug(5970) + << "Task::changeTotalTimes(" << minutesSession << ", " + << minutes << ") for " << name() << endl; _totalSessionTime += minutesSession; _totalTime += minutes; update(); changeParentTotalTimes( minutesSession, minutes ); } void Task::resetTimes() { _totalSessionTime -= _sessionTime; _totalTime -= _time; changeParentTotalTimes( -_sessionTime, -_time); _sessionTime = 0; _time = 0; update(); } void Task::changeParentTotalTimes( long minutesSession, long minutes ) { //kdDebug(5970) // << "Task::changeParentTotalTimes(" << minutesSession << ", " // << minutes << ") for " << name() << endl; if ( isRoot() ) emit totalTimesChanged( minutesSession, minutes ); else parent()->changeTotalTimes( minutesSession, minutes ); } bool Task::remove( QPtrList& activeTasks, KarmStorage* storage) { kdDebug(5970) << "Task::remove: " << _name << endl; bool ok = true; _removing = true; storage->removeTask(this); if( isRunning() ) setRunning( false, storage ); for (Task* child = this->firstChild(); child; child = child->nextSibling()) { if (child->isRunning()) child->setRunning(false, storage); child->remove(activeTasks, storage); } changeParentTotalTimes( -_sessionTime, -_time); _removing = false; return ok; } void Task::updateActiveIcon() { _currentPic = (_currentPic+1) % 8; setPixmap(1, *(*icons)[_currentPic]); } QString Task::fullName() const { if (isRoot()) return name(); else return parent()->fullName() + QString::fromLatin1("/") + name(); } KCal::Todo* Task::asTodo(KCal::Todo* todo) const { + Q_ASSERT( todo != NULL ); + + kdDebug(5970) << "Task::asTodo: name() = '" << name() << "'" << endl; todo->setSummary( name() ); // Note: if the date start is empty, the KOrganizer GUI will have the // checkbox blank, but will prefill the todo's starting datetime to the // time the file is opened. // todo->setDtStart( current ); todo->setCustomProperty( kapp->instanceName(), QCString( "totalTaskTime" ), QString::number( _time ) ); todo->setCustomProperty( kapp->instanceName(), QCString( "totalSessionTime" ), QString::number( _sessionTime) ); if (getDesktopStr().isEmpty()) todo->removeCustomProperty(kapp->instanceName(), QCString("desktopList")); else todo->setCustomProperty( kapp->instanceName(), QCString( "desktopList" ), getDesktopStr() ); todo->setOrganizer( Preferences::instance()->userRealName() ); todo->setPercentComplete(_percentcomplete); return todo; } bool Task::parseIncidence( KCal::Incidence* incident, long& minutes, long& sessionMinutes, QString& name, DesktopList& desktops, int& percent_complete ) { bool ok; name = incident->summary(); _uid = incident->uid(); _comment = incident->description(); ok = false; minutes = incident->customProperty( kapp->instanceName(), QCString( "totalTaskTime" )).toInt( &ok ); if ( !ok ) minutes = 0; ok = false; sessionMinutes = incident->customProperty( kapp->instanceName(), QCString( "totalSessionTime" )).toInt( &ok ); if ( !ok ) sessionMinutes = 0; QString desktopList = incident->customProperty( kapp->instanceName(), QCString( "desktopList" ) ); QStringList desktopStrList = QStringList::split( QString::fromLatin1(","), desktopList ); desktops.clear(); for ( QStringList::iterator iter = desktopStrList.begin(); iter != desktopStrList.end(); ++iter ) { int desktopInt = (*iter).toInt( &ok ); if ( ok ) { desktops.push_back( desktopInt ); } } percent_complete = static_cast(incident)->percentComplete(); //kdDebug(5970) << "Task::parseIncidence: " // << name << ", Minutes: " << minutes // << ", desktop: " << desktopList << endl; return true; } QString Task::getDesktopStr() const { if ( _desktops.empty() ) return QString(); QString desktopstr; for ( DesktopList::const_iterator iter = _desktops.begin(); iter != _desktops.end(); ++iter ) { desktopstr += QString::number( *iter ) + QString::fromLatin1( "," ); } desktopstr.remove( desktopstr.length() - 1, 1 ); return desktopstr; } void Task::cut() { //kdDebug(5970) << "Task::cut - " << name() << endl; changeParentTotalTimes( -_totalSessionTime, -_totalTime); if ( ! parent()) listView()->takeItem(this); else parent()->takeItem(this); } void Task::move(Task* destination) { cut(); paste(destination); } void Task::paste(Task* destination) { destination->insertItem(this); changeParentTotalTimes( _totalSessionTime, _totalTime); } void Task::update() { setText(0, _name); setText(1, formatTime(_sessionTime)); setText(2, formatTime(_time)); setText(3, formatTime(_totalSessionTime)); setText(4, formatTime(_totalTime)); } void Task::addComment( QString comment, KarmStorage* storage ) { _comment = _comment + QString::fromLatin1("\n") + comment; storage->addComment(this, comment); } QString Task::comment() const { return _comment; } int Task::compare ( QListViewItem * i, int col, bool ascending ) const { long thistime = 0; long thattime = 0; Task *task = static_cast(i); switch ( col ) { case 1: thistime = _sessionTime; thattime = task->sessionTime(); break; case 2: thistime = _time; thattime = task->time(); break; case 3: thistime = _totalSessionTime; thattime = task->totalSessionTime(); break; case 4: thistime = _totalTime; thattime = task->totalTime(); break; default: return key(col, ascending).localeAwareCompare( i->key(col, ascending) ); } if ( thistime < thattime ) return -1; if ( thistime > thattime ) return 1; return 0; } #include "task.moc" diff --git a/karm/task.h b/karm/task.h index 7e662bb8c3..4bcb74efdc 100644 --- a/karm/task.h +++ b/karm/task.h @@ -1,284 +1,289 @@ #ifndef KARM_TASK_H #define KARM_TASK_H // Required b/c QPtrList is a struct, not a class. #include // Requred b/c/ QPtrVector is a template (?) #include // Required b/c DesktopList is a typedef not a class. #include "desktoplist.h" // Required b/c of static cast below? (How else can compiler know that a // TaskView is a subclass or QListView?) #include "taskview.h" class QFile; class QString; class KarmStorage; class QTimer; class KCal::Incidence; class KCal::Todo; class QObject; class QPixmap; /// \class Task /** \brief A class representing a task * * A "Task" object stores information about a task such as it's name, * total and session times. * * It can log when the task is started, stoped or deleted. * * If a task is associated with some desktop's activity it can remember that * too. * * It can also contain subtasks - these are managed using the * QListViewItem class. */ class Task : public QObject, public QListViewItem { Q_OBJECT public: //@{ constructors Task( const QString& taskame, long minutes, long sessionTime, DesktopList desktops, TaskView* parent = 0); Task( const QString& taskame, long minutes, long sessionTime, DesktopList desktops, Task* parent = 0); Task( KCal::Todo* incident, TaskView* parent ); //@} /* destructor */ ~Task(); /** return parent Task or null in case of TaskView. * same as QListViewItem::parent() */ Task* firstChild() const { return (Task*)QListViewItem::firstChild(); } Task* nextSibling() const { return (Task*)QListViewItem::nextSibling(); } Task* parent() const { return (Task*)QListViewItem::parent(); } /** Return task view for this task */ TaskView* taskView() const { return static_cast( listView() ); } /** Return unique iCalendar Todo ID for this task. */ QString uid() const { return _uid; } /** * Set unique id for the task. * * The uid is the key used to update the storage. * * @param uid The new unique id. */ void setUid(const QString uid); /** cut Task out of parent Task or the TaskView */ void cut(); /** cut Task out of parent Task or the TaskView and into the * destination Task */ void move(Task* destination); /** insert Task into the destination Task */ void paste(Task* destination); /** Sort times numerically, not alphabetically. */ int compare ( QListViewItem * i, int col, bool ascending ) const; //@{ timing related functions /** * Change task time. Adds minutes to both total time and session time. * * @param minutes minutes to add to - may be negative * @param storage Pointer to KarmStorage instance. * If zero, don't save changes. */ void changeTime( long minutes, KarmStorage* storage ); /** * Add minutes to time and session time, and write to storage. * * @param minutesSession minutes to add to task session time * @param minutes minutes to add to task time * @param storage Pointer to KarmStorage instance. * If zero, don't save changes. */ void changeTimes ( long minutesSession, long minutes, KarmStorage* storage=0); /** adds minutes to total and session time * * @param minutesSession minutes to add to task total session time * @param minutes minutes to add to task total time */ void changeTotalTimes( long minutesSession, long minutes ); /** * Reset all times to 0 */ void resetTimes(); /*@{ returns the times accumulated by the task * @return total time in minutes */ long time() const { return _time; }; long totalTime() const { return _totalTime; }; long sessionTime() const { return _sessionTime; }; long totalSessionTime() const { return _totalSessionTime; }; /** * Return time the task was started. */ QDateTime startTime() const { return _lastStart; }; /** sets session time to zero. */ void startNewSession() { changeTimes( -_sessionTime, 0 ); }; //@} //@{ desktop related functions void setDesktopList ( DesktopList dl ); DesktopList getDesktops() const { return _desktops;} QString getDesktopStr() const; //@} //@{ name related functions /** sets the name of the task * @param name a pointer to the name. A deep copy will be made. * @param storage a pointer to a KarmStorage object. */ void setName( const QString& name, KarmStorage* storage ); /** returns the name of this task. * @return a pointer to the name. */ QString name() const { return _name; }; /** * Returns that task name, prefixed by parent tree up to root. * * Task names are seperated by a forward slash: / */ QString fullName() const; //@} /** Update the display of the task (all columns) in the UI. */ void update(); //@{ the state of a Task - stopped, running /** starts or stops a task * @param on true or false for starting or stopping a task * @param storage a pointer to a KarmStorage object. */ void setRunning(bool on, KarmStorage* storage); /** return the state of a task - if it's running or not * @return true or false depending on whether the task is running */ bool isRunning() const; //@} bool parseIncidence(KCal::Incidence*, long& minutes, long& sessionMinutes, QString& name, DesktopList& desktops, int& percent_complete); /** * Load the todo passed in with this tasks info. */ KCal::Todo* asTodo(KCal::Todo* calendar) const; /** Add a comment to this task. */ void addComment( QString comment, KarmStorage* storage ); /** Retrieve the entire comment for the task. */ QString comment() const; /** tells you whether this task is the root of the task tree */ bool isRoot() const { return parent() == 0; } /** remove Task with all it's children * @param activeTasks - list of aktive tasks * @param storage a pointer to a KarmStorage object. */ bool remove( QPtrList& activeTasks, KarmStorage* storage ); /** * Update percent complete for this task. * * Tasks that are complete (i.e., percent = 100) do not show up in * taskview. If percent NULL, set to zero. If greater than 100, set to * 100. If less than zero, set to zero. */ void setPercentComplete(const int percent, KarmStorage *storage); + + /** Sets an appropriate icon for this task based on its level of + * completion */ + void setPixmapProgress(); + /** Return true if task is complete (percent complete equals 100). */ bool isComplete(); /** Remove current task and all it's children from the view. */ void removeFromView(); protected: void changeParentTotalTimes( long minutesSession, long minutes ); signals: void totalTimesChanged( long minutesSession, long minutes); /** signal that we're about to delete a task */ void deletingTask(Task* thisTask); protected slots: /** animate the active icon */ void updateActiveIcon(); private: /** The iCal unique ID of the Todo for this task. */ QString _uid; /** The comment associated with this Task. */ QString _comment; int _percentcomplete; long totalTimeInSeconds() const { return _totalTime * 60; } /** if the time or session time is negative set them to zero */ void noNegativeTimes(); /** initialize a task */ void init( const QString& taskame, long minutes, long sessionTime, DesktopList desktops, int percent_complete); /** task name */ QString _name; /** Last time this task was started. */ QDateTime _lastStart; //@{ totals of the whole subtree including self long _totalTime; long _totalSessionTime; //@} //@{ times spend on the task itself long _time; long _sessionTime; //@} DesktopList _desktops; QTimer *_timer; int _currentPic; static QPtrVector *icons; /** Don't need to update storage when deleting task from list. */ bool _removing; }; #endif // KARM_TASK_H diff --git a/karm/taskview.cpp b/karm/taskview.cpp index ccedd4c646..de768fc12b 100644 --- a/karm/taskview.cpp +++ b/karm/taskview.cpp @@ -1,782 +1,828 @@ #include #include #include #include #include #include #include #include #include #include #include #include "kapplication.h" // kapp #include #include #include #include // i18n #include #include #include "csvexportdialog.h" #include "desktoptracker.h" #include "edittaskdialog.h" #include "idletimedetector.h" #include "karmstorage.h" #include "plannerparser.h" #include "preferences.h" #include "printdialog.h" #include "reportcriteria.h" #include "task.h" #include "taskview.h" #include "timekard.h" #define T_LINESIZE 1023 #define HIDDEN_COLUMN -10 class DesktopTracker; TaskView::TaskView(QWidget *parent, const char *name, const QString &icsfile ):KListView(parent,name) { _preferences = Preferences::instance( icsfile ); _storage = KarmStorage::instance(); - connect(this, SIGNAL( doubleClicked( QListViewItem * )), - this, SLOT( changeTimer( QListViewItem * ))); - connect( this, SIGNAL( expanded( QListViewItem * ) ), this, SLOT( itemStateChanged( QListViewItem * ) ) ); connect( this, SIGNAL( collapsed( QListViewItem * ) ), this, SLOT( itemStateChanged( QListViewItem * ) ) ); // setup default values previousColumnWidths[0] = previousColumnWidths[1] = previousColumnWidths[2] = previousColumnWidths[3] = HIDDEN_COLUMN; addColumn( i18n("Task Name") ); addColumn( i18n("Session Time") ); addColumn( i18n("Time") ); addColumn( i18n("Total Session Time") ); addColumn( i18n("Total Time") ); setColumnAlignment( 1, Qt::AlignRight ); setColumnAlignment( 2, Qt::AlignRight ); setColumnAlignment( 3, Qt::AlignRight ); setColumnAlignment( 4, Qt::AlignRight ); adaptColumns(); setAllColumnsShowFocus( true ); // set up the minuteTimer _minuteTimer = new QTimer(this); connect( _minuteTimer, SIGNAL( timeout() ), this, SLOT( minuteUpdate() )); _minuteTimer->start(1000 * secsPerMinute); // React when user changes iCalFile connect(_preferences, SIGNAL(iCalFile(QString)), this, SLOT(iCalFileChanged(QString))); // resize columns when config is changed connect(_preferences, SIGNAL( setupChanged() ), this,SLOT( adaptColumns() )); _minuteTimer->start(1000 * secsPerMinute); // Set up the idle detection. _idleTimeDetector = new IdleTimeDetector( _preferences->idlenessTimeout() ); connect( _idleTimeDetector, SIGNAL( extractTime(int) ), this, SLOT( extractTime(int) )); connect( _idleTimeDetector, SIGNAL( stopAllTimers() ), this, SLOT( stopAllTimers() )); connect( _preferences, SIGNAL( idlenessTimeout(int) ), _idleTimeDetector, SLOT( setMaxIdle(int) )); connect( _preferences, SIGNAL( detectIdleness(bool) ), _idleTimeDetector, SLOT( toggleOverAllIdleDetection(bool) )); if (!_idleTimeDetector->isIdleDetectionPossible()) _preferences->disableIdleDetection(); // Setup auto save timer _autoSaveTimer = new QTimer(this); connect( _preferences, SIGNAL( autoSave(bool) ), this, SLOT( autoSaveChanged(bool) )); connect( _preferences, SIGNAL( autoSavePeriod(int) ), this, SLOT( autoSavePeriodChanged(int) )); connect( _autoSaveTimer, SIGNAL( timeout() ), this, SLOT( save() )); // Setup manual save timer (to save changes a little while after they happen) _manualSaveTimer = new QTimer(this); connect( _manualSaveTimer, SIGNAL( timeout() ), this, SLOT( save() )); // Connect desktop tracker events to task starting/stopping _desktopTracker = new DesktopTracker(); connect( _desktopTracker, SIGNAL( reachedtActiveDesktop( Task* ) ), this, SLOT( startTimerFor(Task*) )); connect( _desktopTracker, SIGNAL( leftActiveDesktop( Task* ) ), this, SLOT( stopTimerFor(Task*) )); } KarmStorage* TaskView::storage() { return _storage; } +void TaskView::contentsMousePressEvent ( QMouseEvent * e ) +{ + kdDebug(5970) << "entering contentsMousePressEvent" << endl; + KListView::contentsMousePressEvent(e); + Task *task = current_item(); + // if clicked onto the "completed" icon + if ( e->x()<=18 ) + { + if ( task->isComplete() ) task->setPercentComplete( 0, _storage ); + else task->setPercentComplete( 100, _storage ); + } +} + +void TaskView::contentsMouseDoubleClickEvent ( QMouseEvent * e ) +{ + kdDebug(5970) << "entering contentsMouseDoubleClickEvent" << endl; + KListView::contentsMouseDoubleClickEvent(e); + + // start/stop timer + Task *task = current_item(); + + if ( task != 0 && activeTasks.findRef(task) == -1 ) + { + // Stop all the other timers. + for (unsigned int i=0; isetRunning(false, _storage); + activeTasks.clear(); + + // Start the new timer. + startCurrentTimer(); + } + else stopCurrentTimer(); +} + TaskView::~TaskView() { _preferences->save(); } Task* TaskView::first_child() const { return static_cast(firstChild()); } Task* TaskView::current_item() const { return static_cast(currentItem()); } Task* TaskView::item_at_index(int i) { return static_cast(itemAtIndex(i)); } -void TaskView::load() +void TaskView::load( QString fileName ) { + // if the program is used as an embedded plugin for konqueror, there may be a need + // to load from a file without touching the preferences. _isloading = true; - QString err = _storage->load(this, _preferences); + QString err = _storage->load(this, _preferences, fileName); if (!err.isEmpty()) { KMessageBox::error(this, err); _isloading = false; return; } // Register tasks with desktop tracker int i = 0; for ( Task* t = item_at_index(i); t; t = item_at_index(++i) ) _desktopTracker->registerForDesktops( t, t->getDesktops() ); restoreItemState( first_child() ); setSelected(first_child(), true); setCurrentItem(first_child()); _desktopTracker->startTracking(); _isloading = false; + refresh(); } void TaskView::restoreItemState( QListViewItem *item ) { while( item ) { Task *t = (Task *)item; t->setOpen( _preferences->readBoolEntry( t->uid() ) ); if( item->childCount() > 0 ) restoreItemState( item->firstChild() ); item = item->nextSibling(); } } void TaskView::itemStateChanged( QListViewItem *item ) { if ( !item || _isloading ) return; Task *t = (Task *)item; kdDebug(5970) << "TaskView::itemStateChanged()" << " uid=" << t->uid() << " state=" << t->isOpen() << endl; if( _preferences ) _preferences->writeEntry( t->uid(), t->isOpen() ); } void TaskView::deleteItemState( QListViewItem *item ) { if ( !item ) return; Task *t = (Task *)item; kdDebug(5970) << "TaskView:deleteItemState()" << " uid=" << t->uid() << endl; if( _preferences ) _preferences->deleteEntry( t->uid() ); } void TaskView::closeStorage() { _storage->closeStorage( this ); } void TaskView::iCalFileModified(ResourceCalendar *rc) { kdDebug(5970) << "entering iCalFileModified" << endl; stopAllTimers(); kdDebug(5970) << rc->infoText() << endl; rc->dump(); _storage->buildTaskView(rc,this); kdDebug(5970) << "exiting iCalFileModified" << endl; } void TaskView::refresh() { kdDebug(5970) << "entering TaskView::refresh()" << endl; this->setRootIsDecorated(true); int i = 0; for ( Task* t = item_at_index(i); t; t = item_at_index(++i) ) { - if (!t->isComplete()) - { - t->setOpen(true); - t->setEnabled(true); - } - else - { - t->setOpen(false); - t->setEnabled(false); - } + t->setPixmapProgress(); } // remove root decoration if there is no more children. bool anyChilds = false; for(Task* child = first_child(); child; child = child->nextSibling()) { if (child->childCount() != 0) { anyChilds = true; break; } } if (!anyChilds) { setRootIsDecorated(false); } kdDebug(5970) << "exiting TaskView::refresh()" << endl; } void TaskView::loadFromFlatFile() { kdDebug(5970) << "TaskView::loadFromFlatFile()" << endl; //KFileDialog::getSaveFileName("icalout.ics",i18n("*.ics|ICalendars"),this); QString fileName(KFileDialog::getOpenFileName(QString::null, QString::null, 0)); if (!fileName.isEmpty()) { QString err = _storage->loadFromFlatFile(this, fileName); if (!err.isEmpty()) { KMessageBox::error(this, err); return; } // Register tasks with desktop tracker int task_idx = 0; Task* task = item_at_index(task_idx++); while (task) { // item_at_index returns 0 where no more items. _desktopTracker->registerForDesktops( task, task->getDesktops() ); task = item_at_index(task_idx++); } setSelected(first_child(), true); setCurrentItem(first_child()); _desktopTracker->startTracking(); } } -void TaskView::importPlanner() +QString TaskView::importPlanner(QString fileName) { kdDebug(5970) << "entering importPlanner" << endl; - { - PlannerParser* handler=new PlannerParser(this); - QFile xmlFile(KFileDialog::getOpenFileName(QString::null, QString::null, 0) ); - QXmlInputSource source( xmlFile ); - QXmlSimpleReader reader; - reader.setContentHandler( handler ); - reader.parse( source ); - // we need a refresh - refresh(); - } + PlannerParser* handler=new PlannerParser(this); + if (fileName.isEmpty()) fileName=KFileDialog::getOpenFileName(QString::null, QString::null, 0); + QFile xmlFile( fileName ); + QXmlInputSource source( xmlFile ); + QXmlSimpleReader reader; + reader.setContentHandler( handler ); + reader.parse( source ); + refresh(); + return ""; +} + +QString TaskView::report( const ReportCriteria& rc ) +{ + return _storage->report( this, rc ); } void TaskView::exportcsvFile() { kdDebug(5970) << "TaskView::exportcsvFile()" << endl; CSVExportDialog dialog( ReportCriteria::CSVTotalsExport, this ); if ( current_item() && current_item()->isRoot() ) dialog.enableTasksToExportQuestion(); dialog.urlExportTo->KURLRequester::setMode(KFile::File); if ( dialog.exec() ) { QString err = _storage->report( this, dialog.reportCriteria() ); if ( !err.isEmpty() ) KMessageBox::error( this, i18n(err.ascii()) ); } } QString TaskView::exportcsvHistory() { kdDebug(5970) << "TaskView::exportcsvHistory()" << endl; QString err; CSVExportDialog dialog( ReportCriteria::CSVHistoryExport, this ); if ( current_item() && current_item()->isRoot() ) dialog.enableTasksToExportQuestion(); dialog.urlExportTo->KURLRequester::setMode(KFile::File); if ( dialog.exec() ) { err = _storage->report( this, dialog.reportCriteria() ); } return err; } void TaskView::scheduleSave() { _manualSaveTimer->start( 10, true /*single-shot*/ ); } Preferences* TaskView::preferences() { return _preferences; } QString TaskView::save() { // DF: this code created a new event for the running task(s), // at every call (very frequent with autosave) !!! // -> if one wants autosave to save the current event, then // Task needs to store the "current event" and we need to update // it before calling save. #if 0 // Stop then start all timers so history entries are written. This is // inefficient if more than one task running, but it is correct. It is // inefficient because the iCalendar file is saved every time a task's // setRunning(false, ...) is called. For a big ics file, this could be a // drag. However, it does ensure that the data will be consistent. And // if the most common use case is that one task is running most of the time, // it won't make any difference. for (unsigned int i = 0; i < activeTasks.count(); i++) { activeTasks.at(i)->setRunning(false, _storage); activeTasks.at(i)->setRunning(true, _storage); } // If there was an active task, the iCal file has already been saved. if (activeTasks.count() == 0) #endif { return _storage->save(this); } } void TaskView::startCurrentTimer() { startTimerFor( current_item() ); } long TaskView::count() { long n = 0; for (Task* t = item_at_index(n); t; t=item_at_index(++n)); return n; } void TaskView::startTimerFor(Task* task) { if (task != 0 && activeTasks.findRef(task) == -1) { _idleTimeDetector->startIdleDetection(); task->setRunning(true, _storage); activeTasks.append(task); emit updateButtons(); if ( activeTasks.count() == 1 ) emit timersActive(); emit tasksChanged( activeTasks); } } void TaskView::stopAllTimers() { for ( unsigned int i = 0; i < activeTasks.count(); i++ ) activeTasks.at(i)->setRunning(false, _storage); _idleTimeDetector->stopIdleDetection(); activeTasks.clear(); emit updateButtons(); emit timersInactive(); emit tasksChanged( activeTasks); } void TaskView::startNewSession() { QListViewItemIterator item( first_child()); for ( ; item.current(); ++item ) { Task * task = (Task *) item.current(); task->startNewSession(); } } void TaskView::resetTimeForAllTasks() { QListViewItemIterator item( first_child()); for ( ; item.current(); ++item ) { Task * task = (Task *) item.current(); task->resetTimes(); } } void TaskView::stopTimerFor(Task* task) { if ( task != 0 && activeTasks.findRef(task) != -1 ) { activeTasks.removeRef(task); task->setRunning(false, _storage); if ( activeTasks.count() == 0 ) { _idleTimeDetector->stopIdleDetection(); emit timersInactive(); } emit updateButtons(); } emit tasksChanged( activeTasks); } void TaskView::stopCurrentTimer() { stopTimerFor( current_item()); } - -void TaskView::changeTimer(QListViewItem *) -{ - Task *task = current_item(); - - if ( task != 0 && activeTasks.findRef(task) == -1 ) - { - // Stop all the other timers. - for (unsigned int i=0; isetRunning(false, _storage); - activeTasks.clear(); - - // Start the new timer. - startCurrentTimer(); - } - else stopCurrentTimer(); -} - void TaskView::minuteUpdate() { addTimeToActiveTasks(1, false); } void TaskView::addTimeToActiveTasks(int minutes, bool save_data) { for( unsigned int i = 0; i < activeTasks.count(); i++ ) activeTasks.at(i)->changeTime(minutes, ( save_data ? _storage : 0 ) ); } void TaskView::newTask() { newTask(i18n("New Task"), 0); } void TaskView::newTask(QString caption, Task *parent) { EditTaskDialog *dialog = new EditTaskDialog(caption, false); long total, totalDiff, session, sessionDiff; DesktopList desktopList; int result = dialog->exec(); if ( result == QDialog::Accepted ) { QString taskName = i18n( "Unnamed Task" ); if ( !dialog->taskName().isEmpty()) taskName = dialog->taskName(); total = totalDiff = session = sessionDiff = 0; dialog->status( &total, &totalDiff, &session, &sessionDiff, &desktopList ); // If all available desktops are checked, disable auto tracking, // since it makes no sense to track for every desktop. if ( desktopList.size() == ( unsigned int ) _desktopTracker->desktopCount() ) desktopList.clear(); QString uid = addTask( taskName, total, session, desktopList, parent ); if ( uid.isNull() ) { KMessageBox::error( 0, i18n( - "Error storing new task. Your changes were not saved." ) ); + "Error storing new task. Your changes were not saved. Make sure you can edit your iCalendar file. Also quit all applications using this file and remove any lock file related to its name from ~/.kde/share/apps/kabc/lock/ " ) ); } delete dialog; } } QString TaskView::addTask -( const QString& taskname, long total, long session, const DesktopList& desktops, Task* parent ) +( const QString& taskname, long total, long session, + const DesktopList& desktops, Task* parent ) { Task *task; + kdDebug(5970) << "TaskView::addTask: taskname = " << taskname << endl; + if ( parent ) task = new Task( taskname, total, session, desktops, parent ); else task = new Task( taskname, total, session, desktops, this ); task->setUid( _storage->addTask( task, parent ) ); if ( ! task->uid().isNull() ) { _desktopTracker->registerForDesktops( task, desktops ); setCurrentItem( task ); setSelected( task, true ); + task->setPixmapProgress(); + save(); } else { delete task; } return task->uid(); } void TaskView::newSubTask() { Task* task = current_item(); if(!task) return; newTask(i18n("New Sub Task"), task); task->setOpen(true); refresh(); } void TaskView::editTask() { Task *task = current_item(); if (!task) return; DesktopList desktopList = task->getDesktops(); EditTaskDialog *dialog = new EditTaskDialog(i18n("Edit Task"), true, &desktopList); dialog->setTask( task->name(), task->time(), task->sessionTime() ); int result = dialog->exec(); if (result == QDialog::Accepted) { QString taskName = i18n("Unnamed Task"); if (!dialog->taskName().isEmpty()) { taskName = dialog->taskName(); } // setName only does something if the new name is different task->setName(taskName, _storage); // update session time as well if the time was changed long total, session, totalDiff, sessionDiff; total = totalDiff = session = sessionDiff = 0; DesktopList desktopList; dialog->status( &total, &totalDiff, &session, &sessionDiff, &desktopList); if( totalDiff != 0 || sessionDiff != 0) task->changeTimes( sessionDiff, totalDiff, _storage ); // If all available desktops are checked, disable auto tracking, // since it makes no sense to track for every desktop. if (desktopList.size() == (unsigned int)_desktopTracker->desktopCount()) desktopList.clear(); task->setDesktopList(desktopList); _desktopTracker->registerForDesktops( task, desktopList ); emit updateButtons(); } delete dialog; } //void TaskView::addCommentToTask() //{ // Task *task = current_item(); // if (!task) // return; // bool ok; // QString comment = KLineEditDlg::getText(i18n("Comment"), // i18n("Log comment for task '%1':").arg(task->name()), // QString(), &ok, this); // if ( ok ) // task->addComment( comment, _storage ); //} +void TaskView::reinstateTask(int completion) +{ + Task* task = current_item(); + if (task == 0) { + KMessageBox::information(0,i18n("No task selected.")); + return; + } + + if (completion<0) completion=0; + if (completion<100) + { + task->setPercentComplete(completion, _storage); + task->setPixmapProgress(); + save(); + emit updateButtons(); + } +} void TaskView::deleteTask(bool markingascomplete) { Task *task = current_item(); if (task == 0) { KMessageBox::information(0,i18n("No task selected.")); return; } int response = KMessageBox::Yes; if (!markingascomplete && _preferences->promptDelete()) { if (task->childCount() == 0) { - response = KMessageBox::warningYesNo( 0, + response = KMessageBox::warningContinueCancel( 0, i18n( "Are you sure you want to delete " "the task named\n\"%1\" and its entire history?") .arg(task->name()), - i18n( "Deleting Task")); + i18n( "Deleting Task"), KStdGuiItem::del()); } else { - response = KMessageBox::warningYesNo( 0, + response = KMessageBox::warningContinueCancel( 0, i18n( "Are you sure you want to delete the task named" "\n\"%1\" and its entire history?\n" "NOTE: all its subtasks and their history will also " "be deleted.").arg(task->name()), - i18n( "Deleting Task")); + i18n( "Deleting Task"), KStdGuiItem::del()); } } - if (response == KMessageBox::Yes) + if (response == KMessageBox::Continue) { if (markingascomplete) { task->setPercentComplete(100, _storage); + task->setPixmapProgress(); save(); + emit updateButtons(); // Have to remove after saving, as the save routine only affects tasks // that are in the view. Otherwise, the new percent complete does not // get saved. (No longer remove when marked as complete.) //task->removeFromView(); } else { task->remove(activeTasks, _storage); task->removeFromView(); - save(); deleteItemState( task ); + save(); } // remove root decoration if there is no more children. bool anyChilds = false; for(Task* child = first_child(); child; child = child->nextSibling()) { if (child->childCount() != 0) { anyChilds = true; break; } } if (!anyChilds) { setRootIsDecorated(false); } // Stop idle detection if no more counters are running if (activeTasks.count() == 0) { _idleTimeDetector->stopIdleDetection(); emit timersInactive(); } emit tasksChanged( activeTasks ); } } void TaskView::extractTime(int minutes) { addTimeToActiveTasks(-minutes); } void TaskView::autoSaveChanged(bool on) { if (on) _autoSaveTimer->start(_preferences->autoSavePeriod()*1000*secsPerMinute); else if (_autoSaveTimer->isActive()) _autoSaveTimer->stop(); } void TaskView::autoSavePeriodChanged(int /*minutes*/) { autoSaveChanged(_preferences->autoSave()); } void TaskView::adaptColumns() { // to hide a column X we set it's width to 0 // at that moment we'll remember the original column within // previousColumnWidths[X] // // When unhiding a previously hidden column // (previousColumnWidths[X] != HIDDEN_COLUMN !) // we restore it's width from the saved value and set // previousColumnWidths[X] to HIDDEN_COLUMN for( int x=1; x <= 4; x++) { // the column was invisible before and were switching it on now if( _preferences->displayColumn(x-1) && previousColumnWidths[x-1] != HIDDEN_COLUMN ) { setColumnWidth( x, previousColumnWidths[x-1] ); previousColumnWidths[x-1] = HIDDEN_COLUMN; setColumnWidthMode( x, QListView::Maximum ); } // the column was visible before and were switching it off now else if( ! _preferences->displayColumn(x-1) && previousColumnWidths[x-1] == HIDDEN_COLUMN ) { setColumnWidthMode( x, QListView::Manual ); // we don't want update() // to resize/unhide the col previousColumnWidths[x-1] = columnWidth( x ); setColumnWidth( x, 0 ); } } } void TaskView::deletingTask(Task* deletedTask) { DesktopList desktopList; _desktopTracker->registerForDesktops( deletedTask, desktopList ); activeTasks.removeRef( deletedTask ); emit tasksChanged( activeTasks); } void TaskView::iCalFileChanged(QString file) { kdDebug(5970) << "TaskView:iCalFileChanged: " << file << endl; stopAllTimers(); _storage->save(this); load(); } QValueList TaskView::getHistory(const QDate& from, const QDate& to) const { return _storage->getHistory(from, to); } void TaskView::markTaskAsComplete() { if (current_item()) kdDebug(5970) << "TaskView::markTaskAsComplete: " << current_item()->uid() << endl; else kdDebug(5970) << "TaskView::markTaskAsComplete: null current_item()" << endl; bool markingascomplete = true; deleteTask(markingascomplete); } +void TaskView::markTaskAsIncomplete() +{ + if (current_item()) + kdDebug(5970) << "TaskView::markTaskAsComplete: " + << current_item()->uid() << endl; + else + kdDebug(5970) << "TaskView::markTaskAsComplete: null current_item()" << endl; + + reinstateTask(50); // if it has been reopened, assume half-done +} + + void TaskView::clipTotals() { - TimeKard *t = new TimeKard(); + TimeKard t; if (current_item() && current_item()->isRoot()) { int response = KMessageBox::questionYesNo( 0, i18n("Copy totals for just this task and its subtasks, or copy totals for all tasks?"), i18n("Copy Totals to Clipboard"), i18n("Copy This Task"), i18n("Copy All Tasks") ); if (response == KMessageBox::Yes) // this task only { - KApplication::clipboard()->setText(t->totalsAsText(this)); + KApplication::clipboard()->setText(t.totalsAsText(this)); } else // only task { - KApplication::clipboard()->setText(t->totalsAsText(this, false)); + KApplication::clipboard()->setText(t.totalsAsText(this, false)); } } else { - KApplication::clipboard()->setText(t->totalsAsText(this)); + KApplication::clipboard()->setText(t.totalsAsText(this)); } } void TaskView::clipHistory() { - - PrintDialog *dialog = new PrintDialog(); - if (dialog->exec()== QDialog::Accepted) + PrintDialog dialog; + if (dialog.exec()== QDialog::Accepted) { - TimeKard *t = new TimeKard(); + TimeKard t; KApplication::clipboard()-> - setText(t->historyAsText(this, dialog->from(), dialog->to())); + setText( t.historyAsText(this, dialog.from(), dialog.to(), !dialog.allTasks(), dialog.perWeek(), dialog.totalsOnly() ) ); } } #include "taskview.moc" diff --git a/karm/taskview.h b/karm/taskview.h index 7461d320f3..f286d457a7 100644 --- a/karm/taskview.h +++ b/karm/taskview.h @@ -1,195 +1,216 @@ #ifndef KARM_TASK_VIEW_H #define KARM_TASK_VIEW_H #include #include #include #include #include "desktoplist.h" #include "resourcecalendar.h" #include "karmstorage.h" +#include "reportcriteria.h" #include //#include "desktoptracker.h" //#include "karmutility.h" class QListBox; class QString; class QTextStream; class QTimer; class KMenuBar; class KToolBar; class DesktopTracker; class EditTaskDialog; class IdleTimeDetector; class Preferences; class Task; class KarmStorage; class HistoryEvent; using namespace KCal; /** * Container and interface for the tasks. */ class TaskView : public KListView { Q_OBJECT public: TaskView( QWidget *parent = 0, const char *name = 0, const QString &icsfile = "" ); virtual ~TaskView(); /** Return the first item in the view, cast to a Task pointer. */ Task* first_child() const; /** Return the current item in the view, cast to a Task pointer. */ Task* current_item() const; /** Return the i'th item (zero-based), cast to a Task pointer. */ Task* item_at_index(int i); /** Load the view from storage. */ - void load(); + void load( QString filename="" ); /** Close the storage and release lock. */ void closeStorage(); /** Reset session time to zero for all tasks. */ void startNewSession(); /** Reset session and total time to zero for all tasks. */ void resetTimeForAllTasks(); /** Return the total number if items in the view. */ long count(); /** Return list of start/stop events for given date range. */ QValueList getHistory(const QDate& from, const QDate& to) const; /** Schedule that we should save very soon */ void scheduleSave(); /** Return preferences user selected on settings dialog. **/ Preferences *preferences(); /** Add a task to view and storage. */ QString addTask( const QString& taskame, long total, long session, const DesktopList& desktops, Task* parent = 0 ); public slots: /** Save to persistent storage. */ QString save(); /** Start the timer on the current item (task) in view. */ void startCurrentTimer(); /** Stop the timer for the current item in the view. */ void stopCurrentTimer(); /** Stop all running timers. */ void stopAllTimers(); - /** Stop all running timers, and start timer on current item. */ - void changeTimer( QListViewItem * = 0 ); - - /** Calls newTask with caption "New Task". */ + /** Calls newTask dialog with caption "New Task". */ void newTask(); /** Display edit task dialog and create a new task with results. */ void newTask( QString caption, Task* parent ); /** Used to refresh (e.g. after import) */ void refresh(); /** Used to import a legacy file format. */ void loadFromFlatFile(); /** used to import tasks from imendio planner */ - void importPlanner(); + QString importPlanner( QString fileName="" ); + + /** call export function for csv totals or history */ + QString report( const ReportCriteria &rc ); /** Export comma separated values format for task time totals. */ void exportcsvFile(); /** Export comma-separated values format for task history. */ QString exportcsvHistory(); - /** Calls newTask with caption "New Sub Task". */ + /** Calls newTask dialog with caption "New Sub Task". */ void newSubTask(); void editTask(); + + /** + * Returns a pointer to storage object. + * + * This is poor object oriented design--the task view should + * expose wrappers around the storage methods we want to access instead of + * giving clients full access to objects that we own. + * + * Hopefully, this will be redesigned as part of the Qt4 migration. + */ KarmStorage* storage(); /** * Delete task (and children) from view. * * @param markingascomplete If false (the default), deletes history for * current task and all children. If markingascomplete is true, then sets * percent complete to 100 and removes task and all it's children from the * list view. */ void deleteTask(bool markingascomplete=false); + + /** Reinstates the current task as incomplete. + * @param completion The percentage complete to mark the task as. */ + void reinstateTask(int completion); // void addCommentToTask(); void markTaskAsComplete(); + void markTaskAsIncomplete(); /** Subtracts time from all active tasks, and does not log event. */ void extractTime( int minutes ); void taskTotalTimesChanged( long session, long total) { emit totalTimesChanged( session, total); }; void adaptColumns(); /** receiving signal that a task is being deleted */ void deletingTask(Task* deletedTask); void startTimerFor( Task* task ); void stopTimerFor( Task* task ); /** User has picked a new iCalendar file on preferences screen. */ void iCalFileChanged(QString file); /** Copy totals for current and all sub tasks to clipboard. */ void clipTotals(); /** Copy history for current and all sub tasks to clipboard. */ void clipHistory(); signals: void totalTimesChanged( long session, long total ); void updateButtons(); void timersActive(); void timersInactive(); void tasksChanged( QPtrList activeTasks ); private: // member variables IdleTimeDetector *_idleTimeDetector; QTimer *_minuteTimer; QTimer *_autoSaveTimer; QTimer *_manualSaveTimer; Preferences *_preferences; QPtrList activeTasks; int previousColumnWidths[4]; DesktopTracker* _desktopTracker; bool _isloading; //KCal::CalendarLocal _calendar; KarmStorage * _storage; private: + void contentsMousePressEvent ( QMouseEvent * e ); + void contentsMouseDoubleClickEvent ( QMouseEvent * e ); void updateParents( Task* task, long totalDiff, long sesssionDiff); void deleteChildTasks( Task *item ); void addTimeToActiveTasks( int minutes, bool save_data = true ); + /** item state stores if a task is expanded so you can see the subtasks */ void restoreItemState( QListViewItem *item ); protected slots: void autoSaveChanged( bool ); void autoSavePeriodChanged( int period ); void minuteUpdate(); + /** item state stores if a task is expanded so you can see the subtasks */ void itemStateChanged( QListViewItem *item ); + /** item state stores if a task is expanded so you can see the subtasks */ void deleteItemState( QListViewItem *item ); void iCalFileModified(ResourceCalendar *); }; #endif // KARM_TASK_VIEW diff --git a/karm/test/Makefile.am b/karm/test/Makefile.am index f26026de23..d4f4c1aa07 100644 --- a/karm/test/Makefile.am +++ b/karm/test/Makefile.am @@ -1,17 +1,17 @@ METASOURCES = AUTO check_PROGRAMS = runscripts locking runscripts_SOURCES = script.cpp runscripts.cpp runscripts_LDFLAGS = $(all_libraries) $(KDE_RPATH) runscripts_LDADD = $(LIB_QT) $(LIB_KDECORE) locking_SOURCES = locking.cpp lockerthread.cpp locking_LDFLAGS = $(all_libraries) $(KDE_RPATH) -locking_LDADD = $(LIB_QT) $(LIB_KDEPIM) +locking_LDADD = $(LIB_QT) $(top_builddir)/libkcal/libkcal.la KDE_CXXFLAGS = $(USE_EXCEPTIONS) INCLUDES = -I$(srcdir) -I$(top_srcdir) -I$(top_srcdir)/libkcal $(all_includes) TESTS = runscripts locking diff --git a/karm/test/README b/karm/test/README index b149fdd656..e7c30d0b33 100644 --- a/karm/test/README +++ b/karm/test/README @@ -1,63 +1,76 @@ This directory holds automated tests for karm. -It's in very rough shape. Basically, I consider it usable only by me. +It's in very rough shape. + + +How you start: + + (1) get and install kdepim including karm + + (2) get and install xautomation from http://hoopajoo.net/projects/xautomation.html + + (3) get and install Net::DAV::Server with CPAN + + (4) start the automated tests with the command make check + Here are some of the issues: (1) The tests require KDE to be running in English. The automated XTests use shortcut keys to drive the app. These key combinations are language specific. (2) The tests require that you "make install" first. The XAutomation tests and tests that use DCOP run karm from the bash prompt. (3) The tests are destructive. If you have an already running instance of karm, the tests will kill that instance. So you cannot, for example, record time spent running karm automated tests. The tests are smart enough to use test iCalendar files. But they will alter the karm storage settings for the ics file name. (4) The runscripts program does not kill scripts that never return. You have to monitor the progress and press Control-C if you think a script is hung. (5) No attempt is made to check for installed script interpreters. In addition to required interpreters (Python 2.2, for example), the bash scripts use xte, which on Debian is in the xautomation package. If a required library is not found, runscripts will consider this a script failure and stop. (6) I have only tested this with Bash on GNU/Linux. (7) When a test fails, it is really hard to figure out why. There is too much stuff mixed together on the console output, and the tests themselves do not give much info when they fail. That having been said, I find it so useful that I will keep working on this so it should get better shortly. + Some notes on runscripts.cpp: Parses this directory for script files (Python, PHP, Perl and Bash). It identifies a script file by the extension. It runs any script files it finds. Within each script type, it runs the scripts in alphabetical order. Scripts that start with a double underscore are skipped. When a script fails runscripts stops. Script files should return a non-zero exit code to indicate a failure. -- Mark Bucciarelli December 6, 2004 diff --git a/karm/test/__lib.sh b/karm/test/__lib.sh index fa6f1a665c..06fd9df62b 100644 --- a/karm/test/__lib.sh +++ b/karm/test/__lib.sh @@ -1,75 +1,79 @@ # Expects karm test file in $TESTFILE # Returns dcop id in $DCOP_ID function set_up() { DCOPID=`dcop 2>/dev/null | grep karm` if [ -n "$DCOPID" ]; then dcop $DCOPID KarmDCOPIface quit; fi; - if [ -e "$TESTFILE" ]; then rm $TESTFILE; fi + if [ "x$SKIP_TESTFILE_DELETE" != "xtrue" ]; then + if [ -e "$TESTFILE" ]; then rm $TESTFILE; fi + fi #echo "__lib.sh - starting karm with $TESTFILE" karm "$TESTFILE" & # Make sure karm is up and running limit=10 idx=0 DCOPID="" while [ "$idx" -lt "$limit" ] do #echo "__lib.sh: dcop 2>/dev/null | grep karm" DCOPID=`dcop 2>/dev/null | grep karm` if [ -n "$DCOPID" ] then break else let "idx += 1" fi sleep 1 done # It's not enough to get the dcop id, as this is available almost # immediately. We need to make sure karm (and fam) is done loading data. limit=20 idx=0 KARM_VERSION="" while [ "$idx" -lt "$limit" ] do #echo "__lib.sh: dcop $DCOPID KarmDCOPIface version 2>/dev/null" KARM_VERSION=`dcop $DCOPID KarmDCOPIface version 2>/dev/null` if [ -n "$KARM_VERSION" ] then break else let "idx += 1" fi sleep 1 done - echo "__lib.sh: DCOPID = $DCOPID, KARM_VERSION = $KARM_VERSION" - if [ "x$DCOPID" = x ] then echo "__lib.sh set_up error: could not start karm--no dcop id." exit 1 + else + echo "__lib.sh: DCOPID = $DCOPID, KARM_VERSION = $KARM_VERSION" fi if [ "x$KARM_VERSION" = x ] then echo "__lib.sh set_up error: karm did not return a version string." exit 1 fi } function test_func() { echo "Yep, that works." } function tear_down() { if [ -n "$DCOPID" ]; then dcop "$DCOPID" KarmDCOPIface quit; fi; - if [ -e "$TESTFILE" ]; then rm "$TESTFILE"; fi + if [ "x$SKIP_TESTFILE_DELETE" != "xtrue" ]; then + if [ -e "$TESTFILE" ]; then rm "$TESTFILE"; fi + fi } diff --git a/ktimetracker/test/__webdav.pl b/karm/test/__webdav.pl similarity index 100% rename from ktimetracker/test/__webdav.pl rename to karm/test/__webdav.pl diff --git a/ktimetracker/test/booktime-baddate.sh b/karm/test/booktime-baddate.sh similarity index 100% rename from ktimetracker/test/booktime-baddate.sh rename to karm/test/booktime-baddate.sh diff --git a/ktimetracker/test/booktime-badduration.sh b/karm/test/booktime-badduration.sh similarity index 100% rename from ktimetracker/test/booktime-badduration.sh rename to karm/test/booktime-badduration.sh diff --git a/ktimetracker/test/booktime-badtime.sh b/karm/test/booktime-badtime.sh similarity index 100% rename from ktimetracker/test/booktime-badtime.sh rename to karm/test/booktime-badtime.sh diff --git a/ktimetracker/test/booktime-baduid.sh b/karm/test/booktime-baduid.sh similarity index 100% rename from ktimetracker/test/booktime-baduid.sh rename to karm/test/booktime-baduid.sh diff --git a/ktimetracker/test/booktime-works.sh b/karm/test/booktime-works.sh similarity index 100% rename from ktimetracker/test/booktime-works.sh rename to karm/test/booktime-works.sh diff --git a/karm/test/bug94447.sh b/karm/test/bug94447.sh index ce13d35538..fa163735ba 100755 --- a/karm/test/bug94447.sh +++ b/karm/test/bug94447.sh @@ -1,28 +1,30 @@ #!/bin/sh # Create files relative to current directory if no "/" prefix # in file name given on command line +exec >>check.log 2>&1 + TESTFILE="testkarm.ics" TESTTODO="testtodo" source __lib.sh set_up # make karm create the file. dcop $DCOPID KarmDCOPIface addtodo "$TESTTODO" RVAL=1 if [ -e $TESTFILE ]; then RVAL=0; fi tear_down if [ $RVAL -eq 0 ] then echo "PASS $0" exit 0 else echo "FAIL $0" exit 1 fi diff --git a/ktimetracker/test/delete.sh b/karm/test/delete.sh similarity index 100% rename from ktimetracker/test/delete.sh rename to karm/test/delete.sh diff --git a/karm/test/lifetest.php b/karm/test/lifetest.php index 341c72dd1c..7f4766545d 100644 --- a/karm/test/lifetest.php +++ b/karm/test/lifetest.php @@ -1,219 +1,219 @@ #!/usr/bin/php '); fclose($handle); }; function simkey($s) // This function simulates keypresses that form the string $s, e.g. for $s==hallo, it simulates the keypress of h, then a, then l and so on. // find a useful list of keycodes under /usr/include/X11/keysymdef.h { for ($i=0; $i/dev/null",$rc); if ($rc==0) echo " You have.\n"; if ($rc==127) echo " You do not have, please get it from http://hoopajoo.net/projects/xautomation.html .\n"; echo "This program will test karm by issueing karm, so, make sure, this calls the version you want to test (make install).\n\n"; echo "This program will now stop unless you give the parameter --batch (confirming that you do not touch the keyboard)\n"; $err=""; $exit=0; } else { switch (funkeysim("Alt_L")) { case 1: $err.="this must be run in an X environment\n"; break; case 127: $err.="you do not have XAutomation installed, get it from http://hoopajoo.net/projects/xautomation.html\n"; break; } // the following is the same as 'if file_exist(...) unlink(...)', but atomic @unlink ("/tmp/karmtest.ics"); @unlink ("/tmp/example.planner"); if ($err=="") { // start and wait till mainwindow is up // the mouse can be in the way, so, move it out. This here even works with "focus strictly under mouse". system("xte 'mousemove 1 1'"); echo "\nStarting karm"; - $process=popen("karm --geometry 200x100+0+0", 'w'); + $process=popen("karm --geometry 200x100+0+0 /tmp/karmtest.ics >/dev/null 2>&1", 'w'); $rc=1; while ($rc==1) system("dcop `dcop 2>/dev/null | grep karm` KarmDCOPIface version",$rc); echo "mainwindow is ready"; sleep (1); funkeysim("Alt_L"); funkeysim("Right",3); funkeysim("Down",2); funkeysim("Return"); sleep (1); funkeysim("Down",2); funkeysim("Tab",5); simkey("/tmp/karmtest.ics"); sleep (1); funkeysim("Return"); sleep (1); funkeysim("Return"); sleep (1); # add a new task funkeysim("Alt_L"); funkeysim("Right",2); funkeysim("Down"); sleep (1); funkeysim("Return"); sleep (1); simkey("example 1"); funkeysim("Return"); sleep (1); echo "\nCreating a planner project file..."; createplannerexample(); # import planner project file funkeysim("Alt_L"); funkeysim("Down",5); funkeysim("Right"); funkeysim("Down"); funkeysim("Return"); sleep (2); keysim("/tmp/example.planner"); sleep (1); funkeysim("Return"); sleep (1); # export to CSV file funkeysim("Alt_L"); funkeysim("Down",5); funkeysim("Right"); funkeysim("Down",2); funkeysim("Return"); sleep(1); keysim("/tmp/exporttest.csv"); sleep(1); funkeysim("Tab",6); system ("xte 'keydown Alt_L'"); system ("xte 'key m'"); system ("xte 'keyup Alt_L'"); sleep(1); funkeysim("Return"); # send CTRL_Q sleep (2); echo "\nsending CTRL_Q...\n"; system ("xte 'keydown Control_L'"); system ("xte 'key Q'"); system ("xte 'keyup Control_L'"); $content=file_get_contents("/tmp/karmtest.ics"); $lines=explode("\n",$content); if (!preg_match("/DTSTAMP:[0-9]{1,8}T[0-9]{1,6}Z/", $lines[4])) $err.="iCal file: wrong dtstamp"; if ($lines[12]<>"SUMMARY:example 1") $err.="iCal file: wrong task example 1"; if ($lines[16]<>"END:VTODO") $err.="iCal file: wrong end of vtodo"; if ($lines[27]<>"SUMMARY:task 1") $err.="iCal file: wrong task task 1"; if (!preg_match("/^UID:libkcal-[0-9]{1,8}.[0-9]{1,3}/", $lines[39])) $err.="iCal file: wrong uid"; $content=file_get_contents("/tmp/exporttest.csv"); $lines=explode("\n",$content); if (!preg_match("/\"example 1\",,0[,|.]00,0[,|.]00,0[,|.]00,0[,|.]00/", $lines[0])) $err.="csv export is wrong"; pclose($process); @unlink ("/tmp/karmtest.ics"); @unlink ("/tmp/example.planner"); @unlink ("/tmp/exporttest.csv"); } } echo $err; if ($err!="") exit(1); ?> \ No newline at end of file diff --git a/karm/test/refresh_on_change.sh b/karm/test/refresh_on_change.sh index d189093f2d..5a33f11d74 100755 --- a/karm/test/refresh_on_change.sh +++ b/karm/test/refresh_on_change.sh @@ -1,50 +1,55 @@ #!/bin/sh +# I cannot get this test to work reliably! +# I suspect the culprit is FAM. +# -- Mark + +exec >>check.log 2>&1 source __lib.sh TESTFILE="/tmp/testkarm.ics" + set_up TODO_NAME=$0 TODO_UID=abc-123 TODO_TIME=`date +%Y%m%dT%H%M%SZ` -# file is empty, as karm doesn't write anything till there is data. cat >> $TESTFILE << endl BEGIN:VCALENDAR PRODID:-//K Desktop Environment//NONSGML KArm Test Scripts//EN VERSION:2.0 BEGIN:VTODO DTSTAMP:$TODO_TIME ORGANIZER;CN=Anonymous:MAILTO:nobody@nowhere CREATED:$TODO_TIME UID:$TODO_UID SEQUENCE:0 LAST-MODIFIED:$TODO_TIME SUMMARY:$TODO_NAME CLASS:PUBLIC PRIORITY:5 PERCENT-COMPLETE:0 END:VTODO END:VCALENDAR endl # wait so FAM and KDirWatcher tell karm and karm refreshes view sleep 2 RVAL=`dcop $DCOPID KarmDCOPIface hastodo $TODO_NAME` #echo "RVAL = $RVAL" tear_down # check that todo was found if [ "$RVAL" == "$TODO_UID" ]; then echo "PASS $0" exit 0; else echo "FAIL $0: got /$RVAL/, expected /$TODO_UID/" exit 1; fi diff --git a/karm/test/remote_storage.sh b/karm/test/remote_storage.sh index cae52b90db..a4335b6c10 100755 --- a/karm/test/remote_storage.sh +++ b/karm/test/remote_storage.sh @@ -1,56 +1,58 @@ #!/bin/sh # Karm can read and write to an FTP server for storage file. +exec >>check.log 2>&1 + PORT=8000 TESTFILE="http://localhost:$PORT/testkarm.ics" TESTFILE_LOCAL="testkarm.ics" TESTTODO="testtodo" # Start with clean environment # If runscripts sees output on stderr, it thinks script failed. DCOPID=`dcop | grep karm 2>/dev/null` if [ -n $DCOPID ]; then dcop $DCOPID KarmDCOPIface quit; fi; if [ -e $TESTFILE_LOCAL ]; then rm $TESTFILE_LOCAL; fi # if the file does not exist, kresources pops up a modal dialog box # telling us that a file does not exist. touch $TESTFILE_LOCAL python __httpd.py $PORT & sleep 2 HTTPD_PID=`ps -C "python __httpd.py" -o pid=` karm $TESTFILE & sleep 2 DCOPID=`dcop | grep karm` # karm does not write file until data is saved. echo "DEBUG: dcop $DCOPID KarmDCOPIface addtodo \"$TESTTODO\"" dcop $DCOPID KarmDCOPIface addtodo "$TESTTODO" sleep 1 RVAL=1 if [ -e $TESTFILE_LOCAL ]; then RVAL=0; fi # clean up if [ -n $DCOPID ]; then dcop $DCOPID KarmDCOPIface quit; fi; if [ -e $TESTFILE_LOCAL ]; then rm $TESTFILE_LOCAL; fi if [ -n $HTTPD_PID ]; then kill $HTTPD_PID; fi # return 0 on success, 1 on failure if [ $RVAL -eq 0 ] then echo "PASS $0" exit 0 else echo "FAIL $0" exit 1 fi diff --git a/karm/test/runscripts.cpp b/karm/test/runscripts.cpp index 683f4fc083..deabd879aa 100644 --- a/karm/test/runscripts.cpp +++ b/karm/test/runscripts.cpp @@ -1,125 +1,125 @@ /* This file is part of the KDE project Copyright (C) 2004 Mark Bucciarelli This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include "script.h" static QString srcdir(); static int runscripts ( const QString &interpreter, const QString &extension, const QString &path ); const QString dots = ".................................................."; const QString not_a_test_filename_prefix = "__"; // Read srcdir from Makefile (for builddir != srcdir). QString srcdir() { bool found = false; QString dir; QFile file( "Makefile" ); if ( !file.open( IO_ReadOnly | IO_Translate ) ) return ""; QTextStream in( &file ); QString line; while ( !found && !in.atEnd() ) { line = in.readLine(); if ( line.startsWith( "srcdir = " ) ) { dir = line.mid( 9 ); found = true; } } if ( !found ) dir = ""; return dir; } int runscripts ( const QString &interpreter, const QString &extension, const QString &path ) { int rval = 0; QStringList files; QDir dir( path ); Script* s = new Script( dir ); dir.setNameFilter( extension ); dir.setFilter( QDir::Files ); dir.setSorting( QDir::Name | QDir::IgnoreCase ); const QFileInfoList *list = dir.entryInfoList(); QFileInfoListIterator it( *list ); QFileInfo *fi; while ( !rval && ( fi = it.current() ) != 0 ) { // Don't run scripts that are shared routines. if ( ! fi->fileName().startsWith( not_a_test_filename_prefix ) ) { s->addArgument( interpreter ); s->addArgument( path + QDir::separator() + fi->fileName().latin1() ); // Thorsten's xautomation tests run with user interaction by default. if ( interpreter == "sh" ) s->addArgument( "--batch" ); if ( interpreter == "php" ) s->addArgument( "--batch" ); rval = s->run(); kdDebug() << "runscripts: " << fi->fileName() << " " << dots.left( dots.length() - fi->fileName().length() ) << " " << ( ! rval ? "PASS" : "FAIL" ) << endl; // Don't abort if one test files--run them all if ( rval ) rval = 0; delete s; s = new Script( dir ); } ++it; } delete s; s = 0; return rval; } int main( int, char** ) { int rval = 0; QString path = srcdir(); if ( !rval ) rval = runscripts( "python", "*.py *.Py *.PY *.pY", path ); if ( !rval ) rval = runscripts( "sh", "*.sh *.Sh *.SH *.sH", path ); if ( !rval ) rval = runscripts( "perl", "*.pl *.Pl *.PL *.pL", path ); if ( !rval ) rval = runscripts( "php", "*.php *.php3 *.php4 *.php5", path ); return rval; } diff --git a/karm/test/script.cpp b/karm/test/script.cpp index d5b3c18a7a..37fe058d3f 100644 --- a/karm/test/script.cpp +++ b/karm/test/script.cpp @@ -1,115 +1,115 @@ /* This file is part of the KDE project Copyright (C) 2002 Anders Lund Copyright (C) 2004 Mark Bucciarelli This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include "script.h" /* n.b. Do not use kdDebug statements in this file. With qt-copy 3_3_BRANCH, they cause a Valgrind error. Ref: KDE bug #95237. */ // Wait for terminate() attempt to return before using kill() // kill() doesn't let script interpreter try to clean up. const int NICE_KILL_TIMEOUT_IN_SECS = 5; Script::Script( const QDir& workingDirectory ) { m_status = 0; m_stderr = false; m_timeoutInSeconds = 5; m_proc = new QProcess( this ); m_proc->setWorkingDirectory( workingDirectory ); connect ( m_proc, SIGNAL( readyReadStdout() ), this , SLOT ( stdout() ) ); connect ( m_proc, SIGNAL( readyReadStderr() ), this , SLOT ( stderr() ) ); connect ( m_proc, SIGNAL( processExited() ), this , SLOT ( exit() ) ); } Script::~Script() { delete m_proc; m_proc = 0; } void Script::addArgument( const QString &arg ) { m_proc->addArgument( arg ); } void Script::setTimeout( int seconds ) { if ( seconds <= 0 ) return; m_timeoutInSeconds = seconds; } int Script::run() { m_proc->start(); // This didn't work. But Ctrl-C does. :P //QTimer::singleShot( m_timeoutInSeconds * 1000, m_proc, SLOT( kill() ) ); //while ( ! m_proc->normalExit() ); while ( m_proc->isRunning() ); return m_status; } void Script::terminate() { // These both trigger processExited, so exit() will run. m_proc->tryTerminate(); QTimer::singleShot( NICE_KILL_TIMEOUT_IN_SECS*1000, m_proc, SLOT( kill() ) ); } void Script::exit() { m_status = m_proc->exitStatus(); delete m_proc; m_proc = 0; } void Script::stderr() { // Treat any output to std err as a script failure m_status = 1; QString data = QString( m_proc->readStderr() ); m_stderr= true; } void Script::stdout() { QString data = QString( m_proc->readStdout() ); } #include "script.moc" diff --git a/karm/test/script.h b/karm/test/script.h index 2367a4bf30..f5ae1e2272 100644 --- a/karm/test/script.h +++ b/karm/test/script.h @@ -1,52 +1,52 @@ /* This file is part of the KDE project Copyright (C) 2004 Mark Bucciarelli This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. */ #ifndef _script_h_ #define _script_h_ //#include #include class QDir; class QProcess; class QString; class QStringList; class Script : public QObject { Q_OBJECT public: Script( const QDir& workingDirectory ); virtual ~Script(); void addArgument( const QString &arg ); void setTimeout( int seconds ); int run(); private slots: void exit(); void stderr(); void stdout(); void terminate(); private: QProcess *m_proc; int m_status; bool m_stderr; int m_timeoutInSeconds; }; #endif // _script_h_ diff --git a/karm/test/version.sh b/karm/test/version.sh index 9b8cd80933..64fbc8fb06 100755 --- a/karm/test/version.sh +++ b/karm/test/version.sh @@ -1,22 +1,24 @@ #!/bin/sh # First test, just check version. +exec >>check.log 2>&1 + TESTFILE="/tmp/testkarm1.ics" -VERSION="1.5.0" +VERSION="1.6.0" source __lib.sh set_up RVAL=`dcop $DCOPID KarmDCOPIface version 2>/dev/null` tear_down if [ "$RVAL" == "$VERSION" ]; then echo "PASS $0" exit 0; else echo "FAIL $0: got /$RVAL/, expected /$VERSION/" exit 1; fi diff --git a/ktimetracker/test/webdav.sh b/karm/test/webdav.sh similarity index 100% rename from ktimetracker/test/webdav.sh rename to karm/test/webdav.sh diff --git a/karm/timekard.cpp b/karm/timekard.cpp index 799df7df8a..95884219ad 100644 --- a/karm/timekard.cpp +++ b/karm/timekard.cpp @@ -1,358 +1,377 @@ /* * This file only: * Copyright (C) 2003 Mark Bucciarelli * * 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. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ // #include #include #include #include #include #include #include #include // i18n #include #include "karmutility.h" // formatTime() #include "timekard.h" #include "task.h" #include "taskview.h" +#include const int taskWidth = 40; const int timeWidth = 6; const int totalTimeWidth = 7; const int reportWidth = taskWidth + timeWidth; -const int weekReportWidth = taskWidth + (7 * timeWidth) + totalTimeWidth; const QString cr = QString::fromLatin1("\n"); QString TimeKard::totalsAsText(TaskView* taskview, bool justThisTask) { QString retval; - QString taskhdr, totalhdr; QString line; QString buf; long sum; line.fill('-', reportWidth); line += cr; // header retval += i18n("Task Totals") + cr; retval += KGlobal::locale()->formatDateTime(QDateTime::currentDateTime()); retval += cr + cr; retval += QString(QString::fromLatin1("%1 %2")) .arg(i18n("Time"), timeWidth) .arg(i18n("Task")); retval += cr; retval += line; // tasks if (taskview->current_item()) { if (justThisTask) { // a task's total time includes the sum of all subtask times sum = taskview->current_item()->totalTime(); printTask(taskview->current_item(), retval, 0); } else { sum = 0; for (Task* task= taskview->current_item(); task; task= task->nextSibling()) { sum += task->totalTime(); - printTask(task, retval, 0); + if ( task->totalTime() ) + printTask(task, retval, 0); } } // total buf.fill('-', reportWidth); retval += QString(QString::fromLatin1("%1")).arg(buf, timeWidth) + cr; retval += QString(QString::fromLatin1("%1 %2")) .arg(formatTime(sum),timeWidth) .arg(i18n("Total")); } else retval += i18n("No tasks."); return retval; } +// Print out " ", for task and subtasks. Used by totalsAsText. void TimeKard::printTask(Task *task, QString &s, int level) { QString buf; s += buf.fill(' ', level); s += QString(QString::fromLatin1("%1 %2")) .arg(formatTime(task->totalTime()), timeWidth) .arg(task->name()); s += cr; for (Task* subTask = task->firstChild(); subTask; subTask = subTask->nextSibling()) { - printTask(subTask, s, level+1); + if ( subTask->totalTime() ) // to avoid 00:00 entries + printTask(subTask, s, level+1); } } -void TimeKard::printWeekTask(const Task *task, +void TimeKard::printTaskHistory(const Task *task, const QMap& taskdaytotals, QMap& daytotals, - const Week& week, const int level, QString& s) + const QDate& from, + const QDate& to, + const int level, QString& s, bool totalsOnly) { - QString buf; - QString daytaskkey, daykey; - QDate day; - long weeksum; - - day = week.start(); - weeksum = 0; - for (int i = 0; i < 7; i++) + long sectionsum = 0; + for ( QDate day = from; day <= to; day = day.addDays(1) ) { - daykey = day.toString(QString::fromLatin1("yyyyMMdd")); - daytaskkey = QString::fromLatin1("%1_%2") - .arg(daykey) - .arg(task->uid()); + QString daykey = day.toString(QString::fromLatin1("yyyyMMdd")); + QString daytaskkey = QString::fromLatin1("%1_%2") + .arg(daykey) + .arg(task->uid()); if (taskdaytotals.contains(daytaskkey)) { - s += QString::fromLatin1("%1") - .arg(formatTime(taskdaytotals[daytaskkey]/60), timeWidth); - weeksum += taskdaytotals[daytaskkey]; // in seconds + if ( !totalsOnly ) + { + s += QString::fromLatin1("%1") + .arg(formatTime(taskdaytotals[daytaskkey]/60), timeWidth); + } + sectionsum += taskdaytotals[daytaskkey]; // in seconds if (daytotals.contains(daykey)) daytotals.replace(daykey, daytotals[daykey] + taskdaytotals[daytaskkey]); else daytotals.insert(daykey, taskdaytotals[daytaskkey]); } - else + else if ( !totalsOnly ) { + QString buf; buf.fill(' ', timeWidth); s += buf; } - - day = day.addDays(1); } - // Total for task this week - s += QString::fromLatin1("%1").arg(formatTime(weeksum/60), totalTimeWidth); + // Total for task this section (e.g. week) + s += QString::fromLatin1("%1").arg(formatTime(sectionsum/60), totalTimeWidth); // Task name + QString buf; s += buf.fill(' ', level + 1); s += QString::fromLatin1("%1").arg(task->name()); s += cr; for (Task* subTask = task->firstChild(); subTask; subTask = subTask->nextSibling()) { - printWeekTask(subTask, taskdaytotals, daytotals, week, level+1, s); + // recursive + printTaskHistory(subTask, taskdaytotals, daytotals, from, to, level+1, s, totalsOnly); } } -QString TimeKard::historyAsText(TaskView* taskview, const QDate& from, - const QDate& to, bool justThisTask) +QString TimeKard::sectionHistoryAsText( + TaskView* taskview, + const QDate& sectionFrom, const QDate& sectionTo, + const QDate& from, const QDate& to, + const QString& name, + bool justThisTask, bool totalsOnly) { - QString retval; - QString taskhdr, totalhdr; - QString line, buf; - long sum; - QValueList::iterator week; + const int sectionReportWidth = taskWidth + ( totalsOnly ? 0 : sectionFrom.daysTo(sectionTo) * timeWidth ) + totalTimeWidth; + assert( sectionReportWidth > 0 ); + QString line; + line.fill('-', sectionReportWidth); + line += cr; + QValueList events; - QValueList::iterator event; + if ( sectionFrom < from && sectionTo > to) + { + events = taskview->getHistory(from, to); + } + else if ( sectionFrom < from ) + { + events = taskview->getHistory(from, sectionTo); + } + else if ( sectionTo > to) + { + events = taskview->getHistory(sectionFrom, to); + } + else + { + events = taskview->getHistory(sectionFrom, sectionTo); + } + QMap taskdaytotals; QMap daytotals; - QString daytaskkey, daykey; - QDate day; - - line.fill('-', weekReportWidth); - line += cr; - - // header - retval += i18n("Task History") + cr; - retval += i18n("From %1 to %2") - .arg(KGlobal::locale()->formatDate(from)) - .arg(KGlobal::locale()->formatDate(to)); - retval += cr; - retval += i18n("Printed on: %1") - .arg(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime())); - // output one time card table for each week in the date range - QValueList weeks = Week::weeksFromDateRange(from, to); - for (week = weeks.begin(); week != weeks.end(); ++week) + // Build lookup dictionary used to output data in table cells. keys are + // in this format: YYYYMMDD_NNNNNN, where Y = year, M = month, d = day and + // NNNNN = the VTODO uid. The value is the total seconds logged against + // that task on that day. Note the UID is the todo id, not the event id, + // so times are accumulated for each task. + for (QValueList::iterator event = events.begin(); event != events.end(); ++event) { - if ( (*week).start() < from && (*week).end() > to) - { - events = taskview->getHistory(from, to); - } - else if ( (*week).start() < from ) - { - events = taskview->getHistory(from, (*week).end()); - } - else if ( (*week).end() > to) - { - events = taskview->getHistory((*week).start(), to); - } - else - { - events = taskview->getHistory((*week).start(), (*week).end()); - } + QString daykey = (*event).start().date().toString(QString::fromLatin1("yyyyMMdd")); + QString daytaskkey = QString::fromLatin1("%1_%2") + .arg(daykey) + .arg((*event).todoUid()); - taskdaytotals.clear(); - daytotals.clear(); - - // Build lookup dictionary used to output data in table cells. keys are - // in this format: YYYYMMDD_NNNNNN, where Y = year, M = month, d = day and - // NNNNN = the VTODO uid. The value is the total seconds logged against - // that task on that day. Note the UID is the todo id, not the event id, - // so times are accumulated for each task. - for (event = events.begin(); event != events.end(); ++event) - { - daykey = (*event).start().date().toString(QString::fromLatin1("yyyyMMdd")); - daytaskkey = QString(QString::fromLatin1("%1_%2")) - .arg(daykey) - .arg((*event).todoUid()); - - if (taskdaytotals.contains(daytaskkey)) - taskdaytotals.replace(daytaskkey, - taskdaytotals[daytaskkey] + (*event).duration()); - else - taskdaytotals.insert(daytaskkey, (*event).duration()); - } + if (taskdaytotals.contains(daytaskkey)) + taskdaytotals.replace(daytaskkey, + taskdaytotals[daytaskkey] + (*event).duration()); + else + taskdaytotals.insert(daytaskkey, (*event).duration()); + } - // week name - retval += cr + cr; - buf.fill(' ', int((weekReportWidth - (*week).name().length()) / 2)); - retval += buf + (*week).name() + cr; + QString retval; + // section name (e.g. week name) + retval += cr + cr; + QString buf; + if ( name.length() < (unsigned int)sectionReportWidth ) + buf.fill(' ', int((sectionReportWidth - name.length()) / 2)); + retval += buf + name + cr; + if ( !totalsOnly ) + { // day headings - for (int i = 0; i < 7; i++) + for (QDate day = sectionFrom; day <= sectionTo; day = day.addDays(1)) { - retval += QString::fromLatin1("%1") - .arg((*week).start().addDays(i).day(), timeWidth); + retval += QString::fromLatin1("%1").arg(day.day(), timeWidth); } retval += cr; retval += line; + } - // the tasks - if (events.empty()) + // the tasks + if (events.empty()) + { + retval += " "; + retval += i18n("No hours logged."); + } + else + { + if (justThisTask) { - retval += i18n(" No hours logged."); + printTaskHistory(taskview->current_item(), taskdaytotals, daytotals, + sectionFrom, sectionTo, 0, retval, totalsOnly); } else { - sum = 0; - if (justThisTask) + for (Task* task= taskview->current_item(); task; + task= task->nextSibling()) { - printWeekTask(taskview->current_item(), taskdaytotals, daytotals, - (*week), 0, retval); + printTaskHistory(task, taskdaytotals, daytotals, + sectionFrom, sectionTo, 0, retval, totalsOnly); } - else + } + retval += line; + + // per-day totals at the bottom of the section + long sum = 0; + for (QDate day = sectionFrom; day <= sectionTo; day = day.addDays(1)) + { + QString daykey = day.toString(QString::fromLatin1("yyyyMMdd")); + + if (daytotals.contains(daykey)) { - for (Task* task= taskview->current_item(); task; - task= task->nextSibling()) + if ( !totalsOnly ) { - printWeekTask(task, taskdaytotals, daytotals, (*week), 0, retval); + retval += QString::fromLatin1("%1") + .arg(formatTime(daytotals[daykey]/60), timeWidth); } + sum += daytotals[daykey]; // in seconds } - retval += line; - - // totals - sum = 0; - day = (*week).start(); - for (int i = 0; i < 7; i++) + else if ( !totalsOnly ) { - daykey = day.toString(QString::fromLatin1("yyyyMMdd")); + buf.fill(' ', timeWidth); + retval += buf; + } + } - if (daytotals.contains(daykey)) - { - retval += QString::fromLatin1("%1") - .arg(formatTime(daytotals[daykey]/60), timeWidth); - sum += daytotals[daykey]; // in seconds - } - else - { - buf.fill(' ', timeWidth); - retval += buf; - } + retval += QString::fromLatin1("%1 %2") + .arg(formatTime(sum/60), totalTimeWidth) + .arg(i18n("Total")); + } + return retval; +} - day = day.addDays(1); - } +QString TimeKard::historyAsText(TaskView* taskview, const QDate& from, + const QDate& to, bool justThisTask, bool perWeek, bool totalsOnly) +{ + // header + QString retval; + retval += totalsOnly ? i18n("Task Totals") : i18n("Task History"); + retval += cr; + retval += i18n("From %1 to %2") + .arg(KGlobal::locale()->formatDate(from)) + .arg(KGlobal::locale()->formatDate(to)); + retval += cr; + retval += i18n("Printed on: %1") + .arg(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime())); - retval += QString::fromLatin1("%1 %2") - .arg(formatTime(sum/60), totalTimeWidth) - .arg(i18n("Total")); + if ( perWeek ) + { + // output one time card table for each week in the date range + QValueList weeks = Week::weeksFromDateRange(from, to); + for (QValueList::iterator week = weeks.begin(); week != weeks.end(); ++week) + { + retval += sectionHistoryAsText( taskview, (*week).start(), (*week).end(), from, to, (*week).name(), justThisTask, totalsOnly ); } + } else + { + retval += sectionHistoryAsText( taskview, from, to, from, to, "", justThisTask, totalsOnly ); } return retval; } Week::Week() {} Week::Week(QDate from) { _start = from; } QDate Week::start() const { return _start; } QDate Week::end() const { return _start.addDays(7); } QString Week::name() const { return i18n("Week of %1").arg(KGlobal::locale()->formatDate(start())); } QValueList Week::weeksFromDateRange(const QDate& from, const QDate& to) { QDate start; QValueList weeks; // The QDate weekNumber() method always puts monday as the first day of the // week. // // Not that it matters here, but week 1 always includes the first Thursday // of the year. For example, January 1, 2000 was a Saturday, so // QDate(2000,1,1).weekNumber() returns 52. // Since report always shows a full week, we generate a full week of dates, // even if from and to are the same date. The week starts on the day // that is set in the locale settings. start = from.addDays( -((7 - KGlobal::locale()->weekStartDay() + from.dayOfWeek()) % 7)); for (QDate d = start; d <= to; d = d.addDays(7)) weeks.append(Week(d)); return weeks; } diff --git a/karm/timekard.h b/karm/timekard.h index 5659461131..9d9de6765d 100644 --- a/karm/timekard.h +++ b/karm/timekard.h @@ -1,118 +1,127 @@ /* * This file only: * Copyright (C) 2003 Mark Bucciarelli * * 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. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA. * */ #ifndef KARM_TIMEKARD_H #define KARM_TIMEKARD_H #undef Color // X11 headers #undef GrayScale // X11 headers #include //#include #include "karmstorage.h" class QString; class QDate; class TaskView; /** * Seven consecutive days. * * The timecard report prints out one table for each week of data. The first * day of the week should be read from the KControlPanel. Currently, it is * hardcoded to Sunday. */ class Week { public: /** Need an empty constructor to use in a QValueList. */ Week(); Week(QDate from); QDate start() const; QDate end() const; QValueList days() const; /** * Returns a list of weeks for the given date range. * * The first day of the week is picked up from the settings in the * KontrolPanel. * * The list is inclusive; for example, if you pass in a date range of two * days, one being a Sunday and the other being a Monday, you will get two * weeks back in the list. */ static QValueList weeksFromDateRange(const QDate& from, const QDate& to); /** * Return the name of the week. * * Uses whatever the user has set up for the long date format in * KControlPanel, prefixed by "Week of". */ QString name() const; private: QDate _start; }; /** * Routines to output timecard data. */ class TimeKard { public: TimeKard() {}; /** * Generates ascii text of task totals, for current task on down. * * Formatted for pasting into clipboard. * - * @param taskview a pointer to a TaskView object. + * @param taskview The view whose tasks need to be formatted. + * * @param justThisTask Only useful when user has picked a root task. We * use this parameter to distinguish between when a user just wants to * print the task subtree for a root task and when they want to print * all tasks. */ QString totalsAsText(TaskView* taskview, bool justThisTask = true); /** * Generates ascii text of weekly task history, for current task on down. * * Formatted for pasting into clipboard. */ QString historyAsText(TaskView* taskview, const QDate& from, - const QDate& to, bool justThisTask = true); + const QDate& to, bool justThisTask, bool perWeek, bool totalsOnly); +private: void printTask(Task *t, QString &s, int level); - void printWeekTask(const Task *t, const QMap& datamap, - QMap& daytotals, - const Week& week, const int level, QString& retval); + void printTaskHistory(const Task *t, const QMap& datamap, + QMap& daytotals, + const QDate& from, const QDate& to, + const int level, QString& retval, bool totalsOnly); -}; + QString sectionHistoryAsText(TaskView* taskview, + const QDate& sectionFrom, const QDate& sectionTo, + const QDate& from, const QDate& to, + const QString& name, + bool justThisTask, bool totalsOnly); + + }; #endif // KARM_TIMEKARD_H diff --git a/karm/tray.cpp b/karm/tray.cpp index bf867bf082..228d807d81 100644 --- a/karm/tray.cpp +++ b/karm/tray.cpp @@ -1,155 +1,168 @@ /* * KTray. * * This implements the functionality of the little icon in the kpanel * tray. Among which are tool tips and the running clock animated icon * * Distributed under the GPL. */ // #include // #include #include #include #include #include #include #include // actionPreferences() #include #include #include // UserIcon #include // i18n #include // plug() #include #include "mainwindow.h" #include "task.h" #include "tray.h" QPtrVector *KarmTray::icons = 0; KarmTray::KarmTray(MainWindow* parent) : KSystemTray(parent, "Karm Tray") { // the timer that updates the "running" icon in the tray _taskActiveTimer = new QTimer(this); connect( _taskActiveTimer, SIGNAL( timeout() ), this, SLOT( advanceClock()) ); if (icons == 0) { icons = new QPtrVector(8); for (int i=0; i<8; i++) { QPixmap *icon = new QPixmap(); QString name; name.sprintf("active-icon-%d.xpm",i); *icon = UserIcon(name); icons->insert(i,icon); } } parent->actionPreferences->plug( contextMenu() ); parent->actionStopAll->plug( contextMenu() ); resetClock(); initToolTip(); // start of a kind of menu for the tray // this are experiments/tests /* for (int i=0; i<30; i++) _tray->insertTitle(i 18n("bla ").arg(i)); for (int i=0; i<30; i++) _tray->insertTitle2(i 18n("bli ").arg(i)); */ // experimenting with menus for the tray /* trayPopupMenu = contextMenu(); trayPopupMenu2 = new QPopupMenu(); trayPopupMenu->insertItem(i18n("Submenu"), *trayPopupMenu2); */ } +KarmTray::KarmTray(karmPart * parent) + : KSystemTray( 0 , "Karm Tray") +{ +// it is not convenient if every kpart gets an icon in the systray. + _taskActiveTimer = 0; +} + KarmTray::~KarmTray() { } // experiment /* void KarmTray::insertTitle(QString title) { trayPopupMenu->insertTitle(title); } */ void KarmTray::startClock() { - _taskActiveTimer->start(1000); - setPixmap( *(*icons)[_activeIcon] ); - show(); + if ( _taskActiveTimer ) + { + _taskActiveTimer->start(1000); + setPixmap( *(*icons)[_activeIcon] ); + show(); + } } void KarmTray::stopClock() { - _taskActiveTimer->stop(); - show(); + if ( _taskActiveTimer ) + { + _taskActiveTimer->stop(); + show(); + } } void KarmTray::advanceClock() { _activeIcon = (_activeIcon+1) % 8; setPixmap( *(*icons)[_activeIcon]); } void KarmTray::resetClock() { _activeIcon = 0; setPixmap( *(*icons)[_activeIcon]); show(); } void KarmTray::initToolTip() { updateToolTip(QPtrList ()); } void KarmTray::updateToolTip(QPtrList activeTasks) { if ( activeTasks.isEmpty() ) { QToolTip::add( this, i18n("No active tasks") ); return; } QFontMetrics fm( QToolTip::font() ); const QString continued = i18n( ", ..." ); const int buffer = fm.boundingRect( continued ).width(); const int desktopWidth = KGlobalSettings::desktopGeometry(this).width(); const int maxWidth = desktopWidth - buffer; QString qTip; QString s; // Build the tool tip with all of the names of the active tasks. // If at any time the width of the tool tip is larger than the desktop, // stop building it. QPtrListIterator item( activeTasks ); for ( int i = 0; item.current(); ++item, ++i ) { Task* task = item.current(); if ( i > 0 ) s += i18n( ", " ) + task->name(); else s += task->name(); int width = fm.boundingRect( s ).width(); if ( width > maxWidth ) { qTip += continued; break; } qTip = s; } QToolTip::add( this, qTip ); } #include "tray.moc" diff --git a/karm/tray.h b/karm/tray.h index cb88028444..34701cff4b 100644 --- a/karm/tray.h +++ b/karm/tray.h @@ -1,54 +1,58 @@ #ifndef KARM_TRAY_H #define KARM_TRAY_H #include #include #include // experiement // #include #include #include "task.h" +#include "karm_part.h" + +class KarmPart; class QPopupMenu; class QTimer; class KSystemTray; class MainWindow; // experiment // class KPopupMenu; class KarmTray : public KSystemTray { Q_OBJECT public: KarmTray(MainWindow * parent); + KarmTray(karmPart * parent); ~KarmTray(); private: int _activeIcon; static QPtrVector *icons; QTimer *_taskActiveTimer; public slots: void startClock(); void stopClock(); void resetClock(); void updateToolTip( QPtrList activeTasks); void initToolTip(); protected slots: void advanceClock(); // experiment /* void insertTitle(QString title); private: KPopupMenu *trayPopupMenu; QPopupMenu *trayPopupMenu2; */ }; #endif // KARM_TRAY_H diff --git a/karm/version.h b/karm/version.h index 4fb6f551a8..1a1820cf03 100644 --- a/karm/version.h +++ b/karm/version.h @@ -1,3 +1,3 @@ #ifndef KARM_VERSION -#define KARM_VERSION "1.5.0" +#define KARM_VERSION "1.6.0" #endif diff --git a/kfile-plugins/Makefile.am b/kfile-plugins/Makefile.am index d41feacd47..7ebdda7043 100644 --- a/kfile-plugins/Makefile.am +++ b/kfile-plugins/Makefile.am @@ -1,7 +1,6 @@ if compile_kpilot PILOTPLUGIN = palm-databases endif SUBDIRS=vcf ics $(PILOTPLUGIN) -include $(top_srcdir)/doc/api/Doxyfile.am diff --git a/kfile-plugins/ics/kfile_ics.cpp b/kfile-plugins/ics/kfile_ics.cpp index 4b7e19c518..a78ec04000 100644 --- a/kfile-plugins/ics/kfile_ics.cpp +++ b/kfile-plugins/ics/kfile_ics.cpp @@ -1,96 +1,96 @@ /* This file is part of the KDE project * Copyright (C) 2004 Bram Schoenmakers * * 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 version 2. * * This program is distributed in the hope that t 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. * */ #include #include #include #include #include "kfile_ics.h" #include using namespace KCal; typedef KGenericFactory ICSFactory; K_EXPORT_COMPONENT_FACTORY(kfile_ics, ICSFactory( "kfile_ics" )) ICSPlugin::ICSPlugin( QObject *parent, const char *name, const QStringList& args ) : KFilePlugin( parent, name, args ) { KFileMimeTypeInfo* info = addMimeTypeInfo( "text/calendar" ); //TODO: vcs !! KFileMimeTypeInfo::GroupInfo* group = 0L; group = addGroupInfo(info, "ICSInfo", i18n("Calendar Statistics")); addItemInfo( group, "ProductID", i18n("Product ID"), QVariant::String ); addItemInfo( group, "Events", i18n("Events"), QVariant::Int ); addItemInfo( group, "Todos", i18n("To-dos"), QVariant::Int ); addItemInfo( group, "TodoCompleted", i18n("Completed To-dos"), QVariant::Int ); addItemInfo( group, "TodoOverdue", i18n("Overdue To-dos"), QVariant::Int ); addItemInfo( group, "Journals", i18n("Journals"), QVariant::Int ); // addItemInfo( group, "Reminders", i18n("Reminders"), QVariant::Int ); } /* I chose to use libkcal instead of reading the calendar manually. It's easier to maintain this way. */ bool ICSPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) { KFileMetaInfoGroup group = appendGroup( info, "ICSInfo"); CalendarLocal cal ( QString::fromLatin1( "UTC" ) ); if( !cal.load( info.path() ) ) { kdDebug() << "Could not load calendar" << endl; return false; } appendItem( group, "ProductID", QVariant( cal.productId() ) ); appendItem( group, "Events", QVariant( int( cal.events().count() ) ) ); appendItem( group, "Journals", QVariant( int( cal.journals().count() ) ) ); Todo::List todos = cal.todos(); // count completed and overdue Todo::List::ConstIterator it = todos.begin(); Todo::List::ConstIterator end = todos.end(); int completed = 0; int overdue = 0; for ( ; it != end ; ++it ) { Todo *todo = *it; if ( todo->isCompleted() ) ++completed; else if ( todo->hasDueDate() && todo->dtDue().date() < QDate::currentDate() ) ++overdue; } appendItem( group, "Todos", QVariant( int(todos.count() ) ) ); appendItem( group, "TodoCompleted", QVariant( completed ) ); appendItem( group, "TodoOverdue", QVariant( overdue ) ); cal.close(); return true; } #include "kfile_ics.moc" diff --git a/kfile-plugins/ics/kfile_ics.h b/kfile-plugins/ics/kfile_ics.h index 5e7be40099..27e7e43db8 100644 --- a/kfile-plugins/ics/kfile_ics.h +++ b/kfile-plugins/ics/kfile_ics.h @@ -1,36 +1,36 @@ /* This file is part of the KDE project * Copyright (C) 2004 Bram Schoenmakers * * 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 version 2. * * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. * */ #ifndef KFILE_ICS_H #define KFILE_ICS_H #include class QStringList; class ICSPlugin : public KFilePlugin { Q_OBJECT public: ICSPlugin( QObject *parent, const char *name, const QStringList& args ); virtual bool readInfo( KFileMetaInfo& info, uint what ); }; #endif diff --git a/kfile-plugins/palm-databases/Makefile.am b/kfile-plugins/palm-databases/Makefile.am index fefa4d8b5f..43dbc74960 100644 --- a/kfile-plugins/palm-databases/Makefile.am +++ b/kfile-plugins/palm-databases/Makefile.am @@ -1,22 +1,22 @@ -## Makefile.am for vcf file meta info plugin +## Makefile.am for palm database meta info plugin # set the include path for X, qt and KDE INCLUDES = $(PISOCK_INCLUDE) $(all_includes) # these are the headers for your project noinst_HEADERS = kfile_palm.h kde_module_LTLIBRARIES = kfile_palm.la kfile_palm_la_SOURCES = kfile_palm.cpp -kfile_palm_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) +kfile_palm_la_LDFLAGS = $(PISOCK_LDFLAGS) $(all_libraries) -module $(KDE_PLUGIN) kfile_palm_la_LIBADD = $(LIB_KSYCOCA) $(PISOCK_LIB) # let automoc handle all of the meta source files (moc) METASOURCES = AUTO messages: rc.cpp $(XGETTEXT) kfile_palm.cpp -o $(podir)/kfile_palm.pot services_DATA = kfile_palm.desktop servicesdir = $(kde_servicesdir) diff --git a/kfile-plugins/palm-databases/kfile_palm.cpp b/kfile-plugins/palm-databases/kfile_palm.cpp index 0653f1b5a3..3b6c13c3ef 100644 --- a/kfile-plugins/palm-databases/kfile_palm.cpp +++ b/kfile-plugins/palm-databases/kfile_palm.cpp @@ -1,121 +1,121 @@ /* This file is part of the KDE project * Copyright (C) 2004 Reinhold Kainhofer * Based on the vcf plugin: * Copyright (C) 2002 Shane Wright * * 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 version 2. * * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. * */ #include "kfile_palm.h" #include #include #include #include #include typedef KGenericFactory PalmFactory; K_EXPORT_COMPONENT_FACTORY(kfile_palm, PalmFactory( "kfile_palm" )) KPalmPlugin::KPalmPlugin(QObject *parent, const char *name, const QStringList &args) : KFilePlugin(parent, name, args) { KFileMimeTypeInfo* info = addMimeTypeInfo( "application/vnd.palm" ); KFileMimeTypeInfo::GroupInfo* group; KFileMimeTypeInfo::ItemInfo* item; group = addGroupInfo(info, "General", i18n("General Information")); item = addItemInfo(group, "Name", i18n("Name"), QVariant::String); item = addItemInfo(group, "DBType", i18n("DB Type"), QVariant::String); item = addItemInfo(group, "TypeID", i18n("Type ID"), QVariant::String); item = addItemInfo(group, "CreatorID", i18n("Creator ID"), QVariant::String); item = addItemInfo(group, "NrRecords", i18n("# of Records"), QVariant::Int); group = addGroupInfo(info, "TimeStamps", i18n("Time Stamps")); item = addItemInfo(group, "CreationDate", i18n("Creation Date"), QVariant::DateTime); item = addItemInfo(group, "ModificationDate", i18n("Modification Date"), QVariant::DateTime); item = addItemInfo(group, "BackupDate", i18n("Backup Date"), QVariant::DateTime); group = addGroupInfo(info, "Flags", i18n("Flags")); item = addItemInfo(group, "ReadOnly", i18n("Read-Only"), QVariant::String); item = addItemInfo(group, "MakeBackup", i18n("Make Backup"), QVariant::String); item = addItemInfo(group, "CopyProtected", i18n("Copy Protected"), QVariant::String); item = addItemInfo(group, "Reset", i18n("Reset Handheld After Installing"), QVariant::String); item = addItemInfo(group, "ExcludeFromSync", i18n("Exclude From Sync"), QVariant::String); } bool KPalmPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) { int nrRec; QString tempName = info.path(); QCString fileName = QFile::encodeName(tempName); pi_file *dbFile = pi_file_open(const_cast < char *>((const char *) fileName)); if (dbFile == 0L) return false; struct DBInfo dBInfo; pi_file_get_info( dbFile, &dBInfo ); pi_file_get_entries( dbFile, &nrRec ); pi_file_close(dbFile); KFileMetaInfoGroup generalGroup = appendGroup(info, "General"); appendItem(generalGroup, "Name", dBInfo.name ); appendItem(generalGroup, "DBType", (dBInfo.flags & dlpDBFlagResource)?i18n("PalmOS Application"):i18n("PalmOS Record Database") ); char buff[5]; set_long(buff, dBInfo.type); buff[4]='\0'; appendItem(generalGroup, "TypeID", buff ); set_long(buff, dBInfo.creator); buff[4]='\0'; appendItem(generalGroup, "CreatorID", buff ); appendItem(generalGroup, "NrRecords", nrRec ); KFileMetaInfoGroup timeGroup = appendGroup(info, "TimeStamps"); QDateTime tm; tm.setTime_t( dBInfo.createDate ); appendItem(timeGroup, "CreationDate", tm); tm.setTime_t( dBInfo.modifyDate ); appendItem(timeGroup, "ModificationDate", tm); tm.setTime_t( dBInfo.backupDate ); appendItem(timeGroup, "BackupDate", tm); KFileMetaInfoGroup flagGroup = appendGroup(info, "Flags"); appendItem(flagGroup, "ReadOnly", (dBInfo.flags & dlpDBFlagReadOnly)?i18n("Yes"):i18n("No") ); appendItem(flagGroup, "MakeBackup", (dBInfo.flags & dlpDBFlagBackup)?i18n("Yes"):i18n("No") ); appendItem(flagGroup, "CopyProtected", (dBInfo.flags & dlpDBFlagCopyPrevention)?i18n("Yes"):i18n("No") ); appendItem(flagGroup, "Reset", (dBInfo.flags & dlpDBFlagReset)?i18n("Yes"):i18n("No") ); appendItem(flagGroup, "ExcludeFromSync", (dBInfo.miscFlags & dlpDBMiscFlagExcludeFromSync)?i18n("Yes"):i18n("No") ); return true; } /*bool KPalmPlugin::writeInfo( const KFileMetaInfo& info ) const { // int pi_file_set_info((struct pi_file * pf, struct DBInfo * infop)); //info["tuteTextTechnical"].value("An integer").toInt() // Do the stuff with low-level functions. See lines 1119-1142 of pi-file.cc for writing, 244-273 for reading. }*/ #include "kfile_palm.moc" diff --git a/kfile-plugins/palm-databases/kfile_palm.desktop b/kfile-plugins/palm-databases/kfile_palm.desktop index aab2b381f4..bc29c98829 100644 --- a/kfile-plugins/palm-databases/kfile_palm.desktop +++ b/kfile-plugins/palm-databases/kfile_palm.desktop @@ -1,41 +1,44 @@ [Desktop Entry] Encoding=UTF-8 Type=Service Name=PalmOS Database Info Name[be]=Інфармацыя аб базе дадзеных PalmOS Name[bg]=Информация за БД за PalmOS +Name[br]=Titouroù diwar-benn ar stlennvon PalmOS Name[bs]=Informacije o PalmOS bazi podataka Name[ca]=Informació de base de dades PalmOS +Name[cs]=Informace o databázi PalmOS Name[da]=PalmOS database-info Name[de]=PalmOS Datenbank Informationen Name[es]=Info. de la base de datos de PalmOS Name[et]=PalmOS andmebaasi info Name[fr]=Informations sur les bases de données PalmOS +Name[he]=מידע אודות בסיס הנתונים של PalmOS Name[hu]=PalmOS adatbázis-jellemzők Name[is]=PalmOS gagnagrunnsupplýsingar Name[it]=Informazioni database PalmOs Name[ja]=PalmOS データベース 情報 Name[nb]=PalmOS Database info Name[nl]=PalmOS-database informatie Name[nn]=PalmOS-databaseinfo Name[pl]=Baza danych PalmOS Name[pt]=Informações de Base de Dados PalmOS Name[pt_BR]=Informações da Base de Dados do PalmOS Name[ru]=Сведения о базе данных PalmOS Name[se]=PalmOS-diehtovuođđodieđut Name[sk]=Informácie o databázach PalmOS Name[sl]=Informacije zbirke podatkov za PalmOS Name[sr]=Информације о PalmOS базама података Name[sr@Latn]=Informacije o PalmOS bazama podataka Name[sv]=PalmOS-databasinformation Name[ta]=பால்ம்OS தரவுத்தள தகவல் Name[tg]=Иттилоот дар бораи бонки додаҳои PalmOS Name[tr]=PalmOS Veritabanı Bilgisi Name[uk]=Інформація про базу даних PalmOS Name[xx]=xxPalmOS Database Infoxx Name[zh_CN]=PalmOS 数据库信息 ServiceTypes=KFilePlugin X-KDE-Library=kfile_palm MimeType=application/vnd.palm PreferredGroups=General PreferredItems=Name,DBType,TypeID,CreatorID,NrRecords,Size diff --git a/kfile-plugins/palm-databases/kfile_palm.h b/kfile-plugins/palm-databases/kfile_palm.h index 17579ad028..fcd928a00f 100644 --- a/kfile-plugins/palm-databases/kfile_palm.h +++ b/kfile-plugins/palm-databases/kfile_palm.h @@ -1,40 +1,40 @@ /* This file is part of the KDE project * Copyright (C) 2004 Reinhold Kainhofer * Based on the vcf plugin: * Copyright (C) 2002 Shane Wright * * 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 version 2. * * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. * */ #ifndef __KFILE_PALM_H__ #define __KFILE_PALM_H__ #include class QStringList; class KPalmPlugin: public KFilePlugin { Q_OBJECT public: KPalmPlugin( QObject *parent, const char *name, const QStringList& args ); virtual bool readInfo( KFileMetaInfo& info, uint what); // virtual bool writeInfo( const KFileMetaInfo& info ) const; }; #endif diff --git a/kfile-plugins/rfc822/kfile_rfc822.cpp b/kfile-plugins/rfc822/kfile_rfc822.cpp index 2a3ee0c711..794d335d64 100644 --- a/kfile-plugins/rfc822/kfile_rfc822.cpp +++ b/kfile-plugins/rfc822/kfile_rfc822.cpp @@ -1,161 +1,161 @@ /* This file is part of the KDE project * Copyright (C) 2002 Shane Wright * * 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 version 2. * * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. * */ #include #include "kfile_rfc822.h" #include #include #include #include #include #include #include #include #include #include #if !defined(__osf__) #include #else typedef unsigned short uint32_t; #endif typedef KGenericFactory Rfc822Factory; K_EXPORT_COMPONENT_FACTORY(kfile_rfc822, Rfc822Factory( "kfile_rfc822" )) KRfc822Plugin::KRfc822Plugin(QObject *parent, const char *name, const QStringList &args) : KFilePlugin(parent, name, args) { KFileMimeTypeInfo* info = addMimeTypeInfo( "message/rfc822" ); KFileMimeTypeInfo::GroupInfo* group = 0L; group = addGroupInfo(info, "Technical", i18n("Technical Details")); KFileMimeTypeInfo::ItemInfo* item; item = addItemInfo(group, "From", i18n("From"), QVariant::String); item = addItemInfo(group, "To", i18n("To"), QVariant::String); item = addItemInfo(group, "Subject", i18n("Subject"), QVariant::String); item = addItemInfo(group, "Date", i18n("Date"), QVariant::String); item = addItemInfo(group, "Content-Type", i18n("Content-Type"), QVariant::String); } bool KRfc822Plugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) { QFile file(info.path()); if (!file.open(IO_ReadOnly)) { kdDebug(7034) << "Couldn't open " << QFile::encodeName(info.path()) << endl; return false; } /* Note to self: probably should use QCString for all this, but what we're doing is simple and self-contained so never mind.. */ char id_from[] = "From: "; char id_to[] = "To: "; char id_subject[] = "Subject: "; char id_date[] = "Date: "; char id_contenttype[] = "Content-Type: "; // we need a buffer for lines char linebuf[4096]; // we need a buffer for other stuff char buf_from[1000] = ""; char buf_to[1000] = ""; char buf_subject[1000] = ""; char buf_date[1000] = ""; char buf_contenttype[1000] = ""; memset(buf_from, 0, 999); memset(buf_to, 0, 999); memset(buf_subject, 0, 999); memset(buf_date, 0, 999); memset(buf_contenttype, 0, 999); char * myptr; bool done=false; while (!done) { // read a line file.readLine(linebuf, sizeof( linebuf )); // have we got something useful? if (memcmp(linebuf, id_from, 6) == 0) { // we have a name myptr = linebuf + 6; strncpy(buf_from, myptr, sizeof( buf_from )); buf_from[998]='\0'; } else if (memcmp(linebuf, id_to, 4) == 0) { // we have a name myptr = linebuf + 4; strncpy(buf_to, myptr, sizeof( buf_to )); buf_to[998]='\0'; } else if (memcmp(linebuf, id_subject, 9) == 0) { // we have a name myptr = linebuf + 9; strncpy(buf_subject, myptr, sizeof( buf_subject )); buf_subject[998]='\0'; } else if (memcmp(linebuf, id_date, 6) == 0) { // we have a name myptr = linebuf + 6; strncpy(buf_date, myptr, sizeof( buf_date )); buf_date[998]='\0'; } else if (memcmp(linebuf, id_contenttype, 14) == 0) { // we have a name myptr = linebuf + 14; strncpy(buf_contenttype, myptr, sizeof( buf_contenttype )); buf_contenttype[998]='\0'; } // are we done yet? if ( ((strlen(buf_from) > 0) && (strlen(buf_to) > 0) && (strlen(buf_subject) > 0) && (strlen(buf_date) > 0) && (strlen(buf_contenttype) > 0)) || (file.atEnd()) ) done = true; }; KFileMetaInfoGroup group = appendGroup(info, "Technical"); if (strlen(buf_from) > 0) appendItem(group, "From", buf_from); if (strlen(buf_to) > 0) appendItem(group, "To", buf_to); if (strlen(buf_subject) > 0) appendItem(group, "Subject", buf_subject); if (strlen(buf_date) > 0) appendItem(group, "Date", buf_date); if (strlen(buf_contenttype) > 0) appendItem(group, "Content-Type", buf_contenttype); return true; } #include "kfile_rfc822.moc" diff --git a/kfile-plugins/rfc822/kfile_rfc822.desktop b/kfile-plugins/rfc822/kfile_rfc822.desktop index d0729e5f3c..d41b431c9e 100644 --- a/kfile-plugins/rfc822/kfile_rfc822.desktop +++ b/kfile-plugins/rfc822/kfile_rfc822.desktop @@ -1,50 +1,51 @@ [Desktop Entry] Encoding=UTF-8 Type=Service Name=Email Info Name[be]=Інфармацыя аб паведамленьні электроннай пошты Name[bg]=Информация за е-поща +Name[br]=Titouroù postel Name[ca]=Informació de correu-e Name[cs]=Informace o emailu Name[cy]=Gwybodaeth Ebost Name[da]=Email-info Name[de]=E-Mail-Info Name[el]=Πληροφορίες Email Name[es]=Info de correo electrónico Name[et]=Meili info Name[fi]=Sähköpostitiedot Name[fr]=Informations sur le courrier électronique Name[he]=מידע על דוא"ל Name[hi]=ई-मेल जानकारी Name[hr]=Email Informacije Name[hu]=E-mail-jellemzők Name[is]=Email upplýsingar Name[it]=Informazioni di posta elettronica Name[ja]=Eメール 情報 Name[ms]=Info Emel Name[nb]=E-post-info Name[nl]=E-mail-informatie Name[nn]=Epost-info Name[pa]=ਈ-ਪੱਤਰ ਜਾਣਕਾਰੀ Name[pl]=Informacja o e-mailu Name[pt]=Informação do E-Mail Name[pt_BR]=Informações sobre E-mail Name[ro]=Informaţii e-mail Name[ru]=Сведения об электронной почте Name[se]=E-boastadieđut Name[sk]=Informácie o emaily Name[sl]=Informacije o e-pošti Name[sr]=Е-поштанске информације Name[sr@Latn]=E-poštanske informacije Name[sv]=E-postinformation Name[ta]=மின்னஞ்சல் தகவல் Name[tg]=Иттилоот дар бораи почтаи электронӣ Name[tr]=E-Posta Bilgisi Name[uk]=Інформація про повідомлення ел. пошти Name[xx]=xxEmail Infoxx Name[zh_CN]=电子邮件信息 ServiceTypes=KFilePlugin X-KDE-Library=kfile_rfc822 MimeType=message/rfc822 PreferredGroups=Technical PreferredItems=From,To,Subject,Date,Content-Type diff --git a/kfile-plugins/rfc822/kfile_rfc822.h b/kfile-plugins/rfc822/kfile_rfc822.h index b6027f7017..f2066754af 100644 --- a/kfile-plugins/rfc822/kfile_rfc822.h +++ b/kfile-plugins/rfc822/kfile_rfc822.h @@ -1,37 +1,37 @@ /* This file is part of the KDE project * Copyright (C) 2002 Shane Wright * * 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 version 2. * * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. * */ #ifndef __KFILE_RFC822_H__ #define __KFILE_RFC822_H__ #include class QStringList; class KRfc822Plugin: public KFilePlugin { Q_OBJECT public: KRfc822Plugin( QObject *parent, const char *name, const QStringList& args ); virtual bool readInfo( KFileMetaInfo& info, uint what); }; #endif diff --git a/kfile-plugins/vcf/kfile_vcf.cpp b/kfile-plugins/vcf/kfile_vcf.cpp index b840eb5183..fcdf4984d7 100644 --- a/kfile-plugins/vcf/kfile_vcf.cpp +++ b/kfile-plugins/vcf/kfile_vcf.cpp @@ -1,130 +1,130 @@ /* This file is part of the KDE project * Copyright (C) 2002 Shane Wright * * 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 version 2. * * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. * */ #include #include #include "kfile_vcf.h" #include #include #include #include #include #include #include #include #include #if !defined(__osf__) #include #else typedef unsigned short uint32_t; #endif typedef KGenericFactory VcfFactory; K_EXPORT_COMPONENT_FACTORY(kfile_vcf, VcfFactory( "kfile_vcf" )) KVcfPlugin::KVcfPlugin(QObject *parent, const char *name, const QStringList &args) : KFilePlugin(parent, name, args) { KFileMimeTypeInfo* info = addMimeTypeInfo( "text/x-vcard" ); KFileMimeTypeInfo::GroupInfo* group = 0L; group = addGroupInfo(info, "Technical", i18n("Technical Details")); KFileMimeTypeInfo::ItemInfo* item; item = addItemInfo(group, "Name", i18n("Name"), QVariant::String); item = addItemInfo(group, "Email", i18n("Email"), QVariant::String); item = addItemInfo(group, "Telephone", i18n("Telephone"), QVariant::String); } bool KVcfPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) { QFile file(info.path()); if (!file.open(IO_ReadOnly)) { kdDebug(7034) << "Couldn't open " << QFile::encodeName(info.path()) << endl; return false; } char id_name[] = "FN:"; char id_email[] = "EMAIL;INTERNET:"; // we need a buffer for lines char linebuf[1000]; // we need a buffer for other stuff char buf_name[1000] = ""; char buf_email[1000] = ""; buf_name[999] = '\0'; buf_email[999] = '\0'; char * myptr; // FIXME: This is intensely inefficient!!! bool done=false; while (!done) { // read a line int r = file.readLine(linebuf, sizeof( linebuf )); if ( r < 0 ) { done = true; break; } // have we got something useful? if (memcmp(linebuf, id_name, 3) == 0) { // we have a name myptr = linebuf + 3; strlcpy(buf_name, myptr, sizeof( buf_name )); } else if (memcmp(linebuf, id_email, 15) == 0) { // we have an email myptr = linebuf + 15; strlcpy(buf_email, myptr, sizeof( buf_email )); } // are we done yet? if ((strlen(buf_name) > 0 && strlen(buf_email) > 0) || file.atEnd()) done = true; } KFileMetaInfoGroup group = appendGroup(info, "Technical"); if (strlen(buf_name) > 0) appendItem(group, "Name", QString::fromUtf8(buf_name)); if (strlen(buf_email) > 0) appendItem(group, "Email", buf_email); return true; } #include "kfile_vcf.moc" diff --git a/kfile-plugins/vcf/kfile_vcf.h b/kfile-plugins/vcf/kfile_vcf.h index 038e1407ab..a0b147c637 100644 --- a/kfile-plugins/vcf/kfile_vcf.h +++ b/kfile-plugins/vcf/kfile_vcf.h @@ -1,37 +1,37 @@ /* This file is part of the KDE project * Copyright (C) 2002 Shane Wright * * 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 version 2. * * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. * */ #ifndef __KFILE_VCF_H__ #define __KFILE_VCF_H__ #include class QStringList; class KVcfPlugin: public KFilePlugin { Q_OBJECT public: KVcfPlugin( QObject *parent, const char *name, const QStringList& args ); virtual bool readInfo( KFileMetaInfo& info, uint what); }; #endif diff --git a/kjots/icons/hi16-app-kjots.png b/kjots/icons/hi16-app-kjots.png deleted file mode 100644 index 5466e254ff..0000000000 Binary files a/kjots/icons/hi16-app-kjots.png and /dev/null differ diff --git a/kjots/icons/hi22-app-kjots.png b/kjots/icons/hi22-app-kjots.png deleted file mode 100644 index 36ce904cba..0000000000 Binary files a/kjots/icons/hi22-app-kjots.png and /dev/null differ diff --git a/kjots/icons/hi32-app-kjots.png b/kjots/icons/hi32-app-kjots.png deleted file mode 100644 index b2b128d3ba..0000000000 Binary files a/kjots/icons/hi32-app-kjots.png and /dev/null differ diff --git a/kjots/icons/hi48-app-kjots.png b/kjots/icons/hi48-app-kjots.png deleted file mode 100644 index 142af590f4..0000000000 Binary files a/kjots/icons/hi48-app-kjots.png and /dev/null differ diff --git a/kjots/icons/hi64-app-kjots.png b/kjots/icons/hi64-app-kjots.png deleted file mode 100644 index ec0f2701f2..0000000000 Binary files a/kjots/icons/hi64-app-kjots.png and /dev/null differ diff --git a/kleopatra/Makefile.am b/kleopatra/Makefile.am deleted file mode 100644 index f86b7bc7bc..0000000000 --- a/kleopatra/Makefile.am +++ /dev/null @@ -1,32 +0,0 @@ -SUBDIRS = lib conf kwatchgnupg . - -KDE_CXXFLAGS = -DLIBKLEOPATRA_NO_COMPAT - -INCLUDES = -I$(srcdir)/lib -I$(top_srcdir)/libkdenetwork $(GPGME_CFLAGS) $(all_includes) - -bin_PROGRAMS = kleopatra - -kleopatra_SOURCES = \ - customactions.cpp \ - aboutdata.cpp \ - main.cpp certmanager.cpp \ - hierarchyanalyser.cpp \ - certificatewizard.ui certificatewizardimpl.cpp \ - certificateinfowidget.ui certificateinfowidgetimpl.cpp \ - crlview.cpp storedtransferjob.cpp certlistview.cpp - -METASOURCES = AUTO - -kleopatra_LDFLAGS = $(all_libraries) $(KDE_RPATH) -kleopatra_LDADD = conf/libconf.la lib/libkleopatra.la $(LIB_KUTILS) $(LIB_KABC) - -rcdir = $(kde_datadir)/kleopatra -rc_DATA = kleopatraui.rc - -xdg_apps_DATA = kleopatra_import.desktop - -messages: rc.cpp - $(EXTRACTRC) conf/*.ui >> rc.cpp - $(XGETTEXT) conf/*.cpp *.cpp *.h -o $(podir)/kleopatra.pot - -include $(top_srcdir)/admin/Doxyfile.am diff --git a/kleopatra/aboutdata.cpp b/kleopatra/aboutdata.cpp deleted file mode 100644 index fb5813ec44..0000000000 --- a/kleopatra/aboutdata.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - aboutdata.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "aboutdata.h" - -#include - -static const char kleopatra_version[] = "0.40"; -static const char description[] = I18N_NOOP("KDE Key Manager"); - -struct about_data { - const char * name; - const char * desc; - const char * email; - const char * web; -}; - -static const about_data authors[] = { - { "Marc Mutz", I18N_NOOP("Current Maintainer"), "mutz@kde.org", 0 }, - { "Steffen Hansen", I18N_NOOP("Former Maintainer"), "hansen@kde.org", 0 }, - { "Kalle Dalheimer", I18N_NOOP("Original Author"), "kalle@kde.org", 0 }, - { "Jesper Petersen", I18N_NOOP("Original Author"), "blackie@kde.org", 0 }, -}; - - -static const about_data credits[] = { - { "David Faure", - I18N_NOOP("Backend configuration framework, KIO integration"), - "faure@kde.org", 0 }, - { "Michel Boyer de la Giroday", - I18N_NOOP("Key-state dependant colors and fonts in the key list"), - "michel@klaralvdalens-datakonsult.se", 0 }, - { "Daniel Molkentin", - I18N_NOOP("Certificate Wizard KIOSK integration, infrastructure"), - "molkentin@kde.org", 0 }, - { "Ralf Nolden", - I18N_NOOP("Support for obsolete EMAIL RDN in Certificate Wizard"), - "nolden@kde.org", 0 }, - { "Karl-Heinz Zimmer", - I18N_NOOP("DN display ordering support, infrastructure"), - "khz@kde.org", 0 }, -}; - - -AboutData::AboutData() - : KAboutData( "kleopatra", I18N_NOOP("Kleopatra"), - kleopatra_version, description, License_GPL, - "(c) 2002 Steffen Hansen, Jesper Pedersen,\n" - "Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB\n\n" - "(c) 2004 Marc Mutz, Klar\xC3\xA4lvdalens Datakonsult AB" ) -{ - using ::authors; - using ::credits; - for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i ) - addAuthor( authors[i].name, authors[i].desc, - authors[i].email, authors[i].web ); - for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i ) - addCredit( credits[i].name, credits[i].desc, - credits[i].email, credits[i].web ); -} diff --git a/kleopatra/aboutdata.h b/kleopatra/aboutdata.h deleted file mode 100644 index 29e516f5c1..0000000000 --- a/kleopatra/aboutdata.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - aboutdata.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __ABOUTDATA_H__ -#define __ABOUTDATA_H__ - -#include - -class AboutData : public KAboutData { -public: - AboutData(); -}; - -#endif // __ABOUTDATA_H__ diff --git a/kleopatra/agent.cpp b/kleopatra/agent.cpp deleted file mode 100644 index ab933a00ae..0000000000 --- a/kleopatra/agent.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "agent.h" - -Agent::Agent( const QString& agentName, Agent* provider, QObject* parent, const char* name ) - :QObject( parent, name ), _provider( provider), _agentName( agentName ) -{ -} - -/** - Return a QString with a representation of the CA, and all its parent CA's -*/ -QString Agent::tree() const -{ - int dummy; - return tree( &dummy ); -} - -QString Agent::tree( int* level ) const -{ - QString res; - if ( _provider ) { - res += _provider->tree(level); - (*level)++; - } - else - *level = 0; - - for ( int i = 0; i < *level; ++i ) - res += "\t"; - - res += _agentName + "\n"; // KHZ: Add more attributes for agents here. - - return res; -} - -/** - This method return the string, which is shown in the listview. -*/ -QString Agent::shortName() const -{ - return _agentName; // KHZ: Here you can change the encoding for the ListView. -} diff --git a/kleopatra/agent.h b/kleopatra/agent.h deleted file mode 100644 index 2f73063564..0000000000 --- a/kleopatra/agent.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef __AGENT_H -#define __AGENT_H -#include -#include - -/** - Class representing a Certification Agent (CA) -*/ -class Agent :public QObject -{ -public: - Agent( const QString& agentName, Agent* provider, QObject* parent, const char* name = 0 ); - QString tree() const; - QString shortName() const; -private: - QString tree( int* level ) const; - - Agent* _provider; - QString _agentName; -}; - -#endif //__AGENT_H diff --git a/kleopatra/certbox.cpp b/kleopatra/certbox.cpp deleted file mode 100644 index 21cbe70e9b..0000000000 --- a/kleopatra/certbox.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "certbox.h" -#include -#include "certitem.h" - -CertBox::CertBox( QWidget* parent, const char* name ) :QListView( parent, name ) -{ - QFontMetrics fm = fontMetrics(); - addColumn( i18n("Subject"), fm.width( i18n("Subject") ) * 6 ); - addColumn( i18n("Issuer"), fm.width( i18n("Issuer") ) * 4 ); - addColumn( i18n("Serial")/*, fm.width( i18n("Serial") ) * 3*/ ); - setColumnWidthMode( 0, QListView::Manual ); - setColumnWidthMode( 1, QListView::Manual ); - setAllColumnsShowFocus( true ); - - connect( this, SIGNAL( doubleClicked (QListViewItem*) ), this, SLOT( handleDoubleClick( QListViewItem*) ) ); - connect( this, SIGNAL( returnPressed (QListViewItem*) ), this, SLOT( handleDoubleClick( QListViewItem*) ) ); -} - -void CertBox::handleDoubleClick( QListViewItem* item ) -{ - static_cast(item)->display(); -} - -void CertBox::loadCerts() -{ - -} - -#include "certbox.moc" diff --git a/kleopatra/certbox.h b/kleopatra/certbox.h deleted file mode 100644 index 901b694e69..0000000000 --- a/kleopatra/certbox.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef __CERTBOX__H -#define __CERTBOX__H -#include - -/** - This is the listview that shows all the certificates. -*/ -class CertBox :public QListView -{ -Q_OBJECT - -public: - CertBox( QWidget* parent, const char* name = 0 ); - - void loadCerts(); -protected slots: - void handleDoubleClick( QListViewItem* item ); -}; - -#endif // __CERTBOX__H diff --git a/kleopatra/certificateinfowidget.ui b/kleopatra/certificateinfowidget.ui deleted file mode 100644 index 922aaaf8de..0000000000 --- a/kleopatra/certificateinfowidget.ui +++ /dev/null @@ -1,199 +0,0 @@ - -CertificateInfoWidget - - - CertificateInfoWidget - - - - 0 - 0 - 475 - 398 - - - - Form1 - - - - unnamed - - - 11 - - - 6 - - - - TextLabel1 - - - - 1 - - - - Certificate Information - - - - - Frame3 - - - HLine - - - Sunken - - - - - tabWidget - - - - tab - - - &Details - - - - unnamed - - - 11 - - - 6 - - - - - Description - - - true - - - true - - - - - Information - - - true - - - true - - - - listView - - - true - - - false - - - - - textView - - - true - - - false - - - - - - - tab - - - &Path - - - - - Path - - - true - - - true - - - - pathView - - - - 11 - 11 - 429 - 257 - - - - true - - - - - - - Layout2 - - - - unnamed - - - 0 - - - 6 - - - - Spacer2 - - - Horizontal - - - Expanding - - - - 20 - 0 - - - - - - importButton - - - &Import to Local - - - - - - - - diff --git a/kleopatra/certificateinfowidgetimpl.cpp b/kleopatra/certificateinfowidgetimpl.cpp deleted file mode 100644 index 082c035ba2..0000000000 --- a/kleopatra/certificateinfowidgetimpl.cpp +++ /dev/null @@ -1,438 +0,0 @@ -/* - certificateinfowidgetimpl.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "certificateinfowidgetimpl.h" - -// libkleopatra -#include -#include -#include - -#include - -// gpgme++ -#include - -// KDE -#include -#include -#include -#include -#include -#include - -// Qt -#include -#include -#include -#include -#include -#include -#include - -// other -#include -#include - -CertificateInfoWidgetImpl::CertificateInfoWidgetImpl( const GpgME::Key & key, bool external, - QWidget * parent, const char * name ) - : CertificateInfoWidget( parent, name ), - mExternal( external ), - mFoundIssuer( true ), - mHaveKeyLocally( false ) -{ - importButton->setEnabled( false ); - - listView->setColumnWidthMode( 1, QListView::Maximum ); - QFontMetrics fm = fontMetrics(); - listView->setColumnWidth( 1, fm.width( i18n("Information") ) * 5 ); - - listView->header()->setClickEnabled( false ); - listView->setSorting( -1 ); - - connect( listView, SIGNAL( selectionChanged( QListViewItem* ) ), - this, SLOT( slotShowInfo( QListViewItem* ) ) ); - pathView->setColumnWidthMode( 0, QListView::Maximum ); - pathView->header()->hide(); - - connect( pathView, SIGNAL( doubleClicked( QListViewItem* ) ), - this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) ); - connect( pathView, SIGNAL( returnPressed( QListViewItem* ) ), - this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) ); - connect( importButton, SIGNAL( clicked() ), - this, SLOT( slotImportCertificate() ) ); - - dumpView->setFont( KGlobalSettings::fixedFont() ); - - if ( !key.isNull() ) - setKey( key ); -} - -static QString time_t2string( time_t t ) { - QDateTime dt; - dt.setTime_t( t ); - return dt.toString(); -} - -void CertificateInfoWidgetImpl::setKey( const GpgME::Key & key ) { - mChain.clear(); - mFoundIssuer = true; - mHaveKeyLocally = false; - - listView->clear(); - pathView->clear(); - importButton->setEnabled( false ); - - if ( key.isNull() ) - return; - - mChain.push_front( key ); - startKeyExistanceCheck(); // starts a local keylisting to enable the - // importButton if needed - - QListViewItem * item = 0; - item = new QListViewItem( listView, item, i18n("Valid"), QString("From %1 to %2") - .arg( time_t2string( key.subkey(0).creationTime() ), - time_t2string( key.subkey(0).expirationTime() ) ) ); - item = new QListViewItem( listView, item, i18n("Can be used for signing"), - key.canSign() ? i18n("Yes") : i18n("No") ); - item = new QListViewItem( listView, item, i18n("Can be used for encryption"), - key.canEncrypt() ? i18n("Yes") : i18n("No") ); - item = new QListViewItem( listView, item, i18n("Can be used for certification"), - key.canCertify() ? i18n("Yes") : i18n("No") ); - item = new QListViewItem( listView, item, i18n("Can be used for authentication"), - key.canAuthenticate() ? i18n("Yes") : i18n("No" ) ); - item = new QListViewItem( listView, item, i18n("Fingerprint"), key.primaryFingerprint() ); - item = new QListViewItem( listView, item, i18n("Issuer"), Kleo::DN( key.issuerName() ).prettyDN() ); - item = new QListViewItem( listView, item, i18n("Serial Number"), key.issuerSerial() ); - - const Kleo::DN dn = key.userID(0).id(); - - // FIXME: use the attributeLabelMap from certificatewizardimpl.cpp: - static QMap dnComponentNames; - if ( dnComponentNames.isEmpty() ) { - dnComponentNames["C"] = i18n("Country"); - dnComponentNames["OU"] = i18n("Organizational Unit"); - dnComponentNames["O"] = i18n("Organization"); - dnComponentNames["L"] = i18n("Location"); - dnComponentNames["CN"] = i18n("Common Name"); - dnComponentNames["EMAIL"] = i18n("Email"); - } - - for ( Kleo::DN::const_iterator dnit = dn.begin() ; dnit != dn.end() ; ++dnit ) { - QString displayName = (*dnit).name(); - if( dnComponentNames.contains(displayName) ) displayName = dnComponentNames[displayName]; - item = new QListViewItem( listView, item, displayName, (*dnit).value() ); - } - - const std::vector uids = key.userIDs(); - if ( !uids.empty() ) { - item = new QListViewItem( listView, item, i18n("Subject"), - Kleo::DN( uids.front().id() ).prettyDN() ); - for ( std::vector::const_iterator it = uids.begin() + 1 ; it != uids.end() ; ++it ) { - if ( !(*it).id() ) - continue; - const QString email = QString::fromUtf8( (*it).id() ).stripWhiteSpace(); - if ( email.isEmpty() ) - continue; - if ( email.startsWith( "<" ) ) - item = new QListViewItem( listView, item, i18n("Email"), - email.mid( 1, email.length()-2 ) ); - else - item = new QListViewItem( listView, item, i18n("A.k.a."), email ); - } - } - - updateChainView(); - startCertificateChainListing(); - startCertificateDump(); -} - -static void showChainListError( QWidget * parent, const GpgME::Error & err, const char * subject ) { - assert( err ); - const QString msg = i18n("

An error occurred while fetching " - "the certificate %1 from the backend:

" - "

%2

") - .arg( subject ? QString::fromUtf8( subject ) : QString::null, - QString::fromLocal8Bit( err.asString() ) ); - KMessageBox::error( parent, msg, i18n("Certificate Listing Failed" ) ); -} - -void CertificateInfoWidgetImpl::startCertificateChainListing() { - kdDebug() << "CertificateInfoWidgetImpl::startCertificateChainListing()" << endl; - - if ( mChain.empty() ) { - // we need a seed... - kdWarning() << "CertificateInfoWidgetImpl::startCertificateChainListing(): mChain is empty!" << endl; - return; - } - const char * chainID = mChain.front().chainID(); - if ( !chainID || !*chainID ) { - // cert not found: - kdDebug() << "CertificateInfoWidgetImpl::startCertificateChainListing(): empty chain ID - root not found" << endl; - return; - } - const char * fpr = mChain.front().primaryFingerprint(); - if ( qstricmp( fpr, chainID ) == 0 ) { - kdDebug() << "CertificateInfoWidgetImpl::startCertificateChainListing(): chain_id equals fingerprint -> found root" << endl; - return; - } - if ( mChain.size() > 100 ) { - // safe guard against certificate loops (paranoia factor 8 out of 10)... - kdWarning() << "CertificateInfoWidgetImpl::startCertificateChainListing(): maximum chain length of 100 exceeded!" << endl; - return; - } - if ( !mFoundIssuer ) { - // key listing failed. Don't end up in endless loop - kdDebug() << "CertificateInfoWidgetImpl::startCertificateChainListing(): issuer not found - giving up" << endl; - return; - } - - mFoundIssuer = false; - - // gpgsm / dirmngr / LDAP / whoever doesn't support looking up - // external keys by fingerprint. Furthermore, since we actually got - // a chain-id set on the key, we know that we have the issuer's cert - // in the local keyring, so just use local keylisting. - Kleo::KeyListJob * job = - Kleo::CryptoBackendFactory::instance()->smime()->keyListJob( false ); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::KeyListResult&)), - SLOT(slotCertificateChainListingResult(const GpgME::KeyListResult&)) ); - connect( job, SIGNAL(nextKey(const GpgME::Key&)), - SLOT(slotNextKey(const GpgME::Key&)) ); - - kdDebug() << "Going to fetch" << endl - << " issuer : \"" << mChain.front().issuerName() << "\"" << endl - << " chain id: " << mChain.front().chainID() << endl - << "for" << endl - << " subject : \"" << mChain.front().userID(0).id() << "\"" << endl - << " subj.fpr: " << mChain.front().primaryFingerprint() << endl; - - const GpgME::Error err = job->start( mChain.front().chainID() ); - - if ( err ) - showChainListError( this, err, mChain.front().issuerName() ); - else - (void)new Kleo::ProgressDialog( job, i18n("Fetching Certificate Chain"), this ); -} - -void CertificateInfoWidgetImpl::startCertificateDump() { - KProcess* proc = new KProcess( this ); - (*proc) << "gpgsm"; // must be in the PATH - (*proc) << "--dump-keys"; - (*proc) << mChain.front().primaryFingerprint(); - - QObject::connect( proc, SIGNAL( receivedStdout(KProcess *, char *, int) ), - this, SLOT( slotCollectStdout(KProcess *, char *, int) ) ); - QObject::connect( proc, SIGNAL( receivedStderr(KProcess *, char *, int) ), - this, SLOT( slotCollectStderr(KProcess *, char *, int) ) ); - QObject::connect( proc, SIGNAL( processExited(KProcess*) ), - this, SLOT( slotDumpProcessExited(KProcess*) ) ); - - if ( !proc->start( KProcess::NotifyOnExit, (KProcess::Communication)(KProcess::Stdout | KProcess::Stderr) ) ) { - QString wmsg = i18n("Failed to execute gpgsm:\n%1").arg( i18n( "program not found" ) ); - dumpView->setText( wmsg ); - } -} - -void CertificateInfoWidgetImpl::slotCollectStdout(KProcess *, char *buffer, int buflen) -{ - mDumpOutput += QCString(buffer, buflen+1); // like KProcIO does -} - -void CertificateInfoWidgetImpl::slotCollectStderr(KProcess *, char *buffer, int buflen) -{ - mDumpError += QCString(buffer, buflen+1); // like KProcIO does -} - -void CertificateInfoWidgetImpl::slotDumpProcessExited(KProcess* proc) { - int rc = ( proc->normalExit() ) ? proc->exitStatus() : -1 ; - - if ( rc == 0 ) { - dumpView->setText( QString::fromUtf8( mDumpOutput ) ); - } else { - if ( !mDumpError.isEmpty() ) { - dumpView->setText( QString::fromUtf8( mDumpError ) ); - } else - { - QString wmsg = i18n("Failed to execute gpgsm:\n%1"); - if ( rc == -1 ) - wmsg = wmsg.arg( i18n( "program cannot be executed" ) ); - else - wmsg = wmsg.arg( strerror(rc) ); - dumpView->setText( wmsg ); - } - } - - proc->deleteLater(); -} - -void CertificateInfoWidgetImpl::slotNextKey( const GpgME::Key & key ) { - kdDebug() << "CertificateInfoWidgetImpl::slotNextKey( \"" - << key.userID(0).id() << "\" )" << endl; - if ( key.isNull() ) - return; - - mFoundIssuer = true; - mChain.push_front( key ); - updateChainView(); - // FIXME: cancel the keylisting. We're only interested in _one_ key. -} - -void CertificateInfoWidgetImpl::updateChainView() { - pathView->clear(); - if ( mChain.empty() ) - return; - QListViewItem * item = 0; - - QValueList::const_iterator it = mChain.begin(); - // root item: - if ( (*it).chainID() && qstrcmp( (*it).chainID(), (*it).primaryFingerprint() ) == 0 ) - item = new QListViewItem( pathView, Kleo::DN( (*it++).userID(0).id() ).prettyDN() ); - else { - item = new QListViewItem( pathView, i18n("Issuer certificate not found ( %1)") - .arg( Kleo::DN( (*it).issuerName() ).prettyDN() ) ); - item->setOpen( true ); // Qt bug: doesn't open after setEnabled( false ) :/ - item->setEnabled( false ); - } - item->setOpen( true ); - - // subsequent items: - while ( it != mChain.end() ) { - item = new QListViewItem( item, Kleo::DN( (*it++).userID(0).id() ).prettyDN() ); - item->setOpen( true ); - } -} - -void CertificateInfoWidgetImpl::slotCertificateChainListingResult( const GpgME::KeyListResult & res ) { - if ( res.error() ) - return showChainListError( this, res.error(), mChain.front().issuerName() ); - else - startCertificateChainListing(); -} - -void CertificateInfoWidgetImpl::slotShowInfo( QListViewItem * item ) { - textView->setText( item->text(1) ); -} - -void CertificateInfoWidgetImpl::slotShowCertPathDetails( QListViewItem * item ) { - if ( !item ) - return; - - // find the key corresponding to "item". This hack would not be - // necessary if pathView was a Kleo::KeyListView, but it's - // Qt-Designer-generated and I don't feel like creating a custom - // widget spec for Kleo::KeyListView. - unsigned int totalCount = 0; - int itemIndex = -1; - for ( const QListViewItem * i = pathView->firstChild() ; i ; i = i->firstChild() ) { - if ( i == item ) - itemIndex = totalCount; - ++totalCount; - } - - assert( totalCount == mChain.size() || totalCount == mChain.size() + 1 ); - - // skip pseudo root item with "not found message": - if ( totalCount == mChain.size() + 1 ) - --itemIndex; - - assert( itemIndex >= 0 ); - - KDialogBase * dialog = - new KDialogBase( this, "dialog", false, i18n("Additional Information for Key"), - KDialogBase::Close, KDialogBase::Close ); - CertificateInfoWidgetImpl * top = - new CertificateInfoWidgetImpl( mChain[itemIndex], mExternal, dialog ); - dialog->setMainWidget( top ); - // proxy the signal to our receiver: - connect( top, SIGNAL(requestCertificateDownload(const QString&, const QString&)), - SIGNAL(requestCertificateDownload(const QString&, const QString&)) ); - dialog->show(); -} - - -void CertificateInfoWidgetImpl::slotImportCertificate() -{ - if ( mChain.empty() || mChain.back().isNull() ) - return; - const Kleo::DN dn = mChain.back().userID( 0 ).id(); - emit requestCertificateDownload( mChain.back().primaryFingerprint(), dn.prettyDN() ); - importButton->setEnabled( false ); -} - -void CertificateInfoWidgetImpl::startKeyExistanceCheck() { - if ( !mExternal ) - // we already have it if it's from a local keylisting :) - return; - if ( mChain.empty() || mChain.back().isNull() ) - // need a key to look for - return; - const QString fingerprint = mChain.back().primaryFingerprint(); - if ( fingerprint.isEmpty() ) - // empty pattern means list all keys. We don't want that - return; - - // start _local_ keylistjob (no progressdialog needed here): - Kleo::KeyListJob * job = - Kleo::CryptoBackendFactory::instance()->smime()->keyListJob( false ); - assert( job ); - - connect( job, SIGNAL(nextKey(const GpgME::Key&)), - SLOT(slotKeyExistanceCheckNextCandidate(const GpgME::Key&)) ); - connect( job, SIGNAL(result(const GpgME::KeyListResult&)), - SLOT(slotKeyExistanceCheckFinished()) ); - // nor to check for errors: - job->start( fingerprint ); -} - -void CertificateInfoWidgetImpl::slotKeyExistanceCheckNextCandidate( const GpgME::Key & key ) { - if ( key.isNull() || mChain.empty() || !key.primaryFingerprint() ) - return; - - if ( qstrcmp( key.primaryFingerprint(), - mChain.back().primaryFingerprint() ) == 0 ) - mHaveKeyLocally = true; -} - -void CertificateInfoWidgetImpl::slotKeyExistanceCheckFinished() { - importButton->setEnabled( !mHaveKeyLocally ); -} - - -#include "certificateinfowidgetimpl.moc" diff --git a/kleopatra/certificateinfowidgetimpl.h b/kleopatra/certificateinfowidgetimpl.h deleted file mode 100644 index 961d67c39f..0000000000 --- a/kleopatra/certificateinfowidgetimpl.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - certificateinfowidgetimpl.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef CERTIFICATEINFOWIDGETIMPL_H -#define CERTIFICATEINFOWIDGETIMPL_H - -#include "certificateinfowidget.h" - -#include - -#include - -class KProcess; -class QListViewItem; - -namespace GpgME { - class KeyListResult; -} - -class CertificateInfoWidgetImpl : public CertificateInfoWidget { - Q_OBJECT -public: - CertificateInfoWidgetImpl( const GpgME::Key & key, bool external, - QWidget * parent=0, const char * name=0); - - void setKey( const GpgME::Key & key ); - -signals: - void requestCertificateDownload( const QString & fingerprint, const QString& displayName ); - -private slots: - void slotShowInfo( QListViewItem* ); - void slotShowCertPathDetails( QListViewItem* ); - void slotImportCertificate(); - void slotCertificateChainListingResult( const GpgME::KeyListResult & res ); - void slotNextKey( const GpgME::Key & key ); - void slotKeyExistanceCheckNextCandidate( const GpgME::Key & key ); - void slotKeyExistanceCheckFinished(); - void slotCollectStdout(KProcess *, char *, int); - void slotCollectStderr(KProcess *, char *, int); - void slotDumpProcessExited(KProcess*); - -private: - void startCertificateChainListing(); - void startCertificateDump(); - void startKeyExistanceCheck(); - void updateChainView(); - -private: - QCString mDumpOutput; - QCString mDumpError; - QValueList mChain; - bool mExternal; - bool mFoundIssuer; - bool mHaveKeyLocally; -}; - -#endif // CERTIFICATEINFOWIDGETIMPL_H diff --git a/kleopatra/certificatewizard.ui b/kleopatra/certificatewizard.ui deleted file mode 100644 index 2eb0da67e0..0000000000 --- a/kleopatra/certificatewizard.ui +++ /dev/null @@ -1,436 +0,0 @@ - -CertificateWizard - - - CertificateWizard - - - - 0 - 0 - 444 - 354 - - - - Certificate Wizard - - - - 16 - 1 - - - - - introPage - - - Certificate Wizard - - - - unnamed - - - 11 - - - 6 - - - - TextLabel1 - - - <b>Welcome to the Certificate Wizard!</b> -<br> -<br> -In a few easy steps, this wizard will help you to create a certificate. You use your certificates in order to sign messages, to encrypt messages and to decrypt messages that other people send to you in encrypted form. -<p> -The certificates will be generated in a decentralized manner. Please contact your local help desk if you are unsure how to create a certificate in your organization. - - - - - - - personalDataPage - - - Your Personal Data - - - - unnamed - - - 11 - - - 6 - - - - emailLA - - - &Email address: - - - emailED - - - - - emailED - - - Enter your email address here - - - Enter the email address here which you want to use in connection with the certificate. - - - - - countryLA - - - &Country code: - - - countryED - - - - - countryED - - - - - nameLA - - - &Name: - - - nameED - - - - - locationLA - - - &Location: - - - locationED - - - - - organizationLA - - - &Organization: - - - organizationED - - - - - departmentLA - - - &Department: - - - departmentED - - - - - departmentED - - - - - locationED - - - - - organizationED - - - Enter your organization here - - - Enter your organization (e.g., your company, your department, or your authority) here as it should appear on the certificate. - - - - - nameED - - - Enter your name here - - - Enter your name here as it should be shown in the certificate. - - - - - TextLabel2 - - - On this page, you will enter some personal data that will be stored in your certificate and that will help other people to determine that it is actually you who is sending a message. - - - WordBreak|AlignVCenter - - - - - - - generatePage - - - Decentralized Certificate Generation - - - - unnamed - - - 11 - - - 6 - - - - TextLabel4 - - - On this page, you will create a certificate in a decentralized way. You can either store the certificate in a file for later transmission or send it to the Certificate Authority (CA) directly. Please check with your local help desk if you are unsure what to select here.<br>Once you are done with your settings, click <em>Generate Certificate</em> in order to generate your certificate. - - - WordBreak|AlignVCenter - - - - - Layout21 - - - - unnamed - - - 0 - - - 6 - - - - Spacer13 - - - Horizontal - - - Expanding - - - - 20 - 0 - - - - - - generatePB - - - - 0 - 30 - - - - &Generate Certificate - - - - - Spacer12 - - - Horizontal - - - Expanding - - - - 20 - 0 - - - - - - - - ButtonGroup7 - - - - 5 - 1 - 0 - 0 - - - - Certificate &Generation - - - - unnamed - - - 11 - - - 6 - - - - storeUR - - - - - storeInFileRB - - - &Store in a file - - - - - sendToCARB - - - Send to CA as an &email message - - - true - - - - - caEmailED - - - - - - - - - finishPage - - - Your Certificate Is Ready To Be Sent - - - - unnamed - - - 11 - - - 6 - - - - TextLabel7 - - - <qt> -Your signature key pair is now ready to be sent to the CA (certification authority) which will generate a certificate for you and send it back via email (unless you have selected storage in a file). Please review the certificate shown below. -<p> -If you want to change anything, press Back and make your changes. Otherwise press Finish to send the signature key pair to the CA. -</qt> - - - WordBreak|AlignVCenter - - - - - certificateTE - - - true - - - - - - - - generatePB - clicked() - CertificateWizard - slotGenerateCertificate() - - - sendToCARB - toggled(bool) - caEmailED - setEnabled(bool) - - - emailED - textChanged(const QString&) - CertificateWizard - slotEmailAddressChanged(const QString&) - - - storeInFileRB - toggled(bool) - storeUR - setEnabled(bool) - - - - nameED - locationED - organizationED - departmentED - countryED - emailED - sendToCARB - caEmailED - certificateTE - generatePB - - - slotEmailAddressChanged(const QString&) - slotGenerateCertificate() - - - diff --git a/kleopatra/certificatewizardimpl.cpp b/kleopatra/certificatewizardimpl.cpp deleted file mode 100644 index 8c2d6a8ac8..0000000000 --- a/kleopatra/certificatewizardimpl.cpp +++ /dev/null @@ -1,515 +0,0 @@ -/* - certificatewizardimpl.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "certificatewizardimpl.h" -#include "storedtransferjob.h" - -// libkleopatra -#include -#include -#include -#include - -#include - -// gpgme++ -#include - -// KDE -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Qt -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -static const unsigned int keyLengths[] = { - 1024, 1532, 2048, 3072, 4096 -}; -static const unsigned int numKeyLengths = sizeof keyLengths / sizeof *keyLengths; - -static QString attributeLabel( const QString & attr, bool required ) { - if ( attr.isEmpty() ) - return QString::null; - const QString label = Kleo::DNAttributeMapper::instance()->name2label( attr ); - if ( !label.isEmpty() ) - if ( required ) - return i18n("Format string for the labels in the \"Your Personal Data\" page - required field", - "*%1 (%2):").arg( label, attr ); - else - return i18n("Format string for the labels in the \"Your Personal Data\" page", - "%1 (%2):").arg( label, attr ); - - else if ( required ) - return '*' + attr + ':'; - else - return attr + ':'; -} - -static QString attributeFromKey( QString key ) { - return key.remove( '!' ); -} - -static bool availForMod( const QLineEdit * le ) { - return le && le->isEnabled(); -} - -/* - * Constructs a CertificateWizardImpl which is a child of 'parent', with the - * name 'name' and widget flags set to 'f' - * - * The wizard will by default be modeless, unless you set 'modal' to - * TRUE to construct a modal wizard. - */ -CertificateWizardImpl::CertificateWizardImpl( QWidget* parent, const char* name, bool modal, WFlags fl ) - : CertificateWizard( parent, name, modal, fl ) -{ - // don't allow to go to last page until a key has been generated - setNextEnabled( generatePage, false ); - // setNextEnabled( personalDataPage, false ); // ## disable again once we have a criteria when to enable again - - createPersonalDataPage(); - - // Allow to select remote URLs - storeUR->setMode( KFile::File ); - storeUR->setFilter( "application/pkcs10" ); - connect( storeUR, SIGNAL( urlSelected( const QString& ) ), - this, SLOT( slotURLSelected( const QString& ) ) ); - - const KConfigGroup config( KGlobal::config(), "CertificateCreationWizard" ); - caEmailED->setText( config.readEntry( "CAEmailAddress" ) ); - - connect( this, SIGNAL( helpClicked() ), - this, SLOT( slotHelpClicked() ) ); - connect( insertAddressButton, SIGNAL( clicked() ), - this, SLOT( slotSetValuesFromWhoAmI() ) ); - - for ( unsigned int i = 0 ; i < numKeyLengths ; ++i ) - keyLengthCB->insertItem( i18n("%n bit", "%n bits", keyLengths[i] ) ); -} - -static bool requirementsAreMet( const CertificateWizardImpl::AttrPairList & list ) { - for ( CertificateWizardImpl::AttrPairList::const_iterator it = list.begin() ; - it != list.end() ; ++it ) { - const QLineEdit * le = (*it).second; - if ( !le ) - continue; - const QString key = (*it).first; -#ifndef NDEBUG - kdbgstream s = kdDebug(); -#else - kndbgstream s = kdDebug(); -#endif - s << "requirementsAreMet(): checking \"" << key << "\" against \"" << le->text() << "\": "; - if ( key.endsWith("!") && le->text().stripWhiteSpace().isEmpty() ) { - s << "required field is empty!" << endl; - return false; - } - s << "ok" << endl; - } - return true; -} - -/* - This slot is called when the user changes the text. - */ -void CertificateWizardImpl::slotEnablePersonalDataPageExit() { - setNextEnabled( personalDataPage, requirementsAreMet( _attrPairList ) ); -} - - -/* - * Destroys the object and frees any allocated resources - */ -CertificateWizardImpl::~CertificateWizardImpl() -{ - // no need to delete child widgets, Qt does it all for us -} - -static const char * oidForAttributeName( const QString & attr ) { - QCString attrUtf8 = attr.utf8(); - for ( unsigned int i = 0 ; i < numOidMaps ; ++i ) - if ( qstricmp( attrUtf8, oidmap[i].name ) == 0 ) - return oidmap[i].oid; - return 0; -} - -/* - * protected slot - */ -void CertificateWizardImpl::slotGenerateCertificate() -{ - // Ask gpgme to generate a key and return it - QString certParms; - certParms += "\n"; - certParms += "Key-Type: RSA\n"; - certParms += QString( "Key-Length: %1\n" ).arg( keyLengths[keyLengthCB->currentItem()] ); - certParms += "Key-Usage: "; - if ( signOnlyCB->isChecked() ) - certParms += "Sign"; - else if ( encryptOnlyCB->isChecked() ) - certParms += "Encrypt"; - else - certParms += "Sign, Encrypt"; - certParms += "\n"; - certParms += "name-dn: "; - - QString email; - QStringList rdns; - for( AttrPairList::const_iterator it = _attrPairList.begin(); it != _attrPairList.end(); ++it ) { - const QString attr = attributeFromKey( (*it).first.upper() ); - const QLineEdit * le = (*it).second; - if ( !le ) - continue; - - const QString value = le->text().stripWhiteSpace(); - if ( value.isEmpty() ) - continue; - - if ( attr == "EMAIL" ) { - // EMAIL is special, since it shouldn't be part of the DN, - // except for non-RFC-conformant CAs that require it to be - // there. - email = value; - if ( !brokenCA->isChecked() ) - continue; - } - - if ( const char * oid = oidForAttributeName( attr ) ) { - // we need to translate the attribute name for the backend: - rdns.push_back( QString::fromUtf8( oid ) + '=' + value ); - } else { - rdns.push_back( attr + '=' + value ); - } - } - certParms += rdns.join(","); - if( !email.isEmpty() ) - certParms += "\nname-email: " + email; - certParms += "\n\n"; - - kdDebug() << certParms << endl; - - Kleo::KeyGenerationJob * job = - Kleo::CryptoBackendFactory::instance()->smime()->keyGenerationJob(); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::KeyGenerationResult&,const QByteArray&)), - SLOT(slotResult(const GpgME::KeyGenerationResult&,const QByteArray&)) ); - - certificateTE->setText( certParms ); - - const GpgME::Error err = job->start( certParms ); - if ( err ) - KMessageBox::error( this, - i18n( "Could not start certificate generation: %1" ) - .arg( QString::fromLocal8Bit( err.asString() ) ), - i18n( "Certificate Manager Error" ) ); - else { - generatePB->setEnabled( false ); - setBackEnabled( generatePage, false ); - (void)new Kleo::ProgressDialog( job, i18n("Generating key"), this ); - } -} - - -void CertificateWizardImpl::slotResult( const GpgME::KeyGenerationResult & res, - const QByteArray & keyData ) { - //kdDebug() << "keyData.size(): " << keyData.size() << endl; - _keyData = keyData; - - if ( res.error().isCanceled() || res.error() ) { - setNextEnabled( generatePage, false ); - setBackEnabled( generatePage, true ); - setFinishEnabled( finishPage, false ); - generatePB->setEnabled( true ); - if ( !res.error().isCanceled() ) - KMessageBox::error( this, - i18n( "Could not generate certificate: %1" ) - .arg( QString::fromLatin1( res.error().asString() ) ), - i18n( "Certificate Manager Error" ) ); - } else { - // next will stay enabled until the user clicks Generate - // Certificate again - setNextEnabled( generatePage, true ); - setFinishEnabled( finishPage, true ); - } -} - -void CertificateWizardImpl::slotHelpClicked() -{ - kapp->invokeHelp( "newcert" ); -} - -void CertificateWizardImpl::slotSetValuesFromWhoAmI() -{ - const KABC::Addressee a = KABC::StdAddressBook::self( true )->whoAmI(); - if ( a.isEmpty() ) - return; - const KABC::Address adr = a.address(KABC::Address::Work); - - for ( AttrPairList::const_iterator it = _attrPairList.begin() ; - it != _attrPairList.end() ; ++it ) { - QLineEdit * le = (*it).second; - if ( !availForMod( le ) ) - continue; - - const QString attr = attributeFromKey( (*it).first.upper() ); - if ( attr == "CN" ) - le->setText( a.formattedName() ); - else if ( attr == "EMAIL" ) - le->setText( a.preferredEmail() ); - else if ( attr == "O" ) - le->setText( a.organization() ); - else if ( attr == "OU" ) - le->setText( a.custom( "KADDRESSBOOK", "X-Department" ) ); - else if ( attr == "L" ) - le->setText( adr.locality() ); - else if ( attr == "SP" ) - le->setText( adr.region() ); - else if ( attr == "PC" ) - le->setText( adr.postalCode() ); - else if ( attr == "SN" ) - le->setText( a.familyName() ); - else if ( attr == "GN" ) - le->setText( a.givenName() ); - else if ( attr == "T" ) - le->setText( a.title() ); - else if ( attr == "BC" ) - le->setText( a.role() ); // correct mapping? - } -} - -void CertificateWizardImpl::createPersonalDataPage() -{ - QGridLayout* grid = new QGridLayout( edContainer, 2, 1, - KDialog::marginHint(), KDialog::spacingHint() ); - - KConfigGroup config( KGlobal::config(), "CertificateCreationWizard" ); - QStringList attrOrder = config.readListEntry( "DNAttributeOrder" ); - if ( attrOrder.empty() ) - attrOrder << "CN!" << "L" << "OU" << "O!" << "C!" << "EMAIL!"; - int row = 0; - - for ( QStringList::const_iterator it = attrOrder.begin() ; it != attrOrder.end() ; ++it, ++row ) { - const QString key = (*it).stripWhiteSpace().upper(); - const QString attr = attributeFromKey( key ); - if ( attr.isEmpty() ) { - --row; - continue; - } - const QString preset = config.readEntry( attr ); - const QString label = config.readEntry( attr + "_label", - attributeLabel( attr, key.endsWith("!") ) ); - - QLineEdit * le = new QLineEdit( edContainer ); - grid->addWidget( le, row, 1 ); - grid->addWidget( new QLabel( le, label.isEmpty() ? attr : label, edContainer ), row, 0 ); - - le->setText( preset ); - if ( config.entryIsImmutable( attr ) ) - le->setEnabled( false ); - - _attrPairList.append(qMakePair(key, le)); - - connect( le, SIGNAL(textChanged(const QString&)), - SLOT(slotEnablePersonalDataPageExit()) ); - } - - // enable button only if administrator wants to allow it - if (KABC::StdAddressBook::self( true )->whoAmI().isEmpty() || - !config.readBoolEntry("ShowSetWhoAmI", true)) - insertAddressButton->setEnabled( false ); - - slotEnablePersonalDataPageExit(); -} - -bool CertificateWizardImpl::sendToCA() const { - return sendToCARB->isChecked(); -} - -QString CertificateWizardImpl::caEMailAddress() const { - return caEmailED->text().stripWhiteSpace(); -} - -void CertificateWizardImpl::slotURLSelected( const QString& _url ) -{ - KURL url = KURL::fromPathOrURL( _url.stripWhiteSpace() ); -#if ! KDE_IS_VERSION(3,2,90) - // The application/pkcs10 mimetype didn't have a native extension, - // so the filedialog didn't have the checkbox for auto-adding it. - QString fileName = url.fileName(); - int pos = fileName.findRev( '.' ); - if ( pos < 0 ) // no extension - url.setFileName( fileName + ".p10" ); -#endif - storeUR->setURL( url.prettyURL() ); -} - -KURL CertificateWizardImpl::saveFileUrl() const { - return KURL::fromPathOrURL( storeUR->url().stripWhiteSpace() ); -} - -void CertificateWizardImpl::showPage( QWidget * page ) -{ - CertificateWizard::showPage( page ); - if ( page == generatePage ) { - // Initial settings for the generation page: focus the correct lineedit - // and disable the other one - if ( storeInFileRB->isChecked() ) { - storeUR->setEnabled( true ); - caEmailED->setEnabled( false ); - storeUR->setFocus(); - } else { - storeUR->setEnabled( false ); - caEmailED->setEnabled( true ); - caEmailED->setFocus(); - } - } -} - -static const char* const dcopObjectId = "KMailIface"; -/** - Send the new certificate by mail using KMail - */ -void CertificateWizardImpl::sendCertificate( const QString& email, const QByteArray& certificateData ) -{ - QString error; - QCString dcopService; - int result = KDCOPServiceStarter::self()-> - findServiceFor( "DCOP/Mailer", QString::null, - QString::null, &error, &dcopService ); - if ( result != 0 ) { - kdDebug() << "Couldn't connect to KMail\n"; - KMessageBox::error( this, - i18n( "DCOP Communication Error, unable to send certificate using KMail.\n%1" ).arg( error ) ); - return; - } - - QCString dummy; - // OK, so kmail (or kontact) is running. Now ensure the object we want is available. - // [that's not the case when kontact was already running, but kmail not loaded into it... in theory.] - if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ) { - DCOPRef ref( dcopService, dcopService ); // talk to the KUniqueApplication or its kontact wrapper - DCOPReply reply = ref.call( "load()" ); - if ( reply.isValid() && (bool)reply ) { - Q_ASSERT( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ); - } else - kdWarning() << "Error loading " << dcopService << endl; - } - - DCOPClient* dcopClient = kapp->dcopClient(); - QByteArray data; - QDataStream arg( data, IO_WriteOnly ); - arg << email; - arg << certificateData; - if( !dcopClient->send( dcopService, dcopObjectId, - "sendCertificate(QString,QByteArray)", data ) ) { - KMessageBox::error( this, - i18n( "DCOP Communication Error, unable to send certificate using KMail." ) ); - return; - } - // All good, close dialog - CertificateWizard::accept(); -} - -// Called when pressing Finish -// We want to do the emailing/uploading first, before closing the dialog, -// in case of errors during the upload. -void CertificateWizardImpl::accept() -{ - if( sendToCA() ) { - // Ask KMail to send this key to the CA. - sendCertificate( caEMailAddress(), _keyData ); - } else { - // Save in file/URL - KURL url = saveFileUrl(); - bool overwrite = false; - if ( KIO::NetAccess::exists( url, false /*dest*/, this ) ) { - if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel( - this, - i18n( "A file named \"%1\" already exists. " - "Are you sure you want to overwrite it?" ).arg( url.prettyURL() ), - i18n( "Overwrite File?" ), - i18n( "&Overwrite" ) ) ) - return; - overwrite = true; - } - - KIO::Job* uploadJob = KIOext::put( _keyData, url, -1, overwrite, false /*resume*/ ); - uploadJob->setWindow( this ); - connect( uploadJob, SIGNAL( result( KIO::Job* ) ), - this, SLOT( slotUploadResult( KIO::Job* ) ) ); - // Can't press finish again during the upload - setFinishEnabled( finishPage, false ); - } -} - -/** - This slot is invoked by the KIO job used in newCertificate - to save/upload the certificate, when finished (success or error). -*/ -void CertificateWizardImpl::slotUploadResult( KIO::Job* job ) -{ - if ( job->error() ) { - job->showErrorDialog(); - setFinishEnabled( finishPage, true ); - } else { - // All good, close dialog - CertificateWizard::accept(); - } -} - -#include "certificatewizardimpl.moc" diff --git a/kleopatra/certificatewizardimpl.h b/kleopatra/certificatewizardimpl.h deleted file mode 100644 index d275cbc721..0000000000 --- a/kleopatra/certificatewizardimpl.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - certificatewizardimpl.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef CERTIFICATEWIZARDIMPL_H -#define CERTIFICATEWIZARDIMPL_H -#include "certificatewizard.h" - -#include -#include -#include -#include - -namespace GpgME { - class KeyGenerationResult; -} -namespace KIO { - class Job; -} - -class CertificateWizardImpl : public CertificateWizard -{ - Q_OBJECT - -public: - CertificateWizardImpl( QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0 ); - ~CertificateWizardImpl(); - - bool sendToCA() const; - QString caEMailAddress() const; - KURL saveFileUrl() const; - - typedef QPair StringLEPair; - typedef QValueVector< StringLEPair > AttrPairList; - -public: - virtual void showPage( QWidget * page ); - virtual void accept(); - -private slots: - void slotGenerateCertificate(); - void slotResult( const GpgME::KeyGenerationResult & res, const QByteArray & keyData ); - void slotSetValuesFromWhoAmI(); - void slotEnablePersonalDataPageExit(); - void slotURLSelected( const QString& ); - - void slotHelpClicked(); - - void slotUploadResult( KIO::Job* ); - -private: - void createPersonalDataPage(); - void sendCertificate( const QString& email, const QByteArray& certificateData ); - -private: - AttrPairList _attrPairList; - QByteArray _keyData; -}; - -#endif // CERTIFICATEWIZARDIMPL_H diff --git a/kleopatra/certitem.cpp b/kleopatra/certitem.cpp deleted file mode 100644 index cdc7d5f45e..0000000000 --- a/kleopatra/certitem.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include -#include -#include - -#include -#include - -#include "agent.h" -#include "certitem.h" -#include "certmanager.h" - -#include "certificateinfowidgetimpl.h" - -CertItem::CertItem( const CryptPlugWrapper::CertificateInfo& info, - Agent* agent,CertManager* manager, CertBox* parent ) - : QListViewItem( parent ) , - _info(info), - _agent(agent), - _manager(manager) -{ - init(); -} - -CertItem::CertItem( const CryptPlugWrapper::CertificateInfo& info, - Agent* agent,CertManager* manager, CertItem* parent ) - : QListViewItem( parent ), - _info(info), - _agent(agent), - _manager(manager) -{ - init(); -} - -void CertItem::init() -{ - setOpen( true ); -} - -QString CertItem::text( int col ) const -{ - switch( col ) { - case 0: - return dn(); - case 1: - return issuer(); - case 2: - return serial(); - case 3: - return created().toString(); - case 4: - return expire().toString(); - default: - return QListViewItem::text(col); - } -} - -/** - Certificates may have a variable number of keys, some of these may be dublicates, - an example of this is that a certificate may have several email addresses. - This method allows for adding an arbitrary key. -*/ -void CertItem::addKey( const QString& key, const QString& value ) -{ - _extras.append( QPair(key, value) ); -} - -/** - This method is invoked when the user double clicks on a certificate, and thus wants to - see its details. -*/ -void CertItem::display() -{ - KDialogBase* dialog = new KDialogBase( listView(), "dialog", true, i18n("Additional Information for Key"), KDialogBase::Close, KDialogBase::Close ); - - CertificateInfoWidgetImpl* top = new CertificateInfoWidgetImpl( _manager, _manager->isRemote(), dialog ); - dialog->setMainWidget( top ); - top->setCert( _info ); -#if 0 - // Extra Keys - for ( QValueList< QPair >::iterator it = _extras.begin(); it != _extras.end(); ++it ) { - new QLabel( QString("%1: %2").arg( (*it).first ).arg( (*it).second ), top ); - } - - // Agent Information - QFrame* frame = new QFrame(top); - frame->setFrameStyle( QFrame::HLine | QFrame:: Plain ); - - new QLabel(i18n("CA information"), top); - //new QLabel( _agent->tree(), top ); - //if( parent() ) new QLabel( static_cast(parent())->dn(), top ); - new QLabel(i18n("Issued by: %1").arg( _issuer ), top ); -#endif - - dialog->exec(); - delete dialog; -} diff --git a/kleopatra/certitem.h b/kleopatra/certitem.h deleted file mode 100644 index c4fe4d053a..0000000000 --- a/kleopatra/certitem.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef __CERTITEM_H -#define __CERTITEM_H -#include -#include "certbox.h" -#include -#include -#include -#include -class Agent; -class CertManager; - -/** - One item in the certificate list view. -*/ -class CertItem :public QListViewItem -{ -public: - CertItem( const CryptPlugWrapper::CertificateInfo& info, - Agent* agent, CertManager* manager, CertBox* parent ); - CertItem( const CryptPlugWrapper::CertificateInfo& info, - Agent* agent, CertManager* manager, CertItem* parent ); - void addKey( const QString& key, const QString& value ); - void display(); - - QString dn() const { return _info.userid[0].stripWhiteSpace(); } - QString issuer() const { return _info.issuer.stripWhiteSpace(); } - QString serial() const { return _info.serial; } - QDateTime created() const { return _info.created; } - QDateTime expire() const { return _info.expire; } - - virtual QString text(int) const; - -private: - void init(); - - CryptPlugWrapper::CertificateInfo _info; - - Agent* _agent; - CertManager* _manager; - QValueList< QPair > _extras; -}; - -#endif // __CERTITEM_H diff --git a/kleopatra/certmanager.cpp b/kleopatra/certmanager.cpp deleted file mode 100644 index a94b47e127..0000000000 --- a/kleopatra/certmanager.cpp +++ /dev/null @@ -1,1382 +0,0 @@ -/* - certmanager.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "certmanager.h" - -#include "certlistview.h" -#include "certificatewizardimpl.h" -#include "certificateinfowidgetimpl.h" -#include "crlview.h" -#include "customactions.h" -#include "hierarchyanalyser.h" -#include "storedtransferjob.h" -#include "conf/configuredialog.h" - -// libkleopatra -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -// GPGME++ -#include -#include -#include - -// KDE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Qt -#include -#include - -// other -#include -#include -#include -namespace { - - class KDE_EXPORT DisplayStrategy : public Kleo::KeyListView::DisplayStrategy{ - public: - ~DisplayStrategy() {} - - virtual QFont keyFont( const GpgME::Key& key, const QFont& font ) const { - const Kleo::KeyFilter* filter = Kleo::KeyFilterManager::instance()->filterMatching( key ); - return filter ? filter->font( font ) : font; - } - virtual QColor keyForeground( const GpgME::Key& key, const QColor& c ) const { - const Kleo::KeyFilter* filter = Kleo::KeyFilterManager::instance()->filterMatching( key ); - if ( filter && filter->fgColor().isValid() ) - return filter->fgColor(); - return c; - } - virtual QColor keyBackground( const GpgME::Key& key, const QColor& c ) const { - const Kleo::KeyFilter* filter = Kleo::KeyFilterManager::instance()->filterMatching( key ); - if ( filter && filter->bgColor().isValid() ) - return filter->bgColor(); - return c; - } - }; - - class KDE_EXPORT ColumnStrategy : public Kleo::KeyListView::ColumnStrategy { - public: - ~ColumnStrategy() {} - - QString title( int col ) const; - QString text( const GpgME::Key & key, int col ) const; - int width( int col, const QFontMetrics & fm ) const; - }; - - QString ColumnStrategy::title( int col ) const { - switch ( col ) { - case 0: return i18n("Subject"); - case 1: return i18n("Issuer"); - case 2: return i18n("Serial"); - default: return QString::null; - } - } - - QString ColumnStrategy::text( const GpgME::Key & key, int col ) const { - switch ( col ) { - case 0: return Kleo::DN( key.userID(0).id() ).prettyDN(); - case 1: return Kleo::DN( key.issuerName() ).prettyDN(); - case 2: return key.issuerSerial() ? QString::fromUtf8( key.issuerSerial() ) : QString::null ; - default: return QString::null; - } - } - - int ColumnStrategy::width( int col, const QFontMetrics & fm ) const { - int factor = -1; - switch ( col ) { - case 0: factor = 6; break; - case 1: factor = 4; break; - default: return -1; - } - return fm.width( title( col ) ) * factor; - } -} // anon namespace - -CertManager::CertManager( bool remote, const QString& query, const QString & import, - QWidget* parent, const char* name, WFlags f ) - : KMainWindow( parent, name, f|WDestructiveClose ), - mCrlView( 0 ), - mDirmngrProc( 0 ), - mHierarchyAnalyser( 0 ), - mLineEditAction( 0 ), - mComboAction( 0 ), - mFindAction( 0 ), - mImportCertFromFileAction( 0 ), - mImportCRLFromFileAction( 0 ), - mNextFindRemote( false ), - mRemote( remote ), - mDirMngrFound( false ) -{ - createStatusBar(); - createActions(); - - createGUI(); - setAutoSaveSettings(); - - // Main Window -------------------------------------------------- - mKeyListView = new CertKeyListView( new ColumnStrategy(), new DisplayStrategy(), this, "mKeyListView" ); - mKeyListView->setSelectionMode( QListView::Extended ); - setCentralWidget( mKeyListView ); - - connect( mKeyListView, SIGNAL(doubleClicked(Kleo::KeyListViewItem*,const QPoint&,int)), - SLOT(slotViewDetails(Kleo::KeyListViewItem*)) ); - connect( mKeyListView, SIGNAL(returnPressed(Kleo::KeyListViewItem*)), - SLOT(slotViewDetails(Kleo::KeyListViewItem*)) ); - connect( mKeyListView, SIGNAL(selectionChanged()), - SLOT(slotSelectionChanged()) ); - connect( mKeyListView, SIGNAL(contextMenu(Kleo::KeyListViewItem*, const QPoint&)), - SLOT(slotContextMenu(Kleo::KeyListViewItem*, const QPoint&)) ); - - connect( mKeyListView, SIGNAL(dropped(const KURL::List&) ), - SLOT( slotDropped(const KURL::List&) ) ); - - mLineEditAction->setText(query); - if ( !mRemote || !query.isEmpty() ) - slotSearch(); - - if ( !import.isEmpty() ) - slotImportCertFromFile( KURL( import ) ); - - readConfig(); - updateStatusBarLabels(); - slotSelectionChanged(); // initial state for selection-dependent actions -} - -CertManager::~CertManager() { - writeConfig(); - delete mDirmngrProc; mDirmngrProc = 0; - delete mHierarchyAnalyser; mHierarchyAnalyser = 0; -} - -void CertManager::readConfig() { - KConfig config( "kleopatrarc" ); - config.setGroup( "Display Options" ); - slotToggleHierarchicalView( config.readBoolEntry( "hierarchicalView", false ) ); -} - -void CertManager::writeConfig() { - KConfig config( "kleopatrarc" ); - config.setGroup( "Display Options" ); - config.writeEntry( "hierarchicalView", mKeyListView->hierarchical() ); -} - -void CertManager::createStatusBar() { - KStatusBar * bar = statusBar(); - mProgressBar = new Kleo::ProgressBar( bar, "mProgressBar" ); - mProgressBar->reset(); - mProgressBar->setFixedSize( QSize( 100, mProgressBar->height() * 3 / 5 ) ); - bar->addWidget( mProgressBar, 0, true ); - mStatusLabel = new QLabel( bar, "mStatusLabel" ); - bar->addWidget( mStatusLabel, 1, false ); -} - -static inline void connectEnableOperationSignal( QObject * s, QObject * d ) { - QObject::connect( s, SIGNAL(enableOperations(bool)), - d, SLOT(setEnabled(bool)) ); -} - - -void CertManager::createActions() { - KAction * action = 0; - - (void)KStdAction::quit( this, SLOT(close()), actionCollection() ); - - action = KStdAction::redisplay( this, SLOT(slotRedisplay()), actionCollection() ); - // work around the fact that the stdaction has no shortcut - KShortcut reloadShortcut = KStdAccel::shortcut(KStdAccel::Reload); - reloadShortcut.append(KKey(CTRL + Key_R)); - action->setShortcut( reloadShortcut ); - - connectEnableOperationSignal( this, action ); - - action = new KAction( i18n("Stop Operation"), "stop", Key_Escape, - this, SIGNAL(stopOperations()), - actionCollection(), "view_stop_operations" ); - action->setEnabled( false ); - - (void) new KAction( i18n("New Key Pair..."), "filenew", 0, - this, SLOT(newCertificate()), - actionCollection(), "file_new_certificate" ); - - connect( new KToggleAction( i18n("Hierarchical Key List"), 0, - actionCollection(), "view_hierarchical" ), - SIGNAL(toggled(bool)), SLOT(slotToggleHierarchicalView(bool)) ); - - action = new KAction( i18n("Expand All"), 0, CTRL+Key_Period, - this, SLOT(slotExpandAll()), - actionCollection(), "view_expandall" ); - action = new KAction( i18n("Collapse All"), 0, CTRL+Key_Comma, - this, SLOT(slotCollapseAll()), - actionCollection(), "view_collapseall" ); - - (void) new KAction( i18n("Refresh CRLs"), 0, 0, - this, SLOT(slotRefreshKeys()), - actionCollection(), "certificates_refresh_clr" ); - -#ifdef NOT_IMPLEMENTED_ANYWAY - mRevokeCertificateAction = new KAction( i18n("Revoke"), 0, - this, SLOT(revokeCertificate()), - actionCollection(), "edit_revoke_certificate" ); - connectEnableOperationSignal( this, mRevokeCertificateAction ); - - mExtendCertificateAction = new KAction( i18n("Extend"), 0, - this, SLOT(extendCertificate()), - actionCollection(), "edit_extend_certificate" ); - connectEnableOperationSignal( this, mExtendCertificateAction ); -#endif - - mDeleteCertificateAction = new KAction( i18n("Delete"), "editdelete", Key_Delete, - this, SLOT(slotDeleteCertificate()), - actionCollection(), "edit_delete_certificate" ); - connectEnableOperationSignal( this, mDeleteCertificateAction ); - - mValidateCertificateAction = new KAction( i18n("Validate"), "reload", SHIFT + Key_F5, - this, SLOT(slotValidate()), - actionCollection(), "certificates_validate" ); - connectEnableOperationSignal( this, mValidateCertificateAction ); - - mImportCertFromFileAction = new KAction( i18n("Import Certificates..."), 0, - this, SLOT(slotImportCertFromFile()), - actionCollection(), "file_import_certificates" ); - connectEnableOperationSignal( this, mImportCertFromFileAction ); - - mImportCRLFromFileAction = new KAction( i18n("Import CRLs..."), 0, - this, SLOT(importCRLFromFile()), - actionCollection(), "file_import_crls" ); - connectEnableOperationSignal( this, mImportCRLFromFileAction ); - - mExportCertificateAction = new KAction( i18n("Export Certificates..."), "export", 0, - this, SLOT(slotExportCertificate()), - actionCollection(), "file_export_certificate" ); - - mExportSecretKeyAction = new KAction( i18n("Export Secret Key..."), "export", 0, - this, SLOT(slotExportSecretKey()), - actionCollection(), "file_export_secret_keys" ); - connectEnableOperationSignal( this, mExportSecretKeyAction ); - - mViewCertDetailsAction = new KAction( i18n("Certificate Details..."), 0, 0, - this, SLOT(slotViewDetails()), actionCollection(), - "view_certificate_details" ); - mDownloadCertificateAction = new KAction( i18n( "Download"), 0, 0, - this, SLOT(slotDownloadCertificate()), actionCollection(), - "download_certificate" ); - - const QString dirmngr = KStandardDirs::findExe( "gpgsm" ); - mDirMngrFound = !dirmngr.isEmpty(); - - action = new KAction( i18n("Dump CRL Cache..."), 0, - this, SLOT(slotViewCRLs()), - actionCollection(), "crl_dump_crl_cache" ); - action->setEnabled( mDirMngrFound ); // we also need dirmngr for this - - action = new KAction( i18n("Clear CRL Cache..."), 0, - this, SLOT(slotClearCRLs()), - actionCollection(), "crl_clear_crl_cache" ); - action->setEnabled( mDirMngrFound ); // we also need dirmngr for this - - action = new KAction( i18n("GnuPG Log Viewer..."), "pgp-keys", 0, this, - SLOT(slotStartWatchGnuPG()), actionCollection(), "tools_start_kwatchgnupg"); - // disable action if no kwatchgnupg binary is around - if (KStandardDirs::findExe("kwatchgnupg").isEmpty()) action->setEnabled(false); - - (void)new LabelAction( i18n("Search:"), actionCollection(), "label_action" ); - - mLineEditAction = new LineEditAction( QString::null, actionCollection(), this, - SLOT(slotSearch()), - "query_lineedit_action"); - - QStringList lst; - lst << i18n("In Local Certificates") << i18n("In External Certificates"); - mComboAction = new ComboAction( lst, actionCollection(), this, SLOT( slotToggleRemote(int) ), - "location_combo_action"); - - mFindAction = new KAction( i18n("Find"), "find", 0, this, SLOT(slotSearch()), - actionCollection(), "find" ); - - KStdAction::keyBindings( this, SLOT(slotEditKeybindings()), actionCollection() ); - KStdAction::preferences( this, SLOT(slotShowConfigurationDialog()), actionCollection() ); - - new KAction( i18n( "Configure &GpgME Backend" ), 0, 0, this, SLOT(slotConfigureGpgME()), - actionCollection(), "configure_gpgme" ); - - createStandardStatusBarAction(); - updateImportActions( true ); -} - -void CertManager::updateImportActions( bool enable ) { - mImportCRLFromFileAction->setEnabled( mDirMngrFound && enable ); - mImportCertFromFileAction->setEnabled( enable ); -} - -void CertManager::slotEditKeybindings() { - KKeyDialog::configure( actionCollection(), true ); -} - -void CertManager::slotShowConfigurationDialog() { - ConfigureDialog dlg( this ); - connect( &dlg, SIGNAL( configCommitted() ), SLOT( slotRepaint() ) ); - dlg.exec(); -} - -void CertManager::slotConfigureGpgME() { - Kleo::CryptoConfig* config = Kleo::CryptoBackendFactory::instance()->config(); - if ( config ) { - Kleo::CryptoConfigDialog dlg( config ); - - int result = dlg.exec(); - - // Forget all data parsed from gpgconf, so that we show updated information - // when reopening the configuration dialog. - config->clear(); - - if ( result == QDialog::Accepted ) - { - // Tell other apps (e.g. kmail) that the gpgconf data might have changed - kapp->dcopClient()->emitDCOPSignal( "KPIM::CryptoConfig", "changed()", QByteArray() ); - } - } -} - -void CertManager::slotRepaint() -{ - mKeyListView->repaintContents(); -} - -void CertManager::slotToggleRemote( int idx ) { - mNextFindRemote = idx != 0; -} - -void CertManager::slotToggleHierarchicalView( bool hier ) { - mKeyListView->setHierarchical( hier ); - mKeyListView->setRootIsDecorated( hier ); - if ( KAction * act = action("view_expandall") ) - act->setEnabled( hier ); - if ( KAction * act = action("view_collapseall" ) ) - act->setEnabled( hier ); - if ( KToggleAction * act = - static_cast( action("view_hierarchical") ) ) - act->setChecked( hier ); - - if ( hier && !mCurrentQuery.isEmpty() ) - startRedisplay( false ); -} - -void CertManager::slotExpandAll() { - for ( QListViewItemIterator it( mKeyListView ) ; it.current() ; ++it ) - it.current()->setOpen( true ); -} - -void CertManager::slotCollapseAll() { - for ( QListViewItemIterator it( mKeyListView ) ; it.current() ; ++it ) - it.current()->setOpen( false ); -} - -void CertManager::connectJobToStatusBarProgress( Kleo::Job * job, const QString & initialText ) { - assert( mProgressBar ); - if ( !job ) - return; - if ( !initialText.isEmpty() ) - statusBar()->message( initialText ); - connect( job, SIGNAL(progress(const QString&,int,int)), - mProgressBar, SLOT(slotProgress(const QString&,int,int)) ); - connect( job, SIGNAL(done()), mProgressBar, SLOT(reset()) ); - connect( this, SIGNAL(stopOperations()), job, SLOT(slotCancel()) ); - - action("view_stop_operations")->setEnabled( true ); - emit enableOperations( false ); -} - -void CertManager::disconnectJobFromStatusBarProgress( const GpgME::Error & err ) { - updateStatusBarLabels(); - const QString msg = err.isCanceled() ? i18n("Canceled.") - : err ? i18n("Failed.") - : i18n("Done.") ; - statusBar()->message( msg, 4000 ); - - action("view_stop_operations")->setEnabled( false ); - emit enableOperations( true ); - slotSelectionChanged(); -} - -void CertManager::updateStatusBarLabels() { - mKeyListView->flushKeys(); - int total = 0; - for ( QListViewItemIterator it( mKeyListView ) ; it.current() ; ++it ) - ++total; - mStatusLabel->setText( i18n( "%n Key.","%n Keys.", total ) ); -} - -// -// -// Key Listing: -// -// - - -static std::set extractKeyFingerprints( const QPtrList & items ) { - std::set result; - for ( QPtrListIterator it( items ) ; it.current() ; ++it ) - if ( const char * fpr = it.current()->key().primaryFingerprint() ) - result.insert( fpr ); - return result; -} - -static QStringList stringlistFromSet( const std::set & set ) { - // ARGH. This is madness. Shitty Qt containers don't support QStringList( patterns.begin(), patterns.end() ) :/ - QStringList sl; - for ( std::set::const_iterator it = set.begin() ; it != set.end() ; ++it ) - // let's make extra sure, maybe someone tries to make Qt not support std::string->QString conversion - sl.push_back( QString::fromLatin1( it->c_str() ) ); - return sl; -} - -void CertManager::slotRefreshKeys() { - const QStringList keys = stringlistFromSet( extractKeyFingerprints( mKeyListView->selectedItems() ) ); - Kleo::RefreshKeysJob * job = Kleo::CryptoBackendFactory::instance()->smime()->refreshKeysJob(); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::Error&)), - this, SLOT(slotRefreshKeysResult(const GpgME::Error&)) ); - - connectJobToStatusBarProgress( job, i18n("Refreshing keys...") ); - if ( const GpgME::Error err = job->start( keys ) ) - slotRefreshKeysResult( err ); -} - -void CertManager::slotRefreshKeysResult( const GpgME::Error & err ) { - disconnectJobFromStatusBarProgress( err ); - if ( err.isCanceled() ) - return; - if ( err ) - KMessageBox::error( this, i18n("An error occurred while trying to refresh " - "keys:\n%1").arg( QString::fromLocal8Bit( err.asString() ) ), - i18n("Refreshing Keys Failed") ); -} - -static void showKeyListError( QWidget * parent, const GpgME::Error & err ) { - assert( err ); - const QString msg = i18n( "

An error occurred while fetching " - "the certificates from the backend:

" - "

%1

" ) - .arg( QString::fromLocal8Bit( err.asString() ) ); - - KMessageBox::error( parent, msg, i18n( "Certificate Listing Failed" ) ); -} - -void CertManager::slotSearch() { - mPreviouslySelectedFingerprints.clear(); - // Clear display - mKeyListView->clear(); - mCurrentQuery = mLineEditAction->text(); - startKeyListing( false, false, mCurrentQuery ); -} - -void CertManager::startRedisplay( bool validate ) { - mPreviouslySelectedFingerprints = extractKeyFingerprints( mKeyListView->selectedItems() ); - if ( mPreviouslySelectedFingerprints.empty() ) - startKeyListing( validate, true, mCurrentQuery ); - else - startKeyListing( validate, true, mPreviouslySelectedFingerprints ); -} - -void CertManager::startKeyListing( bool validating, bool refresh, const std::set & patterns ) { - startKeyListing( validating, refresh, stringlistFromSet( patterns ) ); -} - -void CertManager::startKeyListing( bool validating, bool refresh, const QStringList & patterns ) { - mRemote = mNextFindRemote; - mLineEditAction->setEnabled( false ); - mComboAction->setEnabled( false ); - mFindAction->setEnabled( false ); - - Kleo::KeyListJob * job = 0; - if ( !validating && !refresh && mKeyListView->hierarchical() && !patterns.empty() ) - job = new Kleo::HierarchicalKeyListJob( Kleo::CryptoBackendFactory::instance()->smime(), - mRemote, false, validating ); - else - job = Kleo::CryptoBackendFactory::instance()->smime()->keyListJob( mRemote, false, validating ); - assert( job ); - - connect( job, SIGNAL(nextKey(const GpgME::Key&)), - mKeyListView, refresh ? SLOT(slotRefreshKey(const GpgME::Key&)) : SLOT(slotAddKey(const GpgME::Key&)) ); - connect( job, SIGNAL(result(const GpgME::KeyListResult&)), - this, SLOT(slotKeyListResult(const GpgME::KeyListResult&)) ); - - connectJobToStatusBarProgress( job, i18n("Fetching keys...") ); - - const GpgME::Error err = job->start( patterns ) ; - if ( err ) { - showKeyListError( this, err ); - return; - } - mProgressBar->setProgress( 0, 0 ); // enable busy indicator -} - -static void selectKeys( Kleo::KeyListView * lv, const std::set & fprs ) { - if ( !lv || fprs.empty() ) - return; - for ( QListViewItemIterator it( lv ) ; it.current() ; ++it ) - if ( Kleo::KeyListViewItem * item = Kleo::lvi_cast( it.current() ) ) { - const char * fpr = item->key().primaryFingerprint(); - item->setSelected( fpr && fprs.find( fpr ) != fprs.end() ); - } -} - -void CertManager::slotKeyListResult( const GpgME::KeyListResult & res ) { - if ( res.error() ) - showKeyListError( this, res.error() ); - else if ( res.isTruncated() ) - KMessageBox::information( this, - i18n("The query result has been truncated.\n" - "Either the local or a remote limit on " - "the maximum number of returned hits has " - "been exceeded.\n" - "You can try to increase the local limit " - "in the configuration dialog, but if one " - "of the configured servers is the limiting " - "factor, you have to refine your search.") ); - - mLineEditAction->setEnabled( true ); - mComboAction->setEnabled( true ); - mFindAction->setEnabled( true ); - - mLineEditAction->focusAll(); - disconnectJobFromStatusBarProgress( res.error() ); - selectKeys( mKeyListView, mPreviouslySelectedFingerprints ); -} - -void CertManager::slotContextMenu(Kleo::KeyListViewItem* item, const QPoint& point) { - if ( !item ) - return; - if ( QPopupMenu * popup = static_cast(factory()->container("listview_popup",this)) ) - popup->exec( point ); -} - -/** - This slot is invoked when the user selects "New certificate" -*/ -void CertManager::newCertificate() -{ - CertificateWizardImpl wizard( this ); - wizard.exec(); -} - -/** - This slot is invoked when the user selects revoke certificate. - The slot will revoke the selected certificates -*/ -void CertManager::revokeCertificate() -{ - qDebug("Not Yet Implemented"); -} - -/** - This slot is invoked when the user selects extend certificate. - It will send an extension request for the selected certificates -*/ -void CertManager::extendCertificate() -{ - qDebug("Not Yet Implemented"); -} - - -// -// -// Downloading / Importing Certificates -// -// - - -/** - This slot is invoked when the user selects Certificates/Import/From File. -*/ -void CertManager::slotImportCertFromFile() -{ - const QString filter = "application/x-x509-ca-cert application/x-pkcs12 application/pkcs7-mime"; - //const QString filter = QString("*.pem *.der *.p7c *.p12|") + i18n("Certificates (*.pem *.der *.p7c *.p12)"); - slotImportCertFromFile( KFileDialog::getOpenURL( QString::null, filter, this, - i18n( "Select Certificate File" ) ) ); -} - -void CertManager::slotImportCertFromFile( const KURL & certURL ) -{ - if ( !certURL.isValid() ) // empty or malformed - return; - - mPreviouslySelectedFingerprints.clear(); - - // Prevent two simultaneous imports - updateImportActions( false ); - - // Download the cert - KIOext::StoredTransferJob* importJob = KIOext::storedGet( certURL ); - importJob->setWindow( this ); - connect( importJob, SIGNAL(result(KIO::Job*)), SLOT(slotImportResult(KIO::Job*)) ); -} - -void CertManager::slotImportResult( KIO::Job* job ) -{ - if ( job->error() ) { - job->showErrorDialog(); - } else { - KIOext::StoredTransferJob* trJob = static_cast( job ); - startCertificateImport( trJob->data(), trJob->url().fileName() ); - } - - updateImportActions( true ); -} - -static void showCertificateDownloadError( QWidget * parent, const GpgME::Error & err, const QString& certDisplayName ) { - assert( err ); - const QString msg = i18n( "

An error occurred while trying " - "to download the certificate %1:

" - "

%2

" ) - .arg( certDisplayName ) - .arg( QString::fromLocal8Bit( err.asString() ) ); - - KMessageBox::error( parent, msg, i18n( "Certificate Download Failed" ) ); -} - -void CertManager::slotDownloadCertificate() { - mPreviouslySelectedFingerprints.clear(); - QPtrList items = mKeyListView->selectedItems(); - for ( QPtrListIterator it( items ) ; it.current() ; ++it ) - if ( !it.current()->key().isNull() ) - if ( const char * fpr = it.current()->key().primaryFingerprint() ) - slotStartCertificateDownload( fpr, it.current()->text(0) ); -} - -// Called from slotDownloadCertificate and from the certificate-details widget -void CertManager::slotStartCertificateDownload( const QString& fingerprint, const QString& displayName ) { - if ( fingerprint.isEmpty() ) - return; - - Kleo::DownloadJob * job = - Kleo::CryptoBackendFactory::instance()->smime()->downloadJob( false /* no armor */ ); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::Error&,const QByteArray&)), - SLOT(slotCertificateDownloadResult(const GpgME::Error&,const QByteArray&)) ); - - connectJobToStatusBarProgress( job, i18n("Fetching certificate from server...") ); - - const GpgME::Error err = job->start( fingerprint ); - if ( err ) - showCertificateDownloadError( this, err, displayName ); - else { - mProgressBar->setProgress( 0, 0 ); - mJobsDisplayNameMap.insert( job, displayName ); - } -} - -QString CertManager::displayNameForJob( const Kleo::Job *job ) -{ - JobsDisplayNameMap::iterator it = mJobsDisplayNameMap.find( job ); - QString displayName; - if ( it != mJobsDisplayNameMap.end() ) { - displayName = *it; - mJobsDisplayNameMap.remove( it ); - } else { - kdWarning() << "Job not found in map: " << job << endl; - } - return displayName; -} - -// Don't call directly! -void CertManager::slotCertificateDownloadResult( const GpgME::Error & err, const QByteArray & keyData ) { - - QString displayName = displayNameForJob( static_cast( sender() ) ); - - if ( err ) - showCertificateDownloadError( this, err, displayName ); - else - startCertificateImport( keyData, displayName ); - disconnectJobFromStatusBarProgress( err ); -} - -static void showCertificateImportError( QWidget * parent, const GpgME::Error & err, const QString& certDisplayName ) { - assert( err ); - const QString msg = i18n( "

An error occurred while trying " - "to import the certificate %1:

" - "

%2

" ) - .arg( certDisplayName ) - .arg( QString::fromLocal8Bit( err.asString() ) ); - KMessageBox::error( parent, msg, i18n( "Certificate Import Failed" ) ); -} - -void CertManager::startCertificateImport( const QByteArray & keyData, const QString& certDisplayName ) { - Kleo::ImportJob * job = Kleo::CryptoBackendFactory::instance()->smime()->importJob(); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::ImportResult&)), - SLOT(slotCertificateImportResult(const GpgME::ImportResult&)) ); - - connectJobToStatusBarProgress( job, i18n("Importing certificates...") ); - - kdDebug() << "Importing certificate. keyData size:" << keyData.size() << endl; - const GpgME::Error err = job->start( keyData ); - if ( err ) - showCertificateImportError( this, err, certDisplayName ); - else { - mProgressBar->setProgress( 0, 0 ); - mJobsDisplayNameMap.insert( job, certDisplayName ); - } -} - -void CertManager::slotCertificateImportResult( const GpgME::ImportResult & res ) { - QString displayName = displayNameForJob( static_cast( sender() ) ); - - if ( res.error().isCanceled() ) { - // do nothing - } else if ( res.error() ) { - showCertificateImportError( this, res.error(), displayName ); - } else { - - const QString normalLine = i18n("%1%2"); - const QString boldLine = i18n("%1%2"); - - QStringList lines; - lines.push_back( normalLine.arg( i18n("Total number processed:"), - QString::number( res.numConsidered() ) ) ); - lines.push_back( normalLine.arg( i18n("Imported:"), - QString::number( res.numImported() ) ) ); - if ( res.newSignatures() ) - lines.push_back( normalLine.arg( i18n("New signatures:"), - QString::number( res.newSignatures() ) ) ); - if ( res.newUserIDs() ) - lines.push_back( normalLine.arg( i18n("New user IDs:"), - QString::number( res.newUserIDs() ) ) ); - if ( res.numKeysWithoutUserID() ) - lines.push_back( normalLine.arg( i18n("Keys without user IDs:"), - QString::number( res.numKeysWithoutUserID() ) ) ); - if ( res.newSubkeys() ) - lines.push_back( normalLine.arg( i18n("New subkeys:"), - QString::number( res.newSubkeys() ) ) ); - if ( res.newRevocations() ) - lines.push_back( boldLine.arg( i18n("Newly revoked:"), - QString::number( res.newRevocations() ) ) ); - if ( res.notImported() ) - lines.push_back( boldLine.arg( i18n("Not imported:"), - QString::number( res.notImported() ) ) ); - if ( res.numUnchanged() ) - lines.push_back( normalLine.arg( i18n("Unchanged:"), - QString::number( res.numUnchanged() ) ) ); - if ( res.numSecretKeysConsidered() ) - lines.push_back( normalLine.arg( i18n("Secret keys processed:"), - QString::number( res.numSecretKeysConsidered() ) ) ); - if ( res.numSecretKeysImported() ) - lines.push_back( normalLine.arg( i18n("Secret keys imported:"), - QString::number( res.numSecretKeysImported() ) ) ); - if ( res.numSecretKeysConsidered() - res.numSecretKeysImported() - res.numSecretKeysUnchanged() > 0 ) - lines.push_back( boldLine.arg( i18n("Secret keys not imported:"), - QString::number( res.numSecretKeysConsidered() - - res.numSecretKeysImported() - - res.numSecretKeysUnchanged() ) ) ); - if ( res.numSecretKeysUnchanged() ) - lines.push_back( normalLine.arg( i18n("Secret keys unchanged:"), - QString::number( res.numSecretKeysUnchanged() ) ) ); - - KMessageBox::information( this, - i18n( "

Detailed results of importing %1:

" - "%2
" ) - .arg( displayName ).arg( lines.join( QString::null ) ), - i18n( "Certificate Import Result" ) ); - - disconnectJobFromStatusBarProgress( res.error() ); - // save the fingerprints of imported certs for later selection: - const std::vector imports = res.imports(); - for ( std::vector::const_iterator it = imports.begin() ; it != imports.end() ; ++it ) - mPreviouslySelectedFingerprints.insert( it->fingerprint() ); - } - importNextURLOrRedisplay(); -} - - - -/** - This slot is called when the dirmngr process that imports a - certificate file exists. -*/ -void CertManager::slotDirmngrExited() { - if ( !mDirmngrProc->normalExit() ) - KMessageBox::error( this, i18n( "The GpgSM process that tried to import the CRL file ended prematurely because of an unexpected error." ), i18n( "Certificate Manager Error" ) ); - else if ( mDirmngrProc->exitStatus() ) - KMessageBox::error( this, i18n( "An error occurred when trying to import the CRL file. The output from GpgSM was:\n%1").arg( mErrorbuffer ), i18n( "Certificate Manager Error" ) ); - else - KMessageBox::information( this, i18n( "CRL file imported successfully." ), i18n( "Certificate Manager Information" ) ); - - delete mDirmngrProc; mDirmngrProc = 0; - if ( !mImportCRLTempFile.isEmpty() ) - QFile::remove( mImportCRLTempFile ); - updateImportActions( true ); -} - -/** - This slot will import CRLs from a file. -*/ -void CertManager::importCRLFromFile() { - QString filter = QString("*.crl *.arl *-crl.der *-arl.der|") + i18n("Certificate Revocation List (*.crl *.arl *-crl.der *-arl.der)"); - KURL url = KFileDialog::getOpenURL( QString::null, - filter, - this, - i18n( "Select CRL File" ) ); - if ( url.isValid() ) { - updateImportActions( false ); - if ( url.isLocalFile() ) { - startImportCRL( url.path(), false ); - updateImportActions( true ); - } else { - KTempFile tempFile; - KURL destURL; - destURL.setPath( tempFile.name() ); - KIO::Job* copyJob = KIO::file_copy( url, destURL, 0600, true, false ); - copyJob->setWindow( this ); - connect( copyJob, SIGNAL( result( KIO::Job * ) ), - SLOT( slotImportCRLJobFinished( KIO::Job * ) ) ); - } - } -} - -void CertManager::slotImportCRLJobFinished( KIO::Job *job ) -{ - KIO::FileCopyJob* fcjob = static_cast( job ); - QString tempFilePath = fcjob->destURL().path(); - if ( job->error() ) { - job->showErrorDialog(); - QFile::remove( tempFilePath ); // unlink tempfile - updateImportActions( true ); - return; - } - startImportCRL( tempFilePath, true ); -} - -bool CertManager::connectAndStartDirmngr( const char * slot, const char * processname ) { - assert( slot ); - assert( processname ); - assert( mDirmngrProc ); - mErrorbuffer = QString::null; - connect( mDirmngrProc, SIGNAL(processExited(KProcess*)), slot ); - connect( mDirmngrProc, SIGNAL(receivedStderr(KProcess*,char*,int) ), - this, SLOT(slotStderr(KProcess*,char*,int)) ); - if( !mDirmngrProc->start( KProcess::NotifyOnExit, KProcess::Stderr ) ) { - delete mDirmngrProc; mDirmngrProc = 0; - KMessageBox::error( this, i18n( "Unable to start %1 process. Please check your installation." ).arg( processname ), i18n( "Certificate Manager Error" ) ); - return false; - } - return true; -} - -void CertManager::startImportCRL( const QString& filename, bool isTempFile ) -{ - assert( !mDirmngrProc ); - mImportCRLTempFile = isTempFile ? filename : QString::null; - mDirmngrProc = new KProcess(); - *mDirmngrProc << "gpgsm" << "--call-dirmngr" << "loadcrl" << filename; - if ( !connectAndStartDirmngr( SLOT(slotDirmngrExited()), "gpgsm" ) ) { - updateImportActions( true ); - if ( isTempFile ) - QFile::remove( mImportCRLTempFile ); // unlink tempfile - } -} - -void CertManager::startClearCRLs() { - assert( !mDirmngrProc ); - mDirmngrProc = new KProcess(); - *mDirmngrProc << "dirmngr" << "--flush"; - //*mDirmngrProc << "gpgsm" << "--call-dimngr" << "flush"; // use this once it's implemented! - connectAndStartDirmngr( SLOT(slotClearCRLsResult()), "dirmngr" ); -} - -void CertManager::slotStderr( KProcess*, char* buf, int len ) { - mErrorbuffer += QString::fromLocal8Bit( buf, len ); -} - -/** - This slot will import CRLs from an LDAP server. -*/ -void CertManager::importCRLFromLDAP() -{ - qDebug("Not Yet Implemented"); -} - -void CertManager::slotViewCRLs() { - if ( !mCrlView ) - mCrlView = new CRLView( this ); - - mCrlView->show(); - mCrlView->slotUpdateView(); -} - - -void CertManager::slotClearCRLs() { - startClearCRLs(); -} - -void CertManager::slotClearCRLsResult() { - assert( mDirmngrProc ); - if ( !mDirmngrProc->normalExit() ) - KMessageBox::error( this, i18n( "The DirMngr process that tried to clear the CRL cache ended prematurely because of an unexpected error." ), i18n( "Certificate Manager Error" ) ); - else if ( mDirmngrProc->exitStatus() ) - KMessageBox::error( this, i18n( "An error occurred when trying to clear the CRL cache. The output from DirMngr was:\n%1").arg( mErrorbuffer ), i18n( "Certificate Manager Error" ) ); - else - KMessageBox::information( this, i18n( "CRL cache cleared successfully." ), i18n( "Certificate Manager Information" ) ); - delete mDirmngrProc; mDirmngrProc = 0; -} - -static void showDeleteError( QWidget * parent, const GpgME::Error & err ) { - assert( err ); - const QString msg = i18n("

An error occurred while trying to delete " - "the certificates:

" - "

%1

") - .arg( QString::fromLocal8Bit( err.asString() ) ); - KMessageBox::error( parent, msg, i18n("Certificate Deletion Failed") ); -} - -static bool ByFingerprint( const GpgME::Key & left, const GpgME::Key & right ) { - return qstricmp( left.primaryFingerprint(), right.primaryFingerprint() ) < 0 ; -} - -static bool WithRespectToFingerprints( const GpgME::Key & left, const GpgME::Key & right ) { - return qstricmp( left.primaryFingerprint(), right.primaryFingerprint() ) == 0; -} - -void CertManager::slotDeleteCertificate() { - mItemsToDelete = mKeyListView->selectedItems(); - if ( mItemsToDelete.isEmpty() ) - return; - std::vector keys; - keys.reserve( mItemsToDelete.count() ); - QStringList keyDisplayNames; - for ( QPtrListIterator it( mItemsToDelete ) ; it.current() ; ++it ) - if ( !it.current()->key().isNull() ) { - keys.push_back( it.current()->key() ); - keyDisplayNames.push_back( it.current()->text( 0 ) ); - } - if ( keys.empty() ) - return; - - if ( !mHierarchyAnalyser ) { - mHierarchyAnalyser = new HierarchyAnalyser( this, "mHierarchyAnalyser" ); - Kleo::KeyListJob * job = Kleo::CryptoBackendFactory::instance()->smime()->keyListJob(); - assert( job ); - connect( job, SIGNAL(nextKey(const GpgME::Key&)), - mHierarchyAnalyser, SLOT(slotNextKey(const GpgME::Key&)) ); - connect( job, SIGNAL(result(const GpgME::KeyListResult&)), - this, SLOT(slotDeleteCertificate()) ); - connectJobToStatusBarProgress( job, i18n("Checking key dependencies...") ); - if ( const GpgME::Error error = job->start( QStringList() ) ) { - showKeyListError( this, error ); - delete mHierarchyAnalyser; mHierarchyAnalyser = 0; - } - return; - } else - disconnectJobFromStatusBarProgress( 0 ); - - std::vector keysToDelete = keys; - for ( std::vector::const_iterator it = keys.begin() ; it != keys.end() ; ++it ) - if ( !it->isNull() ) { - const std::vector subjects - = mHierarchyAnalyser->subjectsForIssuerRecursive( it->primaryFingerprint() ); - keysToDelete.insert( keysToDelete.end(), subjects.begin(), subjects.end() ); - } - - std::sort( keysToDelete.begin(), keysToDelete.end(), ByFingerprint ); - keysToDelete.erase( std::unique( keysToDelete.begin(), keysToDelete.end(), - WithRespectToFingerprints ), - keysToDelete.end() ); - - delete mHierarchyAnalyser; mHierarchyAnalyser = 0; - - if ( keysToDelete.size() > keys.size() ) - if ( KMessageBox::warningContinueCancel( this, - i18n("Some or all of the selected " - "certificates are issuers (CA certificates) " - "for other, non-selected certificates.\n" - "Deleting a CA certificate will also delete " - "all certificates issued by it."), - i18n("Deleting CA Certificates") ) - != KMessageBox::Continue ) - return; - - const QString msg = keysToDelete.size() > keys.size() - ? i18n("Do you really want to delete this certificate and the %1 certificates it certified?", - "Do you really want to delete these %n certificates and the %1 certificates they certified?", - keys.size() ).arg( keysToDelete.size() - keys.size() ) - : i18n("Do you really want to delete this certificate?", - "Do you really want to delete these %n certificates?", keys.size() ) ; - - if ( KMessageBox::warningContinueCancelList( this, msg, keyDisplayNames, - i18n( "Delete Certificates" ), - KGuiItem( i18n( "Delete" ), "editdelete" ), - "ConfirmDeleteCert", KMessageBox::Dangerous ) - != KMessageBox::Continue ) - return; - - if ( Kleo::DeleteJob * job = Kleo::CryptoBackendFactory::instance()->smime()->deleteJob() ) - job->slotCancel(); - else { - QString str = keys.size() == 1 - ? i18n("

An error occurred while trying to delete " - "the certificate:

" - "

%1

" ) - : i18n( "

An error occurred while trying to delete " - "the certificates:

" - "

%1

" ); - KMessageBox::error( this, - str.arg( i18n("Operation not supported by the backend.") ), - i18n("Certificate Deletion Failed") ); - } - - mItemsToDelete.clear(); // re-create according to the real selection - for ( std::vector::const_iterator it = keysToDelete.begin() ; it != keysToDelete.end() ; ++it ) - if ( Kleo::KeyListViewItem * item = mKeyListView->itemByFingerprint( it->primaryFingerprint() ) ) - mItemsToDelete.append( item ); - - Kleo::MultiDeleteJob * job = new Kleo::MultiDeleteJob( Kleo::CryptoBackendFactory::instance()->smime() ); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::Error&,const GpgME::Key&)), - SLOT(slotDeleteResult(const GpgME::Error&,const GpgME::Key&)) ); - - connectJobToStatusBarProgress( job, i18n("Deleting keys...") ); - - const GpgME::Error err = job->start( keys, true ); - if ( err ) - showDeleteError( this, err ); - else - mProgressBar->setProgress( 0, 0 ); -} - -void CertManager::slotDeleteResult( const GpgME::Error & err, const GpgME::Key & ) { - if ( err ) - showDeleteError( this, err ); - else { - const int infinity = 100; // infinite loop guard... - mItemsToDelete.setAutoDelete( true ); - for ( int i = 0 ; i < infinity ; ++i ) { - QPtrListIterator it( mItemsToDelete ); - while ( Kleo::KeyListViewItem * cur = it.current() ) { - ++it; - if ( cur->childCount() == 0 ) { - mItemsToDelete.remove( cur ); - } - } - if ( mItemsToDelete.isEmpty() ) - break; - } - mItemsToDelete.setAutoDelete( false ); - Q_ASSERT( mItemsToDelete.isEmpty() ); - mItemsToDelete.clear(); - } - disconnectJobFromStatusBarProgress( err ); -} - -void CertManager::slotViewDetails( Kleo::KeyListViewItem * item ) { - if ( !item || item->key().isNull() ) - return; - - // - KDialogBase * dialog = new KDialogBase( this, "dialog", false, i18n("Additional Information for Key"), KDialogBase::Close, KDialogBase::Close ); - - CertificateInfoWidgetImpl * top = new CertificateInfoWidgetImpl( item->key(), isRemote(), dialog ); - dialog->setMainWidget( top ); - // - connect( top, SIGNAL(requestCertificateDownload(const QString&, const QString&)), - SLOT(slotStartCertificateDownload(const QString&, const QString&)) ); - dialog->show(); -} - -void CertManager::slotViewDetails() -{ - QPtrList items = mKeyListView->selectedItems(); - if ( items.isEmpty() ) - return; - - // selectedItem() doesn't work in Extended mode. - // But we only want to show the details of one item... - slotViewDetails( items.first() ); -} - -void CertManager::slotSelectionChanged() -{ - mKeyListView->flushKeys(); - bool b = mKeyListView->hasSelection(); - mExportCertificateAction->setEnabled( b ); - mViewCertDetailsAction->setEnabled( b ); - mDeleteCertificateAction->setEnabled( b ); -#ifdef NOT_IMPLEMENTED_ANYWAY - mRevokeCertificateAction->setEnabled( b ); - mExtendCertificateAction->setEnabled( b ); -#endif - mDownloadCertificateAction->setEnabled( b && mRemote ); - mValidateCertificateAction->setEnabled( !mRemote ); -} - -void CertManager::slotExportCertificate() { - QPtrList items = mKeyListView->selectedItems(); - if ( items.isEmpty() ) - return; - - QStringList fingerprints; - for ( QPtrListIterator it( items ) ; it.current() ; ++it ) - if ( !it.current()->key().isNull() ) - if ( const char * fpr = it.current()->key().primaryFingerprint() ) - fingerprints.push_back( fpr ); - - startCertificateExport( fingerprints ); -} - -static void showCertificateExportError( QWidget * parent, const GpgME::Error & err ) { - assert( err ); - const QString msg = i18n("

An error occurred while trying to export " - "the certificate:

" - "

%1

") - .arg( QString::fromLocal8Bit( err.asString() ) ); - KMessageBox::error( parent, msg, i18n("Certificate Export Failed") ); -} - -void CertManager::startCertificateExport( const QStringList & fingerprints ) { - if ( fingerprints.empty() ) - return; - - // we need to use PEM (ascii armoured) format, since DER (binary) - // can't transport more than one certificate *sigh* this is madness :/ - Kleo::ExportJob * job = Kleo::CryptoBackendFactory::instance()->smime()->publicKeyExportJob( true ); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::Error&,const QByteArray&)), - SLOT(slotCertificateExportResult(const GpgME::Error&,const QByteArray&)) ); - - connectJobToStatusBarProgress( job, i18n("Exporting certificate...") ); - - const GpgME::Error err = job->start( fingerprints ); - if ( err ) - showCertificateExportError( this, err ); - else - mProgressBar->setProgress( 0, 0 ); -} - -// return true if we should proceed, false if we should abort -static bool checkOverwrite( const KURL& url, bool& overwrite, QWidget* w ) -{ - if ( KIO::NetAccess::exists( url, false /*dest*/, w ) ) { - if ( KMessageBox::Cancel == - KMessageBox::warningContinueCancel( - w, - i18n( "A file named \"%1\" already exists. " - "Are you sure you want to overwrite it?" ).arg( url.prettyURL() ), - i18n( "Overwrite File?" ), - i18n( "&Overwrite" ) ) ) - return false; - overwrite = true; - } - return true; -} - -void CertManager::slotCertificateExportResult( const GpgME::Error & err, const QByteArray & data ) { - disconnectJobFromStatusBarProgress( err ); - if ( err ) { - showCertificateExportError( this, err ); - return; - } - - kdDebug() << "CertManager::slotCertificateExportResult(): got " << data.size() << " bytes" << endl; - - const QString filter = QString("*.pem|") + i18n("ASCII Armored Certificate Bundles (*.pem)"); - const KURL url = KFileDialog::getOpenURL( QString::null, - filter, - this, - i18n( "Save Certificate" ) ); - if ( !url.isValid() ) - return; - - bool overwrite = false; - if ( !checkOverwrite( url, overwrite, this ) ) - return; - - KIO::Job* uploadJob = KIOext::put( data, url, -1, overwrite, false /*resume*/ ); - uploadJob->setWindow( this ); - connect( uploadJob, SIGNAL( result( KIO::Job* ) ), - this, SLOT( slotUploadResult( KIO::Job* ) ) ); -} - - -void CertManager::slotExportSecretKey() { - Kleo::KeySelectionDialog dlg( i18n("Secret Key Export"), - i18n("Select the secret key to export " - "(Warning: The PKCS#12 format is insecure; " - "exporting secret keys is discouraged):"), - std::vector(), - Kleo::KeySelectionDialog::SecretKeys|Kleo::KeySelectionDialog::SMIMEKeys, - false /* no multiple selection */, - false /* no remember choice box */, - this, "secret key export key selection dialog" ); - //dlg.setHideInvalidKeys( false ); - - if ( dlg.exec() != QDialog::Accepted ) - return; - - startSecretKeyExport( dlg.fingerprint() ); -} - -static void showSecretKeyExportError( QWidget * parent, const GpgME::Error & err ) { - assert( err ); - const QString msg = i18n("

An error occurred while trying to export " - "the secret key:

" - "

%1

") - .arg( QString::fromLocal8Bit( err.asString() ) ); - KMessageBox::error( parent, msg, i18n("Secret-Key Export Failed") ); -} - -void CertManager::startSecretKeyExport( const QString & fingerprint ) { - if ( fingerprint.isEmpty() ) - return; - - // PENDING(marc): let user choose between binary and PEM format? - Kleo::ExportJob * job = Kleo::CryptoBackendFactory::instance()->smime()->secretKeyExportJob( false ); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::Error&,const QByteArray&)), - SLOT(slotSecretKeyExportResult(const GpgME::Error&,const QByteArray&)) ); - - connectJobToStatusBarProgress( job, i18n("Exporting secret key...") ); - - const GpgME::Error err = job->start( fingerprint ); - if ( err ) - showSecretKeyExportError( this, err ); - else - mProgressBar->setProgress( 0, 0 ); -} - -void CertManager::slotSecretKeyExportResult( const GpgME::Error & err, const QByteArray & data ) { - disconnectJobFromStatusBarProgress( err ); - if ( err ) { - showSecretKeyExportError( this, err ); - return; - } - - kdDebug() << "CertManager::slotSecretKeyExportResult(): got " << data.size() << " bytes" << endl; - QString filter = QString("*.p12|") + i18n("PKCS#12 Key Bundle (*.p12)"); - KURL url = KFileDialog::getOpenURL( QString::null, - filter, - this, - i18n( "Save Certificate" ) ); - if ( !url.isValid() ) - return; - - bool overwrite = false; - if ( !checkOverwrite( url, overwrite, this ) ) - return; - - KIO::Job* uploadJob = KIOext::put( data, url, -1, overwrite, false /*resume*/ ); - uploadJob->setWindow( this ); - connect( uploadJob, SIGNAL( result( KIO::Job* ) ), - this, SLOT( slotUploadResult( KIO::Job* ) ) ); -} - -void CertManager::slotUploadResult( KIO::Job* job ) -{ - if ( job->error() ) - job->showErrorDialog(); -} - -void CertManager::slotDropped(const KURL::List& lst) -{ - mURLsToImport = lst; - if ( !lst.empty() ) - importNextURLOrRedisplay(); -} - -void CertManager::importNextURLOrRedisplay() -{ - if ( !mURLsToImport.empty() ) { - // We can only import them one by one, otherwise the jobs would run into each other - KURL url = mURLsToImport.front(); - mURLsToImport.pop_front(); - slotImportCertFromFile( url ); - } else { - if ( isRemote() ) - return; - startKeyListing( false, true, mPreviouslySelectedFingerprints ); - } -} - -void CertManager::slotStartWatchGnuPG() -{ - KProcess certManagerProc; - certManagerProc << "kwatchgnupg"; - - if( !certManagerProc.start( KProcess::DontCare ) ) - KMessageBox::error( this, i18n( "Could not start GnuPG LogViewer (kwatchgnupg). " - "Please check your installation!" ), - i18n( "Kleopatra Error" ) ); -} - -#include "certmanager.moc" diff --git a/kleopatra/certmanager.h b/kleopatra/certmanager.h deleted file mode 100644 index 50e87712fc..0000000000 --- a/kleopatra/certmanager.h +++ /dev/null @@ -1,216 +0,0 @@ -/* -*- mode: c++; c-basic-offset:4 -*- - certmanager.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef _CERTMANAGER_H_ -#define _CERTMANAGER_H_ - -//#include - -#include -#include -#include -#include -#include - -#include -#include - -namespace Kleo { - class KeyListView; - class KeyListViewItem; - class ProgressBar; - class Job; -} - -namespace KIO { - class Job; -} -class KProcess; -class KToolBar; -class KAction; - -class CRLView; -class HierarchyAnalyser; - -class LineEditAction; -class ComboAction; - -class KURL; -class QFile; -class QStringList; -class QLabel; - -namespace GpgME { - class ImportResult; - class KeyListResult; - class Error; - class Key; -} - -class KDE_EXPORT CertManager : public KMainWindow { - Q_OBJECT -public: - CertManager( bool remote = false, const QString& query = QString::null, - const QString& import=QString::null, - QWidget * parent=0, const char * name=0, WFlags f=0 ); - ~CertManager(); - - bool isRemote() const { return mRemote; } - -signals: - void stopOperations(); - void enableOperations( bool ); - -private slots: - void slotStartCertificateDownload( const QString & fingerprint, const QString& displayName ); - void newCertificate(); - void revokeCertificate(); - void extendCertificate(); - void slotDeleteCertificate(); - void slotExportSecretKey(); - void slotExportCertificate(); - void slotUploadResult( KIO::Job* job ); - - void slotImportCertFromFile(); - void slotImportCertFromFile( const KURL & filename ); - void slotImportResult( KIO::Job* ); - - void slotCertificateImportResult( const GpgME::ImportResult & result ); - void slotCertificateDownloadResult( const GpgME::Error & error, const QByteArray & keyData ); - void slotKeyListResult( const GpgME::KeyListResult & result ); - void slotDeleteResult( const GpgME::Error & error, const GpgME::Key & ); - void slotSecretKeyExportResult( const GpgME::Error & error, const QByteArray & keyData ); - void slotCertificateExportResult( const GpgME::Error & error, const QByteArray & keyData ); - void slotClearCRLsResult(); - - void importCRLFromFile(); - void importCRLFromLDAP(); - void slotImportCRLJobFinished( KIO::Job * ); - - void slotDirmngrExited(); - void slotStderr( KProcess*, char*, int ); - - void slotToggleRemote(int idx); - void slotToggleHierarchicalView( bool ); - - void slotViewCRLs(); - void slotClearCRLs(); - - void slotViewDetails(); - void slotViewDetails( Kleo::KeyListViewItem * item ); - void slotSelectionChanged(); - void slotDownloadCertificate(); - void slotStartWatchGnuPG(); - - void slotEditKeybindings(); - void slotShowConfigurationDialog(); - void slotConfigureGpgME(); - void slotContextMenu(Kleo::KeyListViewItem*, const QPoint& point); - void slotDropped(const KURL::List&); - /** Schedule a repaint for the listview items. E.g. when the - colour config has changed */ - void slotRepaint(); - /** Schedule a validating keylisting for the selected items (or - all items, if none is selected). */ - void slotValidate() { startRedisplay( true ); } - /** Schedule a non-validating keylisting for the selected items - (or all items, if none are selected). */ - void slotRedisplay() { startRedisplay( false ); } - /** Start a keylisting with the current value of the query text as - pattern. */ - void slotSearch(); - - void slotExpandAll(); - void slotCollapseAll(); - void slotRefreshKeys(); - void slotRefreshKeysResult( const GpgME::Error & ); - -private: - void createStatusBar(); - void createActions(); - void updateStatusBarLabels(); - void updateImportActions( bool enable ); - void startKeyListing( bool, bool, const QStringList & ); - void startKeyListing( bool, bool, const std::set & ); - void startCertificateImport( const QByteArray & keyData, const QString& certDisplayName ); - void startImportCRL( const QString& fileName, bool isTempFile ); - void startClearCRLs(); - void startSecretKeyExport( const QString & fingerprint ); - void startCertificateExport( const QStringList & fingerprints ); - bool connectAndStartDirmngr( const char*, const char* ); - void connectJobToStatusBarProgress( Kleo::Job * job, const QString & initialText ); - void disconnectJobFromStatusBarProgress( const GpgME::Error & err ); - void importNextURLOrRedisplay(); - void startRedisplay( bool validating ); - QString displayNameForJob( const Kleo::Job *job ); - void readConfig(); - void writeConfig(); - -private: - Kleo::KeyListView * mKeyListView; - CRLView * mCrlView; - Kleo::ProgressBar * mProgressBar; - QLabel * mStatusLabel; - - KProcess * mDirmngrProc; - QString mErrorbuffer; - QPtrList mItemsToDelete; - KURL::List mURLsToImport; - typedef QMap JobsDisplayNameMap; - JobsDisplayNameMap mJobsDisplayNameMap; - HierarchyAnalyser * mHierarchyAnalyser; - - LineEditAction * mLineEditAction; - ComboAction * mComboAction; - KAction * mFindAction; - KAction * mImportCertFromFileAction; - KAction * mImportCRLFromFileAction; - KAction * mExportCertificateAction; - KAction * mViewCertDetailsAction; - KAction * mDeleteCertificateAction; -#ifdef NOT_IMPLEMENTED_ANYWAY - KAction * mRevokeCertificateAction; - KAction * mExtendCertificateAction; -#endif - KAction * mExportSecretKeyAction; - KAction * mDownloadCertificateAction; - KAction * mValidateCertificateAction; - - QString mImportCRLTempFile; - QString mCurrentQuery; - std::set mPreviouslySelectedFingerprints; - bool mNextFindRemote : 1; // state of the combo, i.e. whether the next find action will be remote - bool mRemote : 1; // whether the currently displayed items are from a remote listing - bool mDirMngrFound : 1; -}; - -#endif // _CERTMANAGER_H_ diff --git a/kleopatra/conf/appearanceconfigpage.cpp b/kleopatra/conf/appearanceconfigpage.cpp deleted file mode 100644 index 5d2a434cc3..0000000000 --- a/kleopatra/conf/appearanceconfigpage.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - appearanceconfigpage.cpp - - This file is part of kleopatra, the KDE key manager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "appearanceconfigpage.h" -#include -#include "appearanceconfigwidget.h" -#include -#include -#include - -#include - -AppearanceConfigurationPage::AppearanceConfigurationPage( QWidget * parent, const char * name ) - : KCModule( parent, name ) -{ - QVBoxLayout* lay = new QVBoxLayout( this ); - mWidget = new Kleo::AppearanceConfigWidget( this ); - lay->addWidget( mWidget ); - connect( mWidget, SIGNAL( changed() ), this, SLOT( slotChanged() ) ); - -#ifndef HAVE_UNBROKEN_KCMULTIDIALOG - load(); -#endif -} - - -void AppearanceConfigurationPage::load() -{ - mWidget->load(); -} - -void AppearanceConfigurationPage::save() -{ - mWidget->save(); - -} - -void AppearanceConfigurationPage::defaults() -{ - mWidget->defaults(); -} - -extern "C" -{ - KDE_EXPORT KCModule *create_kleopatra_config_appear( QWidget *parent, const char * ) - { - AppearanceConfigurationPage *page = - new AppearanceConfigurationPage( parent, "kleopatra_config_appear" ); - return page; - } -} - -// kdelibs-3.2 didn't have the changed signal in KCModule... -void AppearanceConfigurationPage::slotChanged() -{ - emit changed(true); -} - -#include "appearanceconfigpage.moc" diff --git a/kleopatra/conf/appearanceconfigpage.h b/kleopatra/conf/appearanceconfigpage.h deleted file mode 100644 index c3acea0079..0000000000 --- a/kleopatra/conf/appearanceconfigpage.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - appearanceconfigpage.h - - This file is part of kleopatra, the KDE key manager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef _APPEARANCE_CONFIGURE_PAGE_H_ -#define _APPEARANCE_CONFIGURE_PAGE_H_ - -#include - -namespace Kleo { - class AppearanceConfigWidget; -} - -/** - * "Appearance" configuration page for kleopatra's configuration dialog - */ -class AppearanceConfigurationPage : public KCModule { - Q_OBJECT -public: - AppearanceConfigurationPage( QWidget * parent=0, const char * name=0 ); - - virtual void load(); - virtual void save(); - virtual void defaults(); - -private slots: - void slotChanged(); - -private: - Kleo::AppearanceConfigWidget* mWidget; -}; - -#endif // _APPEARANCE_CONFIGURE_DIALOG_PRIVATE_H_ diff --git a/kleopatra/conf/appearanceconfigwidget.cpp b/kleopatra/conf/appearanceconfigwidget.cpp deleted file mode 100644 index a3d177c2ae..0000000000 --- a/kleopatra/conf/appearanceconfigwidget.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/* - appearanceconfigwidget.cpp - - This file is part of kleopatra, the KDE key manager - Copyright (c) 2002,2004 Klarlvdalens Datakonsult AB - Copyright (c) 2002,2003 Marc Mutz - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "appearanceconfigwidget.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace Kleo; - -class CategoryListViewItem : public QListViewItem -{ -public: - CategoryListViewItem( QListView* lv, QListViewItem* prev, const KConfigBase& config ) - : QListViewItem( lv, prev ) { - - setName( config.readEntry( "Name", i18n("") ) ); - mForegroundColor = config.readColorEntry( "foreground-color" ); - mBackgroundColor = config.readColorEntry( "background-color" ); - mHasFont = config.hasKey( "font" ); - if ( mHasFont ) { - setFont( config.readFontEntry( "font" ) ); // sets mItalic and mBold - } - else { - mItalic = config.readBoolEntry( "font-italic", false ); - mBold = config.readBoolEntry( "font-bold", false ); - } - mStrikeOut = config.readBoolEntry( "font-strikeout", false ); - mIsExpired = config.readBoolEntry( "is-expired", false ); - mDirty = false; - } - - void save( KConfigBase& config ) { - config.writeEntry( "Name", text( 0 ) ); - config.writeEntry( "foreground-color", mForegroundColor ); - config.writeEntry( "background-color", mBackgroundColor ); - if ( mHasFont ) - config.writeEntry( "font", mFont ); - else { - config.deleteEntry( "font" ); - config.writeEntry( "font-italic", mItalic ); - config.writeEntry( "font-bold", mBold ); - } - config.writeEntry( "font-strikeout", mStrikeOut ); - } - - void setForegroundColor( const QColor& foreground ) { mForegroundColor = foreground; mDirty = true; } - void setBackgroundColor( const QColor& background ) { mBackgroundColor = background; mDirty = true; } - void setFont( const QFont& font ) { - mFont = font; - mHasFont = true; - mItalic = font.italic(); - mBold = font.bold(); - mDirty = true; - } - - QColor foregroundColor() const { return mForegroundColor; } - QColor backgroundColor() const { return mBackgroundColor; } - QFont font() const { return mFont; } - - void setDefaultAppearance() { - mForegroundColor = mIsExpired ? Qt::red : QColor(); - mBackgroundColor = QColor(); - mHasFont = false; - mFont = QFont(); - mBold = false; - mItalic = false; - mStrikeOut = false; - mDirty = true; - } - - bool isDirty() const { return mDirty; } - bool isItalic() const { return mItalic; } - bool isBold() const { return mBold; } - bool isStrikeout() const { return mStrikeOut; } - bool hasFont() const { return mHasFont; } - - void toggleItalic() { mItalic = !mItalic; if ( mHasFont ) mFont.setItalic( mItalic ); mDirty = true; } - void toggleBold() { mBold = !mBold; if ( mHasFont ) mFont.setBold( mBold ); mDirty = true; } - void toggleStrikeout() { mStrikeOut = !mStrikeOut; mDirty = true; } - -private: - void setName( const QString& name ) { - setText( 0, name ); - } - - void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); - -private: - QColor mForegroundColor, mBackgroundColor; - QFont mFont; - bool mHasFont; - bool mIsExpired; // used for default settings - bool mItalic; - bool mBold; - bool mStrikeOut; - bool mDirty; -}; - -void CategoryListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { - QColorGroup _cg = cg; - QFont font = p->font(); - if ( mHasFont ) - font = mFont; - else { - if ( mItalic ) - font.setItalic( true ); - if ( mBold ) - font.setBold( true ); - } - if ( mStrikeOut ) - font.setStrikeOut( true ); - p->setFont( font ); - - if ( mForegroundColor.isValid() ) - _cg.setColor( QColorGroup::Text, mForegroundColor ); - if ( mBackgroundColor.isValid() ) - _cg.setColor( QColorGroup::Base, mBackgroundColor ); - - QListViewItem::paintCell( p, _cg, column, width, alignment ); -} - -//// - -Kleo::AppearanceConfigWidget::AppearanceConfigWidget ( - QWidget* parent, const char* name, WFlags fl ) - : AppearanceConfigWidgetBase( parent, name, fl ) -{ - categoriesLV->setSorting( -1 ); - load(); -} - - -/* - * Destroys the object and frees any allocated resources - */ - -AppearanceConfigWidget::~AppearanceConfigWidget() -{ - // no need to delete child widgets, Qt does it all for us -} - - -void AppearanceConfigWidget::slotSelectionChanged( QListViewItem* item ) -{ - bool sel = item != 0; - foregroundButton->setEnabled( sel ); - backgroundButton->setEnabled( sel ); - fontButton->setEnabled( sel ); - italicCB->setEnabled( item ); - boldCB->setEnabled( item ); - strikeoutCB->setEnabled( item ); - defaultLookPB->setEnabled( sel ); - if ( item ) { - CategoryListViewItem* clvi = static_cast( item ); - italicCB->setChecked( clvi->isItalic() ); - boldCB->setChecked( clvi->isBold() ); - strikeoutCB->setChecked( clvi->isStrikeout() ); - } else { - italicCB->setChecked( false ); - boldCB->setChecked( false ); - strikeoutCB->setChecked( false ); - } -} - -/* - * set default appearance for selected category - */ -void AppearanceConfigWidget::slotDefaultClicked() -{ - CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); - if ( !item ) - return; - item->setDefaultAppearance(); - item->repaint(); - slotSelectionChanged( item ); - emit changed(); -} - -void AppearanceConfigWidget::load() -{ - categoriesLV->clear(); - KConfig * config = Kleo::CryptoBackendFactory::instance()->configObject(); - if ( !config ) - return; - QStringList groups = config->groupList().grep( QRegExp( "^Key Filter #\\d+$" ) ); - for ( QStringList::const_iterator it = groups.begin() ; it != groups.end() ; ++it ) { - KConfigGroup cfg( config, *it ); - (void) new CategoryListViewItem( categoriesLV, categoriesLV->lastItem(), cfg ); - } -} - -void AppearanceConfigWidget::save() -{ - KConfig * config = Kleo::CryptoBackendFactory::instance()->configObject(); - if ( !config ) - return; - // We know (assume) that the groups in the config object haven't changed, - // so we just iterate over them and over the listviewitems, and map one-to-one. - QStringList groups = config->groupList().grep( QRegExp( "^Key Filter #\\d+$" ) ); - if ( groups.isEmpty() ) { - // If we created the default categories ourselves just now, then we need to make up their list - QListViewItemIterator lvit( categoriesLV ); - for ( ; lvit.current() ; ++lvit ) - groups << lvit.current()->text( 0 ); - } - - QListViewItemIterator lvit( categoriesLV ); - for ( QStringList::const_iterator it = groups.begin() ; it != groups.end() && lvit.current(); ++it, ++lvit ) { - CategoryListViewItem* item = static_cast(lvit.current() ); - KConfigGroup cfg( config, *it ); - item->save( cfg ); - } - config->sync(); - Kleo::KeyFilterManager::instance()->reload(); -} - - -void AppearanceConfigWidget::slotForegroundClicked() { - CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); - Q_ASSERT( item ); - if( !item ) - return; - QColor fg = item->foregroundColor(); - int result = KColorDialog::getColor( fg ); - if ( result == KColorDialog::Accepted ) { - item->setForegroundColor( fg ); - item->repaint(); - emit changed(); - } -} - -void AppearanceConfigWidget::slotBackgroundClicked() { - CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); - Q_ASSERT( item ); - if( !item ) - return; - QColor bg = item->backgroundColor(); - int result = KColorDialog::getColor( bg ); - if ( result == KColorDialog::Accepted ) { - item->setBackgroundColor( bg ); - item->repaint(); - emit changed(); - } -} - -void AppearanceConfigWidget::slotFontClicked() { - CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); - Q_ASSERT( item ); - if( !item ) - return; - QFont font = item->font(); - int result = KFontDialog::getFont( font ); - if ( result == KFontDialog::Accepted ) { - item->setFont( font ); - item->repaint(); - emit changed(); - } -} - -void AppearanceConfigWidget::defaults() -{ - // This simply means "default look for every category" - QListViewItemIterator lvit( categoriesLV ); - for ( ; lvit.current() ; ++lvit ) { - CategoryListViewItem* item = static_cast( lvit.current() ); - item->setDefaultAppearance(); - item->repaint(); - } - emit changed(); -} - -void AppearanceConfigWidget::slotItalicClicked() -{ - CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); - if ( item ) { - item->toggleItalic(); - item->repaint(); - emit changed(); - } -} - -void AppearanceConfigWidget::slotBoldClicked() -{ - CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); - if ( item ) { - item->toggleBold(); - item->repaint(); - emit changed(); - } -} - -void AppearanceConfigWidget::slotStrikeoutClicked() -{ - CategoryListViewItem* item = static_cast(categoriesLV->selectedItem() ); - if ( item ) { - item->toggleStrikeout(); - item->repaint(); - emit changed(); - } -} - -#include "appearanceconfigwidget.moc" diff --git a/kleopatra/conf/appearanceconfigwidget.h b/kleopatra/conf/appearanceconfigwidget.h deleted file mode 100644 index dc5c79766a..0000000000 --- a/kleopatra/conf/appearanceconfigwidget.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - appearanceconfigwidget.h - - This file is part of kleopatra, the KDE key manager - Copyright (c) 2002,2004 Klarlvdalens Datakonsult AB - Copyright (c) 2002,2003 Marc Mutz - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - */ - -#ifndef APPEARANCECONFIGWIDGET_H -#define APPEARANCECONFIGWIDGET_H - -#include "appearanceconfigwidgetbase.h" -#include -class KConfig; - -namespace Kleo { - - class AppearanceConfigWidget : public AppearanceConfigWidgetBase { - Q_OBJECT - - public: - AppearanceConfigWidget( - QWidget * parent=0, const char * name=0, WFlags f=0 ); - ~AppearanceConfigWidget(); - - void load(); - void save(); - - public slots: - void defaults(); - - signals: - void changed(); - - protected slots: - // reimplemented from the base class - virtual void slotDefaultClicked(); - virtual void slotSelectionChanged( QListViewItem * ); - virtual void slotForegroundClicked(); - virtual void slotBackgroundClicked(); - virtual void slotFontClicked(); - virtual void slotItalicClicked(); - virtual void slotBoldClicked(); - virtual void slotStrikeoutClicked(); - }; -} - -#endif // APPEARANCECONFIGWIDGET_H diff --git a/kleopatra/conf/configuredialog.cpp b/kleopatra/conf/configuredialog.cpp deleted file mode 100644 index 87976f1060..0000000000 --- a/kleopatra/conf/configuredialog.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - configuredialog.cpp - - This file is part of kleopatra - Copyright (C) 2000 Espen Sand, espen@kde.org - Copyright (C) 2001-2002 Marc Mutz - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "configuredialog.h" - -#include -#include -#include -#include - -ConfigureDialog::ConfigureDialog( QWidget *parent, const char *name, bool modal ) - : KCMultiDialog( KDialogBase::IconList, i18n( "Configure" ), parent, name, modal ) -{ - KWin::setIcons( winId(), kapp->icon(), kapp->miniIcon() ); - showButton( User1, true ); - - addModule( "kleopatra_config_dirserv", false ); - addModule( "kleopatra_config_appear", false ); - addModule( "kleopatra_config_dnorder", false ); - - // We store the size of the dialog on hide, because otherwise - // the KCMultiDialog starts with the size of the first kcm, not - // the largest one. This way at least after the first showing of - // the largest kcm the size is kept. - const KConfigGroup geometry( KGlobal::config(), "Geometry" ); - const int width = geometry.readNumEntry( "ConfigureDialogWidth" ); - const int height = geometry.readNumEntry( "ConfigureDialogHeight" ); - if ( width != 0 && height != 0 ) { - setMinimumSize( width, height ); - } - -} - -void ConfigureDialog::hideEvent( QHideEvent * ) { - KConfigGroup geometry( KGlobal::config(), "Geometry" ); - geometry.writeEntry( "ConfigureDialogWidth", width() ); - geometry.writeEntry( "ConfigureDialogHeight",height() ); -} - -ConfigureDialog::~ConfigureDialog() { -} - -#include "configuredialog.moc" diff --git a/kleopatra/conf/configuredialog.h b/kleopatra/conf/configuredialog.h deleted file mode 100644 index 40b7e371b4..0000000000 --- a/kleopatra/conf/configuredialog.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - configuredialog.cpp - - This file is part of kleopatra - Copyright (C) 2000 Espen Sand, espen@kde.org - Copyright (C) 2001-2002 Marc Mutz - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef _CONFIGURE_DIALOG_H_ -#define _CONFIGURE_DIALOG_H_ - -#include - -class ConfigureDialog : public KCMultiDialog -{ - Q_OBJECT - -public: - ConfigureDialog( QWidget *parent=0, const char *name=0, bool modal=true ); - ~ConfigureDialog(); - -protected: - void hideEvent( QHideEvent *i ); - -}; - -#endif diff --git a/kleopatra/conf/dirservconfigpage.cpp b/kleopatra/conf/dirservconfigpage.cpp deleted file mode 100644 index 30b21005d5..0000000000 --- a/kleopatra/conf/dirservconfigpage.cpp +++ /dev/null @@ -1,291 +0,0 @@ -/* - dirservconfigpage.cpp - - This file is part of kleopatra - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "dirservconfigpage.h" -#include "directoryserviceswidget.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include - -// For sync'ing kabldaprc -class KABSynchronizer -{ -public: - KABSynchronizer() - : mConfig( "kabldaprc" ) { - mConfig.setGroup( "LDAP" ); - } - - KURL::List readCurrentList() const { - - KURL::List lst; - // stolen from kabc/ldapclient.cpp - const uint numHosts = mConfig.readUnsignedNumEntry( "NumSelectedHosts" ); - for ( uint j = 0; j < numHosts; j++ ) { - const QString num = QString::number( j ); - - KURL url; - url.setProtocol( "ldap" ); - url.setPath( "/" ); // workaround KURL parsing bug - const QString host = mConfig.readEntry( QString( "SelectedHost" ) + num ).stripWhiteSpace(); - url.setHost( host ); - - const int port = mConfig.readUnsignedNumEntry( QString( "SelectedPort" ) + num ); - if ( port != 0 ) - url.setPort( port ); - - const QString base = mConfig.readEntry( QString( "SelectedBase" ) + num ).stripWhiteSpace(); - url.setQuery( base ); - - const QString bindDN = mConfig.readEntry( QString( "SelectedBind" ) + num ).stripWhiteSpace(); - url.setUser( bindDN ); - - const QString pwdBindDN = mConfig.readEntry( QString( "SelectedPwdBind" ) + num ).stripWhiteSpace(); - url.setPass( pwdBindDN ); - lst.append( url ); - } - return lst; - } - - void writeList( const KURL::List& lst ) { - - mConfig.writeEntry( "NumSelectedHosts", lst.count() ); - - KURL::List::const_iterator it = lst.begin(); - KURL::List::const_iterator end = lst.end(); - unsigned j = 0; - for( ; it != end; ++it, ++j ) { - const QString num = QString::number( j ); - KURL url = *it; - - Q_ASSERT( url.protocol() == "ldap" ); - mConfig.writeEntry( QString( "SelectedHost" ) + num, url.host() ); - mConfig.writeEntry( QString( "SelectedPort" ) + num, url.port() ); - - // KURL automatically encoded the query (e.g. for spaces inside it), - // so decode it before writing it out - const QString base = KURL::decode_string( url.query().mid(1) ); - mConfig.writeEntry( QString( "SelectedBase" ) + num, base ); - mConfig.writeEntry( QString( "SelectedBind" ) + num, url.user() ); - mConfig.writeEntry( QString( "SelectedPwdBind" ) + num, url.pass() ); - } - mConfig.sync(); - } - -private: - KConfig mConfig; -}; - -static const char s_dirserv_componentName[] = "dirmngr"; -static const char s_dirserv_groupName[] = "LDAP"; -static const char s_dirserv_entryName[] = "LDAP Server"; - -static const char s_timeout_componentName[] = "dirmngr"; -static const char s_timeout_groupName[] = "LDAP"; -static const char s_timeout_entryName[] = "ldaptimeout"; - -static const char s_maxitems_componentName[] = "dirmngr"; -static const char s_maxitems_groupName[] = "LDAP"; -static const char s_maxitems_entryName[] = "max-replies"; - -static const char s_addnewservers_componentName[] = "dirmngr"; -static const char s_addnewservers_groupName[] = "LDAP"; -static const char s_addnewservers_entryName[] = "add-servers"; - -DirectoryServicesConfigurationPage::DirectoryServicesConfigurationPage( QWidget * parent, const char * name ) - : KCModule( parent, name ) -{ - mConfig = Kleo::CryptoBackendFactory::instance()->config(); - QVBoxLayout* lay = new QVBoxLayout( this, 0, KDialog::spacingHint() ); - Kleo::CryptoConfigEntry* entry = configEntry( s_dirserv_componentName, s_dirserv_groupName, s_dirserv_entryName, - Kleo::CryptoConfigEntry::ArgType_LDAPURL, true ); - mWidget = new Kleo::DirectoryServicesWidget( entry, this ); - lay->addWidget( mWidget ); - connect( mWidget, SIGNAL( changed() ), this, SLOT( slotChanged() ) ); - - // LDAP timeout - QHBox* box = new QHBox( this ); - box->setSpacing( KDialog::spacingHint() ); - lay->addWidget( box ); - QLabel* label = new QLabel( i18n( "LDAP &timeout (minutes:seconds)" ), box ); - mTimeout = new QTimeEdit( box ); - mTimeout->setDisplay( QTimeEdit::Minutes | QTimeEdit::Seconds ); - connect( mTimeout, SIGNAL( valueChanged( const QTime& ) ), this, SLOT( slotChanged() ) ); - label->setBuddy( mTimeout ); - QWidget* stretch = new QWidget( box ); - box->setStretchFactor( stretch, 2 ); - - // Max number of items returned by queries - box = new QHBox( this ); - box->setSpacing( KDialog::spacingHint() ); - lay->addWidget( box ); - mMaxItems = new KIntNumInput( box ); - mMaxItems->setLabel( i18n( "&Maximum number of items returned by query" ), Qt::AlignLeft | Qt::AlignVCenter ); - mMaxItems->setMinValue( 0 ); - connect( mMaxItems, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) ); - stretch = new QWidget( box ); - box->setStretchFactor( stretch, 2 ); - -#ifdef NOT_USEFUL_CURRENTLY - mAddNewServersCB = new QCheckBox( i18n( "Automatically add &new servers discovered in CRL distribution points" ), this ); - connect( mAddNewServersCB, SIGNAL( clicked() ), this, SLOT( slotChanged() ) ); - lay->addWidget( mAddNewServersCB ); -#endif - -#ifndef HAVE_UNBROKEN_KCMULTIDIALOG - load(); -#endif -} - -void DirectoryServicesConfigurationPage::load() -{ - mWidget->load(); - - mTimeoutConfigEntry = configEntry( s_timeout_componentName, s_timeout_groupName, s_timeout_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false ); - if ( mTimeoutConfigEntry ) { - QTime time = QTime().addSecs( mTimeoutConfigEntry->uintValue() ); - //kdDebug() << "timeout:" << mTimeoutConfigEntry->uintValue() << " -> " << time << endl; - mTimeout->setTime( time ); - } - - mMaxItemsConfigEntry = configEntry( s_maxitems_componentName, s_maxitems_groupName, s_maxitems_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false ); - if ( mMaxItemsConfigEntry ) { - mMaxItems->blockSignals( true ); // KNumInput emits valueChanged from setValue! - mMaxItems->setValue( mMaxItemsConfigEntry->uintValue() ); - mMaxItems->blockSignals( false ); - } - -#ifdef NOT_USEFUL_CURRENTLY - mAddNewServersConfigEntry = configEntry( s_addnewservers_componentName, s_addnewservers_groupName, s_addnewservers_entryName, Kleo::CryptoConfigEntry::ArgType_None, false ); - if ( mAddNewServersConfigEntry ) { - mAddNewServersCB->setChecked( mAddNewServersConfigEntry->boolValue() ); - } -#endif -} - -void DirectoryServicesConfigurationPage::save() -{ - mWidget->save(); - - QTime time( mTimeout->time() ); - unsigned int timeout = time.minute() * 60 + time.second(); - if ( mTimeoutConfigEntry && mTimeoutConfigEntry->uintValue() != timeout ) - mTimeoutConfigEntry->setUIntValue( timeout ); - if ( mMaxItemsConfigEntry && mMaxItemsConfigEntry->uintValue() != (uint)mMaxItems->value() ) - mMaxItemsConfigEntry->setUIntValue( mMaxItems->value() ); -#ifdef NOT_USEFUL_CURRENTLY - if ( mAddNewServersConfigEntry && mAddNewServersConfigEntry->boolValue() != mAddNewServersCB->isChecked() ) - mAddNewServersConfigEntry->setBoolValue( mAddNewServersCB->isChecked() ); -#endif - - mConfig->sync( true ); - - // Also write the LDAP URLs to kabldaprc so that they are used by kaddressbook - KABSynchronizer sync; - const KURL::List toAdd = mWidget->urlList(); - KURL::List currentList = sync.readCurrentList(); - - KURL::List::const_iterator it = toAdd.begin(); - KURL::List::const_iterator end = toAdd.end(); - for( ; it != end; ++it ) { - // check if the URL is already in currentList - if ( currentList.find( *it ) == currentList.end() ) - // if not, add it - currentList.append( *it ); - } - sync.writeList( currentList ); -} - -void DirectoryServicesConfigurationPage::defaults() -{ - mWidget->defaults(); - if ( mTimeoutConfigEntry ) - mTimeoutConfigEntry->resetToDefault(); - if ( mMaxItemsConfigEntry ) - mMaxItemsConfigEntry->resetToDefault(); -#ifdef NOT_USEFUL_CURRENTLY - if ( mAddNewServersConfigEntry ) - mAddNewServersConfigEntry->resetToDefault(); -#endif - load(); -} - -extern "C" -{ - KDE_EXPORT KCModule *create_kleopatra_config_dirserv( QWidget *parent, const char * ) - { - DirectoryServicesConfigurationPage *page = - new DirectoryServicesConfigurationPage( parent, "kleopatra_config_dirserv" ); - return page; - } -} - -// kdelibs-3.2 didn't have the changed signal in KCModule... -void DirectoryServicesConfigurationPage::slotChanged() -{ - emit changed(true); -} - - -// Find config entry for ldap servers. Implements runtime checks on the configuration option. -Kleo::CryptoConfigEntry* DirectoryServicesConfigurationPage::configEntry( const char* componentName, - const char* groupName, - const char* entryName, - Kleo::CryptoConfigEntry::ArgType argType, - bool isList ) -{ - Kleo::CryptoConfigEntry* entry = mConfig->entry( componentName, groupName, entryName ); - if ( !entry ) { - KMessageBox::error( this, i18n( "Backend error: gpgconf does not seem to know the entry for %1/%2/%3" ).arg( componentName, groupName, entryName ) ); - return 0; - } - if( entry->argType() != argType || entry->isList() != isList ) { - KMessageBox::error( this, i18n( "Backend error: gpgconf has wrong type for %1/%2/%3: %4 %5" ).arg( componentName, groupName, entryName ).arg( entry->argType() ).arg( entry->isList() ) ); - return 0; - } - return entry; -} - -#include "dirservconfigpage.moc" diff --git a/kleopatra/conf/dirservconfigpage.h b/kleopatra/conf/dirservconfigpage.h deleted file mode 100644 index 8c7c754397..0000000000 --- a/kleopatra/conf/dirservconfigpage.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - dirservconfigpage.h - - This file is part of kleopatra - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef DIRSERVCONFIGPAGE_H -#define DIRSERVCONFIGPAGE_H - -#include -#include -#include - -class QCheckBox; -class QTimeEdit; -class KIntNumInput; -namespace Kleo { - class CryptoConfig; - class CryptoConfigEntry; - class DirectoryServicesWidget; -} - -/** - * "Directory Services" configuration page for kleopatra's configuration dialog - * The user can configure LDAP servers in this page, to be used for listing/fetching - * remote certificates in kleopatra. - */ -class KDE_EXPORT DirectoryServicesConfigurationPage : public KCModule { - Q_OBJECT -public: - DirectoryServicesConfigurationPage( QWidget * parent=0, const char * name=0 ); - - virtual void load(); - virtual void save(); - virtual void defaults(); - -private slots: - void slotChanged(); - -private: - Kleo::CryptoConfigEntry* configEntry( const char* componentName, - const char* groupName, - const char* entryName, - Kleo::CryptoConfigEntry::ArgType argType, - bool isList ); - - Kleo::DirectoryServicesWidget* mWidget; - QTimeEdit* mTimeout; - KIntNumInput* mMaxItems; - QCheckBox* mAddNewServersCB; - - Kleo::CryptoConfigEntry* mTimeoutConfigEntry; - Kleo::CryptoConfigEntry* mMaxItemsConfigEntry; - Kleo::CryptoConfigEntry* mAddNewServersConfigEntry; - - Kleo::CryptoConfig* mConfig; -}; - -#endif diff --git a/kleopatra/conf/dnorderconfigpage.cpp b/kleopatra/conf/dnorderconfigpage.cpp deleted file mode 100644 index 44b86b5b85..0000000000 --- a/kleopatra/conf/dnorderconfigpage.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* - dnorderconfigpage.cpp - - This file is part of kleopatra, the KDE key manager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "dnorderconfigpage.h" - -#include -#include - -#include - -#include - -DNOrderConfigPage::DNOrderConfigPage( QWidget * parent, const char * name ) - : KCModule( parent, name ) -{ - QVBoxLayout * vlay = new QVBoxLayout( this ); - mWidget = Kleo::DNAttributeMapper::instance()->configWidget( this, "mWidget" ); - vlay->addWidget( mWidget ); - - connect( mWidget, SIGNAL(changed()), SLOT(slotChanged()) ); - -#ifndef HAVE_UNBROKEN_KCMULTIDIALOG - load(); -#endif -} - - -void DNOrderConfigPage::load() { - mWidget->load(); -} - -void DNOrderConfigPage::save() { - mWidget->save(); -} - -void DNOrderConfigPage::defaults() { - mWidget->defaults(); -} - -// kdelibs-3.2 didn't have the changed signal in KCModule... -void DNOrderConfigPage::slotChanged() { - emit changed(true); -} - -extern "C" KDE_EXPORT KCModule * create_kleopatra_config_dnorder( QWidget * parent, const char * ) { - return new DNOrderConfigPage( parent, "kleopatra_config_dnorder" ); -} - -#include "dnorderconfigpage.moc" diff --git a/kleopatra/conf/dnorderconfigpage.h b/kleopatra/conf/dnorderconfigpage.h deleted file mode 100644 index c874c7527f..0000000000 --- a/kleopatra/conf/dnorderconfigpage.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - dnorderconfigpage.h - - This file is part of kleopatra, the KDE key manager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEOPATRA_CONF_DNORDERCONFIGPAGE_H__ -#define __KLEOPATRA_CONF_DNORDERCONFIGPAGE_H__ - -#include - -namespace Kleo { - class DNAttributeOrderConfigWidget; -} - -/** - * "DN Order" configuration page for kleopatra's configuration dialog - */ -class DNOrderConfigPage : public KCModule { - Q_OBJECT -public: - DNOrderConfigPage( QWidget * parent=0, const char * name=0 ); - - /*! reimplementation */ - void load(); - /*! reimplementation */ - void save(); - /*! reimplementation */ - void defaults(); - -private slots: - void slotChanged(); - -private: - Kleo::DNAttributeOrderConfigWidget * mWidget; -}; - -#endif // __KLEOPATRA_CONF_DNORDERCONFIGPAGE_H__ diff --git a/kleopatra/conf/kleopatra_config_appear.desktop b/kleopatra/conf/kleopatra_config_appear.desktop deleted file mode 100644 index d758602fb0..0000000000 --- a/kleopatra/conf/kleopatra_config_appear.desktop +++ /dev/null @@ -1,139 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Icon=looknfeel -Type=Service -ServiceTypes=KCModule -DocPath=kleopatra/configuration-appearance.html - -X-KDE-ModuleType=Library -X-KDE-Library=kleopatra -X-KDE-FactoryName=kleopatra_config_appear -X-KDE-HasReadOnlyMode=false -X-KDE-ParentApp=kleopatra -X-KDE-ParentComponents=kleopatra -X-KDE-CfgDlgHierarchy=Kleopatra - -Name=Appearance -Name[be]=Зьнешні выгляд -Name[bg]=Външен вид -Name[br]=Neuziadur -Name[bs]=Izgled -Name[ca]=Aparença -Name[cs]=Vzhled -Name[cy]=Golwg -Name[da]=Udseende -Name[de]=Erscheinungsbild -Name[el]=Εμφάνιση -Name[es]=Apariencia -Name[et]=Välimus -Name[fi]=Ulkoasu -Name[fr]=Apparence -Name[ga]=Cuma -Name[gl]=Apariencia -Name[he]=מראה -Name[hr]=Izgled -Name[hu]=Megjelenés -Name[is]=Útlit -Name[it]=Aspetto -Name[ja]=外観 -Name[mk]=Изглед -Name[nb]=Utseende -Name[nl]=Uiterlijk -Name[nn]=Utsjånad -Name[pl]=Wygląd -Name[pt]=Aparência -Name[pt_BR]=Aparência -Name[ru]=Внешний вид -Name[se]=Fárda -Name[sk]=Vzhľad -Name[sl]=Videz -Name[sr]=Изглед -Name[sr@Latn]=Izgled -Name[sv]=Uppträdande -Name[ta]=தோற்றம் -Name[tg]=Намуди зоҳирӣ -Name[tr]=Görünüm -Name[uk]=Вигляд -Name[xx]=xxAppearancexx -Name[zh_CN]=外观 -Comment=Colors & Fonts Configuration -Comment[be]=Канфігурацыя колераў і шрыфтоў -Comment[bg]=Настройки на цветовете и шрифтовете -Comment[bs]=Podešavanje boja i fontova -Comment[ca]=Configuració de colors i fonts -Comment[cs]=Nastavení barev a písem -Comment[da]=Indstilling af farver & skrifttype -Comment[de]=Farb- & Schriftkonfiguration -Comment[el]=Ρύθμιση χρωμάτων & γραμματοσειρών -Comment[en_GB]=Colours & Fonts Configuration -Comment[es]=Configuración de colores y tipografías -Comment[et]=Värvide ja fontide seadistamine -Comment[fi]=Värien ja kirjasinten asetukset -Comment[fr]=Configuration des polices et des couleurs -Comment[gl]=Configuración de Cores e Fontes -Comment[he]=תצורת צבעים וגופנים -Comment[hu]=A színek és betűtípusok beállítása -Comment[is]=Stilling lita og leturgerða -Comment[it]=Configurazione tipi di carattere e colori -Comment[ja]=色とフォント設定 -Comment[mk]=Конфигурација на бои и фонтови -Comment[nb]=Oppsett av farger og skrifttyper -Comment[nl]=Kleur- en lettertype-instellingen -Comment[nn]=Oppsett av fargar og skrifter -Comment[pl]=Konfiguracja czcionek i kolorów -Comment[pt]=Configuração das Cores e Tipos de Letra -Comment[pt_BR]=Configuração de Cores & Fontes -Comment[ru]=Настройка цветов и шрифтов -Comment[se]=Heivet ivnniid ja fonttaid -Comment[sk]=Nastavenie písiem a farieb -Comment[sl]=Nastavitev pisav in barv -Comment[sr]=Подешавање боја и фонтова -Comment[sr@Latn]=Podešavanje boja i fontova -Comment[sv]=Inställning av färger och teckensnitt -Comment[ta]=வண்ணங்கள்& எழுத்துருக்கள் கட்டமைப்பு -Comment[tg]=Танзимоти ранг ва ҳуруф -Comment[tr]=Renkler ve Yazı Tipleri Yapılandırması -Comment[uk]=Налаштування кольорів і шрифтів -Comment[xx]=xxColors & Fonts Configurationxx -Comment[zh_CN]=颜色和字体配置 -Keywords=color,font, configuration -Keywords[be]=колер, шрыфт, канфігурацыя, color, font, configuration -Keywords[bg]=цвят, шрифт, конфигуриране, настройки color, font, configuration -Keywords[br]=liv,nodrezh, kefluniadur -Keywords[bs]=color,font, configuration,boja,boje,font,podešavanje -Keywords[ca]=color,font, configuració -Keywords[cs]=barva,písmo,nastavení -Keywords[da]=farve,skrifttype,indstilling -Keywords[de]=Farben,Schriftarten,Konfiguration -Keywords[en_GB]=colour,font, configuration -Keywords[es]=color, tipografía, configuración -Keywords[et]=värv, font, seadistamine -Keywords[fi]=värit,kirjasimet, asetukset -Keywords[fr]=couleur,police,configuration,paramètres,réglages,couleurs,polices -Keywords[ga]=dath,cló,cumraíocht -Keywords[gl]=cor,fonte, configuración -Keywords[he]=צבע,צבעים, גופנים, גופן, תצורה, הגדרה -Keywords[hu]=szín,betűtípus,beállítások -Keywords[is]=litir,letur, stillingar -Keywords[it]=colori, font, caratteri, configurazione -Keywords[ja]=色 フォント 設定 -Keywords[mk]=color,font,configuration -Keywords[nb]=farge,skrifttype,oppsett -Keywords[nl]=kleur,kleuren,font,lettertype,configuratie,instellingen,setup -Keywords[nn]=farge,skrift,oppsett -Keywords[pl]=kolor,czcionki,kolory,konfiguracja -Keywords[pt]=cor,tipo de letra, configuração -Keywords[pt_BR]=cor,fonte,configurar,configurações -Keywords[ru]=цвета,шрифты,настройка -Keywords[se]=ivdni,fonta,heivehus -Keywords[sk]=farba,písmo,nastavenie -Keywords[sl]=barva,barve,pisava,pisave,nastavi,nastavitve -Keywords[sr]=боја,фонт,подешавања -Keywords[sr@Latn]=boja,font,podešavanja -Keywords[sv]=färger,teckensnitt, inställningar -Keywords[ta]=Comment=வண்ணம்,எழுத்துரு, கட்டமைப்பு -Keywords[tg]=рангҳо,ҳуруфҳо,танзимот -Keywords[tr]=renk,yazı tipi, yapılandırma -Keywords[uk]=колір, шрифт, налаштування -Keywords[xx]=xxcolor,font, configurationxx -Keywords[zh_CN]=color,font,configuration,颜色,字体,配置 diff --git a/kleopatra/conf/kleopatra_config_dirserv.desktop b/kleopatra/conf/kleopatra_config_dirserv.desktop deleted file mode 100644 index 56bc725ab4..0000000000 --- a/kleopatra/conf/kleopatra_config_dirserv.desktop +++ /dev/null @@ -1,125 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Icon=network -Type=Service -ServiceTypes=KCModule -DocPath=kleopatra/configuration.html#configuration-directory-services - -X-KDE-ModuleType=Library -X-KDE-Library=kleopatra -X-KDE-FactoryName=kleopatra_config_dirserv -X-KDE-HasReadOnlyMode=false -X-KDE-ParentApp=kleopatra -X-KDE-ParentComponents=kleopatra -X-KDE-CfgDlgHierarchy=Kleopatra - -Name=Directory Services -Name[bg]=Директорийни услуги -Name[bs]=Imenički servisi -Name[ca]=Serveis de directori -Name[cs]=Adresářové služby -Name[da]=Opslagstjeneste -Name[de]=Verzeichnisdienste -Name[es]=Servicios de directorio -Name[et]=Kataloogiteenused -Name[fi]=Hakemistopalvelut -Name[fr]=Services de répertoires -Name[gl]=Servicios de Directorio -Name[he]=שירותי ספרייה -Name[hu]=Címtárszolgáltatások -Name[is]=Nafnaþjónustur -Name[it]=Servizi Directory -Name[ja]=ディレクトリ サービス -Name[nb]=Katalogtjenere -Name[nl]=Mapdiensten -Name[nn]=Katalogtenester -Name[pa]=ਡਾਇਰੈਕਟਰੀ ਸੇਵਾਵਾਂ -Name[pl]=Usługi katalogowe -Name[pt]=Serviços de Directório -Name[pt_BR]=Serviços de Diretório -Name[ru]=Службы каталогов -Name[se]=Ohcobálvalusat -Name[sk]=Adresárové služby -Name[sl]=Imeniške storitve -Name[sr]=Сервис директоријума -Name[sr@Latn]=Servis direktorijuma -Name[sv]=Katalogtjänster -Name[ta]= அடைவு சேவைகள் -Name[tg]=Кӯмакҳои каталог -Name[tr]=Dizin Servisleri -Name[uk]=Служби каталогів -Name[xx]=xxDirectory Servicesxx -Name[zh_CN]=目录服务 -Comment=Configuration of LDAP directory services -Comment[bg]=Настройки на директорийните услуги LDAP -Comment[bs]=Podešavanje LDAP usluge imenika -Comment[ca]=Configuractió dels serveis de directori LDAP -Comment[cs]=Nastavení adresářových služeb LDAP -Comment[da]=Indstilling af LDAP opslagstjeneste -Comment[de]=Konfiguration von LDAP-Verzeichnisdiensten -Comment[es]=Configuración de los servicios de directorio LDAP -Comment[et]=LDAP kataloogiteenuste seadistused -Comment[fi]=Hakemistopalveluiden asetukset -Comment[fr]=Configuration des répertoires LDAP -Comment[gl]=Configuración dos servicios de directorio LDAP -Comment[he]=תצורה של שירותי ספרייה עבור LDAP -Comment[hu]=Az LDAP címtárszolgáltatások beállításai -Comment[is]=Stillingar LDAP uppflettingaþjónustunnar -Comment[it]=Configurazione servizi LDAP -Comment[ja]=LDAP ディレクトリー サービスの設定 -Comment[nb]=Oppsett av LDAP katalogtjenester -Comment[nl]=Configuratie voor LDAP-diensten -Comment[nn]=Oppsett av LDAP-katalogtenester -Comment[pl]=Konfiguracja usług katalogowych LDAP -Comment[pt]=Configuração dos serviços de directório LDAP -Comment[pt_BR]=Configuração dos serviços de diretório LDAP -Comment[ru]=Настройка служб каталогов LDAP -Comment[se]=Heivet LDAP-ohcobálvalusaid -Comment[sk]=Nastavenie adresárových služieb LDAP -Comment[sl]=Nastavitve imeniških storitev LDAP -Comment[sr]= Подешавања LDAP сервиса директоријума -Comment[sr@Latn]= Podešavanja LDAP servisa direktorijuma -Comment[sv]=Inställning av LDAP-katalogtjänster -Comment[ta]= LDAP அடைவு சேவைகளின் கட்டமைப்பு -Comment[tg]=Танзимоти кӯмакҳои каталоги LDAP -Comment[tr]=LDAP dizin servislerinin yapılandırması -Comment[uk]=Налаштування служб каталогів LDAP -Comment[xx]=xxConfiguration of LDAP directory servicesxx -Comment[zh_CN]=LDAP 目录服务配置 -Keywords=ldap,directory,services -Keywords[be]=каталёг,сэрвісы,ldap,directory,services -Keywords[bg]=директорийни, услуги, ldap, directory, services -Keywords[br]=ldap,renkell,servijeroù -Keywords[bs]=ldap,directory,services,imenik,servis,usluga,imenički,imeničke,usluge -Keywords[ca]=ldap,directori,serveis -Keywords[cs]=LDAP,adresář,služby -Keywords[da]=ldap,opslag,tjenester -Keywords[de]=LDAP,Verzeichnis,Dienste -Keywords[es]=ldap,directorio,servicios -Keywords[et]=ldap,kataloog,teenused -Keywords[fi]=ldap,hakemisto,palvelut -Keywords[fr]=ldap,dossier,dossiers,service,services -Keywords[gl]=ldap,directorio,servicios -Keywords[he]=ldap,ספרייה,שירותים, directory -Keywords[hu]=ldap,címtár,szolgáltatások -Keywords[is]=ldap,directory,services,nafnaþjónusta -Keywords[it]=ldap, servizi, directory -Keywords[ja]=ldap,ディレクトリー,サービス -Keywords[nb]=ldap,mappe,tjenester -Keywords[nn]=ldap,katalog,tenester -Keywords[pl]=ldap,katalog,usługi katalogowe,usługi,LDAP -Keywords[pt]=ldap,directório,serviços -Keywords[pt_BR]=ldap,diretório,serviços -Keywords[ru]=ldap,службы каталогов -Keywords[se]=ldap,ohcu,bálvalusat -Keywords[sk]=ldap,adresár,služby -Keywords[sl]=ldap,imenik,storitve -Keywords[sr]=ldap,директоријум,сервиси -Keywords[sr@Latn]=ldap,direktorijum,servisi -Keywords[sv]=ldap,katalog,tjänster -Keywords[ta]=ldap, அடைவு, சேவைகள் -Keywords[tg]=ldap,кӯмакҳои каталог -Keywords[tr]=ldap,dizin,servisler -Keywords[uk]=ldap,служби,каталогів -Keywords[xx]=xxldap,directory,servicesxx -Keywords[zh_CN]=ldap,directory,services,目录,服务 diff --git a/kleopatra/conf/kleopatra_config_dnorder.desktop b/kleopatra/conf/kleopatra_config_dnorder.desktop deleted file mode 100644 index e10879022c..0000000000 --- a/kleopatra/conf/kleopatra_config_dnorder.desktop +++ /dev/null @@ -1,124 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Icon=looknfeel -Type=Service -ServiceTypes=KCModule -DocPath=kleopatra/configuration-dn-order.html - -X-KDE-ModuleType=Library -X-KDE-Library=kleopatra -X-KDE-FactoryName=kleopatra_config_dnorder -X-KDE-HasReadOnlyMode=false -X-KDE-ParentApp=kleopatra -X-KDE-ParentComponents=kleopatra -X-KDE-CfgDlgHierarchy=Kleopatra - -Name=DN-Attribute Order -Name[bg]=Подредба -Name[bs]=Redoslijed DN atributa -Name[ca]=Ordre d'atributs DN -Name[cs]=Pořadí DN atributů -Name[da]=DN-Attributrækkefølge -Name[de]=DN-Attribut-Ordnung -Name[es]=Orden de atributos DN -Name[et]=DN-atribuutide järjekord -Name[fi]=DN-attribuuttien järjestys -Name[fr]=Ordre des attributs DN -Name[gl]=Orde de DN-Attribute -Name[he]=סדר של מאפייני DN -Name[hu]=DN-attribútumsorrend -Name[is]=DN eiginleikaröðun -Name[it]=Attributi DN, ordine -Name[ja]=DNー属性 オーダー -Name[nb]=DN-Attributtrekkefølge -Name[nl]=DN-Attribuutvolgorde -Name[nn]=DN-attributtrekkjefølgje -Name[pl]=Porządek atrybutów DN -Name[pt]=Ordem de Atributos DN -Name[pt_BR]=Ordem do Atributo DN -Name[ru]=Порядок атрибутов DN -Name[se]=DN-attribuhttaortnet -Name[sk]=Poradie atribútov DN -Name[sl]=Vrstni red atributov DN -Name[sr]=DN-Атрибут ред -Name[sr@Latn]=DN-Atribut red -Name[sv]=DN-egenskapsordning -Name[ta]=DN-பண்புக்கூறு வரிசை -Name[tg]=Тартиби мушаххасияти DN -Name[tr]=DN-Öznitelik Sırası -Name[uk]=Порядок атрибутів DN -Name[xx]=xxDN-Attribute Orderxx -Name[zh_CN]=DN 属性顺序 -Comment=Configure the order in which DN attributes are shown -Comment[bg]=Настройки на подредбата на атрибутите на индекса (DN) -Comment[bs]=Podesite redoslijed kojim će biti prikazani DN atributi -Comment[ca]=Configura l'ordre en que es mostren els atributs DN -Comment[cs]=Nastavení pořadí zobrazení DN atributů -Comment[da]=Indstil rækkefølgen i hvilken DN-attributter vises -Comment[de]=Konfiguration für die Anzeigeordnung der DN-Attribute -Comment[es]=Configura el orden en el que se muestran los atributos DN -Comment[et]=DN-atribuutide näitamise järjekorra seadistamine -Comment[fi]=Määrittele, missä järjestyksessä DN-attribuutit näytetään -Comment[fr]=Configurer l'ordre dans lequel les attributs DN sont affichés -Comment[gl]=Configurar a orde en que se amosan os atributos DN -Comment[he]=הגדרה של הסדר שבהם מאפייני DN מוצגים -Comment[hu]=A DN-attribútumok megjelenítési sorrendjének beállítása -Comment[is]=Stilla röð DN eiginleikanna -Comment[it]=Configuraz l'ordine in cui sono mostrati gli attributi DN -Comment[ja]=DN-属性が示されるオーダーを設定します。 -Comment[nb]=Still inn rekkefølgen DN-attributtene er sortert i -Comment[nl]=Stel de volgorde in van de DN-attributen -Comment[nn]=Vel kva rekkjefølgje DN-attributtane er sorterte i -Comment[pl]=Konfiguracja kolejności wyświetlania atrybutów DN -Comment[pt]=Configuração da order em que os atributos DN são mostrados -Comment[pt_BR]=Configura a ordem na qual os atributos DN são mostrados -Comment[ru]=Настройка порядка показываемых атрибутов DN -Comment[se]=Vállje makkár ortnegis DN-attribuhttat sorterejuvvojit -Comment[sk]=Nastavenie poradia, v ktorom sú zobrazené atribúty DN -Comment[sl]=Nastavite vrstni red, v katerem so prikazani atributi DN -Comment[sr]=Подешава ред којим су приказани DN атрибути -Comment[sr@Latn]=Podešava red kojim su prikazani DN atributi -Comment[sv]=Anpassa ordningen som DN-egenskaper visas -Comment[ta]= DN விவரங்கள் எந்த வரிசையில் உள்ளதோ அப்படியே அமை -Comment[tg]=Танзимоти мушаххасиятҳои намоишшавандаи тартибии DN -Comment[tr]=DN özniteliklerinin hangi sıralama ile gösterileceğini yapılandır -Comment[uk]=Налаштування порядку показу атрибутів DN -Comment[xx]=xxConfigure the order in which DN attributes are shownxx -Comment[zh_CN]=配置 DN 属性显示的顺序 -Keywords=DN,order,RDN,attribute -Keywords[be]=парадак,атрыбут,DN,order,RDN,attribute -Keywords[bg]=индекс, ред, подредба, атрибут DN, order, RDN, attribute -Keywords[bs]=DN,order,RDN,attribute,redoslijed,atribut -Keywords[ca]=DN,ordre,RDN,atribut -Keywords[cs]=DN,pořadí,RDN,atribut -Keywords[da]=DN,rækkefølge,RDN,attribut -Keywords[de]=DN,Ordnung,RDN,Attribut -Keywords[es]=DN,orden,RDN,atributo -Keywords[et]=DN,järjekord,RDN,atribuut -Keywords[fi]=DN,järjestys,RDN,attribuutti -Keywords[fr]=DN,ordre,RDN,attribut -Keywords[gl]=DN,orde,RDN,atributo -Keywords[he]=DN,סדר,RDN,מאפיין -Keywords[hu]=DN,sorrend,RDN,attribútum -Keywords[is]=DN,röð,order,RDN,attribute -Keywords[it]=DN,ordine,RDN,attributi -Keywords[ja]=DN,オーダー,RDN,属性 -Keywords[nb]=DN,orden,RDN,attributt -Keywords[nl]=DN,volgorde,RDN,attribuut -Keywords[nn]=DN,rekkjefølgje,RDN,attributt -Keywords[pl]=DN,kolejność,RDN,atrybuty -Keywords[pt]=DN,ordem,RDN,atributo -Keywords[pt_BR]=DN, ordem, RDN,atributo -Keywords[ru]=DN,порядок,RDN,атрибут -Keywords[se]=DN,ortnet,RDN,attribuhtta -Keywords[sk]=DN,poradie,RDN,atribút -Keywords[sl]=DN,vrstni red,RDN,atribut -Keywords[sr]=DN,ред,RDN,атрибут -Keywords[sr@Latn]=DN,red,RDN,atribut -Keywords[sv]=DN,ordning,RDN,egenskap -Keywords[ta]=DN,வரிசை,RDN,குணம் -Keywords[tg]=DN,тартибот,RDN,мушаххасот -Keywords[tr]=DN,sıralama,RDN,öznitelik -Keywords[uk]=DN,порядок,RDN,атрибут -Keywords[xx]=xxDN,order,RDN,attributexx -Keywords[zh_CN]=DN,order,RDN,attribute,顺序,属性 diff --git a/kleopatra/crlview.cpp b/kleopatra/crlview.cpp deleted file mode 100644 index 6cf7ddeaa0..0000000000 --- a/kleopatra/crlview.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* - crlview.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "crlview.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -CRLView::CRLView( QWidget* parent, const char* name, bool modal ) - : QDialog( parent, name, modal ), _process(0) -{ - QVBoxLayout* topLayout = new QVBoxLayout( this, 10, 4 ); - - topLayout->addWidget( new QLabel( i18n("CRL cache dump:"), this ) ); - - _textView = new QTextEdit( this ); - _textView->setFont( KGlobalSettings::fixedFont() ); - _textView->setTextFormat( QTextEdit::LogText ); - topLayout->addWidget( _textView ); - - QHBoxLayout* hbLayout = new QHBoxLayout( topLayout ); - - _updateButton = new KPushButton( i18n("&Update"), this ); - _closeButton = new KPushButton( KStdGuiItem::close(), this ); - - hbLayout->addWidget( _updateButton ); - hbLayout->addStretch(); - hbLayout->addWidget( _closeButton ); - - // connections: - connect( _updateButton, SIGNAL( clicked() ), - this, SLOT( slotUpdateView() ) ); - connect( _closeButton, SIGNAL( clicked() ), - this, SLOT( close() ) ); - - resize( _textView->fontMetrics().width( 'M' ) * 80, - _textView->fontMetrics().lineSpacing() * 25 ); - - _timer = new QTimer( this ); - connect( _timer, SIGNAL(timeout()), SLOT(slotAppendBuffer()) ); -} - -CRLView::~CRLView() -{ - delete _process; _process = 0; -} - -void CRLView::closeEvent( QCloseEvent * e ) { - QDialog::closeEvent( e ); - delete _process; _process = 0; -} - -void CRLView::slotUpdateView() -{ - _updateButton->setEnabled( false ); - _textView->clear(); - _buffer = QString::null; - if( _process == 0 ) { - _process = new KProcess(); - *_process << "gpgsm" << "--call-dirmngr" << "listcrls"; - connect( _process, SIGNAL( receivedStdout( KProcess*, char*, int) ), - this, SLOT( slotReadStdout( KProcess*, char*, int ) ) ); - connect( _process, SIGNAL( processExited( KProcess* ) ), - this, SLOT( slotProcessExited() ) ); - } - if( _process->isRunning() ) _process->kill(); - if( !_process->start( KProcess::NotifyOnExit, KProcess::Stdout ) ) { - KMessageBox::error( this, i18n( "Unable to start gpgsm process. Please check your installation." ), i18n( "Certificate Manager Error" ) ); - slotProcessExited(); - } - _timer->start( 1000 ); -} - -void CRLView::slotReadStdout( KProcess*, char* buf, int len) -{ - _buffer.append( QString::fromUtf8( buf, len ) ); -} - -void CRLView::slotAppendBuffer() { - _textView->append( _buffer ); - _buffer = QString::null; -} - -void CRLView::slotProcessExited() -{ - _timer->stop(); - slotAppendBuffer(); - _updateButton->setEnabled( true ); - - if( !_process->normalExit() ) { - KMessageBox::error( this, i18n( "The GpgSM process ended prematurely because of an unexpected error." ), i18n( "Certificate Manager Error" ) ); - } -} - -#include "crlview.moc" diff --git a/kleopatra/crlview.h b/kleopatra/crlview.h deleted file mode 100644 index 55828a90fb..0000000000 --- a/kleopatra/crlview.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - crlview.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef CRLVIEW_H -#define CRLVIEW_H - -#include -#include - -class QTextEdit; -class QPushButton; -class KProcess; -class QTimer; - -class CRLView : public QDialog { - Q_OBJECT -public: - CRLView( QWidget* parent = 0, const char* name = 0, bool modal = false ); - ~CRLView(); -public slots: - void slotUpdateView(); - -protected slots: - void slotReadStdout( KProcess*, char* buf, int len); - void slotProcessExited(); - void slotAppendBuffer(); - -protected: - void closeEvent( QCloseEvent * ); - -private: - QTextEdit* _textView; - QPushButton* _updateButton; - QPushButton* _closeButton; - KProcess* _process; - QTimer* _timer; - QString _buffer; -}; - -#endif // CRLVIEW_H diff --git a/kleopatra/customactions.cpp b/kleopatra/customactions.cpp deleted file mode 100644 index 6a48a47680..0000000000 --- a/kleopatra/customactions.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - customactions.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "customactions.h" - -#include -#include - -#include -#include - - -LabelAction::LabelAction( const QString & text, KActionCollection * parent, - const char* name ) - : KAction( text, QIconSet(), KShortcut(), 0, 0, parent, name ) -{ - -} - -int LabelAction::plug( QWidget * widget, int index ) { - if ( kapp && !kapp->authorizeKAction( name() ) ) - return -1; - if ( widget->inherits( "KToolBar" ) ) { - KToolBar * bar = (KToolBar *)widget; - int id_ = getToolButtonID(); - QLabel* label = new QLabel( text(), bar, "kde toolbar widget" ); - bar->insertWidget( id_, label->width(), label, index ); - addContainer( bar, id_ ); - connect( bar, SIGNAL( destroyed() ), this, SLOT( slotDestroyed() ) ); - return containerCount() - 1; - } - - return KAction::plug( widget, index ); -} - -LineEditAction::LineEditAction( const QString & text, KActionCollection * parent, - QObject * receiver, const char * member, const char * name ) - : KAction( text, QIconSet(), KShortcut(), 0, 0, parent, name ), - _le(0), _receiver(receiver), _member(member) -{ - -} - -int LineEditAction::plug( QWidget * widget, int index ) { - if ( kapp && !kapp->authorizeKAction( name() ) ) - return -1; - if ( widget->inherits( "KToolBar" ) ) { - KToolBar *bar = (KToolBar *)widget; - int id_ = getToolButtonID(); - // The toolbar trick doesn't seem to work for lineedits - //_le = new QLineEdit( bar, "kde toolbar widget" ); - _le = new QLineEdit( bar ); - bar->insertWidget( id_, _le->width(), _le, index ); - bar->setStretchableWidget( _le ); - addContainer( bar, id_ ); - connect( bar, SIGNAL( destroyed() ), this, SLOT( slotDestroyed() ) ); - connect( _le, SIGNAL( returnPressed() ), _receiver, _member ); - return containerCount() - 1; - } - - return KAction::plug( widget, index ); -} - -void LineEditAction::clear() { - _le->clear(); -} - -void LineEditAction::focusAll() { - _le->selectAll(); - _le->setFocus(); -} - -QString LineEditAction::text() const { - return _le->text(); -} - -void LineEditAction::setText( const QString & txt ) { - _le->setText(txt); -} - - -ComboAction::ComboAction( const QStringList & lst, KActionCollection * parent, - QObject * receiver, const char * member, const char * name ) - : KAction( QString::null, QIconSet(), KShortcut(), 0, 0, parent, name ), - _lst(lst), _receiver(receiver), _member(member) -{ - -} - -int ComboAction::plug( QWidget * widget, int index ) { - if ( kapp && !kapp->authorizeKAction( name() ) ) - return -1; - if ( widget->inherits( "KToolBar" ) ) { - KToolBar *bar = (KToolBar *)widget; - int id_ = getToolButtonID(); - bar->insertCombo( _lst, id_, false, SIGNAL( highlighted(int) ), _receiver, _member ); - addContainer( bar, id_ ); - connect( bar, SIGNAL( destroyed() ), this, SLOT( slotDestroyed() ) ); - return containerCount() - 1; - } - - return KAction::plug( widget, index ); -} - -#include "customactions.moc" diff --git a/kleopatra/customactions.h b/kleopatra/customactions.h deleted file mode 100644 index dfbaf54613..0000000000 --- a/kleopatra/customactions.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - customactions.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __CUSTOMACTIONS_H__ -#define __CUSTOMACTIONS_H__ - -#include - -#include - -class QLineEdit; - -class LabelAction : public KAction { - Q_OBJECT -public: - LabelAction( const QString & text, KActionCollection * parent, - const char* name ); - - int plug( QWidget * widget, int index=-1 ); -}; - -class LineEditAction : public KAction { - Q_OBJECT -public: - LineEditAction( const QString & text, KActionCollection * parent, - QObject * receiver, const char * member, const char * name ); - - int plug( QWidget * widget, int index=-1 ); - void clear(); - void focusAll(); - QString text() const; - void setText( const QString & txt ); -private: - QLineEdit* _le; - QObject * _receiver; - const char * _member; -}; - -class ComboAction : public KAction { - Q_OBJECT -public: - ComboAction( const QStringList & lst, KActionCollection * parent, - QObject * receiver, const char * member, const char * name ); - - int plug( QWidget * widget, int index=-1 ); - -private: - QStringList _lst; - QObject * _receiver; - const char * _member; -}; - - - -#endif // __CUSTOMACTIONS_H__ diff --git a/kleopatra/hierarchyanalyser.cpp b/kleopatra/hierarchyanalyser.cpp deleted file mode 100644 index 8e8c13803e..0000000000 --- a/kleopatra/hierarchyanalyser.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* - hierarchyanalyser.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "hierarchyanalyser.h" - -#include -#include - -HierarchyAnalyser::HierarchyAnalyser( QObject * parent, const char * name ) - : QObject( parent, name ) -{ - -} - -HierarchyAnalyser::~HierarchyAnalyser() { - -} - -void HierarchyAnalyser::slotNextKey( const GpgME::Key & key ) { - if ( key.isNull() ) - return; - if ( key.isRoot() || !key.chainID() || !*key.chainID() ) - // root keys have themselves as issuer - we don't want them to - // have parents, though: - mSubjectsByIssuer[0].push_back( key ); - else - mSubjectsByIssuer[key.chainID()].push_back( key ); -} - -const std::vector & HierarchyAnalyser::subjectsForIssuer( const char * issuer_dn ) const { - static const std::vector empty; - std::map< QCString, std::vector >::const_iterator it = - mSubjectsByIssuer.find( issuer_dn ); - return it == mSubjectsByIssuer.end() ? empty : it->second ; -} - -std::vector HierarchyAnalyser::subjectsForIssuerRecursive( const char * issuer_dn ) const { - std::vector keys = subjectsForIssuer( issuer_dn ); - for ( unsigned int i = 0 ; i < keys.size() ; ++i ) // can't use iterators here, since appending would invalidate them - if ( const char * fpr = keys[i].primaryFingerprint() ) { - const std::vector & tmp = subjectsForIssuer( fpr ); - std::copy( tmp.begin(), tmp.end(), std::back_inserter( keys ) ); - } - return keys; -} - - -#include "hierarchyanalyser.moc" diff --git a/kleopatra/hierarchyanalyser.h b/kleopatra/hierarchyanalyser.h deleted file mode 100644 index ccf07d4f30..0000000000 --- a/kleopatra/hierarchyanalyser.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- mode: c++ -*- - hierarchyanalyser.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __HIERARCHYANALYSER_H__ -#define __HIERARCHYANALYSER_H__ - -#include - -#include -#include - -#include -#include - -class HierarchyAnalyser : public QObject { - Q_OBJECT -public: - HierarchyAnalyser( QObject * parent=0, const char * name=0 ); - ~HierarchyAnalyser(); - - const std::vector & rootItems() const { - return subjectsForIssuer( 0 ); - } - const std::vector & subjectsForIssuer( const char * issuer_fpr ) const; - std::vector subjectsForIssuerRecursive( const char * issuer_fpr ) const; - - void clear() { mSubjectsByIssuer.clear(); } - -public slots: - void slotNextKey( const GpgME::Key & key ); - -private: - std::map< QCString, std::vector > mSubjectsByIssuer; -}; - - -#endif // __HIERARCHYANALYSER_H__ diff --git a/kleopatra/kgpgcertmanagerui.rc b/kleopatra/kgpgcertmanagerui.rc deleted file mode 100644 index 1f3e01aade..0000000000 --- a/kleopatra/kgpgcertmanagerui.rc +++ /dev/null @@ -1,33 +0,0 @@ - - - - File - - - - - View - - - - Certificates - - - - - - Import - - - - - - -Main Toolbar - - - - - - - diff --git a/kleopatra/kwatchgnupg/aboutdata.cpp b/kleopatra/kwatchgnupg/aboutdata.cpp deleted file mode 100644 index 4bde521901..0000000000 --- a/kleopatra/kwatchgnupg/aboutdata.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - aboutdata.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2004 Klar�vdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "aboutdata.h" - -#include - -static const char kwatchgnupg_version[] = "1.0"; -static const char description[] = I18N_NOOP("GnuPG log viewer"); - -struct about_data { - const char * name; - const char * desc; - const char * email; - const char * web; -}; - -static const about_data authors[] = { - { "Steffen Hansen", I18N_NOOP("Original Author"), "hansen@kde.org", 0 }, -}; - -#if 0 -// can't create zero size array - doesn't compile -static const about_data credits[] = { - // PENDING(steffen) add stuff -}; -#endif - -AboutData::AboutData() - : KAboutData( "kwatchgnupg", I18N_NOOP("KWatchGnuPG"), - kwatchgnupg_version, description, License_GPL, - "(c) 2004 Klar\xC3\xA4lvdalens Datakonsult AB\n" ) -{ - using ::authors; - //using ::credits; - for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i ) - addAuthor( authors[i].name, authors[i].desc, - authors[i].email, authors[i].web ); -#if 0 - for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i ) - addCredit( credits[i].name, credits[i].desc, - credits[i].email, credits[i].web ); -#endif -} diff --git a/kleopatra/kwatchgnupg/aboutdata.h b/kleopatra/kwatchgnupg/aboutdata.h deleted file mode 100644 index 0e1f9f6318..0000000000 --- a/kleopatra/kwatchgnupg/aboutdata.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - aboutdata.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef ABOUTDATA_H -#define ABOUTDATA_H - -#include - -class AboutData : public KAboutData { -public: - AboutData(); -}; - -#endif // ABOUTDATA_H diff --git a/kleopatra/kwatchgnupg/kwatchgnupgconfig.cpp b/kleopatra/kwatchgnupg/kwatchgnupgconfig.cpp deleted file mode 100644 index b621e92b89..0000000000 --- a/kleopatra/kwatchgnupg/kwatchgnupgconfig.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - kwatchgnupgconfig.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "kwatchgnupgconfig.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -static const char* log_levels[] = { "none", "basic", "advanced", "expert", "guru" }; - -static int log_level_to_int( const QString& loglevel ) -{ - if( loglevel == "none" ) { - return 0; - } else if( loglevel == "basic" ) { - return 1; - } else if( loglevel == "advanced" ) { - return 2; - } else if( loglevel == "expert" ) { - return 3; - } else if( loglevel == "guru" ) { - return 4; - } else { - // default - return 1; - } -} - -KWatchGnuPGConfig::KWatchGnuPGConfig( QWidget* parent, const char* name ) - : KDialogBase( Plain, i18n("Configure KWatchGnuPG"), - Ok|Cancel, Ok, parent, name ) -{ - // tmp vars: - QWidget * w; - QGridLayout * glay; - QGroupBox * group; - - QWidget * top = plainPage(); - - QVBoxLayout * vlay = new QVBoxLayout( top, 0, spacingHint() ); - - group = new QVGroupBox( i18n("WatchGnuPG"), top ); - group->layout()->setSpacing( spacingHint() ); - - w = new QWidget( group ); - - glay = new QGridLayout( w, 3, 2, 0, spacingHint() ); - glay->setColStretch( 1, 1 ); - - int row = -1; - - ++row; - mExeED = new KURLRequester( w ); - glay->addWidget( new QLabel( mExeED, i18n("&Executable:"), w ), row, 0 ); - glay->addWidget( mExeED, row, 1 ); - connect( mExeED, SIGNAL(textChanged(const QString&)), SLOT(slotChanged()) ); - - ++row; - mSocketED = new KURLRequester( w ); - glay->addWidget( new QLabel( mSocketED, i18n("&Socket:"), w ), row, 0 ); - glay->addWidget( mSocketED, row, 1 ); - connect( mSocketED, SIGNAL(textChanged(const QString&)), SLOT(slotChanged()) ); - - ++row; - mLogLevelCB = new QComboBox( false, w ); - mLogLevelCB->insertItem( i18n("None") ); - mLogLevelCB->insertItem( i18n("Basic") ); - mLogLevelCB->insertItem( i18n("Advanced") ); - mLogLevelCB->insertItem( i18n("Expert") ); - mLogLevelCB->insertItem( i18n("Guru") ); - glay->addWidget( new QLabel( mLogLevelCB, i18n("Default &log level:"), w ), row, 0 ); - glay->addWidget( mLogLevelCB, row, 1 ); - connect( mLogLevelCB, SIGNAL(activated(int)), SLOT(slotChanged()) ); - - vlay->addWidget( group ); - - /******************* Log Window group *******************/ - group = new QVGroupBox( i18n("Log Window"), top ); - group->layout()->setSpacing( spacingHint() ); - - w = new QWidget( group ); - - glay = new QGridLayout( w, 2, 3, 0, spacingHint() ); - glay->setColStretch( 1, 1 ); - - row = -1; - - ++row; - mLoglenSB = new QSpinBox( 0, 1000000, 100, w ); - mLoglenSB->setSuffix( i18n("history size spinbox suffix"," lines") ); - mLoglenSB->setSpecialValueText( i18n("unlimited") ); - glay->addWidget( new QLabel( mLoglenSB, i18n("&History size:"), w ), row, 0 ); - glay->addWidget( mLoglenSB, row, 1 ); - QPushButton * button = new QPushButton( i18n("Set &Unlimited"), w ); - glay->addWidget( button, row, 2 ); - - connect( mLoglenSB, SIGNAL(valueChanged(int)), SLOT(slotChanged()) ); - connect( button, SIGNAL(clicked()), SLOT(slotSetHistorySizeUnlimited()) ); - - ++row; - mWordWrapCB = new QCheckBox( i18n("Enable &word wrapping"), w ); - mWordWrapCB->hide(); // QTextEdit doesn't support word wrapping in LogText mode - glay->addMultiCellWidget( mWordWrapCB, row, row, 0, 2 ); - - connect( mWordWrapCB, SIGNAL(clicked()), SLOT(slotChanged()) ); - - vlay->addWidget( group ); - vlay->addStretch( 1 ); - - connect( this, SIGNAL(applyClicked()), SLOT(slotSave()) ); - connect( this, SIGNAL(okClicked()), SLOT(slotSave()) ); -} - -void KWatchGnuPGConfig::slotSetHistorySizeUnlimited() { - mLoglenSB->setValue( 0 ); -} - -void KWatchGnuPGConfig::loadConfig() -{ - KConfig* config = kapp->config(); - config->setGroup("WatchGnuPG"); - mExeED->setURL( config->readEntry( "Executable", "watchgnupg" ) ); - mSocketED->setURL( config->readEntry( "Socket", QDir::home().canonicalPath() - + "/.gnupg/log-socket") ); - mLogLevelCB->setCurrentItem( log_level_to_int( config->readEntry( "LogLevel", "basic" ) ) ); - - config->setGroup("LogWindow"); - mLoglenSB->setValue( config->readNumEntry( "MaxLogLen", 10000 ) ); - mWordWrapCB->setChecked( config->readBoolEntry("WordWrap", false ) ); - - config->setGroup( QString::null ); - enableButtonOK( false ); - enableButtonApply( false ); -} - -void KWatchGnuPGConfig::saveConfig() -{ - KConfig* config = kapp->config(); - config->setGroup("WatchGnuPG"); - config->writeEntry( "Executable", mExeED->url() ); - config->writeEntry( "Socket", mSocketED->url() ); - config->writeEntry( "LogLevel", log_levels[mLogLevelCB->currentItem()] ); - - config->setGroup("LogWindow"); - config->writeEntry( "MaxLogLen", mLoglenSB->value() ); - config->writeEntry( "WordWrap", mWordWrapCB->isChecked() ); - - config->setGroup( QString::null ); - config->sync(); - enableButtonOK( false ); - enableButtonApply( false ); -} - -void KWatchGnuPGConfig::slotChanged() -{ - enableButtonOK( true ); - enableButtonApply( true ); -} - -void KWatchGnuPGConfig::slotSave() -{ - saveConfig(); - emit reconfigure(); -} - -#include "kwatchgnupgconfig.moc" diff --git a/kleopatra/kwatchgnupg/kwatchgnupgconfig.h b/kleopatra/kwatchgnupg/kwatchgnupgconfig.h deleted file mode 100644 index 4a93b463ba..0000000000 --- a/kleopatra/kwatchgnupg/kwatchgnupgconfig.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - kwatchgnupgconfig.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef KWATCHGNUPGCONFIG_H -#define KWATCHGNUPGCONFIG_H - -#include - -class QCheckBox; -class QComboBox; -class QSpinBox; -class KURLRequester; - -class KWatchGnuPGConfig : public KDialogBase { - Q_OBJECT -public: - KWatchGnuPGConfig( QWidget* parent, const char* name = 0 ); - - void loadConfig(); - void saveConfig(); - -signals: - void reconfigure(); - -private slots: - void slotChanged(); - void slotSave(); - void slotSetHistorySizeUnlimited(); - -private: - KURLRequester* mExeED; - KURLRequester* mSocketED; - QComboBox* mLogLevelCB; - QSpinBox* mLoglenSB; - QCheckBox* mWordWrapCB; -}; - -#endif /* KWATCHGNUPGCONFIG_H */ - diff --git a/kleopatra/kwatchgnupg/kwatchgnupgmainwin.cpp b/kleopatra/kwatchgnupg/kwatchgnupgmainwin.cpp deleted file mode 100644 index 19bda278b7..0000000000 --- a/kleopatra/kwatchgnupg/kwatchgnupgmainwin.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/* - kwatchgnupgmainwin.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "kwatchgnupgmainwin.h" -#include "kwatchgnupgconfig.h" -#include "tray.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#define WATCHGNUPGBINARY "watchgnupg" -#define WATCHGNUPGSOCKET ( QDir::home().canonicalPath() + "/.gnupg/log-socket") - -KWatchGnuPGMainWindow::KWatchGnuPGMainWindow( QWidget* parent, const char* name ) - : KMainWindow( parent, name, WType_TopLevel ), mConfig(0) -{ - createActions(); - createGUI(); - - mCentralWidget = new QTextEdit( this, "central log view" ); - mCentralWidget->setTextFormat( QTextEdit::LogText ); - setCentralWidget( mCentralWidget ); - - mWatcher = new KProcIO( QTextCodec::codecForMib( 106 /*utf-8*/ ) ); - connect( mWatcher, SIGNAL( processExited(KProcess*) ), - this, SLOT( slotWatcherExited() ) ); - connect( mWatcher, SIGNAL( readReady(KProcIO*) ), - this, SLOT( slotReadStdout() ) ); - - slotReadConfig(); - mSysTray = new KWatchGnuPGTray( this ); - mSysTray->show(); - connect( mSysTray, SIGNAL( quitSelected() ), - this, SLOT( slotQuit() ) ); - setAutoSaveSettings(); -} - -KWatchGnuPGMainWindow::~KWatchGnuPGMainWindow() -{ - delete mWatcher; -} - -void KWatchGnuPGMainWindow::slotClear() -{ - mCentralWidget->clear(); - mCentralWidget->append( tr("[%1] Log cleared").arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) ); -} - -void KWatchGnuPGMainWindow::createActions() -{ - (void)new KAction( i18n("C&lear History"), "history_clear", CTRL+Key_L, - this, SLOT( slotClear() ), - actionCollection(), "clear_log" ); - (void)KStdAction::saveAs( this, SLOT(slotSaveAs()), actionCollection() ); - (void)KStdAction::close( this, SLOT(close()), actionCollection() ); - (void)KStdAction::quit( this, SLOT(slotQuit()), actionCollection() ); - (void)KStdAction::preferences( this, SLOT(slotConfigure()), actionCollection() ); - ( void )KStdAction::keyBindings(this, SLOT(configureShortcuts()), actionCollection()); - ( void )KStdAction::configureToolbars(this, SLOT(slotConfigureToolbars()), actionCollection()); - -#if 0 - (void)new KAction( i18n("Configure KWatchGnuPG..."), QString::fromLatin1("configure"), - 0, this, SLOT( slotConfigure() ), - actionCollection(), "configure" ); -#endif - -} - -void KWatchGnuPGMainWindow::configureShortcuts() -{ - KKeyDialog::configure( actionCollection(), this ); -} - -void KWatchGnuPGMainWindow::slotConfigureToolbars() -{ - KEditToolbar dlg( factory() ); - - dlg.exec(); -} - -void KWatchGnuPGMainWindow::startWatcher() -{ - disconnect( mWatcher, SIGNAL( processExited(KProcess*) ), - this, SLOT( slotWatcherExited() ) ); - if( mWatcher->isRunning() ) { - mWatcher->kill(); - while( mWatcher->isRunning() ) { - kapp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput); - } - mCentralWidget->append(tr("[%1] Log stopped") - .arg( QDateTime::currentDateTime().toString(Qt::ISODate))); - } - mWatcher->clearArguments(); - KConfig* config = kapp->config(); - config->setGroup("WatchGnuPG"); - *mWatcher << config->readEntry("Executable", WATCHGNUPGBINARY); - *mWatcher << "--force"; - *mWatcher << config->readEntry("Socket", WATCHGNUPGSOCKET); - config->setGroup(QString::null); - if( !mWatcher->start() ) { - KMessageBox::sorry( this, i18n("The watchgnupg logging process could not be started.\nPlease install watchgnupg somewhere in your $PATH.\nThis log window is now completely useless." ) ); - } else { - mCentralWidget->append( tr("[%1] Log started") - .arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) ); - } - connect( mWatcher, SIGNAL( processExited(KProcess*) ), - this, SLOT( slotWatcherExited() ) ); -} - -void KWatchGnuPGMainWindow::setGnuPGConfig() -{ - QStringList logclients; - // Get config object - Kleo::CryptoConfig* cconfig = Kleo::CryptoBackendFactory::instance()->config(); - if ( !cconfig ) - return; - //Q_ASSERT( cconfig ); - KConfig* config = kapp->config(); - config->setGroup("WatchGnuPG"); - QStringList comps = cconfig->componentList(); - for( QStringList::const_iterator it = comps.begin(); it != comps.end(); ++it ) { - Kleo::CryptoConfigComponent* comp = cconfig->component( *it ); - Q_ASSERT(comp); - // Look for log-file entry in Debug group - Kleo::CryptoConfigGroup* group = comp->group("Debug"); - if( group ) { - Kleo::CryptoConfigEntry* entry = group->entry("log-file"); - if( entry ) { - entry->setStringValue( QString("socket://")+ - config->readEntry("Socket", - WATCHGNUPGSOCKET )); - logclients << QString("%1 (%2)").arg(*it).arg(comp->description()); - } - entry = group->entry("debug-level"); - if( entry ) { - entry->setStringValue( config->readEntry("LogLevel", "basic") ); - } - } - } - cconfig->sync(true); - if( logclients.isEmpty() ) { - KMessageBox::sorry( 0, i18n("There are no components available that support logging." ) ); - } -} - -void KWatchGnuPGMainWindow::slotWatcherExited() -{ - if( KMessageBox::questionYesNo( this, i18n("The watchgnupg logging process died.\nDo you want to try to restart it?"), QString::null, i18n("Try Restart"), i18n("Do Not Try") ) == KMessageBox::Yes ) { - mCentralWidget->append( i18n("====== Restarting logging process =====") ); - startWatcher(); - } else { - KMessageBox::sorry( this, i18n("The watchgnupg logging process is not running.\nThis log window is now completely useless." ) ); - } -} - -void KWatchGnuPGMainWindow::slotReadStdout() -{ - if ( !mWatcher ) - return; - QString str; - while( mWatcher->readln(str,false) > 0 ) { - mCentralWidget->append( str ); - if( !isVisible() ) { - // Change tray icon to show something happened - // PENDING(steffen) - mSysTray->setAttention(true); - } - } - QTimer::singleShot( 0, this, SLOT(slotAckRead()) ); -} - -void KWatchGnuPGMainWindow::slotAckRead() { - if ( mWatcher ) - mWatcher->ackRead(); -} - -void KWatchGnuPGMainWindow::show() -{ - mSysTray->setAttention(false); - KMainWindow::show(); -} - -void KWatchGnuPGMainWindow::slotSaveAs() -{ - QString filename = KFileDialog::getSaveFileName( QString::null, QString::null, - this, i18n("Save Log to File") ); - if( filename.isEmpty() ) return; - QFile file(filename); - if( file.exists() ) { - if( KMessageBox::Yes != - KMessageBox::warningYesNo( this, i18n("The file named \"%1\" already " - "exists. Are you sure you want " - "to overwrite it?").arg(filename), - i18n("Overwrite File"), i18n("Overwrite"), KStdGuiItem::cancel() ) ) { - return; - } - } - if( file.open( IO_WriteOnly ) ) { - QTextStream st(&file); - st << mCentralWidget->text(); - file.close(); - } -} - -void KWatchGnuPGMainWindow::slotQuit() -{ - disconnect( mWatcher, SIGNAL( processExited(KProcess*) ), - this, SLOT( slotWatcherExited() ) ); - mWatcher->kill(); - kapp->quit(); -} - -void KWatchGnuPGMainWindow::slotConfigure() -{ - if( !mConfig ) { - mConfig = new KWatchGnuPGConfig( this, "config dialog" ); - connect( mConfig, SIGNAL( reconfigure() ), - this, SLOT( slotReadConfig() ) ); - } - mConfig->loadConfig(); - mConfig->exec(); -} - -void KWatchGnuPGMainWindow::slotReadConfig() -{ - KConfig* config = kapp->config(); - config->setGroup("LogWindow"); - mCentralWidget->setWordWrap( config->readBoolEntry("WordWrap", false) - ?QTextEdit::WidgetWidth - :QTextEdit::NoWrap ); - mCentralWidget->setMaxLogLines( config->readNumEntry( "MaxLogLen", 10000 ) ); - setGnuPGConfig(); - startWatcher(); -} - -bool KWatchGnuPGMainWindow::queryClose() -{ - if ( !kapp->sessionSaving() ) { - hide(); - return false; - } - return KMainWindow::queryClose(); -} - -#include "kwatchgnupgmainwin.moc" diff --git a/kleopatra/kwatchgnupg/kwatchgnupgmainwin.h b/kleopatra/kwatchgnupg/kwatchgnupgmainwin.h deleted file mode 100644 index 2021a65799..0000000000 --- a/kleopatra/kwatchgnupg/kwatchgnupgmainwin.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - main.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef KWATCHGNUPGMAINWIN_H -#define KWATCHGNUPGMAINWIN_H - -#include - -class KWatchGnuPGTray; -class KWatchGnuPGConfig; -class KProcIO; -class QTextEdit; - -class KWatchGnuPGMainWindow : public KMainWindow { - Q_OBJECT -public: - KWatchGnuPGMainWindow( QWidget* parent = 0, const char* name = 0 ); - virtual ~KWatchGnuPGMainWindow(); -public slots: - void slotWatcherExited(); - void slotReadStdout(); - void slotAckRead(); - - void slotSaveAs(); - void slotQuit(); - void slotClear(); - - void slotConfigure(); - void slotConfigureToolbars(); - void configureShortcuts(); - void slotReadConfig(); - - virtual void show(); -protected: - virtual bool queryClose(); -private: - void createActions(); - void startWatcher(); - void setGnuPGConfig(); - - KProcIO* mWatcher; - - QTextEdit* mCentralWidget; - KWatchGnuPGTray* mSysTray; - KWatchGnuPGConfig* mConfig; -}; - -#endif /* KWATCHGNUPGMAINWIN_H */ - diff --git a/kleopatra/kwatchgnupg/main.cpp b/kleopatra/kwatchgnupg/main.cpp deleted file mode 100644 index 7c25a8da0d..0000000000 --- a/kleopatra/kwatchgnupg/main.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - main.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "aboutdata.h" -#include "kwatchgnupgmainwin.h" - -#include -#include -#include -#include -#include -#include -#include - -class KWatchGnuPGApplication : public KUniqueApplication { -public: - KWatchGnuPGApplication(); - ~KWatchGnuPGApplication(); - virtual int newInstance(); -private: - KWatchGnuPGMainWindow* mMainWin; -}; - -KWatchGnuPGApplication::KWatchGnuPGApplication() - : KUniqueApplication(), mMainWin(0) -{ -} - -KWatchGnuPGApplication::~KWatchGnuPGApplication() -{ - delete mMainWin; -} - -int KWatchGnuPGApplication::newInstance() -{ - if( !mMainWin ) { - mMainWin = new KWatchGnuPGMainWindow( 0, "kwatchgnupg mainwin" ); - setMainWidget( mMainWin ); - } - mMainWin->show(); - return KUniqueApplication::newInstance(); -} - -int main( int argc, char** argv ) -{ - AboutData aboutData; - - KCmdLineArgs::init(argc, argv, &aboutData); - static const KCmdLineOptions options[] = { - KCmdLineLastOption// End of options. - }; - KCmdLineArgs::addCmdLineOptions( options ); - KWatchGnuPGApplication::addCmdLineOptions(); - -#if 0 - if (!KWatchGnuPGApplication::start()) { - kdError() << "KWatchGnuPG is already running!" << endl; - return 0; - } -#endif - KWatchGnuPGApplication app; - return app.exec(); -} diff --git a/kleopatra/kwatchgnupg/tray.cpp b/kleopatra/kwatchgnupg/tray.cpp deleted file mode 100644 index 62024b14a1..0000000000 --- a/kleopatra/kwatchgnupg/tray.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - main.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "tray.h" -#include "kwatchgnupgmainwin.h" - -#include -#include -#include -#include -#include - -KWatchGnuPGTray::KWatchGnuPGTray( KWatchGnuPGMainWindow* mainwin ) - : KSystemTray( mainwin, "KWatchGnuPG Tray Window" ) -{ - kdDebug() << "KWatchGnuPGTray::KWatchGnuPGTray" << endl; - - KGlobal::iconLoader()->addAppDir( "kwatchgnupg" ); - - mNormalPix = loadIcon("kwatchgnupg"); - mAttentionPix = loadIcon("kwatchgnupg2"); - - setPixmap( mNormalPix ); - QToolTip::add( this, i18n("KWatchGnuPG Log Viewer") ); -} - -KWatchGnuPGTray::~KWatchGnuPGTray() -{ -} - -void KWatchGnuPGTray::setAttention( bool att ) -{ - if( att ) setPixmap( mAttentionPix ); - else setPixmap( mNormalPix ); -} - -#include "tray.moc" diff --git a/kleopatra/kwatchgnupg/tray.h b/kleopatra/kwatchgnupg/tray.h deleted file mode 100644 index 7f220ecad9..0000000000 --- a/kleopatra/kwatchgnupg/tray.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - main.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef TRAY_H -#define TRAY_H - -#include -#include - -class KWatchGnuPGMainWindow; - -class KWatchGnuPGTray : public KSystemTray { - Q_OBJECT -public: - KWatchGnuPGTray( KWatchGnuPGMainWindow* mainwin ); - virtual ~KWatchGnuPGTray(); - -public slots: - void setAttention( bool att ); -private: - QPixmap mNormalPix; - QPixmap mAttentionPix; -}; - -#endif /* TRAY_H */ - diff --git a/kleopatra/lib/Makefile.am b/kleopatra/lib/Makefile.am deleted file mode 100644 index ae101fd0e0..0000000000 --- a/kleopatra/lib/Makefile.am +++ /dev/null @@ -1,49 +0,0 @@ -INCLUDES = -I$(top_srcdir)/libkdenetwork $(GPGME_CFLAGS) $(all_includes) - -SUBDIRS = pics kleo backends ui . tests - -lib_LTLIBRARIES = libkleopatra.la - -libkleopatra_la_SOURCES = \ - cryptplug.cpp \ - cryptplugwrapper.cpp \ - cryptplugwrapperlist.cpp \ - cryptplugfactory.cpp - -libkleopatra_la_LIBADD = \ - kleo/libkleopatra_core.la \ - backends/qgpgme/libkleopatra_backend_qgpgme.la \ - backends/chiasmus/libkleopatra_backend_chiasmus.la \ - ui/libkleopatra_ui.la \ - \ - $(top_builddir)/libkdenetwork/qgpgme/libqgpgme.la \ - $(LIB_KIO) $(LIB_KDEUI) - -# Disabled for kdepim-3.3, see also kleo/cryptobackendfactory.cpp -# backends/kpgp/libkleopatra_backend_kpgp.la - -# --version-info CURRENT:REVISION:AGE -# (Code changed: REVISION++) -# (Interfaces added/removed/changed: CURRENT++, REVISION=0) -# (Interfaces added: AGE++) -# (Interfaces removed/changed: AGE=0) -libkleopatra_la_LDFLAGS = $(all_libraries) -version-info 1:0:0 -no-undefined - -METASOURCES = AUTO - -# remove the .desktop suffix on install (which is needed for translation) -install-data-local: - $(mkinstalldirs) $(DESTDIR)$(kde_confdir) - $(INSTALL_DATA) $(srcdir)/libkleopatrarc.desktop $(DESTDIR)$(kde_confdir)/libkleopatrarc - -uninstall-local: - rm -f $(DESTDIR)$(kde_confdir)/libkleopatrarc - -messages: #rc.cpp - $(EXTRACTRC) */*.ui > rc.cpp - $(XGETTEXT) *.cpp *.h \ - kleo/*.cpp kleo/*.h \ - ui/*.cpp ui/*.h \ - backends/*/*.cpp backends/*/*.h -o $(podir)/libkleopatra.pot - -include $(top_srcdir)/admin/Doxyfile.am diff --git a/kleopatra/lib/backends/Makefile.am b/kleopatra/lib/backends/Makefile.am deleted file mode 100644 index 0219d76277..0000000000 --- a/kleopatra/lib/backends/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -SUBDIRS = qgpgme chiasmus diff --git a/kleopatra/lib/backends/kpgp/gpg1backend.h b/kleopatra/lib/backends/kpgp/gpg1backend.h deleted file mode 100644 index f9413accf9..0000000000 --- a/kleopatra/lib/backends/kpgp/gpg1backend.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - gpg1backend.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - - -#ifndef __KLEO_GPG1BACKEND_H__ -#define __KLEO_GPG1BACKEND_H__ - -#include "kpgpbackendbase.h" - -class QString; - -namespace Kleo { - - class GPG1Backend : public KpgpBackendBase { - public: - QString name() const; - QString displayName() const; - }; - -} - - -#endif // __KLEO_GPG1BACKEND_H__ diff --git a/kleopatra/lib/backends/kpgp/kpgpbackendbase.cpp b/kleopatra/lib/backends/kpgp/kpgpbackendbase.cpp deleted file mode 100644 index 2d4d17ab2b..0000000000 --- a/kleopatra/lib/backends/kpgp/kpgpbackendbase.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - kpgpbackendbase.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "kpgpbackendbase.h" - -#include "pgp2backend.h" -#include "pgp5backend.h" -#include "pgp6backend.h" -#include "gpg1backend.h" - -#include - -#include - -#include "kpgpwrapper.h" - -Kleo::KpgpBackendBase::KpgpBackendBase() - : Kleo::CryptoBackend(), - mOpenPGPProtocol( 0 ) -{ -} - -Kleo::KpgpBackendBase::~KpgpBackendBase() -{ - delete mOpenPGPProtocol; mOpenPGPProtocol = 0; -} - -QString Kleo::GPG1Backend::name() const { - return GPG1_BACKEND_NAME; -} - -QString Kleo::GPG1Backend::displayName() const { - return i18n("Kpgp/gpg"); -} - -QString Kleo::PGP2Backend::name() const { - return PGP2_BACKEND_NAME; -} - -QString Kleo::PGP2Backend::displayName() const { - return i18n("Kpgp/pgp v2"); -} - -QString Kleo::PGP5Backend::name() const { - return PGP5_BACKEND_NAME; -} - -QString Kleo::PGP5Backend::displayName() const { - return i18n("Kpgp/pgp v5"); -} - -QString Kleo::PGP6Backend::name() const { - return PGP6_BACKEND_NAME; -} - -QString Kleo::PGP6Backend::displayName() const { - return i18n("Kpgp/pgp v6"); -} - -static const QString notSupported() { - return i18n("This backend does not support S/MIME"); -} - -bool Kleo::KpgpBackendBase::checkForOpenPGP( QString * /*reason*/ ) const { - return true; -} - -bool Kleo::KpgpBackendBase::checkForSMIME( QString * reason ) const { - if ( reason ) *reason = notSupported(); - return false; -} - -Kleo::CryptoBackend::Protocol * Kleo::KpgpBackendBase::openpgp() const { - if ( !mOpenPGPProtocol ) - if ( checkForOpenPGP() ) - mOpenPGPProtocol = new KpgpWrapper( name() ); - return mOpenPGPProtocol; -} diff --git a/kleopatra/lib/backends/kpgp/kpgpbackendbase.h b/kleopatra/lib/backends/kpgp/kpgpbackendbase.h deleted file mode 100644 index 854e800c31..0000000000 --- a/kleopatra/lib/backends/kpgp/kpgpbackendbase.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - kpgpbackendbase.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - - -#ifndef __KLEO_KPGPBACKENDBASE_H__ -#define __KLEO_KPGPBACKENDBASE_H__ - -#include "kleo/cryptobackend.h" - -#define GPG1_BACKEND_NAME "Kpgp/gpg1" -#define PGP2_BACKEND_NAME "Kpgp/pgp2" -#define PGP5_BACKEND_NAME "Kpgp/pgp5" -#define PGP6_BACKEND_NAME "Kpgp/pgp6" - -namespace Kleo { - class CryptoConfig; -} -class QString; -class KpgpWrapper; - -namespace Kleo { - - class KpgpBackendBase : public Kleo::CryptoBackend { - public: - KpgpBackendBase(); - ~KpgpBackendBase(); - - CryptoConfig * config() const { return 0; } - Protocol * openpgp() const; - Protocol * smime() const { return 0; } - - bool supportsOpenPGP() const { return true; } - bool supportsSMIME() const { return false; } - - bool checkForOpenPGP( QString * reason=0 ) const; - bool checkForSMIME( QString * reason=0 ) const; - private: - mutable KpgpWrapper * mOpenPGPProtocol; - }; - -} - - -#endif // __KLEO_KPGPBACKENDBASE_H__ diff --git a/kleopatra/lib/backends/kpgp/kpgpkeylistjob.cpp b/kleopatra/lib/backends/kpgp/kpgpkeylistjob.cpp deleted file mode 100644 index 4c328adeef..0000000000 --- a/kleopatra/lib/backends/kpgp/kpgpkeylistjob.cpp +++ /dev/null @@ -1,303 +0,0 @@ -/* - kpgpkeylistjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Ingo Kloecker - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "kpgpkeylistjob.h" - -#include -#include - -#include -#include - -#include - -#include - -#include -#include -#include - -Kleo::KpgpKeyListJob::KpgpKeyListJob( Kpgp::Base * pgpBase ) - : KeyListJob( 0, "Kleo::KpgpKeyListJob" ), - mPgpBase( pgpBase ) -{ -} - -Kleo::KpgpKeyListJob::~KpgpKeyListJob() { -} - -// the following function is a verbatim copy from gpgme/key.c -static char * -set_user_id_part (char *tail, const char *buf, size_t len) -{ - while (len && (buf[len - 1] == ' ' || buf[len - 1] == '\t')) - len--; - for (; len; len--) - *tail++ = *buf++; - *tail++ = 0; - return tail; -} - -// the following function is a verbatim copy from gpgme/key.c -static void -parse_user_id (char *src, char **name, char **email, - char **comment, char *tail) -{ - const char *start = NULL; - int in_name = 0; - int in_email = 0; - int in_comment = 0; - - while (*src) - { - if (in_email) - { - if (*src == '<') - /* Not legal but anyway. */ - in_email++; - else if (*src == '>') - { - if (!--in_email && !*email) - { - *email = tail; - tail = set_user_id_part (tail, start, src - start); - } - } - } - else if (in_comment) - { - if (*src == '(') - in_comment++; - else if (*src == ')') - { - if (!--in_comment && !*comment) - { - *comment = tail; - tail = set_user_id_part (tail, start, src - start); - } - } - } - else if (*src == '<') - { - if (in_name) - { - if (!*name) - { - *name = tail; - tail = set_user_id_part (tail, start, src - start); - } - in_name = 0; - } - in_email = 1; - start = src + 1; - } - else if (*src == '(') - { - if (in_name) - { - if (!*name) - { - *name = tail; - tail = set_user_id_part (tail, start, src - start); - } - in_name = 0; - } - in_comment = 1; - start = src + 1; - } - else if (!in_name && *src != ' ' && *src != '\t') - { - in_name = 1; - start = src; - } - src++; - } - - if (in_name) - { - if (!*name) - { - *name = tail; - tail = set_user_id_part (tail, start, src - start); - } - } - - /* Let unused parts point to an EOS. */ - tail--; - if (!*name) - *name = tail; - if (!*email) - *email = tail; - if (!*comment) - *comment = tail; -} - -gpgme_user_id_t KpgpUserID2GPGMEUserID( const Kpgp::UserID * kUserId ) -{ - // inspired by _gpgme_key_append_name - - const QCString text = kUserId->text().utf8(); - const int src_len = text.length(); - - gpgme_user_id_t uid; - /* Allocate enough memory for the _gpgme_user_id struct, for the actual user - id (the text) and for the parsed version. */ - uid = (gpgme_user_id_t) malloc( sizeof( *uid ) + 2 * src_len + 3 ); - memset( uid, 0, sizeof *uid ); - uid->revoked = kUserId->revoked(); - uid->invalid = kUserId->invalid(); - uid->validity = (gpgme_validity_t) kUserId->validity(); - - uid->uid = ((char *) uid) + sizeof (*uid); - char *dst = uid->uid; - memcpy( dst, text.data(), src_len + 1 ); - - dst += src_len + 1; - parse_user_id( uid->uid, &uid->name, &uid->email, - &uid->comment, dst ); - - return uid; -} - -gpgme_subkey_t KpgpSubkey2GPGMESubKey( const Kpgp::Subkey * kSubkey ) -{ - gpgme_subkey_t subkey; - - const QCString fpr = kSubkey->fingerprint(); - const unsigned int fpr_len = fpr.length(); - const QCString keyId = kSubkey->longKeyID(); - - subkey = (gpgme_subkey_t) calloc( 1, sizeof( *subkey ) + fpr_len + 1 ); - subkey->revoked = kSubkey->revoked(); - subkey->expired = kSubkey->expired(); - subkey->disabled = kSubkey->disabled(); - subkey->invalid = kSubkey->invalid(); - subkey->can_encrypt = kSubkey->canEncrypt(); - subkey->can_sign = kSubkey->canSign(); - subkey->can_certify = kSubkey->canCertify(); - subkey->secret = kSubkey->secret(); - subkey->pubkey_algo = (gpgme_pubkey_algo_t) kSubkey->keyAlgorithm(); - subkey->length = kSubkey->keyLength(); - subkey->keyid = subkey->_keyid; - memcpy( subkey->_keyid, keyId.data(), keyId.length() + 1 ); - subkey->fpr = ((char *) subkey) + sizeof( *subkey ); - memcpy( subkey->fpr, fpr.data(), fpr_len + 1 ); - subkey->timestamp = kSubkey->creationDate(); - subkey->expires = kSubkey->expirationDate(); - - return subkey; -} - -gpgme_key_t KpgpKey2gpgme_key( const Kpgp::Key * kKey ) -{ - gpgme_key_t key; - - key = (gpgme_key_t) calloc( 1, sizeof( *key ) ); - key->revoked = kKey->revoked(); - key->expired = kKey->expired(); - key->disabled = kKey->disabled(); - key->invalid = kKey->invalid(); - key->can_encrypt = kKey->canEncrypt(); - key->can_sign = kKey->canSign(); - key->can_certify = kKey->canCertify(); - key->secret = kKey->secret(); - key->protocol = GPGME_PROTOCOL_OpenPGP; - key->owner_trust = GPGME_VALIDITY_UNKNOWN; // FIXME? - - Kpgp::UserIDList kUserIDs = kKey->userIDs(); - for ( Kpgp::UserIDListIterator it( kUserIDs ); it.current(); ++it ) { - gpgme_user_id_t uid = KpgpUserID2GPGMEUserID( *it ); - if ( !key->uids ) - key->uids = uid; - if ( key->_last_uid ) - key->_last_uid->next = uid; - key->_last_uid = uid; - } - - Kpgp::SubkeyList kSubkeys = kKey->subkeys(); - for ( Kpgp::SubkeyListIterator it( kSubkeys ); it.current(); ++it ) { - gpgme_subkey_t subkey = KpgpSubkey2GPGMESubKey( *it ); - if (!key->subkeys) - key->subkeys = subkey; - if (key->_last_subkey) - key->_last_subkey->next = subkey; - key->_last_subkey = subkey; - } - - return key; -} - -GpgME::Error Kleo::KpgpKeyListJob::start( const QStringList & patterns, - bool secretOnly ) { - mPatterns = patterns; - mSecretOnly = secretOnly; - QTimer::singleShot( 0, this, SLOT( slotDoIt() ) ); - return GpgME::Error( 0 ); -} - -void Kleo::KpgpKeyListJob::slotDoIt() { - std::vector keys; - GpgME::KeyListResult res = exec( mPatterns, mSecretOnly, keys ); - for ( std::vector::const_iterator it = keys.begin(); - it != keys.end(); ++it ) - emit nextKey( *it ); - emit done(); - emit result( res ); - deleteLater(); -} - -GpgME::KeyListResult Kleo::KpgpKeyListJob::exec( const QStringList & patterns, - bool secretOnly, - std::vector & keys ) { - Kpgp::KeyList kKeys; - if ( secretOnly ) - kKeys = mPgpBase->secretKeys( patterns ); - else - kKeys = mPgpBase->publicKeys( patterns ); - - keys.clear(); - for ( Kpgp::KeyListIterator it( kKeys ); it.current(); ++it ) { - keys.push_back( GpgME::Key( KpgpKey2gpgme_key(*it), true ) ); - } - - _gpgme_op_keylist_result res; - res.truncated = 0; // key list is not truncated - res._unused = 0; - - return GpgME::KeyListResult( GpgME::Error( 0 ), res ); -} - -#include "kpgpkeylistjob.moc" diff --git a/kleopatra/lib/backends/kpgp/kpgpkeylistjob.h b/kleopatra/lib/backends/kpgp/kpgpkeylistjob.h deleted file mode 100644 index 779680c2dd..0000000000 --- a/kleopatra/lib/backends/kpgp/kpgpkeylistjob.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -*- mode: C++ -*- - kpgpkeylistjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Ingo Kloecker - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KPGPKEYLISTJOB_H__ -#define __KLEO_KPGPKEYLISTJOB_H__ - -#include - -#include - -namespace GpgME { - class Error; - class Context; - class Key; -} - -namespace Kpgp { - class Base; -} - -namespace Kleo { - - class KpgpKeyListJob : public KeyListJob { - Q_OBJECT - public: - KpgpKeyListJob( Kpgp::Base * pgpBase ); - ~KpgpKeyListJob(); - - /*! \reimp from KeyListJob */ - GpgME::Error start( const QStringList & patterns, bool secretOnly ); - - /*! \reimp from KeyListJob */ - GpgME::KeyListResult exec( const QStringList & patterns, bool secretOnly, - std::vector & keys ); - - /*! \reimp from Job */ - void slotCancel() { /*FIXME*/ } - - private slots: - void slotDoIt(); - - private: - Kpgp::Base * mPgpBase; - QStringList mPatterns; - bool mSecretOnly; - }; - -} - -#endif // __KLEO_KPGPKEYLISTJOB_H__ diff --git a/kleopatra/lib/backends/kpgp/kpgpwrapper.cpp b/kleopatra/lib/backends/kpgp/kpgpwrapper.cpp deleted file mode 100644 index 20d885dd51..0000000000 --- a/kleopatra/lib/backends/kpgp/kpgpwrapper.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - kpgpwrapper.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Ingo Kloecker - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "kpgpwrapper.h" - -#include "kpgpbackendbase.h" - -#include - -#include -//#include -//#include -//#include -//#include -//#include -//#include -//#include -//#include -//#include -//#include -//#include -//#include -//#include -//#include - -KpgpWrapper::KpgpWrapper( const QString & name ) - : mName( name ), - mPgpBase( 0 ) -{ - -} - -KpgpWrapper::~KpgpWrapper() -{ - -} - -QString KpgpWrapper::name() const -{ - return mName; -} - -QString KpgpWrapper::displayName() const -{ - return mName; -} - -Kleo::KeyListJob * KpgpWrapper::keyListJob( bool /*remote*/, - bool /*includeSigs*/, - bool /*validate*/ ) const -{ - return new Kleo::KpgpKeyListJob( pgpBase() ); -} - -Kleo::EncryptJob * KpgpWrapper::encryptJob( bool /*armor*/, - bool /*textmode*/ ) const -{ - return 0; -} - -Kleo::DecryptJob * KpgpWrapper::decryptJob() const -{ - return 0; -} - -Kleo::SignJob * KpgpWrapper::signJob( bool /*armor*/, bool /*textMode*/ ) const -{ - return 0; -} - -Kleo::VerifyDetachedJob * KpgpWrapper::verifyDetachedJob( bool /*textmode*/ ) const -{ - return 0; -} - -Kleo::VerifyOpaqueJob * KpgpWrapper::verifyOpaqueJob( bool /*textmode*/ ) const -{ - return 0; -} - -Kleo::KeyGenerationJob * KpgpWrapper::keyGenerationJob() const -{ - return 0; -} - -Kleo::ImportJob * KpgpWrapper::importJob() const -{ - return 0; -} - -Kleo::ExportJob * KpgpWrapper::publicKeyExportJob( bool /*armor*/ ) const -{ - return 0; -} - -Kleo::ExportJob * KpgpWrapper::secretKeyExportJob( bool /*armor*/ ) const -{ - return 0; -} - -Kleo::DownloadJob * KpgpWrapper::downloadJob( bool /*armor*/ ) const -{ - return 0; -} - -Kleo::DeleteJob * KpgpWrapper::deleteJob() const -{ - return 0; -} - -Kleo::SignEncryptJob * KpgpWrapper::signEncryptJob( bool /*armor*/, - bool /*textMode*/ ) const -{ - return 0; -} - -Kleo::DecryptVerifyJob * KpgpWrapper::decryptVerifyJob( bool /*textmode*/ ) const -{ - return 0; -} - -Kleo::RefreshKeysJob * KpgpWrapper::refreshKeysJob() const -{ - return 0; -} - -Kpgp::Base * KpgpWrapper::pgpBase() const -{ - if ( !mPgpBase ) { - if ( name() == GPG1_BACKEND_NAME ) - mPgpBase = new Kpgp::BaseG(); - else if ( name() == PGP2_BACKEND_NAME ) - mPgpBase = new Kpgp::Base2(); - else if ( name() == PGP5_BACKEND_NAME ) - mPgpBase = new Kpgp::Base5(); - else if ( name() == PGP6_BACKEND_NAME ) - mPgpBase = new Kpgp::Base6(); - } - return mPgpBase; -} diff --git a/kleopatra/lib/backends/kpgp/kpgpwrapper.h b/kleopatra/lib/backends/kpgp/kpgpwrapper.h deleted file mode 100644 index 182661ec48..0000000000 --- a/kleopatra/lib/backends/kpgp/kpgpwrapper.h +++ /dev/null @@ -1,97 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - kpgpwrapper.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Ingo Kloecker - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KPGPWRAPPER_H__ -#define __KLEO_KPGPWRAPPER_H__ - -#include - -#include - -namespace Kleo { - class KeyListJob; - class EncryptJob; - class DecryptJob; - class SignJob; - class VerifyDetachedJob; - class VerifyOpaqueJob; - class KeyGenerationJob; - class ImportJob; - class ExportJob; - class DownloadJob; - class DeleteJob; - class SignEncryptJob; - class DecryptVerifyJob; - class CryptoConfig; - class RefreshKeysJob; -} - -namespace Kpgp { - class Base; -} - -class KpgpWrapper : public Kleo::CryptoBackend::Protocol { -public: - KpgpWrapper( const QString & name ); - ~KpgpWrapper(); - - QString name() const; - - QString displayName() const; - - Kleo::KeyListJob * keyListJob( bool remote=false, bool includeSigs=false, - bool validate=false ) const; - Kleo::EncryptJob * encryptJob( bool armor=false, bool textmode=false ) const; - Kleo::DecryptJob * decryptJob() const; - Kleo::SignJob * signJob( bool armor=false, bool textMode=false ) const; - Kleo::VerifyDetachedJob * verifyDetachedJob( bool textmode=false) const; - Kleo::VerifyOpaqueJob * verifyOpaqueJob( bool textmode=false ) const; - Kleo::KeyGenerationJob * keyGenerationJob() const; - Kleo::ImportJob * importJob() const; - Kleo::ExportJob * publicKeyExportJob( bool armor=false ) const; - Kleo::ExportJob * secretKeyExportJob( bool armor=false ) const; - Kleo::DownloadJob * downloadJob( bool armor=false ) const; - Kleo::DeleteJob * deleteJob() const; - Kleo::SignEncryptJob * signEncryptJob( bool armor=false, - bool textMode=false ) const; - Kleo::DecryptVerifyJob * decryptVerifyJob( bool textmode=false ) const; - Kleo::RefreshKeysJob * refreshKeysJob() const; - -private: - Kpgp::Base * pgpBase() const; - -private: - QString mName; - mutable Kpgp::Base * mPgpBase; -}; - -#endif // __KLEO_KPGPWRAPPER_H__ diff --git a/kleopatra/lib/backends/kpgp/pgp2backend.h b/kleopatra/lib/backends/kpgp/pgp2backend.h deleted file mode 100644 index fc053a20c4..0000000000 --- a/kleopatra/lib/backends/kpgp/pgp2backend.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - pgp2backend.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - - -#ifndef __KLEO_PGP2BACKEND_H__ -#define __KLEO_PGP2BACKEND_H__ - -#include "kpgpbackendbase.h" - -class QString; - -namespace Kleo { - - class PGP2Backend : public KpgpBackendBase { - public: - QString name() const; - QString displayName() const; - }; - -} - - -#endif // __KLEO_PGP2BACKEND_H__ diff --git a/kleopatra/lib/backends/kpgp/pgp5backend.h b/kleopatra/lib/backends/kpgp/pgp5backend.h deleted file mode 100644 index bf323b6fb2..0000000000 --- a/kleopatra/lib/backends/kpgp/pgp5backend.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - pgp5backend.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - - -#ifndef __KLEO_PGP5BACKEND_H__ -#define __KLEO_PGP5BACKEND_H__ - -#include "kpgpbackendbase.h" - -class QString; - -namespace Kleo { - - class PGP5Backend : public KpgpBackendBase { - public: - QString name() const; - QString displayName() const; - }; - -} - - -#endif // __KLEO_PGP5BACKEND_H__ diff --git a/kleopatra/lib/backends/kpgp/pgp6backend.h b/kleopatra/lib/backends/kpgp/pgp6backend.h deleted file mode 100644 index 827cf239b8..0000000000 --- a/kleopatra/lib/backends/kpgp/pgp6backend.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - pgp6backend.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - - -#ifndef __KLEO_PGP6BACKEND_H__ -#define __KLEO_PGP6BACKEND_H__ - -#include "kpgpbackendbase.h" - -class QString; - -namespace Kleo { - - class PGP6Backend : public KpgpBackendBase { - public: - QString name() const; - QString displayName() const; - }; - -} - - -#endif // __KLEO_PGP6BACKEND_H__ diff --git a/kleopatra/lib/backends/qgpgme/gnupgprocessbase.cpp b/kleopatra/lib/backends/qgpgme/gnupgprocessbase.cpp deleted file mode 100644 index 2d3ca74096..0000000000 --- a/kleopatra/lib/backends/qgpgme/gnupgprocessbase.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - gnupgprocessbase.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "gnupgprocessbase.h" - -#include -#include - -#include -#include -#include - -#include -#include -#include -#include - -struct Kleo::GnuPGProcessBase::Private { - Private() : useStatusFD( false ), statnot( 0 ) { - statusFD[0] = statusFD[1] = -1; - } - - bool useStatusFD; - int statusFD[2]; - QSocketNotifier * statnot; - QCString statusBuffer; -}; - - -Kleo::GnuPGProcessBase::GnuPGProcessBase( QObject * parent, const char * name ) - : KProcess( parent, name ) -{ - d = new Private(); -} - -Kleo::GnuPGProcessBase::~GnuPGProcessBase() { - delete d; d = 0; -} - -void Kleo::GnuPGProcessBase::setUseStatusFD( bool use ) { - assert( d ); - d->useStatusFD = use; -} - -bool Kleo::GnuPGProcessBase::start( RunMode runmode, Communication comm ) { - if ( d->useStatusFD ) { - // set up the status-fd. This should be in setupCommunication(), - // but then it's too late: we need the fd of the pipe to pass it - // as argument to the --status-fd option: - // PENDING(marc) find out why KProcess uses both pipe() and socketpair()... - if ( ::pipe( d->statusFD ) < 0 ) { - kdDebug( 5150 ) << "Kleo::GnuPGProcessBase::start: pipe(2) failed: " << perror << endl; - return false; - } - ::fcntl( d->statusFD[0], F_SETFD, FD_CLOEXEC ); - ::fcntl( d->statusFD[1], F_SETFD, FD_CLOEXEC ); - if ( !arguments.empty() ) { - QValueList::iterator it = arguments.begin(); - ++it; - arguments.insert( it, "--status-fd" ); - char buf[25]; - sprintf( buf, "%d", d->statusFD[1] ); - arguments.insert( it, buf ); - arguments.insert( it, "--no-tty" ); - //arguments.insert( it, "--enable-progress-filter" ); // gpgsm doesn't know this - } - } - return KProcess::start( runmode, comm ); -} - -int Kleo::GnuPGProcessBase::setupCommunication( Communication comm ) { - if ( int ok = KProcess::setupCommunication( comm ) ) - return ok; - if ( d->useStatusFD ) { - // base class impl returned error, so close our fd's, too - ::close( d->statusFD[0] ); - ::close( d->statusFD[1] ); - d->statusFD[0] = d->statusFD[1] = -1; - } - return 0; // Error -} - -int Kleo::GnuPGProcessBase::commSetupDoneP() { - if ( d->useStatusFD ) { - ::close( d->statusFD[1] ); // close the input end of the pipe, we're the reader - d->statnot = new QSocketNotifier( d->statusFD[0], QSocketNotifier::Read, this ); - connect( d->statnot, SIGNAL(activated(int)), SLOT(slotChildStatus(int)) ); - } - return KProcess::commSetupDoneP(); -} - -int Kleo::GnuPGProcessBase::commSetupDoneC() { - if ( d->useStatusFD ) - ::fcntl( d->statusFD[1], F_SETFD, 0 ); - return KProcess::commSetupDoneC(); -} - -void Kleo::GnuPGProcessBase::slotChildStatus( int fd ) { - if ( !childStatus(fd) ) - closeStatus(); -} - -bool Kleo::GnuPGProcessBase::closeStatus() { - if ( !d->useStatusFD ) - return false; - d->useStatusFD = false; - delete d->statnot; d->statnot = 0; - ::close( d->statusFD[0] ); d->statusFD[0] = -1; - return true; -} - -int Kleo::GnuPGProcessBase::childStatus( int fd ) { - char buf[1024]; - const int len = ::read( fd, buf, sizeof(buf)-1 ); - if ( len > 0 ) { - buf[len] = 0; - d->statusBuffer += buf; - parseStatusOutput(); - } - return len; -} - -static QString fromHexEscapedUtf8( const QCString & str ) { - return KURL::decode_string( str.data(), 106 /* utf-8 */ ); -} - -void Kleo::GnuPGProcessBase::parseStatusOutput() { - static const char startToken[] = "[GNUPG:] "; - static const int startTokenLen = sizeof startToken / sizeof *startToken - 1; - - int lineStart = 0; - for ( int lineEnd = d->statusBuffer.find( '\n' ) ; lineEnd >= 0 ; lineEnd = d->statusBuffer.find( '\n', lineStart = lineEnd+1 ) ) { - // get next line: - const QCString line = d->statusBuffer.mid( lineStart, lineEnd - lineStart ).stripWhiteSpace(); - if ( line.isEmpty() ) - continue; - // check status token - if ( line.left( startTokenLen ) != startToken ) { - kdDebug( 5150 ) << "Kleo::GnuPGProcessBase::childStatus: status-fd protocol error: line doesn't begin with \"" - << startToken << "\"" << endl; - continue; - } - // remove status token: - const QCString command = line.mid( startTokenLen ).simplifyWhiteSpace() + ' '; - if ( command == " " ) { - kdDebug( 5150 ) << "Kleo::GnuPGProcessBase::childStatus: status-fd protocol error: line without content." << endl; - continue; - } - // split into base and args - QString cmd; - QStringList args; - int tagStart = 0; - for ( int tagEnd = command.find( ' ' ) ; tagEnd >= 0 ; tagEnd = command.find( ' ', tagStart = tagEnd+1 ) ) { - const QCString tag = command.mid( tagStart, tagEnd - tagStart ); - if ( cmd.isNull() ) - cmd = fromHexEscapedUtf8( tag ); - else - args.push_back( fromHexEscapedUtf8( tag ) ); - } - emit status( this, cmd, args ); - } - d->statusBuffer = d->statusBuffer.mid( lineStart ); -} - -void Kleo::GnuPGProcessBase::virtual_hook( int id, void * data ) { - KProcess::virtual_hook( id, data ); -} - -#include "gnupgprocessbase.moc" diff --git a/kleopatra/lib/backends/qgpgme/gnupgprocessbase.h b/kleopatra/lib/backends/qgpgme/gnupgprocessbase.h deleted file mode 100644 index 73e31e2959..0000000000 --- a/kleopatra/lib/backends/qgpgme/gnupgprocessbase.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - gnupgprocessbase.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_GNUPGPROCESSBASE_H__ -#define __KLEO_GNUPGPROCESSBASE_H__ - -#include - -namespace Kleo { - - /** - * @short a base class for GPG and GPGSM processes. - * - * This KProcess subclass implements the status-fd handling common - * to GPG and GPGSM. - * - * @author Marc Mutz - */ - class GnuPGProcessBase : public KProcess { - Q_OBJECT - public: - GnuPGProcessBase( QObject * parent=0, const char * name=0 ); - ~GnuPGProcessBase(); - - void setUseStatusFD( bool use ); - - /*! reimplementation */ - bool start( RunMode runmode, Communication comm ); - - bool closeStatus(); - - signals: - void status( Kleo::GnuPGProcessBase * proc, const QString & type, const QStringList & args ); - - protected: - /*! reimplementation */ - int setupCommunication( Communication comm ); - /*! reimplementation */ - int commSetupDoneP(); - /*! reimplementation */ - int commSetupDoneC(); - - int childStatus( int fd ); - - - private slots: - void slotChildStatus( int fd ); - - private: - void parseStatusOutput(); - - private: - class Private; - Private * d; - protected: - /*! reimplementation */ - void virtual_hook( int id, void * data ); - }; - -} - -#endif // __KLEO_GNUPGPROCESSBASE_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmebackend.cpp b/kleopatra/lib/backends/qgpgme/qgpgmebackend.cpp deleted file mode 100644 index de05eb1603..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmebackend.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - qgpgmebackend.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmebackend.h" - -#include "qgpgmecryptoconfig.h" -#include "cryptplugwrapper.h" - -#include -#include - -#include -#include - -#include -#include - -Kleo::QGpgMEBackend::QGpgMEBackend() - : Kleo::CryptoBackend(), - mCryptoConfig( 0 ), - mOpenPGPProtocol( 0 ), - mSMIMEProtocol( 0 ) -{ - -} - -Kleo::QGpgMEBackend::~QGpgMEBackend() { - delete mCryptoConfig; mCryptoConfig = 0; - delete mOpenPGPProtocol; mOpenPGPProtocol = 0; - delete mSMIMEProtocol; mSMIMEProtocol = 0; -} - -QString Kleo::QGpgMEBackend::name() const { - return "gpgme"; -} - -QString Kleo::QGpgMEBackend::displayName() const { - return i18n( "GpgME" ); -} - -Kleo::CryptoConfig * Kleo::QGpgMEBackend::config() const { - if ( !mCryptoConfig ) { - static bool hasGpgConf = !KStandardDirs::findExe( "gpgconf" ).isEmpty(); - if ( hasGpgConf ) - mCryptoConfig = new QGpgMECryptoConfig(); - } - return mCryptoConfig; -} - -static bool check( GpgME::Context::Protocol proto, QString * reason ) { - if ( !GpgME::checkEngine( proto ) ) - return true; - if ( !reason ) - return false; - // error, check why: - const GpgME::EngineInfo ei = GpgME::engineInfo( proto ); - if ( ei.isNull() ) - *reason = i18n("GPGME was compiled without support for %1.").arg( proto == GpgME::Context::CMS ? "S/MIME" : "OpenPGP" ); - else if ( ei.fileName() && !ei.version() ) - *reason = i18n("Engine %1 is not installed properly.").arg( QFile::decodeName( ei.fileName() ) ); - else if ( ei.fileName() && ei.version() && ei.requiredVersion() ) - *reason = i18n("Engine %1 version %2 installed, " - "but at least version %3 is required.") - .arg( QFile::decodeName( ei.fileName() ), ei.version(), ei.requiredVersion() ); - else - *reason = i18n("Unknown problem with engine for protocol %1.").arg( proto == GpgME::Context::CMS ? "S/MIME" : "OpenPGP" ); - return false; -} - -bool Kleo::QGpgMEBackend::checkForOpenPGP( QString * reason ) const { - return check( GpgME::Context::OpenPGP, reason ); -} - -bool Kleo::QGpgMEBackend::checkForSMIME( QString * reason ) const { - return check( GpgME::Context::CMS, reason ); -} - -bool Kleo::QGpgMEBackend::checkForProtocol( const char * name, QString * reason ) const { - if ( qstricmp( name, OpenPGP ) == 0 ) - return check( GpgME::Context::OpenPGP, reason ); - if ( qstricmp( name, SMIME ) == 0 ) - return check( GpgME::Context::CMS, reason ); - if ( reason ) - *reason = i18n( "Unsupported protocol \"%1\"" ).arg( name ); - return false; -} - -Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::openpgp() const { - if ( !mOpenPGPProtocol ) - if ( checkForOpenPGP() ) - mOpenPGPProtocol = new CryptPlugWrapper( "gpg", "openpgp" ); - return mOpenPGPProtocol; -} - -Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::smime() const { - if ( !mSMIMEProtocol ) - if ( checkForSMIME() ) - mSMIMEProtocol = new CryptPlugWrapper( "gpgsm", "smime" ); - return mSMIMEProtocol; -} - -Kleo::CryptoBackend::Protocol * Kleo::QGpgMEBackend::protocol( const char * name ) const { - if ( qstricmp( name, OpenPGP ) == 0 ) - return openpgp(); - if ( qstricmp( name, SMIME ) == 0 ) - return smime(); - return 0; -} - -bool Kleo::QGpgMEBackend::supportsProtocol( const char * name ) const { - return qstricmp( name, OpenPGP ) == 0 || qstricmp( name, SMIME ); -} - -const char * Kleo::QGpgMEBackend::enumerateProtocols( int i ) const { - switch ( i ) { - case 0: return OpenPGP; - case 1: return SMIME; - default: return 0; - } -} diff --git a/kleopatra/lib/backends/qgpgme/qgpgmebackend.h b/kleopatra/lib/backends/qgpgme/qgpgmebackend.h deleted file mode 100644 index fae2dd68e8..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmebackend.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - qgpgmebackend.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - - -#ifndef __KLEO_QGPGMEBACKEND_H__ -#define __KLEO_QGPGMEBACKEND_H__ - -#include "kleo/cryptobackend.h" - -class CryptPlugWrapper; - -namespace Kleo { - class CryptoConfig; -} -class QGpgMECryptoConfig; -class QString; - -namespace Kleo { - - class QGpgMEBackend : public Kleo::CryptoBackend { - public: - QGpgMEBackend(); - ~QGpgMEBackend(); - - QString name() const; - QString displayName() const; - - CryptoConfig * config() const; - - Protocol * openpgp() const; - Protocol * smime() const; - Protocol * protocol( const char * name ) const; - - bool checkForOpenPGP( QString * reason=0 ) const; - bool checkForSMIME( QString * reason=0 ) const; - bool checkForProtocol( const char * name, QString * reason ) const; - - bool supportsOpenPGP() const { return true; } - bool supportsSMIME() const { return true; } - bool supportsProtocol( const char * name ) const; - - const char * enumerateProtocols( int i ) const; - - private: - mutable QGpgMECryptoConfig * mCryptoConfig; - mutable CryptPlugWrapper * mOpenPGPProtocol; - mutable CryptPlugWrapper * mSMIMEProtocol; - }; - -} - - -#endif // __KLEO_QGPGMEBACKEND_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmecryptoconfig.cpp b/kleopatra/lib/backends/qgpgme/qgpgmecryptoconfig.cpp deleted file mode 100644 index f8aa068b3e..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmecryptoconfig.cpp +++ /dev/null @@ -1,831 +0,0 @@ -/* - qgpgmecryptoconfig.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "qgpgmecryptoconfig.h" -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -// Just for the Q_ASSERT in the dtor. Not thread-safe, but who would -// have 2 threads talking to gpgconf anyway? :) -static bool s_duringClear = false; - -#define GPGCONF_FLAG_GROUP 1 -#define GPGCONF_FLAG_OPTIONAL 2 -#define GPGCONF_FLAG_LIST 4 -#define GPGCONF_FLAG_RUNTIME 8 -#define GPGCONF_FLAG_DEFAULT 16 // fixed default value available -#define GPGCONF_FLAG_DEFAULT_DESC 32 // runtime default value available -#define GPGCONF_FLAG_NOARG_DESC 64 // option with optional arg; special meaning if no arg set -// Change size of mFlags bitfield if adding new values here - -QGpgMECryptoConfig::QGpgMECryptoConfig() - : mComponents( 7 ), mParsed( false ) -{ - mComponents.setAutoDelete( true ); -} - -QGpgMECryptoConfig::~QGpgMECryptoConfig() -{ -} - -void QGpgMECryptoConfig::runGpgConf( bool showErrors ) -{ - // Run gpgconf --list-components to make the list of components - - KProcIO proc( QTextCodec::codecForName( "utf8" ) ); - proc << "gpgconf"; // must be in the PATH - proc << "--list-components"; - - QObject::connect( &proc, SIGNAL( readReady(KProcIO*) ), - this, SLOT( slotCollectStdOut(KProcIO*) ) ); - - // run the process: - int rc = 0; - if ( !proc.start( KProcess::Block ) ) - rc = -1; - else - rc = ( proc.normalExit() ) ? proc.exitStatus() : -2 ; - - // handle errors, if any (and if requested) - if ( showErrors && rc != 0 ) { - QString wmsg = i18n("Failed to execute gpgconf:
%1
"); - if ( rc == -1 ) - wmsg = wmsg.arg( i18n( "program not found" ) ); - else if ( rc == -2 ) - wmsg = wmsg.arg( i18n( "program cannot be executed" ) ); - else - wmsg = wmsg.arg( strerror(rc) ); - kdWarning(5150) << wmsg << endl; // to see it from test_cryptoconfig.cpp - KMessageBox::error(0, wmsg); - } - mParsed = true; -} - -void QGpgMECryptoConfig::slotCollectStdOut( KProcIO* proc ) -{ - QString line; - int result; - while( ( result = proc->readln(line) ) != -1 ) { - //kdDebug(5150) << "GOT LINE:" << line << endl; - // Format: NAME:DESCRIPTION - QStringList lst = QStringList::split( ':', line, true ); - if ( lst.count() >= 2 ) { - mComponents.insert( lst[0], new QGpgMECryptoConfigComponent( this, lst[0], lst[1] ) ); - } else { - kdWarning(5150) << "Parse error on gpgconf --list-components output: " << line << endl; - } - } -} - -QStringList QGpgMECryptoConfig::componentList() const -{ - if ( !mParsed ) - const_cast( this )->runGpgConf( true ); - QDictIterator it( mComponents ); - QStringList names; - for( ; it.current(); ++it ) - names.push_back( it.currentKey() ); - return names; -} - -Kleo::CryptoConfigComponent* QGpgMECryptoConfig::component( const QString& name ) const -{ - if ( !mParsed ) - const_cast( this )->runGpgConf( false ); - return mComponents.find( name ); -} - -void QGpgMECryptoConfig::sync( bool runtime ) -{ - QDictIterator it( mComponents ); - for( ; it.current(); ++it ) - it.current()->sync( runtime ); -} - -void QGpgMECryptoConfig::clear() -{ - s_duringClear = true; - mComponents.clear(); - s_duringClear = false; - mParsed = false; // next call to componentList/component will need to run gpgconf again -} - -//// - -QGpgMECryptoConfigComponent::QGpgMECryptoConfigComponent( QGpgMECryptoConfig*, const QString& name, const QString& description ) - : mGroups( 7 ), mName( name ), mDescription( description ) -{ - mGroups.setAutoDelete( true ); - runGpgConf(); -} - -QGpgMECryptoConfigComponent::~QGpgMECryptoConfigComponent() -{ -} - -void QGpgMECryptoConfigComponent::runGpgConf() -{ - // Run gpgconf --list-options , and create all groups and entries for that component - - KProcIO proc( QTextCodec::codecForName( "utf8" ) ); - proc << "gpgconf"; // must be in the PATH - proc << "--list-options"; - proc << mName; - - //kdDebug(5150) << "Running gpgconf --list-options " << mName << endl; - - QObject::connect( &proc, SIGNAL( readReady(KProcIO*) ), - this, SLOT( slotCollectStdOut(KProcIO*) ) ); - mCurrentGroup = 0; - - // run the process: - int rc = 0; - if ( !proc.start( KProcess::Block ) ) - rc = -1; - else - rc = ( proc.normalExit() ) ? proc.exitStatus() : -1 ; - - if( rc != 0 ) // can happen when using the wrong version of gpg... - kdWarning(5150) << "Running 'gpgconf --list-options " << mName << "' failed. " << strerror( rc ) << ", but try that command to see the real output" << endl; - else { - if ( mCurrentGroup && !mCurrentGroup->mEntries.isEmpty() ) // only add non-empty groups - mGroups.insert( mCurrentGroupName, mCurrentGroup ); - } -} - -void QGpgMECryptoConfigComponent::slotCollectStdOut( KProcIO* proc ) -{ - QString line; - int result; - while( ( result = proc->readln(line) ) != -1 ) { - //kdDebug(5150) << "GOT LINE:" << line << endl; - // Format: NAME:FLAGS:LEVEL:DESCRIPTION:TYPE:ALT-TYPE:ARGNAME:DEFAULT:ARGDEF:VALUE - const QStringList lst = QStringList::split( ':', line, true ); - if ( lst.count() >= 10 ) { - const int flags = lst[1].toInt(); - const int level = lst[2].toInt(); - if ( level > 2 ) // invisible or internal -> skip it; - continue; - if ( flags & GPGCONF_FLAG_GROUP ) { - if ( mCurrentGroup && !mCurrentGroup->mEntries.isEmpty() ) // only add non-empty groups - mGroups.insert( mCurrentGroupName, mCurrentGroup ); - //else - // kdDebug(5150) << "Discarding empty group " << mCurrentGroupName << endl; - mCurrentGroup = new QGpgMECryptoConfigGroup( lst[0], lst[3], level ); - mCurrentGroupName = lst[0]; - } else { - // normal entry - if ( !mCurrentGroup ) { // first toplevel entry -> create toplevel group - mCurrentGroup = new QGpgMECryptoConfigGroup( "", QString::null, 0 ); - mCurrentGroupName = ""; - } - mCurrentGroup->mEntries.insert( lst[0], new QGpgMECryptoConfigEntry( lst ) ); - } - } else { - // This happens on lines like - // dirmngr[31465]: error opening `/home/dfaure/.gnupg/dirmngr_ldapservers.conf': No such file or directory - // so let's not bother the user with it. - //kdWarning(5150) << "Parse error on gpgconf --list-options output: " << line << endl; - } - } -} - -QStringList QGpgMECryptoConfigComponent::groupList() const -{ - QDictIterator it( mGroups ); - QStringList names; - for( ; it.current(); ++it ) - names.push_back( it.currentKey() ); - return names; -} - -Kleo::CryptoConfigGroup* QGpgMECryptoConfigComponent::group(const QString& name ) const -{ - return mGroups.find( name ); -} - -void QGpgMECryptoConfigComponent::sync( bool runtime ) -{ - KTempFile tmpFile; - tmpFile.setAutoDelete( true ); - - QValueList dirtyEntries; - - // Collect all dirty entries - QDictIterator groupit( mGroups ); - for( ; groupit.current(); ++groupit ) { - QDictIterator it( groupit.current()->mEntries ); - for( ; it.current(); ++it ) { - if ( it.current()->isDirty() ) { - // OK, we can set it.currentKey() to it.current()->outputString() - QString line = it.currentKey(); - if ( it.current()->isSet() ) { // set option - line += ":0:"; - line += it.current()->outputString(); - } else { // unset option - line += ":16:"; - } - line += '\n'; - QCString line8bit = line.utf8(); // encode with utf8, and KProcIO uses utf8 when reading. - tmpFile.file()->writeBlock( line8bit.data(), line8bit.size()-1 /*no 0*/ ); - dirtyEntries.append( it.current() ); - } - } - } - tmpFile.close(); - if ( dirtyEntries.isEmpty() ) - return; - - // Call gpgconf --change-options - QString commandLine = "gpgconf"; - if ( runtime ) - commandLine += " --runtime"; - commandLine += " --change-options "; - commandLine += KProcess::quote( mName ); - commandLine += " < "; - commandLine += KProcess::quote( tmpFile.name() ); - - //kdDebug(5150) << commandLine << endl; - //system( QCString( "cat " ) + tmpFile.name().latin1() ); // DEBUG - - KProcess proc; - proc.setUseShell( true ); - proc << commandLine; - - // run the process: - int rc = 0; - if ( !proc.start( KProcess::Block ) ) - rc = -1; - else - rc = ( proc.normalExit() ) ? proc.exitStatus() : -1 ; - - if ( rc == -1 ) - { - QString wmsg = i18n( "Could not start gpgconf\nCheck that gpgconf is in the PATH and that it can be started" ); - kdWarning(5150) << wmsg << endl; - KMessageBox::error(0, wmsg); - } - else if( rc != 0 ) // Happens due to bugs in gpgconf (e.g. issues 104/115) - { - QString wmsg = i18n( "Error from gpgconf while saving configuration: %1" ).arg( strerror( rc ) ); - kdWarning(5150) << k_funcinfo << ":" << strerror( rc ) << endl; - KMessageBox::error(0, wmsg); - } - else - { - QValueList::Iterator it = dirtyEntries.begin(); - for( ; it != dirtyEntries.end(); ++it ) { - (*it)->setDirty( false ); - } - } -} - -//// - -QGpgMECryptoConfigGroup::QGpgMECryptoConfigGroup( const QString & name, const QString& description, int level ) - : mEntries( 29 ), - mName( name ), - mDescription( description ), - mLevel( static_cast( level ) ) -{ - mEntries.setAutoDelete( true ); -} - -QStringList QGpgMECryptoConfigGroup::entryList() const -{ - QDictIterator it( mEntries ); - QStringList names; - for( ; it.current(); ++it ) - names.push_back( it.currentKey() ); - return names; -} - -Kleo::CryptoConfigEntry* QGpgMECryptoConfigGroup::entry( const QString& name ) const -{ - return mEntries.find( name ); -} - -//// - -static QString gpgconf_unescape( const QString& str ) -{ - // Looks like it's the same rules as KURL. - return KURL::decode_string( str, 106 ); -} - -static QString gpgconf_escape( const QString& str ) -{ - // Escape special chars (including ':' and '%') - QString enc = KURL::encode_string( str, 106 ); // and convert to utf8 first (to get %12%34 for one special char) - // Also encode commas, for lists. - enc.replace( ',', "%2c" ); - return enc; -} - -static QString urlpart_encode( const QString& str ) -{ - QString enc( str ); - enc.replace( '%', "%25" ); // first! - enc.replace( ':', "%3a" ); - //kdDebug() << " urlpart_encode: " << str << " -> " << enc << endl; - return enc; -} - -static QString urlpart_decode( const QString& str ) -{ - return KURL::decode_string( str ); -} - -// gpgconf arg type number -> CryptoConfigEntry arg type enum mapping -static Kleo::CryptoConfigEntry::ArgType knownArgType( int argType, bool& ok ) { - ok = true; - switch( argType ) { - case 0: // none - return Kleo::CryptoConfigEntry::ArgType_None; - case 1: // string - return Kleo::CryptoConfigEntry::ArgType_String; - case 2: // int32 - return Kleo::CryptoConfigEntry::ArgType_Int; - case 3: // uint32 - return Kleo::CryptoConfigEntry::ArgType_UInt; - case 32: // pathname - return Kleo::CryptoConfigEntry::ArgType_Path; - case 33: // ldap server - return Kleo::CryptoConfigEntry::ArgType_LDAPURL; - default: - ok = false; - return Kleo::CryptoConfigEntry::ArgType_None; - } -} - -QGpgMECryptoConfigEntry::QGpgMECryptoConfigEntry( const QStringList& parsedLine ) -{ - // Format: NAME:FLAGS:LEVEL:DESCRIPTION:TYPE:ALT-TYPE:ARGNAME:DEFAULT:ARGDEF:VALUE - assert( parsedLine.count() >= 10 ); // called checked for it already - QStringList::const_iterator it = parsedLine.begin(); - mName = *it++; - mFlags = (*it++).toInt(); - mLevel = (*it++).toInt(); - mDescription = *it++; - bool ok; - // we keep the real (int) arg type, since it influences the parsing (e.g. for ldap urls) - mRealArgType = (*it++).toInt(); - mArgType = knownArgType( mRealArgType, ok ); - if ( !ok && !(*it).isEmpty() ) { - // use ALT-TYPE - mRealArgType = (*it).toInt(); - mArgType = knownArgType( mRealArgType, ok ); - } - if ( !ok ) - kdWarning(5150) << "Unsupported datatype: " << parsedLine[4] << " : " << *it << " for " << parsedLine[0] << endl; - ++it; // done with alt-type - ++it; // skip argname (not useful in GUIs) - - mSet = false; - QString value; - if ( mFlags & GPGCONF_FLAG_DEFAULT ) { - value = *it; // get default value - mDefaultValue = stringToValue( value, true ); - } - ++it; // done with DEFAULT - ++it; // ### skip ARGDEF for now. It's only for options with an "optional arg" - //kdDebug(5150) << "Entry " << parsedLine[0] << " val=" << *it << endl; - - if ( !(*it).isEmpty() ) { // a real value was set - mSet = true; - value = *it; - mValue = stringToValue( value, true ); - } - else { - mValue = mDefaultValue; - } - - mDirty = false; -} - -QVariant QGpgMECryptoConfigEntry::stringToValue( const QString& str, bool unescape ) const -{ - bool isString = isStringType(); - - if ( isList() ) { - QValueList lst; - QStringList items = QStringList::split( ',', str ); - for( QStringList::const_iterator valit = items.begin(); valit != items.end(); ++valit ) { - QString val = *valit; - if ( isString ) { - if ( val.isEmpty() ) { - lst << QString::null; - continue; - } - else if ( unescape ) { - if( val[0] != '"' ) // see README.gpgconf - kdWarning(5150) << "String value should start with '\"' : " << val << endl; - val = val.mid( 1 ); - } - } - lst << QVariant( unescape ? gpgconf_unescape( val ) : val ); - } - return lst; - } else { // not a list - QString val( str ); - if ( isString ) { - if ( val.isEmpty() ) - return QVariant( QString::null ); // not set [ok with lists too?] - else if ( unescape ) { - Q_ASSERT( val[0] == '"' ); // see README.gpgconf - val = val.mid( 1 ); - } - } - return QVariant( unescape ? gpgconf_unescape( val ) : val ); - } -} - -QGpgMECryptoConfigEntry::~QGpgMECryptoConfigEntry() -{ -#ifndef NDEBUG - if ( !s_duringClear && mDirty ) - kdWarning(5150) << "Deleting a QGpgMECryptoConfigEntry that was modified (" << mDescription << ")\n" - << "You forgot to call sync() (to commit) or clear() (to discard)" << endl; -#endif -} - -bool QGpgMECryptoConfigEntry::isOptional() const -{ - return mFlags & GPGCONF_FLAG_OPTIONAL; -} - -bool QGpgMECryptoConfigEntry::isList() const -{ - return mFlags & GPGCONF_FLAG_LIST; -} - -bool QGpgMECryptoConfigEntry::isRuntime() const -{ - return mFlags & GPGCONF_FLAG_RUNTIME; -} - -bool QGpgMECryptoConfigEntry::isSet() const -{ - return mSet; -} - -bool QGpgMECryptoConfigEntry::boolValue() const -{ - Q_ASSERT( mArgType == ArgType_None ); - Q_ASSERT( !isList() ); - return mValue.toBool(); -} - -QString QGpgMECryptoConfigEntry::stringValue() const -{ - return toString( false ); -} - -int QGpgMECryptoConfigEntry::intValue() const -{ - Q_ASSERT( mArgType == ArgType_Int ); - Q_ASSERT( !isList() ); - return mValue.toInt(); -} - -unsigned int QGpgMECryptoConfigEntry::uintValue() const -{ - Q_ASSERT( mArgType == ArgType_UInt ); - Q_ASSERT( !isList() ); - return mValue.toUInt(); -} - -static KURL parseURL( int mRealArgType, const QString& str ) -{ - if ( mRealArgType == 33 ) { // LDAP server - // The format is HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN - QStringList items = QStringList::split( ':', str, true ); - if ( items.count() == 5 ) { - QStringList::const_iterator it = items.begin(); - KURL url; - url.setProtocol( "ldap" ); - url.setHost( urlpart_decode( *it++ ) ); - url.setPort( (*it++).toInt() ); - url.setPath( "/" ); // workaround KURL parsing bug - url.setUser( urlpart_decode( *it++ ) ); - url.setPass( urlpart_decode( *it++ ) ); - url.setQuery( urlpart_decode( *it ) ); - return url; - } else - kdWarning(5150) << "parseURL: malformed LDAP server: " << str << endl; - } - // other URLs : assume wellformed URL syntax. - return KURL( str ); -} - -// The opposite of parseURL -static QString splitURL( int mRealArgType, const KURL& url ) -{ - if ( mRealArgType == 33 ) { // LDAP server - // The format is HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN - Q_ASSERT( url.protocol() == "ldap" ); - return urlpart_encode( url.host() ) + ":" + - QString::number( url.port() ) + ":" + - urlpart_encode( url.user() ) + ":" + - urlpart_encode( url.pass() ) + ":" + - // KURL automatically encoded the query (e.g. for spaces inside it), - // so decode it before writing it out to gpgconf (issue119) - urlpart_encode( KURL::decode_string( url.query().mid(1) ) ); - } - return url.path(); -} - -KURL QGpgMECryptoConfigEntry::urlValue() const -{ - Q_ASSERT( mArgType == ArgType_Path || mArgType == ArgType_URL || mArgType == ArgType_LDAPURL ); - Q_ASSERT( !isList() ); - QString str = mValue.toString(); - if ( mArgType == ArgType_Path ) - { - KURL url; - url.setPath( str ); - return url; - } - return parseURL( mRealArgType, str ); -} - -unsigned int QGpgMECryptoConfigEntry::numberOfTimesSet() const -{ - Q_ASSERT( mArgType == ArgType_None ); - Q_ASSERT( isList() ); - return mValue.toUInt(); -} - -QStringList QGpgMECryptoConfigEntry::stringValueList() const -{ - Q_ASSERT( isStringType() ); - Q_ASSERT( isList() ); - return mValue.toStringList(); -} - -QValueList QGpgMECryptoConfigEntry::intValueList() const -{ - Q_ASSERT( mArgType == ArgType_Int ); - Q_ASSERT( isList() ); - QValueList ret; - QValueList lst = mValue.toList(); - for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { - ret.append( (*it).toInt() ); - } - return ret; -} - -QValueList QGpgMECryptoConfigEntry::uintValueList() const -{ - Q_ASSERT( mArgType == ArgType_UInt ); - Q_ASSERT( isList() ); - QValueList ret; - QValueList lst = mValue.toList(); - for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { - ret.append( (*it).toUInt() ); - } - return ret; -} - -KURL::List QGpgMECryptoConfigEntry::urlValueList() const -{ - Q_ASSERT( mArgType == ArgType_Path || mArgType == ArgType_URL || mArgType == ArgType_LDAPURL ); - Q_ASSERT( isList() ); - QStringList lst = mValue.toStringList(); - - KURL::List ret; - for( QStringList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { - if ( mArgType == ArgType_Path ) { - KURL url; - url.setPath( *it ); - ret << url; - } else { - ret << parseURL( mRealArgType, *it ); - } - } - return ret; -} - -void QGpgMECryptoConfigEntry::resetToDefault() -{ - mSet = false; - mDirty = true; - if ( mFlags & GPGCONF_FLAG_DEFAULT ) - mValue = mDefaultValue; - else if ( mArgType == ArgType_None ) - mValue = false; -} - -void QGpgMECryptoConfigEntry::setBoolValue( bool b ) -{ - Q_ASSERT( mArgType == ArgType_None ); - Q_ASSERT( !isList() ); - // A "no arg" option is either set or not set. - // Being set means mSet==true + mValue==true, being unset means resetToDefault(), i.e. both false - mValue = b; - mSet = b; - mDirty = true; -} - -void QGpgMECryptoConfigEntry::setStringValue( const QString& str ) -{ - mValue = stringToValue( str, false ); - // When setting a string to empty (and there's no default), we need to act like resetToDefault - // Otherwise we try e.g. "ocsp-responder:0:" and gpgconf answers: - // "gpgconf: argument required for option ocsp-responder" - if ( str.isEmpty() && !isOptional() ) - mSet = false; - else - mSet = true; - mDirty = true; -} - -void QGpgMECryptoConfigEntry::setIntValue( int i ) -{ - Q_ASSERT( mArgType == ArgType_Int ); - Q_ASSERT( !isList() ); - mValue = i; - mSet = true; - mDirty = true; -} - -void QGpgMECryptoConfigEntry::setUIntValue( unsigned int i ) -{ - mValue = i; - mSet = true; - mDirty = true; -} - -void QGpgMECryptoConfigEntry::setURLValue( const KURL& url ) -{ - QString str = splitURL( mRealArgType, url ); - if ( str.isEmpty() && !isOptional() ) - mSet = false; - else - mSet = true; - mValue = str; - mDirty = true; -} - -void QGpgMECryptoConfigEntry::setNumberOfTimesSet( unsigned int i ) -{ - Q_ASSERT( mArgType == ArgType_None ); - Q_ASSERT( isList() ); - setUIntValue( i ); -} - -void QGpgMECryptoConfigEntry::setStringValueList( const QStringList& lst ) -{ - mValue = lst; - if ( lst.isEmpty() && !isOptional() ) - mSet = false; - else - mSet = true; - mDirty = true; -} - -void QGpgMECryptoConfigEntry::setIntValueList( const QValueList& lst ) -{ - QValueList ret; - for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { - ret << QVariant( *it ); - } - mValue = ret; - if ( ret.isEmpty() && !isOptional() ) - mSet = false; - else - mSet = true; - mDirty = true; -} - -void QGpgMECryptoConfigEntry::setUIntValueList( const QValueList& lst ) -{ - QValueList ret; - for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { - ret << QVariant( *it ); - } - if ( ret.isEmpty() && !isOptional() ) - mSet = false; - else - mSet = true; - mValue = ret; - mDirty = true; -} - -void QGpgMECryptoConfigEntry::setURLValueList( const KURL::List& urls ) -{ - QStringList lst; - for( KURL::List::const_iterator it = urls.begin(); it != urls.end(); ++it ) { - lst << splitURL( mRealArgType, *it ); - } - mValue = lst; - if ( lst.isEmpty() && !isOptional() ) - mSet = false; - else - mSet = true; - mDirty = true; -} - -QString QGpgMECryptoConfigEntry::toString( bool escape ) const -{ - // Basically the opposite of stringToValue - if ( isStringType() ) { - if ( mValue.isNull() ) - return QString::null; - else if ( isList() ) { // string list - QStringList lst = mValue.toStringList(); - if ( escape ) { - for( QStringList::iterator it = lst.begin(); it != lst.end(); ++it ) { - if ( !(*it).isNull() ) - *it = gpgconf_escape( *it ).prepend( "\"" ); - } - } - QString res = lst.join( "," ); - kdDebug(5150) << "toString: " << res << endl; - return res; - } else { // normal string - QString res = mValue.toString(); - if ( escape ) - res = gpgconf_escape( res ).prepend( "\"" ); - return res; - } - } - if ( !isList() ) // non-list non-string - { - if ( mArgType == ArgType_None ) { - return mValue.toBool() ? QString::fromLatin1( "1" ) : QString::null; - } else { // some int - Q_ASSERT( mArgType == ArgType_Int || mArgType == ArgType_UInt ); - return mValue.toString(); // int to string conversion - } - } - - // Lists (of other types than strings) - if ( mArgType == ArgType_None ) - return QString::number( numberOfTimesSet() ); - QStringList ret; - QValueList lst = mValue.toList(); - for( QValueList::const_iterator it = lst.begin(); it != lst.end(); ++it ) { - ret << (*it).toString(); // QVariant does the conversion - } - return ret.join( "," ); -} - -QString QGpgMECryptoConfigEntry::outputString() const -{ - Q_ASSERT( mSet ); - return toString( true ); -} - -bool QGpgMECryptoConfigEntry::isStringType() const -{ - return ( mArgType == Kleo::CryptoConfigEntry::ArgType_String - || mArgType == Kleo::CryptoConfigEntry::ArgType_Path - || mArgType == Kleo::CryptoConfigEntry::ArgType_URL - || mArgType == Kleo::CryptoConfigEntry::ArgType_LDAPURL ); -} - -void QGpgMECryptoConfigEntry::setDirty( bool b ) -{ - mDirty = b; -} - -#include "qgpgmecryptoconfig.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmecryptoconfig.h b/kleopatra/lib/backends/qgpgme/qgpgmecryptoconfig.h deleted file mode 100644 index cc3de2a2df..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmecryptoconfig.h +++ /dev/null @@ -1,185 +0,0 @@ -/* - qgpgmecryptoconfig.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef KLEO_QGPGMECRYPTOCONFIG_H -#define KLEO_QGPGMECRYPTOCONFIG_H - -#include -#include -#include -#include -#include -class KProcIO; - -class QGpgMECryptoConfigComponent; -class QGpgMECryptoConfigEntry; -/** - * CryptoConfig implementation around the gpgconf command-line tool - * For method docu, see kleo/cryptoconfig.h - */ -class QGpgMECryptoConfig : public QObject, public Kleo::CryptoConfig { - - Q_OBJECT -public: - /** - * Constructor - */ - QGpgMECryptoConfig(); - virtual ~QGpgMECryptoConfig(); - - virtual QStringList componentList() const; - - virtual Kleo::CryptoConfigComponent* component( const QString& name ) const; - - virtual void clear(); - virtual void sync( bool runtime ); - -private slots: - void slotCollectStdOut( KProcIO* proc ); -private: - /// @param showErrors if true, a messagebox will be shown if e.g. gpgconf wasn't found - void runGpgConf( bool showErrors ); - -private: - QDict mComponents; - bool mParsed; -}; - -class QGpgMECryptoConfigGroup; - -/// For docu, see kleo/cryptoconfig.h -class QGpgMECryptoConfigComponent : public QObject, public Kleo::CryptoConfigComponent { - - Q_OBJECT -public: - QGpgMECryptoConfigComponent( QGpgMECryptoConfig*, const QString& name, const QString& description ); - ~QGpgMECryptoConfigComponent(); - - QString name() const { return mName; } - QString iconName() const { return mName; } - QString description() const { return mDescription; } - QStringList groupList() const; - Kleo::CryptoConfigGroup* group( const QString& name ) const; - - void sync( bool runtime ); - -private slots: - void slotCollectStdOut( KProcIO* proc ); -private: - void runGpgConf(); - -private: - QDict mGroups; - QString mName; - QString mDescription; - QGpgMECryptoConfigGroup* mCurrentGroup; // during parsing - QString mCurrentGroupName; // during parsing -}; - -class QGpgMECryptoConfigGroup : public Kleo::CryptoConfigGroup { - -public: - QGpgMECryptoConfigGroup( const QString & name, const QString& description, int level ); - ~QGpgMECryptoConfigGroup() {} - - QString name() const { return mName; } - QString iconName() const { return QString::null; } - QString description() const { return mDescription; } - Kleo::CryptoConfigEntry::Level level() const { return mLevel; } - QStringList entryList() const; - Kleo::CryptoConfigEntry* entry( const QString& name ) const; - -private: - friend class QGpgMECryptoConfigComponent; // it adds the entries - QDict mEntries; - QString mName; - QString mDescription; - Kleo::CryptoConfigEntry::Level mLevel; -}; - -class QGpgMECryptoConfigEntry : public Kleo::CryptoConfigEntry { -public: - QGpgMECryptoConfigEntry( const QStringList& parsedLine ); - ~QGpgMECryptoConfigEntry(); - - QString name() const { return mName; } - QString description() const { return mDescription; } - bool isOptional() const; - bool isList() const; - bool isRuntime() const; - Level level() const { return static_cast( mLevel ); } - ArgType argType() const { return static_cast( mArgType ); } - bool isSet() const; - bool boolValue() const; - QString stringValue() const; - int intValue() const; - unsigned int uintValue() const; - KURL urlValue() const; - unsigned int numberOfTimesSet() const; - QStringList stringValueList() const; - QValueList intValueList() const; - QValueList uintValueList() const; - KURL::List urlValueList() const; - void resetToDefault(); - void setBoolValue( bool ); - void setStringValue( const QString& ); - void setIntValue( int ); - void setUIntValue( unsigned int ); - void setURLValue( const KURL& ); - void setNumberOfTimesSet( unsigned int ); - void setStringValueList( const QStringList& ); - void setIntValueList( const QValueList& ); - void setUIntValueList( const QValueList& ); - void setURLValueList( const KURL::List& ); - bool isDirty() const { return mDirty; } - - void setDirty( bool b ); - QString outputString() const; - -protected: - bool isStringType() const; - QVariant stringToValue( const QString& value, bool unescape ) const; - QString toString( bool escape ) const; -private: - QString mName; - QString mDescription; - QVariant mDefaultValue; - QVariant mValue; - uint mFlags : 7; // bitfield with 7 bits - uint mLevel : 3; // max is 4 (2, in fact) -> 3 bits - uint mRealArgType : 6; // max is 33 -> 6 bits - uint mArgType : 3; // max is 6 (ArgType enum) -> 3 bits; - uint mDirty : 1; - uint mSet : 1; -}; - -#endif /* KLEO_QGPGMECRYPTOCONFIG_H */ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmedecryptjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmedecryptjob.cpp deleted file mode 100644 index 884f1a4a05..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmedecryptjob.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - qgpgmedecryptjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmedecryptjob.h" - -#include -#include - -#include -#include -#include - -#include - -Kleo::QGpgMEDecryptJob::QGpgMEDecryptJob( GpgME::Context * context ) - : DecryptJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEDecryptJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEDecryptJob::~QGpgMEDecryptJob() { -} - -void Kleo::QGpgMEDecryptJob::setup( const QByteArray & cipherText ) { - assert( !mInData ); - assert( !mOutData ); - - createInData( cipherText ); - createOutData(); -} - -GpgME::Error Kleo::QGpgMEDecryptJob::start( const QByteArray & cipherText ) { - setup( cipherText ); - - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startDecryption( *mInData, *mOutData ); - - if ( err ) - deleteLater(); - return err; -} - -GpgME::DecryptionResult Kleo::QGpgMEDecryptJob::exec( const QByteArray & cipherText, - QByteArray & plainText ) { - setup( cipherText ); - const GpgME::DecryptionResult result = mCtx->decrypt( *mInData, *mOutData ); - plainText = mOutDataDataProvider->data(); - return result; -} - -void Kleo::QGpgMEDecryptJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mCtx->decryptionResult(), mOutDataDataProvider->data() ); -} - -#include "qgpgmedecryptjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmedecryptjob.h b/kleopatra/lib/backends/qgpgme/qgpgmedecryptjob.h deleted file mode 100644 index 7fc89dff22..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmedecryptjob.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - qgpgmedecryptjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEDECRYPTJOB_H__ -#define __KLEO_QGPGMEDECRYPTJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include - -namespace GpgME { - class Error; - class Context; -} - -namespace Kleo { - - class QGpgMEDecryptJob : public DecryptJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEDecryptJob( GpgME::Context * context ); - ~QGpgMEDecryptJob(); - - /*! \reimp from DecryptJob */ - GpgME::Error start( const QByteArray & cipherText ); - - /*! \reimp from DecryptJob */ - GpgME::DecryptionResult exec( const QByteArray & cipherText, - QByteArray & plainText ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - void setup( const QByteArray & cipherText ); - }; - -} - -#endif // __KLEO_QGPGMEDECRYPTJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmedecryptverifyjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmedecryptverifyjob.cpp deleted file mode 100644 index 509327aa84..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmedecryptverifyjob.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - qgpgmedecryptverifyjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmedecryptverifyjob.h" - -#include -#include - -#include -#include -#include -#include - -#include - -Kleo::QGpgMEDecryptVerifyJob::QGpgMEDecryptVerifyJob( GpgME::Context * context ) - : DecryptVerifyJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEDecryptVerifyJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEDecryptVerifyJob::~QGpgMEDecryptVerifyJob() { -} - -void Kleo::QGpgMEDecryptVerifyJob::setup( const QByteArray & cipherText ) { - assert( !mInData ); - assert( !mOutData ); - - createInData( cipherText ); - createOutData(); -} - -GpgME::Error Kleo::QGpgMEDecryptVerifyJob::start( const QByteArray & cipherText ) { - setup( cipherText ); - - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startCombinedDecryptionAndVerification( *mInData, *mOutData ); - - if ( err ) - deleteLater(); - return err; -} - -std::pair -Kleo::QGpgMEDecryptVerifyJob::exec( const QByteArray & cipherText, QByteArray & plainText ) { - setup( cipherText ); - const std::pair result = - mCtx->decryptAndVerify( *mInData, *mOutData ); - plainText = mOutDataDataProvider->data(); - return result; -} - -void Kleo::QGpgMEDecryptVerifyJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mCtx->decryptionResult(), - mCtx->verificationResult(), - mOutDataDataProvider->data() ); -} - -#include "qgpgmedecryptverifyjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmedecryptverifyjob.h b/kleopatra/lib/backends/qgpgme/qgpgmedecryptverifyjob.h deleted file mode 100644 index a391887463..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmedecryptverifyjob.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - qgpgmedecryptverifyjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEDECRYPTVERIFYJOB_H__ -#define __KLEO_QGPGMEDECRYPTVERIFYJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include -#include - -namespace GpgME { - class Error; - class Context; -} - -namespace Kleo { - - class KDE_EXPORT QGpgMEDecryptVerifyJob : public DecryptVerifyJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEDecryptVerifyJob( GpgME::Context * context ); - ~QGpgMEDecryptVerifyJob(); - - /*! \reimp from DecryptVerifyJob */ - GpgME::Error start( const QByteArray & cipherText ); - - /*! \reimp from DecryptVerifyJob */ - std::pair - exec( const QByteArray & cipherText, QByteArray & plainText ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - void setup( const QByteArray & ); - }; - -} - -#endif // __KLEO_QGPGMEDECRYPTVERIFYJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmedeletejob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmedeletejob.cpp deleted file mode 100644 index c06907eeaa..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmedeletejob.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - qgpgmedeletejob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmedeletejob.h" - -#include - -#include - -#include - -Kleo::QGpgMEDeleteJob::QGpgMEDeleteJob( GpgME::Context * context ) - : DeleteJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEDeleteJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEDeleteJob::~QGpgMEDeleteJob() { -} - -GpgME::Error Kleo::QGpgMEDeleteJob::start( const GpgME::Key & key, bool allowSecretKeyDeletion ) { - - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startKeyDeletion( key, allowSecretKeyDeletion ); - - if ( err ) - deleteLater(); - return err; -} - -void Kleo::QGpgMEDeleteJob::doOperationDoneEvent( const GpgME::Error & error ) { - emit result( error ); -} - -#include "qgpgmedeletejob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmedeletejob.h b/kleopatra/lib/backends/qgpgme/qgpgmedeletejob.h deleted file mode 100644 index 9dec128f75..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmedeletejob.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - qgpgmedeletejob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEDELETEJOB_H__ -#define __KLEO_QGPGMEDELETEJOB_H__ - -#include - -#include "qgpgmejob.h" - -namespace GpgME { - class Error; - class Context; - class Key; -} - -namespace Kleo { - - class QGpgMEDeleteJob : public DeleteJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEDeleteJob( GpgME::Context * context ); - ~QGpgMEDeleteJob(); - - /*! \reimp from DeleteJob */ - GpgME::Error start( const GpgME::Key & key, bool allowSecretKeyDeletion ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - }; - -} - -#endif // __KLEO_QGPGMEDELETEJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmedownloadjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmedownloadjob.cpp deleted file mode 100644 index 6ee771a046..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmedownloadjob.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - qgpgmedownloadjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmedownloadjob.h" - -#include -#include - -#include -#include - -#include - -#include - -Kleo::QGpgMEDownloadJob::QGpgMEDownloadJob( GpgME::Context * context ) - : DownloadJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEDownloadJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEDownloadJob::~QGpgMEDownloadJob() { -} - -GpgME::Error Kleo::QGpgMEDownloadJob::start( const QStringList & pats ) { - assert( !patterns() ); - assert( !mOutData ); - - createOutData(); - setPatterns( pats ); - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startPublicKeyExport( patterns(), *mOutData ); - - if ( err ) - deleteLater(); - return err; -} - -void Kleo::QGpgMEDownloadJob::doOperationDoneEvent( const GpgME::Error & error ) { - emit result( error, mOutDataDataProvider->data() ); -} - -#include "qgpgmedownloadjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmedownloadjob.h b/kleopatra/lib/backends/qgpgme/qgpgmedownloadjob.h deleted file mode 100644 index 1402b127c8..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmedownloadjob.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - qgpgmedownloadjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEDOWNLOADJOB_H__ -#define __KLEO_QGPGMEDOWNLOADJOB_H__ - -#include - -#include "qgpgmejob.h" - -namespace GpgME { - class Error; - class Context; -} - -namespace Kleo { - - class QGpgMEDownloadJob : public DownloadJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEDownloadJob( GpgME::Context * context ); - ~QGpgMEDownloadJob(); - - /*! \reimp from DownloadJob */ - GpgME::Error start( const QStringList & fingerprints ); - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - }; - -} - -#endif // __KLEO_QGPGMEDOWNLOADJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeencryptjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmeencryptjob.cpp deleted file mode 100644 index 01ef6b445f..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeencryptjob.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* - qgpgmeencryptjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmeencryptjob.h" - -#include -#include - -#include -#include - -#include -#include -#include - -#include - -Kleo::QGpgMEEncryptJob::QGpgMEEncryptJob( GpgME::Context * context ) - : EncryptJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEEncryptJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEEncryptJob::~QGpgMEEncryptJob() { -} - -void Kleo::QGpgMEEncryptJob::setup( const QByteArray & plainText ) { - assert( !mInData ); - assert( !mOutData ); - - createInData( plainText ); - createOutData(); -} - -GpgME::Error Kleo::QGpgMEEncryptJob::start( const std::vector & recipients, - const QByteArray & plainText, bool alwaysTrust ) { - setup( plainText ); - - hookupContextToEventLoopInteractor(); - - const GpgME::Context::EncryptionFlags flags = - alwaysTrust ? GpgME::Context::AlwaysTrust : GpgME::Context::None; - const GpgME::Error err = mCtx->startEncryption( recipients, *mInData, *mOutData, flags ); - - if ( err ) - deleteLater(); - return err; -} - -GpgME::EncryptionResult Kleo::QGpgMEEncryptJob::exec( const std::vector & recipients, - const QByteArray & plainText, - bool alwaysTrust, - QByteArray & ciphertext ) { - setup( plainText ); - const GpgME::Context::EncryptionFlags flags = - alwaysTrust ? GpgME::Context::AlwaysTrust : GpgME::Context::None; - mResult = mCtx->encrypt( recipients, *mInData, *mOutData, flags ); - ciphertext = mOutDataDataProvider->data(); - return mResult; -} - -void Kleo::QGpgMEEncryptJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mResult, mOutDataDataProvider->data() ); -} - -void Kleo::QGpgMEEncryptJob::showErrorDialog( QWidget * parent, const QString & caption ) const { - if ( !mResult.error() || mResult.error().isCanceled() ) - return; - const QString msg = i18n("Encryption failed: %1") - .arg( QString::fromLocal8Bit( mResult.error().asString() ) ); - KMessageBox::error( parent, msg, caption ); -} - -#include "qgpgmeencryptjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeencryptjob.h b/kleopatra/lib/backends/qgpgme/qgpgmeencryptjob.h deleted file mode 100644 index 362fb4e061..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeencryptjob.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - qgpgmeencryptjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEENCRYPTJOB_H__ -#define __KLEO_QGPGMEENCRYPTJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include - -#include - -namespace GpgME { - class Error; - class Context; - class Key; -} - -namespace Kleo { - - class QGpgMEEncryptJob : public EncryptJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEEncryptJob( GpgME::Context * context ); - ~QGpgMEEncryptJob(); - - /*! \reimp from EncryptJob */ - GpgME::Error start( const std::vector & recipients, - const QByteArray & plainText, bool alwaysTrust ); - - /*! \reimp from EncryptJob */ - GpgME::EncryptionResult exec( const std::vector & recipients, - const QByteArray & plainText, bool alwaysTrust, - QByteArray & cipherText ); - - /*! \reimp from Job */ - void showErrorDialog( QWidget * parent, const QString & caption ) const; - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - void setup( const QByteArray & ); - - private: - GpgME::EncryptionResult mResult; - }; - -} - -#endif // __KLEO_QGPGMEENCRYPTJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeexportjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmeexportjob.cpp deleted file mode 100644 index c9274f3b7c..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeexportjob.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - qgpgmeexportjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmeexportjob.h" - -#include -#include - -#include -#include - -#include - -#include - -Kleo::QGpgMEExportJob::QGpgMEExportJob( GpgME::Context * context ) - : ExportJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEExportJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEExportJob::~QGpgMEExportJob() { -} - -GpgME::Error Kleo::QGpgMEExportJob::start( const QStringList & pats ) { - assert( !patterns() ); - assert( !mOutData ); - - createOutData(); - setPatterns( pats ); - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startPublicKeyExport( patterns(), *mOutData ); - - if ( err ) - deleteLater(); - return err; -} - -void Kleo::QGpgMEExportJob::doOperationDoneEvent( const GpgME::Error & error ) { - emit result( error, mOutDataDataProvider->data() ); -} - -#include "qgpgmeexportjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeexportjob.h b/kleopatra/lib/backends/qgpgme/qgpgmeexportjob.h deleted file mode 100644 index 8b799b583c..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeexportjob.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - qgpgmeexportjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEEXPORTJOB_H__ -#define __KLEO_QGPGMEEXPORTJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include - -namespace GpgME { - class Error; - class Context; -} - -namespace Kleo { - - class QGpgMEExportJob : public ExportJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEExportJob( GpgME::Context * context ); - ~QGpgMEExportJob(); - - /*! \reimp from ExportJob */ - GpgME::Error start( const QStringList & patterns ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - }; - -} - -#endif // __KLEO_QGPGMEEXPORTJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeimportjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmeimportjob.cpp deleted file mode 100644 index fd1251b654..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeimportjob.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - qgpgmeimportjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmeimportjob.h" - -#include -#include - -#include -#include -#include - -#include - -Kleo::QGpgMEImportJob::QGpgMEImportJob( GpgME::Context * context ) - : ImportJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEImportJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEImportJob::~QGpgMEImportJob() { -} - -void Kleo::QGpgMEImportJob::setup( const QByteArray & keyData ) { - assert( !mInData ); - - createInData( keyData ); -} - -GpgME::Error Kleo::QGpgMEImportJob::start( const QByteArray & keyData ) { - setup( keyData ); - - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startKeyImport( *mInData ); - - if ( err ) - deleteLater(); - return err; -} - -GpgME::ImportResult Kleo::QGpgMEImportJob::exec( const QByteArray & keyData ) { - setup( keyData ); - return mCtx->importKeys( *mInData ); -} - -void Kleo::QGpgMEImportJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mCtx->importResult() ); -} - - -#include "qgpgmeimportjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeimportjob.h b/kleopatra/lib/backends/qgpgme/qgpgmeimportjob.h deleted file mode 100644 index 8c2ee1ad45..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeimportjob.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - qgpgmeimportjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEIMPORTJOB_H__ -#define __KLEO_QGPGMEIMPORTJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include - -namespace GpgME { - class Error; - class Context; -} - -namespace Kleo { - - class QGpgMEImportJob : public ImportJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEImportJob( GpgME::Context * context ); - ~QGpgMEImportJob(); - - /*! \reimp from ImportJob */ - GpgME::Error start( const QByteArray & keyData ); - - /*! \reimp from ImportJob */ - GpgME::ImportResult exec( const QByteArray & keyData ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - void setup( const QByteArray & ); - }; - -} - -#endif // __KLEO_QGPGMEIMPORTJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmejob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmejob.cpp deleted file mode 100644 index afd58e301b..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmejob.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/* - qgpgmejob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmejob.h" -#include "qgpgmeprogresstokenmapper.h" - -#include -#include - -#include -#include - -#include -#include - -#include -#include - -#include -#include - -#include - -#include -#include - -namespace { - class InvarianceChecker { - public: -#ifdef NDEBUG - InvarianceChecker( const Kleo::QGpgMEJob * ) {} -#else - InvarianceChecker( const Kleo::QGpgMEJob * job ) - : _this( job ) - { - assert( _this ); - _this->checkInvariants(); - } - ~InvarianceChecker() { - _this->checkInvariants(); - } - private: - const Kleo::QGpgMEJob * _this; -#endif - }; -} - -Kleo::QGpgMEJob::QGpgMEJob( Kleo::Job * _this, GpgME::Context * context ) - : GpgME::ProgressProvider(), - GpgME::PassphraseProvider(), - mThis( _this ), - mCtx( context ), - mInData( 0 ), - mInDataDataProvider( 0 ), - mOutData( 0 ), - mOutDataDataProvider( 0 ), - mPatterns( 0 ), - mReplacedPattern( 0 ), - mNumPatterns( 0 ), - mChunkSize( 1024 ), - mPatternStartIndex( 0 ), mPatternEndIndex( 0 ) -{ - InvarianceChecker check( this ); - assert( context ); - QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(aboutToDestroy()), - _this, SLOT(slotCancel()) ); - context->setProgressProvider( this ); - // (mmutz) work around a gpgme bug in versions at least <= 0.9.0. - // These versions will return GPG_ERR_NOT_IMPLEMENTED from - // a CMS sign operation when a passphrase callback is set. - if ( context->protocol() == GpgME::Context::OpenPGP ) - context->setPassphraseProvider( this ); -} - -void Kleo::QGpgMEJob::checkInvariants() const { -#ifndef NDEBUG - if ( mPatterns ) { - assert( mPatterns[mNumPatterns] == 0 ); - if ( mPatternEndIndex > 0 ) { - assert( mPatternEndIndex > mPatternStartIndex ); - assert( mPatternEndIndex - mPatternStartIndex == mChunkSize ); - } else { - assert( mPatternEndIndex == mPatternStartIndex ); - } - if ( mPatternEndIndex < mNumPatterns ) { - assert( mPatterns[mPatternEndIndex] == 0 ); - assert( mReplacedPattern != 0 ); - } else { - assert( mReplacedPattern == 0 ); - } - } else { - assert( mNumPatterns == 0 ); - assert( mPatternStartIndex == 0 ); - assert( mPatternEndIndex == 0 ); - assert( mReplacedPattern == 0 ); - } -#endif -} - -Kleo::QGpgMEJob::~QGpgMEJob() { - InvarianceChecker check( this ); - delete mCtx; mCtx = 0; - delete mInData; mInData = 0; - delete mInDataDataProvider; mInDataDataProvider = 0; - delete mOutData; mOutData = 0; - delete mOutDataDataProvider; mOutDataDataProvider = 0; - deleteAllPatterns(); -} - -void Kleo::QGpgMEJob::deleteAllPatterns() { - if ( mPatterns ) - for ( unsigned int i = 0 ; i < mNumPatterns ; ++i ) - free( (void*)mPatterns[i] ); - free( (void*)mReplacedPattern ); mReplacedPattern = 0; - delete[] mPatterns; mPatterns = 0; - mPatternEndIndex = mPatternStartIndex = mNumPatterns = 0; -} - -void Kleo::QGpgMEJob::hookupContextToEventLoopInteractor() { - mCtx->setManagedByEventLoopInteractor( true ); - QObject::connect( QGpgME::EventLoopInteractor::instance(), - SIGNAL(operationDoneEventSignal(GpgME::Context*,const GpgME::Error&)), - mThis, SLOT(slotOperationDoneEvent(GpgME::Context*,const GpgME::Error&)) ); -} - -void Kleo::QGpgMEJob::setPatterns( const QStringList & sl, bool allowEmpty ) { - InvarianceChecker check( this ); - deleteAllPatterns(); - // create a new null-terminated C array of char* from patterns: - mPatterns = new const char*[ sl.size() + 1 ]; - const char* * pat_it = mPatterns; - mNumPatterns = 0; - for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it ) { - if ( (*it).isNull() ) - continue; - if ( (*it).isEmpty() && !allowEmpty ) - continue; - *pat_it++ = strdup( (*it).utf8().data() ); - ++mNumPatterns; - } - *pat_it++ = 0; - mReplacedPattern = 0; - mPatternEndIndex = mChunkSize = mNumPatterns; -} - -void Kleo::QGpgMEJob::setChunkSize( unsigned int chunksize ) { - InvarianceChecker check( this ); - if ( mReplacedPattern ) { - mPatterns[mPatternEndIndex] = mReplacedPattern; - mReplacedPattern = 0; - } - mChunkSize = std::min( chunksize, mNumPatterns ); - mPatternStartIndex = 0; - mPatternEndIndex = mChunkSize; - mReplacedPattern = mPatterns[mPatternEndIndex]; - mPatterns[mPatternEndIndex] = 0; -} - -const char* * Kleo::QGpgMEJob::nextChunk() { - InvarianceChecker check( this ); - if ( mReplacedPattern ) { - mPatterns[mPatternEndIndex] = mReplacedPattern; - mReplacedPattern = 0; - } - mPatternStartIndex += mChunkSize; - mPatternEndIndex += mChunkSize; - if ( mPatternEndIndex < mNumPatterns ) { // could safely be <=, but the last entry is NULL anyway - mReplacedPattern = mPatterns[mPatternEndIndex]; - mPatterns[mPatternEndIndex] = 0; - } - return patterns(); -} - -const char* * Kleo::QGpgMEJob::patterns() const { - InvarianceChecker check( this ); - if ( mPatternStartIndex < mNumPatterns ) - return mPatterns + mPatternStartIndex; - return 0; -} - -GpgME::Error Kleo::QGpgMEJob::setSigningKeys( const std::vector & signers ) { - mCtx->clearSigningKeys(); - for ( std::vector::const_iterator it = signers.begin() ; it != signers.end() ; ++it ) { - if ( (*it).isNull() ) - continue; - if ( const GpgME::Error err = mCtx->addSigningKey( *it ) ) - return err; - } - return 0; -} - -void Kleo::QGpgMEJob::createInData( const QByteArray & in ) { - mInDataDataProvider = new QGpgME::QByteArrayDataProvider( in ); - mInData = new GpgME::Data( mInDataDataProvider ); - assert( !mInData->isNull() ); -} - -void Kleo::QGpgMEJob::createOutData() { - mOutDataDataProvider = new QGpgME::QByteArrayDataProvider(); - mOutData = new GpgME::Data( mOutDataDataProvider ); - assert( !mOutData->isNull() ); -} - -void Kleo::QGpgMEJob::doSlotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - if ( context == mCtx ) { - doEmitDoneSignal(); - doOperationDoneEvent( e ); - mThis->deleteLater(); - } -} - -void Kleo::QGpgMEJob::doSlotCancel() { - mCtx->cancelPendingOperation(); -} - -void Kleo::QGpgMEJob::showProgress( const char * what, int type, int current, int total ) { - doEmitProgressSignal( QGpgMEProgressTokenMapper::instance()->map( what, type, current, total ), current, total ); -} - -char * Kleo::QGpgMEJob::getPassphrase( const char * useridHint, const char * /*description*/, - bool previousWasBad, bool & canceled ) { - // DF: here, description is the key fingerprint, twice, then "17 0". Not really descriptive. - // So I'm ignoring QString::fromLocal8Bit( description ) ) - QString msg = previousWasBad ? - i18n( "You need a passphrase to unlock the secret key for user:
%1 (retry)" ) : - i18n( "You need a passphrase to unlock the secret key for user:
%1" ); - msg = msg.arg( QString::fromUtf8( useridHint ) ) + "

"; - msg.prepend( "" ); - msg += i18n( "This dialog will reappear every time the passphrase is needed. For a more secure solution that also allows caching the passphrase, use gpg-agent." ) + "
"; - const QString gpgAgent = KStandardDirs::findExe( "gpg-agent" ); - if ( !gpgAgent.isEmpty() ) { - msg += i18n( "gpg-agent was found in %1, but does not appear to be running." ) - .arg( gpgAgent ); - } else { - msg += i18n( "gpg-agent is part of gnupg-%1, which you can download from %2" ) - .arg( "1.9" ) - .arg( "http://www.gnupg.org/download" ); // add #gnupg2 if you can make this a real link - } - msg += "
"; - msg += i18n( "For information on how to set up gpg-agent, see %1" ) - .arg( "http://kmail.kde.org/kmail-pgpmime-howto.html" ); - msg += "

"; - msg += i18n( "Enter passphrase:" ); - Kleo::PassphraseDialog dlg( msg, i18n("Passphrase Dialog") ); - if ( dlg.exec() != QDialog::Accepted ) { - canceled = true; - return 0; - } - canceled = false; - // gpgme++ free()s it, and we need to copy as long as dlg isn't deleted :o - return strdup( dlg.passphrase() ); -} diff --git a/kleopatra/lib/backends/qgpgme/qgpgmejob.h b/kleopatra/lib/backends/qgpgme/qgpgmejob.h deleted file mode 100644 index aff16ce901..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmejob.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - qgpgmejob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEJOB_H__ -#define __KLEO_QGPGMEJOB_H__ - -#include -#include - -#include - -#include - -#include -#include - -namespace GpgME { - class Error; - class Context; - class Data; -} - -namespace Kleo { - class Job; -} - -namespace QGpgME { - class QByteArrayDataProvider; -} - -class QString; -class QStringList; - -namespace Kleo { - - /** This is a hackish helper class to avoid code duplication in this - backend's Kleo::Job subclasses. It contains several workarounds - for moc/signal/slot shortcomings, most of which the author of - this thinks are Qt bugs (lazy implementations), first and - foremost the inability of moc to handle inheritance from - multiple QObject-derived subclasses. - - To use it, inherit from the Job-subclass, then from this class, - add QGPGME_JOB to just after Q OBJECT and implement - doOperationDoneEvent() by emitting your variant of the result() - signal there. Pass "this" as the first argument this QGpgMEJOb's - ctor. The rest is dealt with automatically. - */ - class KDE_EXPORT QGpgMEJob : public GpgME::ProgressProvider, public GpgME::PassphraseProvider { - public: - QGpgMEJob( Kleo::Job * _this, GpgME::Context * context ); - ~QGpgMEJob(); - - protected: - /*! Called on operation-done events, between emitting done() and - calling deleteLater(). You should emit your result signal here. */ - virtual void doOperationDoneEvent( const GpgME::Error & e ) = 0; - /*! Hooks up mCtx to be managed by the event loop interactor */ - void hookupContextToEventLoopInteractor(); - /*! Fills mPatterns from the stringlist, resets chunking to the full list */ - void setPatterns( const QStringList & sl, bool allowEmpty=false ); - /*! Returnes the number of patterns set */ - unsigned int numPatterns() const { return mNumPatterns; } - /*! Skips to the next chunk of patterns. @return patterns() */ - const char* * nextChunk(); - /*! @return patterns, offset by the current chunk */ - const char* * patterns() const; - /*! Set the current pattern chunksize to size and reset the chunk index to zero */ - void setChunkSize( unsigned int size ); - /*! @return current chunksize */ - unsigned int chunkSize() const { return mChunkSize; } - /*! Creates an empty GpgME::Data/QGpgME::QByteArrayDataProvider pair */ - void createOutData(); - /*! Creates a GpgME::Data/QGpgME::QByteArrayDataProvider pair, - filled with the contents of \a in */ - void createInData( const QByteArray & in ); - /*! Sets the list of signing keys */ - GpgME::Error setSigningKeys( const std::vector & signers ); - /*! Call this to implement a slotOperationDoneEvent() */ - void doSlotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ); - - // - // only boring stuff below this line... - // - - protected: - virtual void doEmitProgressSignal( const QString & what, int current, int total ) = 0; - virtual void doEmitDoneSignal() = 0; - void doSlotCancel(); - - private: - /*! \reimp from GpgME::ProgressProvider */ - void showProgress( const char * what, int type, int current, int total ); - char * getPassphrase( const char * useridHint, const char * description, - bool previousWasBad, bool & canceled ); - void deleteAllPatterns(); - - public: - void checkInvariants() const; - - protected: - Kleo::Job * mThis; - GpgME::Context * mCtx; - GpgME::Data * mInData; - QGpgME::QByteArrayDataProvider * mInDataDataProvider; - GpgME::Data * mOutData; - QGpgME::QByteArrayDataProvider * mOutDataDataProvider; - private: - const char* * mPatterns; - // holds the entry - if any - in mPattern that was replaced with - // NULL to create a temporary end-of-array marker for gpgme: - const char * mReplacedPattern; - unsigned int mNumPatterns; - unsigned int mChunkSize; - unsigned int mPatternStartIndex, mPatternEndIndex; - }; - -} - -#define make_slot_cancel private: void slotCancel() { QGpgMEJob::doSlotCancel(); } -#define make_progress_emitter private: void doEmitProgressSignal( const QString & what, int cur, int tot ) { emit progress( what, cur, tot ); } -#define make_done_emitter private: void doEmitDoneSignal() { emit done(); } -#define QGPGME_JOB make_slot_cancel make_progress_emitter make_done_emitter - -#endif // __KLEO_QGPGMEJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmekeygenerationjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmekeygenerationjob.cpp deleted file mode 100644 index a0ab78f237..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmekeygenerationjob.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - qgpgmekeygenerationjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmekeygenerationjob.h" - -#include -#include - -#include -#include -#include - -#include - -Kleo::QGpgMEKeyGenerationJob::QGpgMEKeyGenerationJob( GpgME::Context * context ) - : KeyGenerationJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEKeyGenerationJob" ), - QGpgMEJob( this, context ), - mPubKeyDataProvider( 0 ), - mPubKey( 0 ) -{ - assert( context ); -} - -Kleo::QGpgMEKeyGenerationJob::~QGpgMEKeyGenerationJob() { - delete mPubKey; mPubKey = 0; - delete mPubKeyDataProvider; mPubKeyDataProvider = 0; -} - -GpgME::Error Kleo::QGpgMEKeyGenerationJob::start( const QString & parameters ) { - assert( !mPubKey ); - - // set up empty data object for the public key data - if ( mCtx->protocol() == GpgME::Context::CMS ) { - mPubKeyDataProvider = new QGpgME::QByteArrayDataProvider(); - mPubKey = new GpgME::Data( mPubKeyDataProvider ); - assert( !mPubKey->isNull() ); - } - - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = - mCtx->startKeyGeneration( parameters.utf8().data(), mPubKey ? *mPubKey : GpgME::Data::null ); - - if ( err ) - deleteLater(); - return err; -} - -void Kleo::QGpgMEKeyGenerationJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mCtx->keyGenerationResult(), mPubKeyDataProvider ? mPubKeyDataProvider->data() : QByteArray() ); -} - -#include "qgpgmekeygenerationjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmekeygenerationjob.h b/kleopatra/lib/backends/qgpgme/qgpgmekeygenerationjob.h deleted file mode 100644 index 973aeb12d0..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmekeygenerationjob.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - qgpgmekeygenerationjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEKEYGENERATIONJOB_H__ -#define __KLEO_QGPGMEKEYGENERATIONJOB_H__ - -#include - -#include "qgpgmejob.h" -#include - -namespace GpgME { - class Error; - class Context; - class Key; - class Data; -} - -namespace QGpgME { - class QByteArrayDataProvider; -} - -namespace Kleo { - - class KDE_EXPORT QGpgMEKeyGenerationJob : public KeyGenerationJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEKeyGenerationJob( GpgME::Context * context ); - ~QGpgMEKeyGenerationJob(); - - /*! \reimp from KeygenerationJob */ - GpgME::Error start( const QString & parameters ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & error ) { - QGpgMEJob::doSlotOperationDoneEvent( context, error ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - - private: - QGpgME::QByteArrayDataProvider * mPubKeyDataProvider; - GpgME::Data * mPubKey; - }; - -} - -#endif // __KLEO_QGPGMEKEYGENERATIONJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmekeylistjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmekeylistjob.cpp deleted file mode 100644 index 9c87e3ef62..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmekeylistjob.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* - qgpgmekeylistjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmekeylistjob.h" - -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include - -#include - -#include -#include -#include - -Kleo::QGpgMEKeyListJob::QGpgMEKeyListJob( GpgME::Context * context ) - : KeyListJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEKeyListJob" ), - QGpgMEJob( this, context ), - mResult(), mSecretOnly( false ) -{ - assert( context ); -} - -Kleo::QGpgMEKeyListJob::~QGpgMEKeyListJob() { -} - -void Kleo::QGpgMEKeyListJob::setup( const QStringList & pats, bool secretOnly ) { - assert( !patterns() ); - - mSecretOnly = secretOnly; - setPatterns( pats ); -} - -GpgME::Error Kleo::QGpgMEKeyListJob::start( const QStringList & pats, bool secretOnly ) { - setup( pats, secretOnly ); - - hookupContextToEventLoopInteractor(); - connect( QGpgME::EventLoopInteractor::instance(), - SIGNAL(nextKeyEventSignal(GpgME::Context*,const GpgME::Key&)), - SLOT(slotNextKeyEvent(GpgME::Context*,const GpgME::Key&)) ); - - // The communication channel between gpgme and gpgsm is limited in - // the number of patterns that can be transported, but they won't - // say to how much, so we need to find out ourselves if we get a - // LINE_TOO_LONG error back... - - // We could of course just feed them single patterns, and that would - // probably be easier, but the performance penalty would currently - // be noticable. - - while ( const GpgME::Error err = mCtx->startKeyListing( patterns(), mSecretOnly ) ) { - if ( err.code() == GPG_ERR_LINE_TOO_LONG ) { - setChunkSize( chunkSize()/2 ); - if ( chunkSize() >= 1 ) { - kdDebug(5150) << "QGpgMEKeyListJob::start(): retrying keylisting with chunksize " << chunkSize() << endl; - continue; - } - } - deleteLater(); - mResult = GpgME::KeyListResult( 0, err ); - return err; - } - mResult = GpgME::KeyListResult( 0, 0 ); - return 0; -} - -GpgME::KeyListResult Kleo::QGpgMEKeyListJob::exec( const QStringList & pats, bool secretOnly, std::vector & keys ) { - setup( pats, secretOnly ); - - // The communication channel between gpgme and gpgsm is limited in - // the number of patterns that can be transported, but they won't - // say to how much, so we need to find out ourselves if we get a - // LINE_TOO_LONG error back... - - // We could of course just feed them single patterns, and that would - // probably be easier, but the performance penalty would currently - // be noticable. - - for (;;) { - keys.clear(); - mResult = attemptSyncKeyListing( keys ); - if ( !mResult.error() || mResult.error().code() != GPG_ERR_LINE_TOO_LONG ) - return mResult; - // got LINE_TOO_LONG, try a smaller chunksize: - setChunkSize( chunkSize()/2 ); - if ( chunkSize() < 1 ) - // chunks smaller than one can't be -> return the error. - return mResult; - kdDebug(5150) << "QGpgMEKeyListJob::exec(): retrying keylisting with chunksize " << chunkSize() << endl; - } - kdFatal(5150) << "QGpgMEKeyListJob::exec(): Oops, this is not supposed to happen!" << endl; - return GpgME::KeyListResult(); -} - -GpgME::KeyListResult Kleo::QGpgMEKeyListJob::attemptSyncKeyListing( std::vector & keys ) { - GpgME::KeyListResult result; - for ( const char* * chunk = patterns() ; chunk ; chunk = nextChunk() ) { - - if ( const GpgME::Error err = mCtx->startKeyListing( chunk, mSecretOnly ) ) - return GpgME::KeyListResult( 0, err ); - - GpgME::Error err; - do - keys.push_back( mCtx->nextKey( err ) ); - while ( !err ); - keys.pop_back(); - result.mergeWith( mCtx->endKeyListing() ); - if ( result.error() ) - break; - } - return result; -} - -void Kleo::QGpgMEKeyListJob::slotNextKeyEvent( GpgME::Context * context, const GpgME::Key & key ) { - if ( context == mCtx ) - emit nextKey( key ); -} - -void Kleo::QGpgMEKeyListJob::slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & ) { - if ( context != mCtx ) - return; - mResult.mergeWith( mCtx->keyListResult() ); - if ( !mResult.error() ) - if ( const char* * chunk = nextChunk() ) { - if ( const GpgME::Error err = mCtx->startKeyListing( chunk, mSecretOnly ) ) - mResult.mergeWith( GpgME::KeyListResult( 0, err ) ); - else - return; - } - emit done(); - emit result( mResult ); - deleteLater(); -} - -void Kleo::QGpgMEKeyListJob::showErrorDialog( QWidget * parent, const QString & caption ) const { - if ( !mResult.error() || mResult.error().isCanceled() ) - return; - const QString msg = i18n( "

An error occurred while fetching " - "the keys from the backend:

" - "

%1

" ) - .arg( QString::fromLocal8Bit( mResult.error().asString() ) ); - KMessageBox::error( parent, msg, caption ); -} - -#include "qgpgmekeylistjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmekeylistjob.h b/kleopatra/lib/backends/qgpgme/qgpgmekeylistjob.h deleted file mode 100644 index 8320e0134e..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmekeylistjob.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - qgpgmekeylistjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEKEYLISTJOB_H__ -#define __KLEO_QGPGMEKEYLISTJOB_H__ - -#include - -#include - -#include "qgpgmejob.h" - -namespace GpgME { - class Error; - class Context; - class Key; -} - -namespace Kleo { - - class QGpgMEKeyListJob : public KeyListJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEKeyListJob( GpgME::Context * context ); - ~QGpgMEKeyListJob(); - - /*! \reimp from KeyListJob */ - GpgME::Error start( const QStringList & patterns, bool secretOnly ); - - /*! \reimp from KeyListJob */ - GpgME::KeyListResult exec( const QStringList & patterns, bool secretOnly, std::vector & keys ); - - /*! \reimp from Job */ - void showErrorDialog( QWidget * parent, const QString & caption ) const; - - private slots: - void slotNextKeyEvent( GpgME::Context * context, const GpgME::Key & key ); - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ); - - private: - void doOperationDoneEvent( const GpgME::Error &) {} // unused, we implement slotOperationDoneEvent ourselves. - void setup( const QStringList &, bool ); - GpgME::KeyListResult attemptSyncKeyListing( std::vector & ); - - private: - GpgME::KeyListResult mResult; - bool mSecretOnly; - }; - -} - -#endif // __KLEO_QGPGMEKEYLISTJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeprogresstokenmapper.cpp b/kleopatra/lib/backends/qgpgme/qgpgmeprogresstokenmapper.cpp deleted file mode 100644 index 792bc2f434..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeprogresstokenmapper.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* -*- mode: C++; c-file-style: "gnu" -*- - qgpgmeprogresstokenmapper.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmeprogresstokenmapper.h" - -#include - -#include - -#include -#include - -struct Desc { - int type; // 0 == fallback - const char * display; // add %1 for useCur ^ useTot and %1 %2 for useCur == useTot == true - bool useCur : 1; - bool useTot : 1; -}; - -static const struct Desc pk_dsa[] = { - { 0, I18N_NOOP("Generating DSA key..."), false, false } -}; - -static const struct Desc pk_elg[] = { - { 0, I18N_NOOP("Generating ElGamal key..."), false, false } -}; - -static const struct Desc primegen[] = { - // FIXME: add all type's? - { 0, I18N_NOOP("Searching for a large prime number..."), false, false } -}; - -static const struct Desc need_entropy[] = { - { 0, I18N_NOOP("Waiting for new entropy from random number generator (you might want to excercise the harddisks or move the mouse)..."), false, false } -}; - -static const struct Desc tick[] = { - { 0, I18N_NOOP("Please wait..."), false, false } -}; - -static const struct Desc starting_agent[] = { - { 0, I18N_NOOP("Starting gpg-agent (you should consider starting a global instance instead)..."), false, false } -}; - -static const struct { - const char * token; - const Desc * desc; - unsigned int numDesc; -} tokens[] = { -#define make_token(x) { #x, x, sizeof(x) / sizeof(*x) } - make_token(pk_dsa), - make_token(pk_elg), - make_token(primegen), - make_token(need_entropy), - make_token(tick), - make_token(starting_agent) -#undef make_token -}; - - - -Kleo::QGpgMEProgressTokenMapper * Kleo::QGpgMEProgressTokenMapper::mSelf = 0; - -const Kleo::QGpgMEProgressTokenMapper * Kleo::QGpgMEProgressTokenMapper::instance() { - if ( !mSelf ) - (void) new QGpgMEProgressTokenMapper(); - return mSelf; -} - -Kleo::QGpgMEProgressTokenMapper::QGpgMEProgressTokenMapper() { - mSelf = this; -} - -Kleo::QGpgMEProgressTokenMapper::~QGpgMEProgressTokenMapper() { - mSelf = 0; -} - -typedef std::map< QString, std::map > Map; - -static const Map & makeMap() { // return a reference to a static to avoid copying - static Map map; - for ( unsigned int i = 0 ; i < sizeof tokens / sizeof *tokens ; ++i ) { - assert( tokens[i].token ); - const QString token = QString::fromLatin1( tokens[i].token ).lower(); - for ( unsigned int j = 0 ; j < tokens[i].numDesc ; ++j ) { - const Desc & desc = tokens[i].desc[j]; - assert( desc.display ); - map[ token ][ desc.type ] = desc; - } - } - return map; -} - -QString Kleo::QGpgMEProgressTokenMapper::map( const char * tokenUtf8, int subtoken, int cur, int tot ) const { - if ( !tokenUtf8 || !*tokenUtf8 ) - return QString::null; - - if ( qstrcmp( tokenUtf8, "file:" ) == 0 ) - return QString::null; // gpgme's job - - return map( QString::fromUtf8( tokenUtf8 ), subtoken, cur, tot ); -} - -QString Kleo::QGpgMEProgressTokenMapper::map( const QString & token, int subtoken, int cur, int tot ) const { - if ( token.startsWith( "file:" ) ) - return QString::null; // gpgme's job - - static const Map & tokenMap = makeMap(); - - const Map::const_iterator it1 = tokenMap.find( token.lower() ); - if ( it1 == tokenMap.end() ) - return token; - std::map::const_iterator it2 = it1->second.find( subtoken ); - if ( it2 == it1->second.end() ) - it2 = it1->second.find( 0 ); - if ( it2 == it1->second.end() ) - return token; - const Desc & desc = it2->second; - QString result = i18n( desc.display ); - if ( desc.useCur ) - result = result.arg( cur ); - if ( desc.useTot ) - result = result.arg( tot ); - return result; -} - diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeprogresstokenmapper.h b/kleopatra/lib/backends/qgpgme/qgpgmeprogresstokenmapper.h deleted file mode 100644 index d0a8da6c3a..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeprogresstokenmapper.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - qgpgmeprogresstokenmapper.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - - -#ifndef __KLEO_QGPGMEPROGRESSTOKENMAPPER_H__ -#define __KLEO_QGPGMEPROGRESSTOKENMAPPER_H__ - - -class QString; - -namespace Kleo { - - class QGpgMEProgressTokenMapper { - QGpgMEProgressTokenMapper(); - ~QGpgMEProgressTokenMapper(); - public: - static const QGpgMEProgressTokenMapper * instance(); - - QString map( const char * token, int subtoken, int current, int total ) const; - QString map( const QString & token, int subtoken, int current, int total ) const; - - private: - static QGpgMEProgressTokenMapper * mSelf; - }; - -} - - -#endif // __KLEO_QGPGMEPROGRESSTOKENMAPPER_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmerefreshkeysjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmerefreshkeysjob.cpp deleted file mode 100644 index 325306e8cd..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmerefreshkeysjob.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* - qgpgmerefreshkeysjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmerefreshkeysjob.h" - -#include "gnupgprocessbase.h" -#include "qgpgmeprogresstokenmapper.h" - -#include - -#include - -#include - -#include - -#include - -#include - -Kleo::QGpgMERefreshKeysJob::QGpgMERefreshKeysJob() - : RefreshKeysJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMERefreshKeysJob" ), - mProcess( 0 ), - mError( 0 ) -{ - -} - -Kleo::QGpgMERefreshKeysJob::~QGpgMERefreshKeysJob() { - -} - -GpgME::Error Kleo::QGpgMERefreshKeysJob::start( const QStringList & patterns ) { - assert( mPatternsToDo.empty() ); - - mPatternsToDo = patterns; - if ( mPatternsToDo.empty() ) - mPatternsToDo.push_back( " " ); // empty list means all -> mae - // sure to fail the first - // startAProcess() guard clause - - return startAProcess(); -} - -#if MAX_CMD_LENGTH < 65 + 128 -#error MAX_CMD_LENGTH is too low -#endif - -GpgME::Error Kleo::QGpgMERefreshKeysJob::startAProcess() { - if ( mPatternsToDo.empty() ) - return 0; - // create and start gpgsm process: - mProcess = new GnuPGProcessBase( this, "gpgsm -k --with-validation --force-crl-refresh --enable-crl-checks" ); - - // FIXME: obbtain the path to gpgsm from gpgme, so we use the same instance. - *mProcess << "gpgsm" << "-k" << "--with-validation" << "--force-crl-refresh" - << "--enable-crl-checks"; - unsigned int commandLineLength = MAX_CMD_LENGTH; - commandLineLength -= - strlen("gpgsm") + 1 + strlen("-k") + 1 + - strlen("--with-validation") + 1 + strlen("--force-crl-refresh") + 1 + - strlen("--enable-crl-checks") + 1; - while ( !mPatternsToDo.empty() ) { - const QCString pat = mPatternsToDo.front().utf8().stripWhiteSpace(); - const unsigned int patLength = pat.length(); - if ( patLength >= commandLineLength ) - break; - mPatternsToDo.pop_front(); - if ( pat.isEmpty() ) - continue; - *mProcess << pat; - commandLineLength -= patLength + 1; - } - - mProcess->setUseStatusFD( true ); - - connect( mProcess, SIGNAL(processExited(KProcess*)), - SLOT(slotProcessExited(KProcess*)) ); - connect( mProcess, SIGNAL(receivedStderr(KProcess*,char*,int)), - SLOT(slotStderr(KProcess*,char*,int)) ); - connect( mProcess, SIGNAL(status(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)), - SLOT(slotStatus(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)) ); - - if ( !mProcess->start( KProcess::NotifyOnExit, KProcess::Stderr ) ) { - mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_ENOENT ); // what else? - deleteLater(); - return mError; - } else - return 0; -} - -void Kleo::QGpgMERefreshKeysJob::slotCancel() { - if ( mProcess ) - mProcess->kill(); - mProcess = 0; - mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_CANCELED ); -} - -void Kleo::QGpgMERefreshKeysJob::slotStatus( GnuPGProcessBase * proc, const QString & type, const QStringList & args ) { - if ( proc != mProcess ) - return; - QStringList::const_iterator it = args.begin(); - bool ok = false; - - if ( type == "ERROR" ) { - - - if ( args.size() < 2 ) { - kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() not recognising ERROR with < 2 args!" << endl; - return; - } - const int source = (*++it).toInt( &ok ); - if ( !ok ) { - kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() expected number for first ERROR arg, got something else" << endl; - return; - } - ok = false; - const int code = (*++it).toInt( &ok ); - if ( !ok ) { - kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() expected number for second ERROR arg, got something else" << endl; - return; - } - mError = gpg_err_make( (gpg_err_source_t)source, (gpg_err_code_t)code ); - - - } else if ( type == "PROGRESS" ) { - - - if ( args.size() < 4 ) { - kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() not recognising PROGRESS with < 4 args!" << endl; - return; - } - const QString what = *++it; - ++it; // don't use "type"... - const int cur = (*++it).toInt( &ok ); - if ( !ok ) { - kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() expected number for \"cur\", got something else" << endl; - return; - } - ok = false; - const int total = (*++it).toInt( &ok ); - if ( !ok ) { - kdDebug( 5150 ) << "Kleo::QGpgMERefreshKeysJob::slotStatus() expected number for \"total\", got something else" << endl; - return; - } - emit progress( QGpgMEProgressTokenMapper::instance()->map( what, 0, cur, total ), cur, total ); - - - } -} - -void Kleo::QGpgMERefreshKeysJob::slotStderr( KProcess *, char *, int ) { - // implement? or not? -} - -void Kleo::QGpgMERefreshKeysJob::slotProcessExited( KProcess * proc ) { - if ( proc != mProcess ) - return; - - if ( !mError && !mPatternsToDo.empty() ) - if ( const GpgME::Error err = startAProcess() ) - mError = err; - else - return; - - emit done(); - if ( !mError && - ( !mProcess->normalExit() || mProcess->exitStatus() != 0 ) ) - mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_GENERAL ); - emit result( mError ); - deleteLater(); -} - -#include "qgpgmerefreshkeysjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmerefreshkeysjob.h b/kleopatra/lib/backends/qgpgme/qgpgmerefreshkeysjob.h deleted file mode 100644 index a0132f223b..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmerefreshkeysjob.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - qgpgmerefreshkeysjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEREFRESHKEYSJOB_H__ -#define __KLEO_QGPGMEREFRESHKEYSJOB_H__ - -#include - -#include - -namespace Kleo { - class GnuPGProcessBase; -} - -namespace GpgME { - class Error; -} - -class KProcess; - -namespace Kleo { - - class QGpgMERefreshKeysJob : public RefreshKeysJob { - Q_OBJECT - public: - QGpgMERefreshKeysJob(); - ~QGpgMERefreshKeysJob(); - - /*! \reimp from RefreshKeysJob */ - GpgME::Error start( const QStringList & patterns ); - - private slots: - /*! \reimp from Job */ - void slotCancel(); - - void slotStatus( Kleo::GnuPGProcessBase *, const QString &, const QStringList & ); - void slotStderr( KProcess *, char *, int ); - void slotProcessExited( KProcess * ); - - private: - GpgME::Error startAProcess(); - - private: - GnuPGProcessBase * mProcess; - int mError; - QStringList mPatternsToDo; - }; - -} - -#endif // __KLEO_QGPGMEREFRESHKEYSJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmesecretkeyexportjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmesecretkeyexportjob.cpp deleted file mode 100644 index afc51b5e21..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmesecretkeyexportjob.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/* - qgpgmesecretexportjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmesecretkeyexportjob.h" - -#include "gnupgprocessbase.h" -#include "qgpgmeprogresstokenmapper.h" - -#include - -#include -#include - -#include - -#include - -#include - -#include -#include - -Kleo::QGpgMESecretKeyExportJob::QGpgMESecretKeyExportJob( bool armour ) - : ExportJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMESecretKeyExportJob" ), - mProcess( 0 ), - mError( 0 ), - mArmour( armour ) -{ - -} - -Kleo::QGpgMESecretKeyExportJob::~QGpgMESecretKeyExportJob() { - -} - -GpgME::Error Kleo::QGpgMESecretKeyExportJob::start( const QStringList & patterns ) { - assert( mKeyData.isEmpty() ); - - if ( patterns.size() != 1 || patterns.front().isEmpty() ) { - deleteLater(); - return mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_INV_VALUE ); - } - - // create and start gpgsm process: - mProcess = new GnuPGProcessBase( this, "gpgsm --export-secret-key-p12" ); - - // FIXME: obbtain the path to gpgsm from gpgme, so we use the same instance. - *mProcess << "gpgsm" << "--export-secret-key-p12"; - if ( mArmour ) - *mProcess << "--armor"; - *mProcess << patterns.front().utf8(); - - mProcess->setUseStatusFD( true ); - - connect( mProcess, SIGNAL(processExited(KProcess*)), - SLOT(slotProcessExited(KProcess*)) ); - connect( mProcess, SIGNAL(receivedStdout(KProcess*,char*,int)), - SLOT(slotStdout(KProcess*,char*,int)) ); - connect( mProcess, SIGNAL(receivedStderr(KProcess*,char*,int)), - SLOT(slotStderr(KProcess*,char*,int)) ); - connect( mProcess, SIGNAL(status(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)), - SLOT(slotStatus(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)) ); - - if ( !mProcess->start( KProcess::NotifyOnExit, KProcess::AllOutput ) ) { - mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_ENOENT ); // what else? - deleteLater(); - return mError; - } else - return 0; -} - -void Kleo::QGpgMESecretKeyExportJob::slotCancel() { - if ( mProcess ) - mProcess->kill(); - mProcess = 0; - mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_CANCELED ); -} - -void Kleo::QGpgMESecretKeyExportJob::slotStatus( GnuPGProcessBase * proc, const QString & type, const QStringList & args ) { - if ( proc != mProcess ) - return; - QStringList::const_iterator it = args.begin(); - bool ok = false; - - if ( type == "ERROR" ) { - - - if ( args.size() < 2 ) { - kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() not recognising ERROR with < 2 args!" << endl; - return; - } - const int source = (*++it).toInt( &ok ); - if ( !ok ) { - kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() expected number for first ERROR arg, got something else" << endl; - return; - } - ok = false; - const int code = (*++it).toInt( &ok ); - if ( !ok ) { - kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() expected number for second ERROR arg, got something else" << endl; - return; - } - mError = gpg_err_make( (gpg_err_source_t)source, (gpg_err_code_t)code ); - - - } else if ( type == "PROGRESS" ) { - - - if ( args.size() < 4 ) { - kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() not recognising PROGRESS with < 4 args!" << endl; - return; - } - const QString what = *++it; - ++it; // don't use "type"... - const int cur = (*++it).toInt( &ok ); - if ( !ok ) { - kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() expected number for \"cur\", got something else" << endl; - return; - } - ok = false; - const int total = (*++it).toInt( &ok ); - if ( !ok ) { - kdDebug( 5150 ) << "Kleo::QGpgMESecretKeyExportJob::slotStatus() expected number for \"total\", got something else" << endl; - return; - } - emit progress( QGpgMEProgressTokenMapper::instance()->map( what, 0, cur, total ), cur, total ); - - - } -} - -void Kleo::QGpgMESecretKeyExportJob::slotStdout( KProcess * proc, char * buf, int buflen ) { - if ( proc != mProcess ) - return; - if ( buflen <= 0 ) - return; - if ( !buf ) - return; - const unsigned int oldlen = mKeyData.size(); - mKeyData.resize( oldlen + buflen ); - memcpy( mKeyData.data() + oldlen, buf, buflen ); -} - -void Kleo::QGpgMESecretKeyExportJob::slotStderr( KProcess *, char *, int ) { - // implement? or not? -} - -void Kleo::QGpgMESecretKeyExportJob::slotProcessExited( KProcess * proc ) { - if ( proc != mProcess ) - return; - - emit done(); - if ( !mError && - ( !mProcess->normalExit() || mProcess->exitStatus() != 0 ) ) - mError = gpg_err_make( GPG_ERR_SOURCE_GPGSM, GPG_ERR_GENERAL ); - emit result( mError, mKeyData ); - deleteLater(); -} - -#include "qgpgmesecretkeyexportjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmesecretkeyexportjob.h b/kleopatra/lib/backends/qgpgme/qgpgmesecretkeyexportjob.h deleted file mode 100644 index dca23d7b65..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmesecretkeyexportjob.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - qgpgmesecretkeyexportjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMESECRETKEYEXPORTJOB_H__ -#define __KLEO_QGPGMESECRETKEYEXPORTJOB_H__ - -#include - -#include - -namespace Kleo { - class GnuPGProcessBase; -} - -namespace GpgME { - class Error; - class Data; -} - -namespace QGpgME { - class QByteArrayDataProvider; -} - -class KProcess; - -namespace Kleo { - - class QGpgMESecretKeyExportJob : public ExportJob { - Q_OBJECT - public: - QGpgMESecretKeyExportJob( bool armour ); - ~QGpgMESecretKeyExportJob(); - - /*! \reimp from ExportJob */ - GpgME::Error start( const QStringList & patterns ); - - private slots: - /*! \reimp from Job */ - void slotCancel(); - - void slotStatus( Kleo::GnuPGProcessBase *, const QString &, const QStringList & ); - void slotStdout( KProcess *, char *, int ); - void slotStderr( KProcess *, char *, int ); - void slotProcessExited( KProcess * ); - - private: - GnuPGProcessBase * mProcess; - QByteArray mKeyData; - int mError; - bool mArmour; - }; - -} - -#endif // __KLEO_QGPGMESECRETKEYEXPORTJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmesignencryptjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmesignencryptjob.cpp deleted file mode 100644 index 1ed6fe0eaf..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmesignencryptjob.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - qgpgmesignencryptjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmesignencryptjob.h" - -#include -#include - -#include -#include - -#include -#include -#include - -#include - -Kleo::QGpgMESignEncryptJob::QGpgMESignEncryptJob( GpgME::Context * context ) - : SignEncryptJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMESignEncryptJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMESignEncryptJob::~QGpgMESignEncryptJob() { -} - -GpgME::Error Kleo::QGpgMESignEncryptJob::setup( const std::vector & signers, - const QByteArray & plainText ) { - assert( !mInData ); - assert( !mOutData ); - - createInData( plainText ); - createOutData(); - - return setSigningKeys( signers ); -} - -GpgME::Error Kleo::QGpgMESignEncryptJob::start( const std::vector & signers, - const std::vector & recipients, - const QByteArray & plainText, bool alwaysTrust ) { - if ( const GpgME::Error error = setup( signers, plainText ) ) { - deleteLater(); - return error; - } - - hookupContextToEventLoopInteractor(); - - const GpgME::Context::EncryptionFlags flags = - alwaysTrust ? GpgME::Context::AlwaysTrust : GpgME::Context::None ; - const GpgME::Error err = mCtx->startCombinedSigningAndEncryption( recipients, *mInData, *mOutData, flags ); - - if ( err ) - deleteLater(); - return err; -} - -std::pair -Kleo::QGpgMESignEncryptJob::exec( const std::vector & signers, - const std::vector & recipients, - const QByteArray & plainText, bool alwaysTrust, - QByteArray & cipherText ) { - if ( GpgME::Error err = setup( signers, plainText ) ) - return std::make_pair( GpgME::SigningResult( 0, err ), GpgME::EncryptionResult() ); - const GpgME::Context::EncryptionFlags flags = - alwaysTrust ? GpgME::Context::AlwaysTrust : GpgME::Context::None ; - const std::pair result = - mCtx->signAndEncrypt( recipients, *mInData, *mOutData, flags ); - cipherText = mOutDataDataProvider->data(); - return result; -} - -void Kleo::QGpgMESignEncryptJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mCtx->signingResult(), - mCtx->encryptionResult(), - mOutDataDataProvider->data() ); -} - -void Kleo::QGpgMESignEncryptJob::showErrorDialog( QWidget * parent, const QString & caption ) const { - if ( !mResult.first.error() && !mResult.second.error() ) - return; - if ( mResult.first.error().isCanceled() || mResult.second.error().isCanceled() ) - return; - const QString msg = mResult.first.error() - ? i18n("Signing failed: %1" ).arg( QString::fromLocal8Bit( mResult.first.error().asString() ) ) - : i18n("Encryption failed: %1").arg( QString::fromLocal8Bit( mResult.second.error().asString() ) ) ; - KMessageBox::error( parent, msg, caption ); -} - -#include "qgpgmesignencryptjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmesignencryptjob.h b/kleopatra/lib/backends/qgpgme/qgpgmesignencryptjob.h deleted file mode 100644 index a826edcbf7..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmesignencryptjob.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - qgpgmesignencryptjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMESIGNENCRYPTJOB_H__ -#define __KLEO_QGPGMESIGNENCRYPTJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include -#include - -#include - -#include - -#include -namespace GpgME { - class Error; - class Context; - class Key; -} - -namespace Kleo { - - class KDE_EXPORT QGpgMESignEncryptJob : public SignEncryptJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMESignEncryptJob( GpgME::Context * context ); - ~QGpgMESignEncryptJob(); - - /*! \reimp from SignEncryptJob */ - GpgME::Error start( const std::vector & signers, - const std::vector & recipients, - const QByteArray & plainText, bool alwaysTrust ); - - std::pair - exec( const std::vector & signers, - const std::vector & recipients, - const QByteArray & plainText, bool alwaysTrust, - QByteArray & cipherText ); - - /*! \reimp from Job */ - void showErrorDialog( QWidget * parent, const QString & caption ) const; - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - GpgME::Error setup( const std::vector &, - const QByteArray & ); - private: - std::pair mResult; - }; - -} - -#endif // __KLEO_QGPGMESIGNENCRYPTJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmesignjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmesignjob.cpp deleted file mode 100644 index 585e898b66..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmesignjob.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* - qgpgmesignjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmesignjob.h" - -#include -#include - -#include -#include -#include -#include - -#include -#include - -#include - -Kleo::QGpgMESignJob::QGpgMESignJob( GpgME::Context * context ) - : SignJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMESignJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMESignJob::~QGpgMESignJob() { -} - -GpgME::Error Kleo::QGpgMESignJob::setup( const std::vector & signers, - const QByteArray & plainText ) { - assert( !mInData ); - assert( !mOutData ); - - createInData( plainText ); - createOutData(); - - return setSigningKeys( signers ); -} - -GpgME::Error Kleo::QGpgMESignJob::start( const std::vector & signers, - const QByteArray & plainText, - GpgME::Context::SignatureMode mode ) { - if ( const GpgME::Error error = setup( signers, plainText ) ) { - deleteLater(); - return error; - } - - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startSigning( *mInData, *mOutData, mode ); - - if ( err ) - deleteLater(); - return err; -} - -GpgME::SigningResult Kleo::QGpgMESignJob::exec( const std::vector & signers, - const QByteArray & plainText, - GpgME::Context::SignatureMode mode, - QByteArray & signature ) { - if ( const GpgME::Error err = setup( signers, plainText ) ) - return mResult = GpgME::SigningResult( 0, err ); - mResult = mCtx->sign( *mInData, *mOutData, mode ); - signature = mOutDataDataProvider->data(); - return mResult; -} - -void Kleo::QGpgMESignJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mResult, mOutDataDataProvider->data() ); -} - -void Kleo::QGpgMESignJob::showErrorDialog( QWidget * parent, const QString & caption ) const { - if ( !mResult.error() || mResult.error().isCanceled() ) - return; - const QString msg = i18n("Signing failed: %1") - .arg( QString::fromLocal8Bit( mResult.error().asString() ) ); - KMessageBox::error( parent, msg, caption ); -} - -#include "qgpgmesignjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmesignjob.h b/kleopatra/lib/backends/qgpgme/qgpgmesignjob.h deleted file mode 100644 index c2589b4770..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmesignjob.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - qgpgmesignjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMESIGNJOB_H__ -#define __KLEO_QGPGMESIGNJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include - -#include - -namespace GpgME { - class Error; - class Context; - class Key; -} - -namespace Kleo { - - class QGpgMESignJob : public SignJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMESignJob( GpgME::Context * context ); - ~QGpgMESignJob(); - - /*! \reimp from SignJob */ - GpgME::Error start( const std::vector & signers, - const QByteArray & plainText, - GpgME::Context::SignatureMode mode ); - - /*! \reimp from SignJob */ - GpgME::SigningResult exec( const std::vector & signers, - const QByteArray & plainText, - GpgME::Context::SignatureMode mode, - QByteArray & signature ); - - /*! \reimp from Job */ - void showErrorDialog( QWidget * parent, const QString & caption ) const; - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - GpgME::Error setup( const std::vector &, const QByteArray & ); - - private: - GpgME::SigningResult mResult; - }; - -} - -#endif // __KLEO_QGPGMESIGNJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeverifydetachedjob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmeverifydetachedjob.cpp deleted file mode 100644 index 1adf12bc28..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeverifydetachedjob.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - qgpgmeverifydetachedjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmeverifydetachedjob.h" - -#include -#include - -#include -#include -#include - -#include - -Kleo::QGpgMEVerifyDetachedJob::QGpgMEVerifyDetachedJob( GpgME::Context * context ) - : VerifyDetachedJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEVerifyDetachedJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEVerifyDetachedJob::~QGpgMEVerifyDetachedJob() { -} - -void Kleo::QGpgMEVerifyDetachedJob::setup( const QByteArray & signature, const QByteArray & signedData ) { - assert( !mInData ); - assert( !mOutData ); - - createInData( signature ); - - // two "in" data objects - (mis|re)use the "out" data object for the second... - mOutDataDataProvider = new QGpgME::QByteArrayDataProvider( signedData ); - mOutData = new GpgME::Data( mOutDataDataProvider ); - assert( !mOutData->isNull() ); -} - -GpgME::Error Kleo::QGpgMEVerifyDetachedJob::start( const QByteArray & signature, - const QByteArray & signedData ) { - setup( signature, signedData ); - - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startDetachedSignatureVerification( *mInData, *mOutData ); - - if ( err ) - deleteLater(); - return err; -} - -GpgME::VerificationResult Kleo::QGpgMEVerifyDetachedJob::exec( const QByteArray & signature, - const QByteArray & signedData ) { - setup( signature, signedData ); - return mCtx->verifyDetachedSignature( *mInData, *mOutData ); -} - -void Kleo::QGpgMEVerifyDetachedJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mCtx->verificationResult() ); -} - - -#include "qgpgmeverifydetachedjob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeverifydetachedjob.h b/kleopatra/lib/backends/qgpgme/qgpgmeverifydetachedjob.h deleted file mode 100644 index 76141fb804..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeverifydetachedjob.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - qgpgmeverifydetachedjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEVERIFYDETACHEDJOB_H__ -#define __KLEO_QGPGMEVERIFYDETACHEDJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include - -namespace GpgME { - class Error; - class Context; -} - -namespace Kleo { - - class QGpgMEVerifyDetachedJob : public VerifyDetachedJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEVerifyDetachedJob( GpgME::Context * context ); - ~QGpgMEVerifyDetachedJob(); - - /*! \reimp from VerifyDetachedJob */ - GpgME::Error start( const QByteArray & signature, - const QByteArray & signedData ); - - /*! \reimp from VerifyDetachedJob */ - GpgME::VerificationResult exec( const QByteArray & signature, - const QByteArray & signedData ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - void setup( const QByteArray &, const QByteArray & ); - }; - -} - -#endif // __KLEO_QGPGMEVERIFYDETACHEDJOB_H__ diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeverifyopaquejob.cpp b/kleopatra/lib/backends/qgpgme/qgpgmeverifyopaquejob.cpp deleted file mode 100644 index 374206bb68..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeverifyopaquejob.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - qgpgmeverifyopaquejob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "qgpgmeverifyopaquejob.h" - -#include -#include - -#include -#include -#include - -#include - -Kleo::QGpgMEVerifyOpaqueJob::QGpgMEVerifyOpaqueJob( GpgME::Context * context ) - : VerifyOpaqueJob( QGpgME::EventLoopInteractor::instance(), "Kleo::QGpgMEVerifyOpaqueJob" ), - QGpgMEJob( this, context ) -{ - assert( context ); -} - -Kleo::QGpgMEVerifyOpaqueJob::~QGpgMEVerifyOpaqueJob() { -} - -void Kleo::QGpgMEVerifyOpaqueJob::setup( const QByteArray & signedData ) { - assert( !mInData ); - assert( !mOutData ); - - createInData( signedData ); - createOutData(); -} - -GpgME::Error Kleo::QGpgMEVerifyOpaqueJob::start( const QByteArray & signedData ) { - setup( signedData ); - - hookupContextToEventLoopInteractor(); - - const GpgME::Error err = mCtx->startOpaqueSignatureVerification( *mInData, *mOutData ); - - if ( err ) - deleteLater(); - return err; -} - -GpgME::VerificationResult Kleo::QGpgMEVerifyOpaqueJob::exec( const QByteArray & signedData, QByteArray & plainText ) { - setup( signedData ); - const GpgME::VerificationResult res = mCtx->verifyOpaqueSignature( *mInData, *mOutData ); - plainText = mOutDataDataProvider->data(); - return res; -} - -void Kleo::QGpgMEVerifyOpaqueJob::doOperationDoneEvent( const GpgME::Error & ) { - emit result( mCtx->verificationResult(), mOutDataDataProvider->data() ); -} - - -#include "qgpgmeverifyopaquejob.moc" diff --git a/kleopatra/lib/backends/qgpgme/qgpgmeverifyopaquejob.h b/kleopatra/lib/backends/qgpgme/qgpgmeverifyopaquejob.h deleted file mode 100644 index 2c167fb1de..0000000000 --- a/kleopatra/lib/backends/qgpgme/qgpgmeverifyopaquejob.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - qgpgmeverifyopaquejob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_QGPGMEVERIFYOPAQUEJOB_H__ -#define __KLEO_QGPGMEVERIFYOPAQUEJOB_H__ - -#include - -#include "qgpgmejob.h" - -#include - -namespace GpgME { - class Error; - class Context; -} - -namespace Kleo { - - class QGpgMEVerifyOpaqueJob : public VerifyOpaqueJob, private QGpgMEJob { - Q_OBJECT QGPGME_JOB - public: - QGpgMEVerifyOpaqueJob( GpgME::Context * context ); - ~QGpgMEVerifyOpaqueJob(); - - /*! \reimp from VerifyOpaqueJob */ - GpgME::Error start( const QByteArray & signedData ); - - /*! \reimp form VerifyOpaqueJob */ - GpgME::VerificationResult exec( const QByteArray & signedData, QByteArray & plainData ); - - private slots: - void slotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) { - QGpgMEJob::doSlotOperationDoneEvent( context, e ); - } - - private: - void doOperationDoneEvent( const GpgME::Error & e ); - void setup( const QByteArray & ); - }; - -} - -#endif // __KLEO_QGPGMEVERIFYOPAQUEJOB_H__ diff --git a/kleopatra/lib/cryptplug.cpp b/kleopatra/lib/cryptplug.cpp deleted file mode 100644 index 7a58cbe048..0000000000 --- a/kleopatra/lib/cryptplug.cpp +++ /dev/null @@ -1,1123 +0,0 @@ -/* -*- Mode: C++ -*- - - this is a C++-ification of: - GPGMEPLUG - an GPGME based cryptography plug-in following - the common CRYPTPLUG specification. - - Copyright (C) 2001 by Klarlvdalens Datakonsult AB - Copyright (C) 2002 g10 Code GmbH - Copyright (C) 2004 Klarlvdalens Datakonsult AB - - GPGMEPLUG is free software; you can redistribute it and/or modify - it under the terms of GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - GPGMEPLUG is distributed in the hope that it will be useful, - it under the terms of GNU General Public License as published by - the Free Software Foundation; version 2 of the License - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "kleo/oidmap.h" - -#include -#include -#include - -/*! \file gpgmeplug.c - \brief GPGME implementation of CRYPTPLUG following the - specification located in common API header cryptplug.h. - - CRYPTPLUG is an independent cryptography plug-in API - developed for Sphinx-enabeling KMail and Mutt. - - CRYPTPLUG was designed for the Aegypten project, but it may - be used by 3rd party developers as well to design pluggable - crypto backends for the above mentioned MUAs. - - \note All string parameters appearing in this API are to be - interpreted as UTF-8 encoded. - - \see cryptplug.h -*/ - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#define __GPGMEPLUG_ERROR_CLEARTEXT_IS_ZERO "Error: Cannot run checkMessageSignature() with cleartext == 0" - -/* Note: The following specification will result in - function encryptAndSignMessage() producing - _empty_ mails. - This must be changed as soon as our plugin - is supporting the encryptAndSignMessage() function. */ -#ifndef GPGMEPLUG_ENCSIGN_MAKE_MIME_OBJECT -#define GPGMEPLUG_ENCSIGN_INCLUDE_CLEARTEXT false -#define GPGMEPLUG_ENCSIGN_MAKE_MIME_OBJECT false -#define GPGMEPLUG_ENCSIGN_MAKE_MULTI_MIME false -#define GPGMEPLUG_ENCSIGN_CTYPE_MAIN "" -#define GPGMEPLUG_ENCSIGN_CDISP_MAIN "" -#define GPGMEPLUG_ENCSIGN_CTENC_MAIN "" -#define GPGMEPLUG_ENCSIGN_CTYPE_VERSION "" -#define GPGMEPLUG_ENCSIGN_CDISP_VERSION "" -#define GPGMEPLUG_ENCSIGN_CTENC_VERSION "" -#define GPGMEPLUG_ENCSIGN_BTEXT_VERSION "" -#define GPGMEPLUG_ENCSIGN_CTYPE_CODE "" -#define GPGMEPLUG_ENCSIGN_CDISP_CODE "" -#define GPGMEPLUG_ENCSIGN_CTENC_CODE "" -#define GPGMEPLUG_ENCSIGN_FLAT_PREFIX "" -#define GPGMEPLUG_ENCSIGN_FLAT_SEPARATOR "" -#define GPGMEPLUG_ENCSIGN_FLAT_POSTFIX "" -#endif - -#include "cryptplug.h" -#include - -SMIMECryptPlug::SMIMECryptPlug() : CryptPlug() { - GPGMEPLUG_PROTOCOL = GPGME_PROTOCOL_CMS; - mProtocol = GpgME::Context::CMS; - - /* definitions for signing */ - // 1. opaque signatures (only used for S/MIME) - GPGMEPLUG_OPA_SIGN_INCLUDE_CLEARTEXT = false; - GPGMEPLUG_OPA_SIGN_MAKE_MIME_OBJECT = true; - GPGMEPLUG_OPA_SIGN_MAKE_MULTI_MIME = false; - GPGMEPLUG_OPA_SIGN_CTYPE_MAIN = "application/pkcs7-mime; smime-type=signed-data; name=\"smime.p7m\""; - GPGMEPLUG_OPA_SIGN_CDISP_MAIN = "attachment; filename=\"smime.p7m\""; - GPGMEPLUG_OPA_SIGN_CTENC_MAIN = "base64"; - GPGMEPLUG_OPA_SIGN_CTYPE_VERSION = ""; - GPGMEPLUG_OPA_SIGN_CDISP_VERSION = ""; - GPGMEPLUG_OPA_SIGN_CTENC_VERSION = ""; - GPGMEPLUG_OPA_SIGN_BTEXT_VERSION = ""; - GPGMEPLUG_OPA_SIGN_CTYPE_CODE = ""; - GPGMEPLUG_OPA_SIGN_CDISP_CODE = ""; - GPGMEPLUG_OPA_SIGN_CTENC_CODE = ""; - GPGMEPLUG_OPA_SIGN_FLAT_PREFIX = ""; - GPGMEPLUG_OPA_SIGN_FLAT_SEPARATOR = ""; - GPGMEPLUG_OPA_SIGN_FLAT_POSTFIX = ""; - // 2. detached signatures (used for S/MIME and for OpenPGP) - GPGMEPLUG_DET_SIGN_INCLUDE_CLEARTEXT = true; - GPGMEPLUG_DET_SIGN_MAKE_MIME_OBJECT = true; - GPGMEPLUG_DET_SIGN_MAKE_MULTI_MIME = true; - GPGMEPLUG_DET_SIGN_CTYPE_MAIN = "multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha1"; - GPGMEPLUG_DET_SIGN_CDISP_MAIN = ""; - GPGMEPLUG_DET_SIGN_CTENC_MAIN = ""; - GPGMEPLUG_DET_SIGN_CTYPE_VERSION = ""; - GPGMEPLUG_DET_SIGN_CDISP_VERSION = ""; - GPGMEPLUG_DET_SIGN_CTENC_VERSION = ""; - GPGMEPLUG_DET_SIGN_BTEXT_VERSION = ""; - GPGMEPLUG_DET_SIGN_CTYPE_CODE = "application/pkcs7-signature; name=\"smime.p7s\""; - GPGMEPLUG_DET_SIGN_CDISP_CODE = "attachment; filename=\"smime.p7s\""; - GPGMEPLUG_DET_SIGN_CTENC_CODE = "base64"; - GPGMEPLUG_DET_SIGN_FLAT_PREFIX = ""; - GPGMEPLUG_DET_SIGN_FLAT_SEPARATOR = ""; - GPGMEPLUG_DET_SIGN_FLAT_POSTFIX = ""; - // 3. common definitions for opaque and detached signing - __GPGMEPLUG_SIGNATURE_CODE_IS_BINARY = true; - - /* definitions for encoding */ - GPGMEPLUG_ENC_INCLUDE_CLEARTEXT = false; - GPGMEPLUG_ENC_MAKE_MIME_OBJECT = true; - GPGMEPLUG_ENC_MAKE_MULTI_MIME = false; - GPGMEPLUG_ENC_CTYPE_MAIN = "application/pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\""; - GPGMEPLUG_ENC_CDISP_MAIN = "attachment; filename=\"smime.p7m\""; - GPGMEPLUG_ENC_CTENC_MAIN = "base64"; - GPGMEPLUG_ENC_CTYPE_VERSION = ""; - GPGMEPLUG_ENC_CDISP_VERSION = ""; - GPGMEPLUG_ENC_CTENC_VERSION = ""; - GPGMEPLUG_ENC_BTEXT_VERSION = ""; - GPGMEPLUG_ENC_CTYPE_CODE = ""; - GPGMEPLUG_ENC_CDISP_CODE = ""; - GPGMEPLUG_ENC_CTENC_CODE = ""; - GPGMEPLUG_ENC_FLAT_PREFIX = ""; - GPGMEPLUG_ENC_FLAT_SEPARATOR = ""; - GPGMEPLUG_ENC_FLAT_POSTFIX = ""; - __GPGMEPLUG_ENCRYPTED_CODE_IS_BINARY = true; -} - -OpenPGPCryptPlug::OpenPGPCryptPlug() : CryptPlug() { - GPGMEPLUG_PROTOCOL = GPGME_PROTOCOL_OpenPGP; - mProtocol = GpgME::Context::OpenPGP; - - /* definitions for signing */ - // 1. opaque signatures (only used for S/MIME) - GPGMEPLUG_OPA_SIGN_INCLUDE_CLEARTEXT = false; - GPGMEPLUG_OPA_SIGN_MAKE_MIME_OBJECT = false; - GPGMEPLUG_OPA_SIGN_MAKE_MULTI_MIME = false; - GPGMEPLUG_OPA_SIGN_CTYPE_MAIN = ""; - GPGMEPLUG_OPA_SIGN_CDISP_MAIN = ""; - GPGMEPLUG_OPA_SIGN_CTENC_MAIN = ""; - GPGMEPLUG_OPA_SIGN_CTYPE_VERSION = ""; - GPGMEPLUG_OPA_SIGN_CDISP_VERSION = ""; - GPGMEPLUG_OPA_SIGN_CTENC_VERSION = ""; - GPGMEPLUG_OPA_SIGN_BTEXT_VERSION = ""; - GPGMEPLUG_OPA_SIGN_CTYPE_CODE = ""; - GPGMEPLUG_OPA_SIGN_CDISP_CODE = ""; - GPGMEPLUG_OPA_SIGN_CTENC_CODE = ""; - GPGMEPLUG_OPA_SIGN_FLAT_PREFIX = ""; - GPGMEPLUG_OPA_SIGN_FLAT_SEPARATOR = ""; - GPGMEPLUG_OPA_SIGN_FLAT_POSTFIX = ""; - // 2. detached signatures (used for S/MIME and for OpenPGP) - GPGMEPLUG_DET_SIGN_INCLUDE_CLEARTEXT = true; - GPGMEPLUG_DET_SIGN_MAKE_MIME_OBJECT = true; - GPGMEPLUG_DET_SIGN_MAKE_MULTI_MIME = true; - GPGMEPLUG_DET_SIGN_CTYPE_MAIN = "multipart/signed; protocol=\"application/pgp-signature\"; micalg=pgp-sha1"; - GPGMEPLUG_DET_SIGN_CDISP_MAIN = ""; - GPGMEPLUG_DET_SIGN_CTENC_MAIN = ""; - GPGMEPLUG_DET_SIGN_CTYPE_VERSION = ""; - GPGMEPLUG_DET_SIGN_CDISP_VERSION = ""; - GPGMEPLUG_DET_SIGN_CTENC_VERSION = ""; - GPGMEPLUG_DET_SIGN_BTEXT_VERSION = ""; - GPGMEPLUG_DET_SIGN_CTYPE_CODE = "application/pgp-signature"; - GPGMEPLUG_DET_SIGN_CDISP_CODE = ""; - GPGMEPLUG_DET_SIGN_CTENC_CODE = ""; - GPGMEPLUG_DET_SIGN_FLAT_PREFIX = ""; - GPGMEPLUG_DET_SIGN_FLAT_SEPARATOR = ""; - GPGMEPLUG_DET_SIGN_FLAT_POSTFIX = ""; - // 3. common definitions for opaque and detached signing - __GPGMEPLUG_SIGNATURE_CODE_IS_BINARY = false; - - /* definitions for encoding */ - GPGMEPLUG_ENC_INCLUDE_CLEARTEXT = false; - GPGMEPLUG_ENC_MAKE_MIME_OBJECT = true; - GPGMEPLUG_ENC_MAKE_MULTI_MIME = true; - GPGMEPLUG_ENC_CTYPE_MAIN = "multipart/encrypted; protocol=\"application/pgp-encrypted\""; - GPGMEPLUG_ENC_CDISP_MAIN = ""; - GPGMEPLUG_ENC_CTENC_MAIN = ""; - GPGMEPLUG_ENC_CTYPE_VERSION = "application/pgp-encrypted"; - GPGMEPLUG_ENC_CDISP_VERSION = "attachment"; - GPGMEPLUG_ENC_CTENC_VERSION = ""; - GPGMEPLUG_ENC_BTEXT_VERSION = "Version: 1"; - GPGMEPLUG_ENC_CTYPE_CODE = "application/octet-stream"; - GPGMEPLUG_ENC_CDISP_CODE = "inline; filename=\"msg.asc\""; - GPGMEPLUG_ENC_CTENC_CODE = ""; - GPGMEPLUG_ENC_FLAT_PREFIX = ""; - GPGMEPLUG_ENC_FLAT_SEPARATOR = ""; - GPGMEPLUG_ENC_FLAT_POSTFIX = ""; - __GPGMEPLUG_ENCRYPTED_CODE_IS_BINARY = false; -} - -#define days_from_seconds(x) ((x)/86400) - -/* Max number of parts in a DN */ -#define MAX_GPGME_IDX 20 - -/* some macros to replace ctype ones and avoid locale problems */ -#define spacep(p) (*(p) == ' ' || *(p) == '\t') -#define digitp(p) (*(p) >= '0' && *(p) <= '9') -#define hexdigitp(a) (digitp (a) \ - || (*(a) >= 'A' && *(a) <= 'F') \ - || (*(a) >= 'a' && *(a) <= 'f')) -/* the atoi macros assume that the buffer has only valid digits */ -#define atoi_1(p) (*(p) - '0' ) -#define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1)) -#define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2)) -#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ - *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) -#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) - -static void * -xmalloc (size_t n) -{ - void *p = malloc (n); - if (!p) - { - fputs ("\nfatal: out of core\n", stderr); - exit (4); - } - return p; -} - -/* Please: Don't call an allocation function xfoo when it may return NULL. */ -/* Wrong: #define xstrdup( x ) (x)?strdup(x):0 */ -/* Right: */ -static char * -xstrdup (const char *string) -{ - char *p = (char*)xmalloc (strlen (string)+1); - strcpy (p, string); - return p; -} - - -CryptPlug::CryptPlug() { -} - -CryptPlug::~CryptPlug() { -} - -bool CryptPlug::initialize() { - GpgME::setDefaultLocale( LC_CTYPE, setlocale( LC_CTYPE, 0 ) ); - GpgME::setDefaultLocale( LC_MESSAGES, setlocale( LC_MESSAGES, 0 ) ); - return (gpgme_engine_check_version (GPGMEPLUG_PROTOCOL) == GPG_ERR_NO_ERROR); -} - - -bool CryptPlug::hasFeature( Feature flag ) -{ - /* our own plugins are supposed to support everything */ - switch ( flag ) { - case Feature_SignMessages: - case Feature_VerifySignatures: - case Feature_EncryptMessages: - case Feature_DecryptMessages: - case Feature_SendCertificates: - case Feature_PinEntrySettings: - case Feature_StoreMessagesWithSigs: - case Feature_EncryptionCRLs: - case Feature_StoreMessagesEncrypted: - case Feature_CheckCertificatePath: - return true; - case Feature_WarnSignCertificateExpiry: - case Feature_WarnSignEmailNotInCertificate: - case Feature_WarnEncryptCertificateExpiry: - case Feature_WarnEncryptEmailNotInCertificate: - return GPGMEPLUG_PROTOCOL == GPGME_PROTOCOL_CMS; - /* undefined or not yet implemented: */ - case Feature_CRLDirectoryService: - case Feature_CertificateDirectoryService: - case Feature_undef: - default: - return false; - } -} - - -static -void storeNewCharPtr( char** dest, const char* src ) -{ - int sLen = strlen( src ); - *dest = (char*)xmalloc( sLen + 1 ); - strcpy( *dest, src ); -} - -bool CryptPlug::decryptMessage( const char* ciphertext, - bool cipherIsBinary, - int cipherLen, - const char** cleartext, - const char* /*certificate*/, - int* errId, - char** errTxt ) -{ - gpgme_ctx_t ctx; - gpgme_error_t err; - gpgme_data_t gCiphertext, gPlaintext; - size_t rCLen = 0; - char* rCiph = 0; - bool bOk = false; - - if( !ciphertext ) - return false; - - err = gpgme_new (&ctx); - gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); - - gpgme_set_armor (ctx, cipherIsBinary ? 0 : 1); - /* gpgme_set_textmode (ctx, cipherIsBinary ? 0 : 1); */ - - /* - gpgme_data_new_from_mem( &gCiphertext, ciphertext, - 1+strlen( ciphertext ), 1 ); */ - gpgme_data_new_from_mem( &gCiphertext, - ciphertext, - cipherIsBinary - ? cipherLen - : strlen( ciphertext ), - 1 ); - - gpgme_data_new( &gPlaintext ); - - err = gpgme_op_decrypt( ctx, gCiphertext, gPlaintext ); - if( err ) { - fprintf( stderr, "\ngpgme_op_decrypt() returned this error code: %i\n\n", err ); - if( errId ) - *errId = err; - if( errTxt ) { - const char* _errTxt = gpgme_strerror( err ); - *errTxt = (char*)malloc( strlen( _errTxt ) + 1 ); - if( *errTxt ) - strcpy(*errTxt, _errTxt ); - } - } - - gpgme_data_release( gCiphertext ); - - rCiph = gpgme_data_release_and_get_mem( gPlaintext, &rCLen ); - - *cleartext = (char*)malloc( rCLen + 1 ); - if( *cleartext ) { - if( rCLen ) { - bOk = true; - strncpy((char*)*cleartext, rCiph, rCLen ); - } - ((char*)(*cleartext))[rCLen] = 0; - } - - free( rCiph ); - gpgme_release( ctx ); - return bOk; -} - - -static char * -trim_trailing_spaces( char *string ) -{ - char *p, *mark; - - for( mark = NULL, p = string; *p; p++ ) { - if( isspace( *p ) ) { - if( !mark ) - mark = p; - } - else - mark = NULL; - } - if( mark ) - *mark = '\0' ; - - return string ; -} - -/* Parse a DN and return an array-ized one. This is not a validating - parser and it does not support any old-stylish syntax; gpgme is - expected to return only rfc2253 compatible strings. */ -static const unsigned char * -parse_dn_part (CryptPlug::DnPair *array, const unsigned char *string) -{ - const unsigned char *s, *s1; - size_t n; - char *p; - - /* parse attributeType */ - for (s = string+1; *s && *s != '='; s++) - ; - if (!*s) - return NULL; /* error */ - n = s - string; - if (!n) - return NULL; /* empty key */ - p = (char*)xmalloc (n+1); - - - memcpy (p, string, n); - p[n] = 0; - trim_trailing_spaces ((char*)p); - // map OIDs to their names: - for ( unsigned int i = 0 ; i < numOidMaps ; ++i ) - if ( !strcasecmp ((char*)p, oidmap[i].oid) ) { - free( p ); - p = xstrdup (oidmap[i].name); - break; - } - array->key = p; - string = s + 1; - - if (*string == '#') - { /* hexstring */ - string++; - for (s=string; hexdigitp (s); s++) - s++; - n = s - string; - if (!n || (n & 1)) - return NULL; /* empty or odd number of digits */ - n /= 2; - array->value = p = (char*)xmalloc (n+1); - - - for (s1=string; n; s1 += 2, n--) - *p++ = xtoi_2 (s1); - *p = 0; - } - else - { /* regular v3 quoted string */ - for (n=0, s=string; *s; s++) - { - if (*s == '\\') - { /* pair */ - s++; - if (*s == ',' || *s == '=' || *s == '+' - || *s == '<' || *s == '>' || *s == '#' || *s == ';' - || *s == '\\' || *s == '\"' || *s == ' ') - n++; - else if (hexdigitp (s) && hexdigitp (s+1)) - { - s++; - n++; - } - else - return NULL; /* invalid escape sequence */ - } - else if (*s == '\"') - return NULL; /* invalid encoding */ - else if (*s == ',' || *s == '=' || *s == '+' - || *s == '<' || *s == '>' || *s == '#' || *s == ';' ) - break; - else - n++; - } - - array->value = p = (char*)xmalloc (n+1); - - - for (s=string; n; s++, n--) - { - if (*s == '\\') - { - s++; - if (hexdigitp (s)) - { - *p++ = xtoi_2 (s); - s++; - } - else - *p++ = *s; - } - else - *p++ = *s; - } - *p = 0; - } - return s; -} - - -/* Parse a DN and return an array-ized one. This is not a validating - parser and it does not support any old-stylish syntax; gpgme is - expected to return only rfc2253 compatible strings. */ -static CryptPlug::DnPair * -parse_dn (const unsigned char *string) -{ - struct CryptPlug::DnPair *array; - size_t arrayidx, arraysize; - - if( !string ) - return NULL; - - arraysize = 7; /* C,ST,L,O,OU,CN,email */ - arrayidx = 0; - array = (CryptPlug::DnPair*)xmalloc ((arraysize+1) * sizeof *array); - - - while (*string) - { - while (*string == ' ') - string++; - if (!*string) - break; /* ready */ - if (arrayidx >= arraysize) - { /* mutt lacks a real safe_realoc - so we need to copy */ - struct CryptPlug::DnPair *a2; - - arraysize += 5; - a2 = (CryptPlug::DnPair*)xmalloc ((arraysize+1) * sizeof *array); - for (unsigned int i=0; i < arrayidx; i++) - { - a2[i].key = array[i].key; - a2[i].value = array[i].value; - } - free (array); - array = a2; - } - array[arrayidx].key = NULL; - array[arrayidx].value = NULL; - string = parse_dn_part (array+arrayidx, string); - arrayidx++; - if (!string) - goto failure; - while (*string == ' ') - string++; - if (*string && *string != ',' && *string != ';' && *string != '+') - goto failure; /* invalid delimiter */ - if (*string) - string++; - } - array[arrayidx].key = NULL; - array[arrayidx].value = NULL; - return array; - - failure: - for (unsigned i=0; i < arrayidx; i++) - { - free (array[i].key); - free (array[i].value); - } - free (array); - return NULL; -} - -static void -add_dn_part( QCString& result, struct CryptPlug::DnPair& dnPair ) -{ - /* email hack */ - QCString mappedPart( dnPair.key ); - for ( unsigned int i = 0 ; i < numOidMaps ; ++i ){ - if( !strcasecmp( dnPair.key, oidmap[i].oid ) ) { - mappedPart = oidmap[i].name; - break; - } - } - result.append( mappedPart ); - result.append( "=" ); - result.append( dnPair.value ); -} - -static int -add_dn_parts( QCString& result, struct CryptPlug::DnPair* dn, const char* part ) -{ - int any = 0; - - if( dn ) { - for(; dn->key; ++dn ) { - if( !strcmp( dn->key, part ) ) { - if( any ) - result.append( "," ); - add_dn_part( result, *dn ); - any = 1; - } - } - } - return any; -} - -static char* -reorder_dn( struct CryptPlug::DnPair *dn, - char** attrOrder = 0, - const char* unknownAttrsHandling = 0 ) -{ - struct CryptPlug::DnPair *dnOrg = dn; - - /* note: The must parts are: CN, L, OU, O, C */ - const char* defaultpart[] = { - "CN", "S", "SN", "GN", "T", "UID", - "MAIL", "EMAIL", "MOBILE", "TEL", "FAX", "STREET", - "L", "PC", "SP", "ST", - "OU", - "O", - "C", - NULL - }; - const char** stdpart = attrOrder ? ((const char**)attrOrder) : defaultpart; - int any=0, any2=0, found_X_=0, i; - QCString result; - QCString resultUnknowns; - - /* find and save the non-standard parts in their original order */ - if( dn ){ - for(; dn->key; ++dn ) { - for( i = 0; stdpart[i]; ++i ) { - if( !strcmp( dn->key, stdpart[i] ) ) { - break; - } - } - if( !stdpart[i] ) { - if( any2 ) - resultUnknowns.append( "," ); - add_dn_part( resultUnknowns, *dn ); - any2 = 1; - } - } - dn = dnOrg; - } - - /* prepend the unknown attrs if desired */ - if( unknownAttrsHandling && - !strcmp(unknownAttrsHandling, "PREFIX") - && *resultUnknowns ){ - result.append( resultUnknowns ); - any = 1; - }else{ - any = 0; - } - - /* add standard parts */ - for( i = 0; stdpart[i]; ++i ) { - dn = dnOrg; - if( any ) { - result.append( "," ); - } - if( any2 && - !strcmp(stdpart[i], "_X_") && - unknownAttrsHandling && - !strcmp(unknownAttrsHandling, "INFIX") ){ - if ( !resultUnknowns.isEmpty() ) { - result.append( resultUnknowns ); - any = 1; - } - found_X_ = 1; - }else{ - any = add_dn_parts( result, dn, stdpart[i] ); - } - } - - /* append the unknown attrs if desired */ - if( !unknownAttrsHandling || - !strcmp(unknownAttrsHandling, "POSTFIX") || - ( !strcmp(unknownAttrsHandling, "INFIX") && !found_X_ ) ){ - if( !resultUnknowns.isEmpty() ) { - if( any ){ - result.append( "," ); - } - result.append( resultUnknowns ); - } - } - - char* cResult = (char*)xmalloc( (result.length()+1)*sizeof(char) ); - if( result.isEmpty() ) - *cResult = 0; - else - strcpy( cResult, result ); - return cResult; -} - -GpgME::ImportResult CryptPlug::importCertificateFromMem( const char* data, size_t length ) -{ - using namespace GpgME; - - std::auto_ptr context( Context::createForProtocol( mProtocol ) ); - if ( !context.get() ) - return ImportResult(); - - Data keydata( data, length, false ); - if ( keydata.isNull() ) - return ImportResult(); - - return context->importKeys( keydata ); -} - - -/* == == == == == == == == == == == == == == == == == == == == == == == == == - == == - == Continuation of CryptPlug code == - == == -== == == == == == == == == == == == == == == == == == == == == == == == == */ - -// these are from gpgme-0.4.3: -static gpgme_sig_stat_t -sig_stat_from_status( gpgme_error_t err ) -{ - switch ( gpg_err_code(err) ) { - case GPG_ERR_NO_ERROR: - return GPGME_SIG_STAT_GOOD; - case GPG_ERR_BAD_SIGNATURE: - return GPGME_SIG_STAT_BAD; - case GPG_ERR_NO_PUBKEY: - return GPGME_SIG_STAT_NOKEY; - case GPG_ERR_NO_DATA: - return GPGME_SIG_STAT_NOSIG; - case GPG_ERR_SIG_EXPIRED: - return GPGME_SIG_STAT_GOOD_EXP; - case GPG_ERR_KEY_EXPIRED: - return GPGME_SIG_STAT_GOOD_EXPKEY; - default: - return GPGME_SIG_STAT_ERROR; - } -} - - -static gpgme_sig_stat_t -intersect_stati( gpgme_signature_t first ) -{ - if ( !first ) - return GPGME_SIG_STAT_NONE; - gpgme_sig_stat_t result = sig_stat_from_status( first->status ); - for ( gpgme_signature_t sig = first->next ; sig ; sig = sig->next ) - if ( sig_stat_from_status( sig->status ) != result ) - return GPGME_SIG_STAT_DIFF; - return result; -} - -static const char* -sig_status_to_string( gpgme_sig_stat_t status ) -{ - const char *result; - - switch (status) { - case GPGME_SIG_STAT_NONE: - result = "Oops: Signature not verified"; - break; - case GPGME_SIG_STAT_NOSIG: - result = "No signature found"; - break; - case GPGME_SIG_STAT_GOOD: - result = "Good signature"; - break; - case GPGME_SIG_STAT_BAD: - result = "BAD signature"; - break; - case GPGME_SIG_STAT_NOKEY: - result = "No public key to verify the signature"; - break; - case GPGME_SIG_STAT_ERROR: - result = "Error verifying the signature"; - break; - case GPGME_SIG_STAT_DIFF: - result = "Different results for signatures"; - break; - default: - result = "Error: Unknown status"; - break; - } - - return result; -} - -// WARNING: if you fix a bug here, you have to likely fix it in the -// gpgme 0.3 version below, too! -static -void obtain_signature_information( gpgme_ctx_t ctx, - gpgme_sig_stat_t & overallStatus, - struct CryptPlug::SignatureMetaData* sigmeta, - char** attrOrder, - const char* unknownAttrsHandling, - bool * signatureFound=0 ) -{ - gpgme_error_t err; - unsigned long sumGPGME; - SigStatusFlags sumPlug; - struct CryptPlug::DnPair* a; - int sig_idx=0; - - assert( ctx ); - assert( sigmeta ); - - sigmeta->extended_info = 0; - gpgme_verify_result_t result = gpgme_op_verify_result( ctx ); - if ( !result ) - return; - for ( gpgme_signature_t signature = result->signatures ; signature ; signature = signature->next, ++sig_idx ) { - void* alloc_return = realloc( sigmeta->extended_info, - sizeof( CryptPlug::SignatureMetaDataExtendedInfo ) - * ( sig_idx + 1 ) ); - if ( !alloc_return ) - break; - sigmeta->extended_info = (CryptPlug::SignatureMetaDataExtendedInfo*)alloc_return; - - /* shorthand notation :) */ - CryptPlug::SignatureMetaDataExtendedInfo & this_info = sigmeta->extended_info[sig_idx]; - - /* clear the data area */ - memset( &this_info, 0, sizeof (CryptPlug::SignatureMetaDataExtendedInfo) ); - - /* the creation time */ - if ( signature->timestamp ) { - this_info.creation_time = (tm*)malloc( sizeof( struct tm ) ); - if ( this_info.creation_time ) { - struct tm * ctime_val = localtime( (time_t*)&signature->timestamp ); - memcpy( this_info.creation_time, - ctime_val, sizeof( struct tm ) ); - } - } - - /* the extended signature verification status */ - sumGPGME = signature->summary; - fprintf( stderr, "gpgmeplug checkMessageSignature status flags: %lX\n", sumGPGME ); - /* translate GPGME status flags to common CryptPlug status flags */ - sumPlug = 0; -#define convert(X) if ( sumGPGME & GPGME_SIGSUM_##X ) sumPlug |= SigStat_##X - convert(VALID); - convert(GREEN); - convert(RED); - convert(KEY_REVOKED); - convert(KEY_EXPIRED); - convert(SIG_EXPIRED); - convert(KEY_MISSING); - convert(CRL_MISSING); - convert(CRL_TOO_OLD); - convert(BAD_POLICY); - convert(SYS_ERROR); -#undef convert - if( sumGPGME && !sumPlug ) - sumPlug = SigStat_NUMERICAL_CODE | sumGPGME; - this_info.sigStatusFlags = sumPlug; - - /* extract finger print */ - if ( signature->fpr ) - storeNewCharPtr( &this_info.fingerprint, signature->fpr ); - - /* validity */ - this_info.validity = GPGME_VALIDITY_UNKNOWN; - - /* sig key data */ - gpgme_key_t key = 0; - // PENDING(marc) if this is deprecated, how shall we get at all - // the infos below? - err = gpgme_get_sig_key (ctx, sig_idx, &key); - - if ( !err && key ) { - const char* attr_string; - unsigned long attr_ulong; - - /* extract key identidy */ - attr_string = key->subkeys ? key->subkeys->keyid : 0 ; - if ( attr_string ) - storeNewCharPtr( &this_info.keyid, attr_string ); - - /* pubkey algorithm */ - attr_string = key->subkeys ? gpgme_pubkey_algo_name( key->subkeys->pubkey_algo ) : 0 ; - if (attr_string != 0) - storeNewCharPtr( &this_info.algo, attr_string ); - attr_ulong = key->subkeys ? key->subkeys->pubkey_algo : 0 ; - this_info.algo_num = attr_ulong; - - /* extract key validity */ - attr_ulong = key->uids ? key->uids->validity : 0 ; - this_info.validity = attr_ulong; - - /* extract user id, according to the documentation it's representable - * as a number, but it seems that it also has a string representation - */ - attr_string = key->uids ? key->uids->uid : 0 ; - if (attr_string != 0) { - a = parse_dn( (const unsigned char*)attr_string ); - this_info.userid = reorder_dn( a, attrOrder, unknownAttrsHandling ); - } - - attr_ulong = 0; - this_info.userid_num = attr_ulong; - - /* extract the length */ - this_info.keylen = key->subkeys ? key->subkeys->length : 0 ; - - /* extract the creation time of the key */ - attr_ulong = key->subkeys ? key->subkeys->timestamp : 0 ; - this_info.key_created = attr_ulong; - - /* extract the expiration time of the key */ - attr_ulong = key->subkeys ? key->subkeys->expires : 0 ; - this_info.key_expires = attr_ulong; - - /* extract user name */ - attr_string = key->uids ? key->uids->name : 0 ; - if (attr_string != 0) { - a = parse_dn( (const unsigned char*)attr_string ); - this_info.name = reorder_dn( a, attrOrder, unknownAttrsHandling ); - } - - /* extract email(s) */ - this_info.emailCount = 0; - this_info.emailList = 0; - for ( gpgme_user_id_t uid = key->uids ; uid ; uid = uid->next ) { - attr_string = uid->email; - if ( attr_string && *attr_string) { - fprintf( stderr, "gpgmeplug checkMessageSignature found email: %s\n", attr_string ); - if( !this_info.emailCount ) - alloc_return = malloc( sizeof( char*) ); - else - alloc_return = realloc( this_info.emailList, - sizeof( char*) - * (this_info.emailCount + 1) ); - if( alloc_return ) { - this_info.emailList = (char**)alloc_return; - storeNewCharPtr( &( this_info.emailList[ this_info.emailCount ] ), - attr_string ); - ++this_info.emailCount; - } - } - } - if( !this_info.emailCount ) - fprintf( stderr, "gpgmeplug checkMessageSignature found NO EMAIL\n" ); - - /* extract the comment */ - attr_string = key->uids ? key->uids->comment : 0 ; - if (attr_string != 0) - storeNewCharPtr( &this_info.comment, attr_string ); - } - - gpgme_sig_stat_t status = sig_stat_from_status( signature->status ); - const char* sig_status = sig_status_to_string( status ); - storeNewCharPtr( &this_info.status_text, sig_status ); - } - sigmeta->extended_info_count = sig_idx; - overallStatus = intersect_stati( result->signatures ); - sigmeta->status_code = overallStatus; - storeNewCharPtr( &sigmeta->status, sig_status_to_string( overallStatus ) ); - if ( signatureFound ) - *signatureFound = ( overallStatus != GPGME_SIG_STAT_NONE ); -} - -bool CryptPlug::checkMessageSignature( char** cleartext, - const char* signaturetext, - bool signatureIsBinary, - int signatureLen, - struct CryptPlug::SignatureMetaData* sigmeta, - char** attrOrder, - const char* unknownAttrsHandling ) -{ - gpgme_ctx_t ctx; - gpgme_sig_stat_t status = GPGME_SIG_STAT_NONE; - gpgme_data_t datapart, sigpart; - char* rClear = 0; - size_t clearLen; - bool isOpaqueSigned; - - if( !cleartext ) { - if( sigmeta ) - storeNewCharPtr( &sigmeta->status, - __GPGMEPLUG_ERROR_CLEARTEXT_IS_ZERO ); - - return false; - } - - isOpaqueSigned = !*cleartext; - - gpgme_new( &ctx ); - gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); - gpgme_set_armor (ctx, signatureIsBinary ? 0 : 1); - /* gpgme_set_textmode (ctx, signatureIsBinary ? 0 : 1); */ - - if( isOpaqueSigned ) - gpgme_data_new( &datapart ); - else - gpgme_data_new_from_mem( &datapart, *cleartext, - strlen( *cleartext ), 1 ); - - gpgme_data_new_from_mem( &sigpart, - signaturetext, - signatureIsBinary - ? signatureLen - : strlen( signaturetext ), - 1 ); - - if ( isOpaqueSigned ) - gpgme_op_verify( ctx, sigpart, 0, datapart ); - else - gpgme_op_verify( ctx, sigpart, datapart, 0 ); - - if( isOpaqueSigned ) { - rClear = gpgme_data_release_and_get_mem( datapart, &clearLen ); - *cleartext = (char*)malloc( clearLen + 1 ); - if( *cleartext ) { - if( clearLen ) - strncpy(*cleartext, rClear, clearLen ); - (*cleartext)[clearLen] = '\0'; - } - free( rClear ); - } - else - gpgme_data_release( datapart ); - - gpgme_data_release( sigpart ); - - obtain_signature_information( ctx, status, sigmeta, - attrOrder, unknownAttrsHandling ); - - gpgme_release( ctx ); - return ( status == GPGME_SIG_STAT_GOOD ); -} - -bool CryptPlug::decryptAndCheckMessage( const char* ciphertext, - bool cipherIsBinary, - int cipherLen, - const char** cleartext, - const char* /*certificate*/, - bool* signatureFound, - struct CryptPlug::SignatureMetaData* sigmeta, - int* errId, - char** errTxt, - char** attrOrder, - const char* unknownAttrsHandling ) -{ - gpgme_ctx_t ctx; - gpgme_error_t err; - gpgme_decrypt_result_t decryptresult; - gpgme_data_t gCiphertext, gPlaintext; - gpgme_sig_stat_t sigstatus = GPGME_SIG_STAT_NONE; - size_t rCLen = 0; - char* rCiph = 0; - bool bOk = false; - bool bWrongKeyUsage = false; - - if( !ciphertext ) - return false; - - err = gpgme_new (&ctx); - gpgme_set_protocol (ctx, GPGMEPLUG_PROTOCOL); - - gpgme_set_armor (ctx, cipherIsBinary ? 0 : 1); - /* gpgme_set_textmode (ctx, cipherIsBinary ? 0 : 1); */ - - /* - gpgme_data_new_from_mem( &gCiphertext, ciphertext, - 1+strlen( ciphertext ), 1 ); */ - gpgme_data_new_from_mem( &gCiphertext, - ciphertext, - cipherIsBinary - ? cipherLen - : strlen( ciphertext ), - 1 ); - - gpgme_data_new( &gPlaintext ); - - err = gpgme_op_decrypt_verify( ctx, gCiphertext, gPlaintext ); - gpgme_data_release( gCiphertext ); - - decryptresult = gpgme_op_decrypt_result( ctx ); -#ifdef HAVE_GPGME_WRONG_KEY_USAGE - if( decryptresult->wrong_key_usage ) - bWrongKeyUsage = true; -#endif - - if( err ) { - fprintf( stderr, "\ngpgme_op_decrypt_verify() returned this error code: %i\n\n", err ); - if( errId ) - *errId = err; - if( errTxt ) { - const char* _errTxt = gpgme_strerror( err ); - *errTxt = (char*)malloc( strlen( _errTxt ) + 1 ); - if( *errTxt ) - strcpy(*errTxt, _errTxt ); - } - gpgme_data_release( gPlaintext ); - gpgme_release( ctx ); - return bOk; - } - - if( bWrongKeyUsage ) { - if( errId ) - *errId = CRYPTPLUG_ERR_WRONG_KEY_USAGE; // report the wrong key usage - } - - rCiph = gpgme_data_release_and_get_mem( gPlaintext, &rCLen ); - - *cleartext = (char*)malloc( rCLen + 1 ); - if( *cleartext ) { - if( rCLen ) { - bOk = true; - strncpy((char*)*cleartext, rCiph, rCLen ); - } - ((char*)(*cleartext))[rCLen] = 0; - } - free( rCiph ); - - obtain_signature_information( ctx, sigstatus, sigmeta, - attrOrder, unknownAttrsHandling, - signatureFound ); - - gpgme_release( ctx ); - return bOk; -} - diff --git a/kleopatra/lib/cryptplug.h b/kleopatra/lib/cryptplug.h deleted file mode 100644 index 0e3ccb6961..0000000000 --- a/kleopatra/lib/cryptplug.h +++ /dev/null @@ -1,954 +0,0 @@ -/* -*- Mode: C++ -*- - - this is a C++-ification of: - CRYPTPLUG - an independent cryptography plug-in API - - Copyright (C) 2001,2004 Klarlvdalens Datakonsult AB - - CRYPTPLUG is free software; you can redistribute it and/or modify - it under the terms of GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - CRYPTPLUG 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ - -#ifndef CRYPTPLUG_H -#define CRYPTPLUG_H - -#include - -#include -#include // need it for gpgme_protocol_t :( -#include - -namespace GpgME { - class ImportResult; -} - -/*! \file cryptplug.h - \brief Common API header for CRYPTPLUG. - - CRYPTPLUG is an independent cryptography plug-in API - developed for Sphinx-enabeling KMail and Mutt. - - CRYPTPLUG was designed for the Aegypten project, but it may - be used by 3rd party developers as well to design pluggable - crypto backends for the above mentioned MUAs. - - \note All string parameters appearing in this API are to be - interpreted as UTF-8 encoded. - - \see pgpplugin.c - \see gpgplugin.c -*/ - -/*! \defgroup groupGeneral Loading and Unloading the Plugin, General Functionality - - The functions in this section are used for loading and - unloading plugins. Note that the actual locating of the plugin - and the loading and unloading of the dynamic library is not - covered here; this is MUA-specific code for which support code - might already exist in the programming environments. -*/ - -/*! \defgroup groupDisplay Graphical Display Functionality - - The functions in this section return stationery that the - MUAs can use in order to display security functionality - graphically. This can be toolbar icons, shortcuts, tooltips, - etc. Not all MUAs will use all this functionality. -*/ - -/*! \defgroup groupConfig Configuration Support - - The functions in this section provide the necessary - functionality to configure the security functionality as well - as to query configuration settings. Since all configuration - settings will not be saved with the plugin, but rather with - the MUA, there are also functions to set configuration - settings programmatically; these will be used on startup of - the plugin when the MUA transfers the configuration values it - has read into the plugin. Usually, the functions to query and - set the configuration values are not needed for anything but - saving to and restoring from configuration files. -*/ - - -/*! \defgroup groupConfigSign Signature Configuration - \ingroup groupConfig - - The functions in this section provide the functionality - to configure signature handling and set and query the - signature configuration. -*/ - -/*! \defgroup groupConfigCrypt Encryption Configuration - \ingroup groupConfig - - The functions in this section provide the functionality - to configure encryption handling and set and query the - encryption configuration. - - \note Whenever the term encryption is used here, - it is supposed to mean both encryption and decryption, - unless otherwise specified. -*/ - -/*! \defgroup groupConfigDir Directory Service Configuration - \ingroup groupConfig - - This section contains messages for configuring the - directory service. -*/ - - -/*! \defgroup groupCertHand Certificate Handling - - The following methods are used to maintain and query certificates. -*/ - - -/*! \defgroup groupSignCryptAct Signing and Encrypting Actions - - This section describes methods and structures - used for signing and/or encrypting your mails. -*/ - - -/*! \defgroup groupSignAct Signature Actions - \ingroup groupSignCryptAct - - This section describes methods that are used for working - with signatures. -*/ - -/*! \defgroup groupCryptAct Encryption and Decryption - \ingroup groupSignCryptAct - - The following methods are used to encrypt and decrypt - email messages. -*/ - -/*! \defgroup groupCertAct Certificate Handling Actions - - The functions in this section provide local certificate management. -*/ - -/*! \defgroup groupCRLAct CRL Handling Actions - - This section describes functions for managing CRLs. -*/ - -/*! \defgroup groupAdUsoInterno Important functions to be used by plugin implementors ONLY. - - This section describes functions that have to be used by - plugin implementors but should not be used by plugin users - directly. - - If you are not planning to write your own cryptography - plugin you should ignore this section! -*/ - -/*! \defgroup certList Certificate Info listing functions - */ - -typedef enum { - Feature_undef = 0, - - Feature_SignMessages = 1, - Feature_VerifySignatures = 2, - Feature_EncryptMessages = 3, - Feature_DecryptMessages = 4, - Feature_SendCertificates = 5, - Feature_WarnSignCertificateExpiry = 6, - Feature_WarnSignEmailNotInCertificate = 7, - Feature_PinEntrySettings = 8, - Feature_StoreMessagesWithSigs = 9, - Feature_EncryptionCRLs = 10, - Feature_WarnEncryptCertificateExpiry = 11, - Feature_WarnEncryptEmailNotInCertificate = 12, - Feature_StoreMessagesEncrypted = 13, - Feature_CheckCertificatePath = 14, - Feature_CertificateDirectoryService = 15, - Feature_CRLDirectoryService = 16, - Feature_CertificateInfo = 17 -} Feature; - -/* dummy values */ -typedef enum { - PinRequest_undef = 0, - - PinRequest_Always = 1, - PinRequest_WhenAddingCerts = 2, - PinRequest_AlwaysWhenSigning = 3, - PinRequest_OncePerSession = 4, - PinRequest_AfterMinutes = 5 -} PinRequests; - - -typedef enum { - SignatureCompoundMode_undef = 0, - - SignatureCompoundMode_Opaque = 1, - SignatureCompoundMode_Detached = 2 -} SignatureCompoundMode; - - -typedef enum { - SendCert_undef = 0, - - SendCert_DontSend = 1, - SendCert_SendOwn = 2, - SendCert_SendChainWithoutRoot = 3, - SendCert_SendChainWithRoot = 4 -} SendCertificates; - - -typedef enum { - SignAlg_undef = 0, - - SignAlg_SHA1 = 1 -} SignatureAlgorithm; - - - -typedef enum { - EncryptAlg_undef = 0, - - EncryptAlg_RSA = 1, - EncryptAlg_SHA1 = 2, - EncryptAlg_TripleDES = 3 -} EncryptionAlgorithm; - -typedef enum { - SignEmail_undef = 0, - - SignEmail_SignAll = 1, - SignEmail_Ask = 2, - SignEmail_DontSign = 3 -} SignEmail; - -typedef enum { - EncryptEmail_undef = 0, - - EncryptEmail_EncryptAll = 1, - EncryptEmail_Ask = 2, - EncryptEmail_DontEncrypt = 3 -} EncryptEmail; - -typedef enum { - CertSrc_undef = 0, - - CertSrc_Server = 1, - CertSrc_Local = 2, - CertSrc_ServerLocal = CertSrc_Server | CertSrc_Local -} CertificateSource; - - -/*! \ingroup groupSignAct - \brief Flags used to compose the SigStatusFlags value. - - This status flags are used to compose the SigStatusFlags value - returned in \c SignatureMetaDataExtendedInfo after trying to - verify a signed message part's signature status. - - The normal flags may not be used together with the - special SigStat_NUMERICAL_CODE flag. When finding the special - SigStat_NUMERICAL_CODE flag in a SigStatusFlags value you - can obtain the respective error code number by substracting - the SigStatusFlags value by SigStat_NUMERICAL_CODE: this is - used to transport special status information NOT matching - any of the normal predefined status codes. - - \note to PlugIn developers: Implementations of the CryptPlug API - should try to express their signature states by bit-wise OR'ing - the normal SigStatusFlags values. Using the SigStat_NUMERICAL_CODE - flag should only be used as for exceptional situations where no - other flag(s) could be used. By using the normal status flags your - PlugIn's users will be told an understandable description of the - status - when using (SigStat_NUMERICAL_CODE + internalCode) they - will only be shown the respective code number and have to look - into your PlugIn's manual to learn about it's meaning... -*/ -enum { - SigStat_VALID = 0x0001, /* The signature is fully valid */ - SigStat_GREEN = 0x0002, /* The signature is good. */ - SigStat_RED = 0x0004, /* The signature is bad. */ - SigStat_KEY_REVOKED = 0x0010, /* One key has been revoked. */ - SigStat_KEY_EXPIRED = 0x0020, /* One key has expired. */ - SigStat_SIG_EXPIRED = 0x0040, /* The signature has expired. */ - SigStat_KEY_MISSING = 0x0080, /* Can't verify: key missing. */ - SigStat_CRL_MISSING = 0x0100, /* CRL not available. */ - SigStat_CRL_TOO_OLD = 0x0200, /* Available CRL is too old. */ - SigStat_BAD_POLICY = 0x0400, /* A policy was not met. */ - SigStat_SYS_ERROR = 0x0800, /* A system error occurred. */ - - SigStat_NUMERICAL_CODE = 0x8000 /* An other error occurred. */ -}; -typedef unsigned long SigStatusFlags; - -class CryptPlugWrapper; - -class KDE_EXPORT CryptPlug { - friend class CryptPlugWrapper; -protected: - CryptPlug(); - virtual ~CryptPlug(); - - // these must be set by subclasses: - gpgme_protocol_t GPGMEPLUG_PROTOCOL; - GpgME::Context::Protocol mProtocol; - - /* definitions for signing */ - // 1. opaque signatures (only used for S/MIME) - int GPGMEPLUG_OPA_SIGN_INCLUDE_CLEARTEXT; - int GPGMEPLUG_OPA_SIGN_MAKE_MIME_OBJECT; - int GPGMEPLUG_OPA_SIGN_MAKE_MULTI_MIME; - const char * GPGMEPLUG_OPA_SIGN_CTYPE_MAIN; - const char * GPGMEPLUG_OPA_SIGN_CDISP_MAIN; - const char * GPGMEPLUG_OPA_SIGN_CTENC_MAIN; - const char * GPGMEPLUG_OPA_SIGN_CTYPE_VERSION; - const char * GPGMEPLUG_OPA_SIGN_CDISP_VERSION; - const char * GPGMEPLUG_OPA_SIGN_CTENC_VERSION; - const char * GPGMEPLUG_OPA_SIGN_BTEXT_VERSION; - const char * GPGMEPLUG_OPA_SIGN_CTYPE_CODE; - const char * GPGMEPLUG_OPA_SIGN_CDISP_CODE; - const char * GPGMEPLUG_OPA_SIGN_CTENC_CODE; - const char * GPGMEPLUG_OPA_SIGN_FLAT_PREFIX; - const char * GPGMEPLUG_OPA_SIGN_FLAT_SEPARATOR; - const char * GPGMEPLUG_OPA_SIGN_FLAT_POSTFIX; - // 2. detached signatures (used for S/MIME and for OpenPGP) - int GPGMEPLUG_DET_SIGN_INCLUDE_CLEARTEXT; - int GPGMEPLUG_DET_SIGN_MAKE_MIME_OBJECT; - int GPGMEPLUG_DET_SIGN_MAKE_MULTI_MIME; - const char * GPGMEPLUG_DET_SIGN_CTYPE_MAIN; - const char * GPGMEPLUG_DET_SIGN_CDISP_MAIN; - const char * GPGMEPLUG_DET_SIGN_CTENC_MAIN; - const char * GPGMEPLUG_DET_SIGN_CTYPE_VERSION; - const char * GPGMEPLUG_DET_SIGN_CDISP_VERSION; - const char * GPGMEPLUG_DET_SIGN_CTENC_VERSION; - const char * GPGMEPLUG_DET_SIGN_BTEXT_VERSION; - const char * GPGMEPLUG_DET_SIGN_CTYPE_CODE; - const char * GPGMEPLUG_DET_SIGN_CDISP_CODE; - const char * GPGMEPLUG_DET_SIGN_CTENC_CODE; - const char * GPGMEPLUG_DET_SIGN_FLAT_PREFIX; - const char * GPGMEPLUG_DET_SIGN_FLAT_SEPARATOR; - const char * GPGMEPLUG_DET_SIGN_FLAT_POSTFIX; - // 3. common definitions for opaque and detached signing - int __GPGMEPLUG_SIGNATURE_CODE_IS_BINARY; - - /* definitions for encoding */ - int GPGMEPLUG_ENC_INCLUDE_CLEARTEXT; - int GPGMEPLUG_ENC_MAKE_MIME_OBJECT; - int GPGMEPLUG_ENC_MAKE_MULTI_MIME; - const char * GPGMEPLUG_ENC_CTYPE_MAIN; - const char * GPGMEPLUG_ENC_CDISP_MAIN; - const char * GPGMEPLUG_ENC_CTENC_MAIN; - const char * GPGMEPLUG_ENC_CTYPE_VERSION; - const char * GPGMEPLUG_ENC_CDISP_VERSION; - const char * GPGMEPLUG_ENC_CTENC_VERSION; - const char * GPGMEPLUG_ENC_BTEXT_VERSION; - const char * GPGMEPLUG_ENC_CTYPE_CODE; - const char * GPGMEPLUG_ENC_CDISP_CODE; - const char * GPGMEPLUG_ENC_CTENC_CODE; - const char * GPGMEPLUG_ENC_FLAT_PREFIX; - const char * GPGMEPLUG_ENC_FLAT_SEPARATOR; - const char * GPGMEPLUG_ENC_FLAT_POSTFIX; - int __GPGMEPLUG_ENCRYPTED_CODE_IS_BINARY; - // end-of(these must be set by subclasses) - -public: - -#define CRYPTPLUG_CERT_DOES_NEVER_EXPIRE 365000 -#define CRYPTPLUG_ERR_WRONG_KEY_USAGE 0x7070 - -/*! \ingroup groupGeneral - \brief This function sets up all internal structures. - - Plugins that need no initialization should provide an empty - implementation. The method returns \c true if the initialization was - successful and \c false otherwise. Before this function is called, - no other plugin functions should be called; the behavior is - undefined in this case. - - \note This function must be implemented by each plug-in using - this API specification. -*/ -bool initialize( void ); - -/*! \ingroup groupGeneral - \brief This function frees all internal structures. - - Plugins that do not keep any internal structures should provide an - empty implementation. After this function has been called, - no other plugin functions should be called; the behavior is - undefined in this case. - - \note This function must be implemented by each plug-in using - this API specification. -*/ -//void deinitialize( void ); - -/*! \ingroup groupGeneral - \brief This function returns \c true if the - specified feature is available in the plugin, and - \c false otherwise. - - Not all plugins will support all features; a complete Sphinx - implementation will support all features contained in the enum, - however. - - \note This function must be implemented by each plug-in using - this API specification. -*/ -bool hasFeature( Feature ); - -/*! \ingroup groupSignCryptAct - \brief Information record returned by signing and by encrypting - functions - this record should be used together with a - corresponding \c free_StructuringInfo() function call. - - Use this information to compose a MIME object containing signed - and/or encrypted content (or to build a text frame around your - flat non-MIME message body, resp.) - - If value returned in \c makeMimeObject is TRUE the - text strings returned in \c contentTypeMain and \c contentDispMain - and \c contentTEncMain (and, if required, \c content[..]Version and - \c bodyTextVersion and \c content[..]Sig) should be used to compose - a respective MIME object.
- If FALSE the texts returned in \c flatTextPrefix and - \c flatTextSeparator and \c flatTextPostfix are to be used instead.
- Allways either the \c content[..] and \c bodyTextVersion - parameters or the \c flatText[..] parameters are holding - valid data - never both of them may be used simultaneously - as plugins will just ignore the parameters not matching their - \c makeMimeObject setting. - - When creating your MIME object please observe these common rules: - \li Parameters named \c contentType[..] and \c contentDisp[..] and - \c contentTEnc[..] will return the values for the respective MIME - headers 'Content-Type' and 'Content-Disposition' and - 'Content-Transfer-Encoding'. The following applies to these parameters: - \li The relevant MIME part may only be created if the respective - \c contentType[..] parameter is holding a non-zero-length string. If the - \c contentType[..] parameter value is invalid or holding an empty string - the respective \c contentDisp[..] and \c contentTEnc[..] parameters - should be ignored. - \li If the respective \c contentDisp[..] or \c contentTEnc[..] parameter - is NULL or holding a zero-length string it is up to you whether you want - to add the relevant MIME header yourself, but since it in in the - responsibility of the plugin implementors to provide you with all - neccessary 'Content-[..]' header information you should not need - to define them if they are not returned by the signing or encrypting - function - otherwise this may be considered as a bug in the plugin and - you could report the missing MIME header information to the address - returned by the \c bugURL() function. - - If \c makeMultiMime returns FALSE the \c contentTypeMain returned must - not be altered but used to specify a single part mime object holding the - code bloc, e.g. this is used for 'enveloped-data' single part MIME - objects. In this case you should ignore both the \c content[..]Version - and \c content[..]Code parameters. - - If \c makeMultiMime returns TRUE also the following rules apply: - \li If \c includeCleartext is TRUE you should include the cleartext - as first part of our multipart MIME object, typically this is TRUE - when signing mails but FALSE when encrypting. - \li The \c contentTypeMain returned typically starts with - "multipart/" while providing a "protocol" and a "micalg" parameter: just - add an appropriate \c "; boundary=[your \c boundary \c string]" to get - the complete Content-Type value to be used for the MIME object embedding - both the signed part and the signature part (or - in case of - encrypting - the version part and the code part, resp.). - \li If \c contentTypeVersion is holding a non-zero-length string an - additional MIME part must added immediately before the code part, this - version part's MIME headers must have the unaltered values of - \c contentTypeVersion and (if they are holding non-zero-length strings) - \c contentDispVersion and \c contentTEncVersion, the unaltered contents - of \c bodyTextVersion must be it's body. - \li The value returned in \c contentTypeCode is specifying the complete - Content-Type to be used for this multipart MIME object's signature part - (or - in case of encrypting - for the code part following after the - version part, resp.), you should not add/change/remove anything here - but just use it's unaltered value for specifying the Content-Type header - of the respective MIME part. - \li The same applies to the \c contentDispCode value: just use it's - unaltered value to specify the Content-Disposition header entry of - the respective MIME part. - \li The same applies to the \c contentTEncCode value: just use it's - unaltered value to specify the Content-Transfer-Encoding header of - the respective MIME part. - - If value returned in \c makeMimeObject is FALSE the - text strings returned in \c flatTextPrefix and \c flatTextPostfix - should be used to build a frame around the cleartext and the code - bloc holding the signature (or - in case of encrypting - the encoded - data bloc, resp.).
- If \c includeCleartext is TRUE this frame should also include the - cleartext as first bloc, this bloc should be divided from the code bloc - by the contents of \c flatTextSeparator - typically this is used for - signing but not when encrypting.
- If \c includeCleartext is FALSE you should ignore both the cleartext - and the \c flatTextSeparator parameter. - - How to use StructuringInfo data in your program: - \li To compose a signed message please act as described below. - \li For constructing an encrypted message just replace the - \c signMessage() call by the respective \c encryptMessage() call - and then proceed exactly the same way. - \li In any case make sure to free your \c ciphertext and - to call \c free_StructuringInfo() when you are done with processing - the data returned by the signing (or encrypting, resp.) function. - -\verbatim - - char* ciphertext; - StructuringInfo structInf; - - if( ! signMessage( cleartext, &ciphertext, certificate, - &structuring ) ) { - - myErrorDialog( "Error: could not sign the message!" ); - - } else { - if( structInf.makeMimeObject ) { - - // Build the main MIME object. - // This is done by - // using the header values returned in - // structInf.contentTypeMain and in - // structInf.contentDispMain and in - // structInf.contentTEncMain. - .. - - if( ! structInf.makeMultiMime ) { - - // Build the main MIME object's body. - // This is done by - // using the code bloc returned in - // ciphertext. - .. - - } else { - - // Build the encapsulated MIME parts. - if( structInf.includeCleartext ) { - - // Build a MIME part holding the cleartext. - // This is done by - // using the original cleartext's headers and by - // taking it's original body text. - .. - - } - if( structInf.contentTypeVersion - && 0 < strlen( structInf.contentTypeVersion ) ) { - - // Build a MIME part holding the version information. - // This is done by - // using the header values returned in - // structInf.contentTypeVersion and - // structInf.contentDispVersion and - // structInf.contentTEncVersion and by - // taking the body contents returned in - // structInf.bodyTextVersion. - .. - - } - if( structInf.contentTypeCode - && 0 < strlen( structInf.contentTypeCode ) ) { - - // Build a MIME part holding the code information. - // This is done by - // using the header values returned in - // structInf.contentTypeCode and - // structInf.contentDispCode and - // structInf.contentTEncCode and by - // taking the body contents returned in - // ciphertext. - .. - - } else { - - // Plugin error! - myErrorDialog( "Error: Cryptography plugin returned a main" - "Content-Type=Multipart/.. but did not " - "specify the code bloc's Content-Type header." - "\nYou may report this bug:" - "\n" + cryptplug.bugURL() ); - } - } - } else { - - // Build a plain message body - // based on the values returned in structInf. - // Note: We do _not_ insert line breaks between the parts since - // it is the plugin job to provide us with ready-to-use - // texts containing all neccessary line breaks. - strcpy( myMessageBody, structInf.plainTextPrefix ); - if( structInf.includeCleartext ) { - strcat( myMessageBody, cleartext ); - strcat( myMessageBody, structInf.plainTextSeparator ); - } - strcat( myMessageBody, *ciphertext ); - strcat( myMessageBody, structInf.plainTextPostfix ); - } - - // free the memory that was allocated - // for the ciphertext - free( ciphertext ); - - // free the memory that was allocated - // for our StructuringInfo's char* members - free_StructuringInfo( &structuring ); - } - -\endverbatim - - \note Make sure to call \c free_StructuringInfo() when you are done - with processing the StructuringInfo data! - - \see free_StructuringInfo - \see signMessage, encryptMessage, encryptAndSignMessage -*/ -struct StructuringInfo { - bool includeCleartext; /*!< specifies whether we should include the - cleartext as first part of our multipart - MIME object (or - for non-MIME - messages - as flat text to be set before - the ciphertext, resp.), typically this - is TRUE when signing mails but FALSE - when encrypting
- (this parameter is relevant no matter - whether \c makeMimeObject is TRUE or - FALSE) */ - bool makeMimeObject; /*!< specifies whether we should create a MIME - object or a flat text message body */ - /* the following are used for MIME messages only */ - bool makeMultiMime; /*!< specifies whether we should create a - 'Multipart' MIME object or a single part - object, if FALSE only \c contentTypeMain, - \c contentDispMain and \c contentTEncMain - may be used and all other parameters have - to be ignored
- (ignore this parameter if \c makeMimeObject - is FALSE) */ - char* contentTypeMain; /*!< value of the main 'Content-Type' - header
- (ignore this parameter if \c makeMimeObject - is FALSE) */ - char* contentDispMain; /*!< value of the main 'Content-Disposition' - header
- (ignore this parameter if \c makeMimeObject - is FALSE) */ - char* contentTEncMain; /*!< value of the main - 'Content-TransferEncoding' header
- (ignore this parameter if \c makeMimeObject - is FALSE) */ - char* contentTypeVersion; /*!< 'Content-Type' of the additional version - part that might preceed the code part - - if NULL or zero length no version part - must be created
- (ignore this parameter if either - \c makeMimeObject or \c makeMultiMime - is FALSE) */ - char* contentDispVersion; /*!< 'Content-Disposition' of the additional - preceeding the code part (only valid if - \c contentTypeVersion holds a - non-zero-length string)
- (ignore this parameter if either - \c makeMimeObject or \c makeMultiMime - is FALSE or if \c contentTypeVersion does - not return a non-zero-length string) */ - char* contentTEncVersion; /*!< 'Content-Transfer-Encoding' of the - additional version part (only valid if - \c contentTypeVersion holds a - non-zero-length string)
- (ignore this parameter if either - \c makeMimeObject or \c makeMultiMime - is FALSE or if \c contentTypeVersion does - not return a non-zero-length string) */ - char* bodyTextVersion; /*!< body text of the additional version part - (only valid if \c contentTypeVersion - holds a non-zero-length string)
- (ignore this parameter if either - \c makeMimeObject or \c makeMultiMime - is FALSE or if \c contentTypeVersion does - not return a non-zero-length string) */ - char* contentTypeCode; /*!< 'Content-Type' of the code part holding - the signature code (or the encrypted - data, resp.)
- (ignore this parameter if either - \c makeMimeObject or \c makeMultiMime - is FALSE) */ - char* contentDispCode; /*!< 'Content-Disposition' of the code part
- (ignore this parameter if either - \c makeMimeObject or \c makeMultiMime - is FALSE or if \c contentTypeCode does - not return a non-zero-length string) */ - char* contentTEncCode; /*!< 'Content-Type' of the code part
- (ignore this parameter if either - \c makeMimeObject or \c makeMultiMime - is FALSE or if \c contentTypeCode does - not return a non-zero-length string) */ - /* the following are used for flat non-MIME messages only */ - char* flatTextPrefix; /*!< text to preceed the main text (or the - code bloc containing the encrypted main - text, resp.)
- (ignore this parameter if - \c makeMimeObject is TRUE) */ - char* flatTextSeparator; /*!< text to be put between the main text and - the signature code bloc (not used when - encrypting)
- (ignore this parameter if - \c makeMimeObject is TRUE or if - \c includeCleartext is FALSE) */ - char* flatTextPostfix; /*!< text to follow the signature code bloc - (or the encrypted data bloc, resp.)
- (ignore this parameter if - \c makeMimeObject is TRUE) */ -}; - - -/*! \ingroup groupAdUsoInterno - \brief If you are not planning to write your own cryptography - plugin you should ignore this function! - - Usage of this function is depreciated for plugin users but highly - recommended for plugin implementors since this is an internal - function for initializing all char* members of a \c StructuringInfo - struct.
- This function must be called in any plugin's - implementations of the following functions: - - \c signMessage()
- \c encryptMessage()
- \c encryptAndSignMessage() - - Calling this function makes sure the corresponding - \c free_StructuringInfo() calls which will be embedded by - your plugin's users into their code will be able to - determine which of the char* members belonging to the - respective's StructuringInfo had been allocated memory - for during previous signing or encrypting actions. - - \see free_StructuringInfo, StructuringInfo - \see signMessage, encryptMessage, encryptAndSignMessage -*/ - inline void init_StructuringInfo( struct StructuringInfo* s ) - { - if( ! s ) return; - - s->includeCleartext = false; - - s->makeMimeObject = false; - s->makeMultiMime = false; - - s->contentTypeMain = 0; - s->contentDispMain = 0; - s->contentTEncMain = 0; - - s->contentTypeVersion = 0; - s->contentDispVersion = 0; - s->contentTEncVersion = 0; - s->bodyTextVersion = 0; - - s->contentTypeCode = 0; - s->contentDispCode = 0; - s->contentTEncCode = 0; - - s->flatTextPrefix = 0; - s->flatTextSeparator = 0; - s->flatTextPostfix = 0; - } - -/*! \ingroup groupSignCryptAct - \brief Important method for freeing all memory that was allocated - for the char* members of a \c StructuringInfo struct - use - this function after each signing or encrypting function - call. - - \note Even when intending to call \c encryptMessage() immediately - after having called \c signMessage() you first must call - the \c free_StructuringInfo() function to make sure all memory is - set free that was allocated for your StructuringInfo's char* members - by the \c signMessage() function! - - \see StructuringInfo -*/ - inline void free_StructuringInfo( struct StructuringInfo* s ) - { - if( ! s ) return; - if( s->contentTypeMain ) free( s->contentTypeMain ); - if( s->contentDispMain ) free( s->contentDispMain ); - if( s->contentTEncMain ) free( s->contentTEncMain ); - if( s->contentTypeVersion ) free( s->contentTypeVersion ); - if( s->contentDispVersion ) free( s->contentDispVersion ); - if( s->contentTEncVersion ) free( s->contentTEncVersion ); - if( s->bodyTextVersion ) free( s->bodyTextVersion ); - if( s->contentTypeCode ) free( s->contentTypeCode ); - if( s->contentDispCode ) free( s->contentDispCode ); - if( s->contentTEncCode ) free( s->contentTEncCode ); - if( s->flatTextPrefix ) free( s->flatTextPrefix ); - if( s->flatTextSeparator ) free( s->flatTextSeparator ); - if( s->flatTextPostfix ) free( s->flatTextPostfix ); - } - - -/*! \ingroup groupSignAct - */ -struct SignatureMetaDataExtendedInfo -{ - struct tm* creation_time; - SigStatusFlags sigStatusFlags; - char* status_text; - char* keyid; - char* fingerprint; - char* algo; - char* userid; - char* name; - char* comment; - char** emailList; - int emailCount; - unsigned long algo_num; - unsigned long validity; - unsigned long userid_num; - unsigned long keylen; - unsigned long key_created; - unsigned long key_expires; -}; - -/*! \ingroup groupSignAct -*/ -struct SignatureMetaData { - char* status; - struct SignatureMetaDataExtendedInfo* extended_info; - int extended_info_count; - int status_code; -}; - -/*! \ingroup groupSignAct - \brief Checks whether the signature of a message is - valid. - - \c cleartext must never be 0 but be a valid pointer. - - If \c *cleartext > 0 then **cleartext specifies the message text - that was signed and \c signaturetext is the signature itself. - - If \c *cleartext == 0 is an empty string then \c signaturetext is - supposed to contain an opaque signed message part. After checking the - data and verifying the signature the cleartext of the message will be - returned in \c cleartext. The user must free the respective memory - ocupied by *cleartext. - - Depending on the configuration, MUAs might not need to use this. - If \c sigmeta is non-null, the - \c SignatureMetaData object pointed to will - contain meta information about the signature after the - function call. -*/ -bool checkMessageSignature( char** cleartext, - const char* signaturetext, - bool signatureIsBinary, - int signatureLen, - struct SignatureMetaData* sigmeta, - char** attrOrder, - const char* unknownAttrsHandling ); - - -/*! \ingroup groupCryptAct - \brief Tries to decrypt an email message - \c ciphertext and returns the decrypted - message in \c cleartext. - - The \c certificate is used for decryption. If - the message could be decrypted, the function returns - \c true, otherwise - \c false. -*/ -bool decryptMessage( const char* ciphertext, - bool cipherIsBinary, - int cipherLen, - const char** cleartext, - const char* certificate, - int* errId, - char** errTxt ); - -/*! \ingroup groupCryptAct - \brief Combines the functionality of - \c checkMessageSignature() and - \c decryptMessage(). - - If \c certificate is \c NULL, - the default certificate will be used. - If \c sigmeta is non-null, the \c SignatureMetaData - object pointed to will contain meta information about - the signature after the function call. -*/ -bool decryptAndCheckMessage( const char* ciphertext, - bool cipherIsBinary, - int cipherLen, - const char** cleartext, - const char* certificate, - bool* signatureFound, - struct SignatureMetaData* sigmeta, - int* errId, - char** errTxt, - char** attrOrder, - const char* unknownAttrsHandling ); - -struct DnPair { - char *key; - char *value; -}; - -struct CertificateInfo { - char** userid; - char* userid_0_org; - char* serial; - char* fingerprint; - - char* issuer_org; - char* issuer_reord; - char* chainid; - - char* caps; - - unsigned long created; - unsigned long expire; - - int secret : 1; - int invalid : 1; - int expired : 1; - int disabled : 1; - - struct DnPair *dnarray; /* parsed values from userid[0] */ -}; - - /*! - Import a certificate from memory. - */ - GpgME::ImportResult importCertificateFromMem( const char* data, size_t length ); -}; // class CryptPlug - -class SMIMECryptPlug : public CryptPlug { -public: - SMIMECryptPlug(); -}; - -class OpenPGPCryptPlug : public CryptPlug { -public: - OpenPGPCryptPlug(); -}; - -#endif /*CRYPTPLUG_H*/ - diff --git a/kleopatra/lib/cryptplugfactory.cpp b/kleopatra/lib/cryptplugfactory.cpp deleted file mode 100644 index 7000d9a905..0000000000 --- a/kleopatra/lib/cryptplugfactory.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - cryptplugfactory.cpp - - This file is part of libkleopatra, the KDE key management library - Copyright (c) 2001,2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "cryptplugfactory.h" -#include "cryptplugwrapperlist.h" - -#include -#include -#include -#include -#include - -#include - -KMail::CryptPlugFactory * KMail::CryptPlugFactory::mSelf = 0; - -// -// -// KMail::CryptPlugFactory: backwards compat stuff (ugly) -// -// - - -KMail::CryptPlugFactory::CryptPlugFactory() - : Kleo::CryptoBackendFactory(), - mCryptPlugWrapperList( 0 ) -{ - mSelf = this; - - mCryptPlugWrapperList = new CryptPlugWrapperList(); - mCryptPlugWrapperList->setAutoDelete( false ); - updateCryptPlugWrapperList(); -} - -KMail::CryptPlugFactory::~CryptPlugFactory() { - mSelf = 0; - delete mCryptPlugWrapperList; mCryptPlugWrapperList = 0; -} - -KMail::CryptPlugFactory * KMail::CryptPlugFactory::instance() { - if ( !mSelf ) - mSelf = new CryptPlugFactory(); - return mSelf; -} - -CryptPlugWrapper * KMail::CryptPlugFactory::active() const { - if ( smime() && smime()->active() ) - return smime(); - if ( openpgp() && openpgp()->active() ) - return openpgp(); - return 0; -} - -CryptPlugWrapper * KMail::CryptPlugFactory::createForProtocol( const QString & proto ) const { - QString p = proto.lower(); - if ( p == "application/pkcs7-signature" || p == "application/x-pkcs7-signature" ) - return smime(); - if ( p == "application/pgp-signature" || p == "application/x-pgp-signature" ) - return openpgp(); - return 0; -} - -CryptPlugWrapper * KMail::CryptPlugFactory::smime() const { - return mCryptPlugWrapperList->findForLibName( "smime" ); -} - -CryptPlugWrapper * KMail::CryptPlugFactory::openpgp() const { - return mCryptPlugWrapperList->findForLibName( "openpgp" ); -} - -void KMail::CryptPlugFactory::scanForBackends( QStringList * reason ) { - Kleo::CryptoBackendFactory::scanForBackends( reason ); - updateCryptPlugWrapperList(); -} - -void KMail::CryptPlugFactory::updateCryptPlugWrapperList() { - mCryptPlugWrapperList->clear(); - for ( std::vector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { - if ( CryptPlugWrapper * w = dynamic_cast( (*it)->openpgp() ) ) - mCryptPlugWrapperList->append( w ); - if ( CryptPlugWrapper * w = dynamic_cast( (*it)->smime() ) ) - mCryptPlugWrapperList->append( w ); - } -} - -#include "cryptplugfactory.moc" diff --git a/kleopatra/lib/cryptplugfactory.h b/kleopatra/lib/cryptplugfactory.h deleted file mode 100644 index a50c3909ca..0000000000 --- a/kleopatra/lib/cryptplugfactory.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - cryptplugfactory.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_CRYPTPLUGFACTORY_H__ -#define __KLEO_CRYPTPLUGFACTORY_H__ - -#include "kleo/cryptobackendfactory.h" - -#include - -#ifndef LIBKLEOPATRA_NO_COMPAT -namespace Kleo { - //typedef CryptoBackendFactory CryptPlugFactory KDE_DEPRECATED; -} - -class CryptPlugWrapper; -class CryptPlugWrapperList; - -namespace KMail { - - class KDE_EXPORT CryptPlugFactory : public Kleo::CryptoBackendFactory { - Q_OBJECT - protected: - CryptPlugFactory(); - ~CryptPlugFactory(); - - public: - static CryptPlugFactory * instance(); - - CryptPlugWrapper * active() const; - CryptPlugWrapper * smime() const; - CryptPlugWrapper * openpgp() const; - - CryptPlugWrapperList & list() const { return *mCryptPlugWrapperList; } - - CryptPlugWrapper * createForProtocol( const QString & proto ) const; - - void scanForBackends( QStringList * reason ); - - private: - void updateCryptPlugWrapperList(); - - private: - CryptPlugFactory( const CryptPlugFactory & ); - void operator=( const CryptPlugFactory & ); - CryptPlugWrapperList * mCryptPlugWrapperList; - - static CryptPlugFactory * mSelf; - }; - -} -#endif - -#endif // __KLEO_CRYPTPLUGFACTORY_H__ diff --git a/kleopatra/lib/cryptplugwrapper.cpp b/kleopatra/lib/cryptplugwrapper.cpp deleted file mode 100644 index 7ab112171c..0000000000 --- a/kleopatra/lib/cryptplugwrapper.cpp +++ /dev/null @@ -1,850 +0,0 @@ -/** - * cryptplugwrapper.cpp - * - * Copyright (c) 2001 Karl-Heinz Zimmer, Klaraelvdalens Datakonsult AB - * - * This CRYPTPLUG wrapper implementation is based on cryptplug.h by - * Karl-Heinz Zimmer which is based on 'The Aegypten Plugin API' as - * specified by Matthias Kalle Dalheimer, Klaraelvdalens Datakonsult AB, - * see file mua-integration.sgml located on Aegypten CVS: - * http://www.gnupg.org/aegypten/development.en.html - * - * purpose: Wrap up all Aegypten Plugin API functions in one C++ class - * for usage by KDE programs, e.g. KMail (or KMime, resp.) - * - * 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; version 2 of the License. - * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "cryptplugwrapper.h" -#include "cryptplug.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// qgpgme -#include - -// gpgme++ -#include -#include -#include - -// kde -#include -#include -#include -#include -#include - -// other -#include - -#include -#include -#include - - - - -/* - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * * - * This file's source comments - as well as those in interface file * - * cryptplugwrapper.h - are optimized for processing by Doxygen. * - * * - * To obtain best results please get an updated version of Doxygen, * - * for sources and binaries goto http://www.doxygen.org/index.html * - * * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * - */ - - - -/*! \file cryptplugwrapper.cpp - \brief C++ wrapper for the CRYPTPLUG library API. - - This CRYPTPLUG wrapper implementation is based on cryptplug.h by - Karl-Heinz Zimmer which is based on 'The Aegypten Plugin API' as - specified by Matthias Kalle Dalheimer, Klaraelvdalens Datakonsult AB, - see file mua-integration.sgml located on Aegypten CVS: - http://www.gnupg.org/aegypten/development.en.html - - purpose: Wrap up all Aegypten Plugin API functions in one C++ class - for usage by KDE programs, e.g. KMail (or KMime, resp.) - - CRYPTPLUG is an independent cryptography plug-in API - developed for Sphinx-enabeling KMail and Mutt. - - CRYPTPLUG was designed for the Aegypten project, but it may - be used by 3rd party developers as well to design pluggable - crypto backends for the above mentioned MUAs. - - \note All string parameters appearing in this API are to be - interpreted as UTF-8 encoded. - - \see cryptplugwrapper.h -*/ - - -// a little helper class for reordering of DN attributes -class DNBeautifier { -public: - enum UnknownAttrsHandling { unknownAttrsHide, - unknownAttrsPrefix, - unknownAttrsPostfix, - unknownAttrsInfix }; - // infix: at the position of "_X_", if any, else Postfix - - DNBeautifier() - { - // the attrOrder is defaulted to an empty string automatically - _unknownAttrsHandling = unknownAttrsInfix; - _unknownAttrsHandlingChar = "INFIX"; - } - DNBeautifier( KConfig* config, - const QString& cfgGroup, - const QString& cfgAttributeOrderEntry, - const QString& cfgUnknownAttrsEntry, - const QStringList& fallbackAttrOrder = QStringList(), - UnknownAttrsHandling fallbackUnknowAttrsHandling = unknownAttrsInfix ) - { - _unknownAttrsHandling = unknownAttrsInfix; - _unknownAttrsHandlingChar = "INFIX"; - if( config ){ - const QString oldGroup( config->group() ); - config->setGroup( cfgGroup ); // e.g. "General" - _attrOrder = - config->readListEntry( cfgAttributeOrderEntry ); // e.g. "DNAttributeOrder" - _unknownAttrsHandlingChar = - config->readEntry( cfgUnknownAttrsEntry ).upper().latin1(); // e.g. "DNUnknownAttributes" - config->setGroup( oldGroup ); - if( _unknownAttrsHandlingChar == "HIDE" ) - _unknownAttrsHandling = unknownAttrsHide; - else if( _unknownAttrsHandlingChar == "PREFIX" ) - _unknownAttrsHandling = unknownAttrsPrefix; - else if( _unknownAttrsHandlingChar == "POSTFIX" ) - _unknownAttrsHandling = unknownAttrsPostfix; - else if( _unknownAttrsHandlingChar == "INFIX" ) - _unknownAttrsHandling = unknownAttrsInfix; - else - _unknownAttrsHandlingChar = "INFIX"; - } - if( _attrOrder.isEmpty() && ! fallbackAttrOrder.isEmpty() ) - _attrOrder = fallbackAttrOrder; - - if( _attrOrder.isEmpty() ){ - _attrOrderChar = 0; - }else{ - _attrOrderChar = new char*[ _attrOrder.count()+1 ]; - int i=0; - for( QStringList::ConstIterator itOrder = _attrOrder.begin(); - itOrder != _attrOrder.end(); - ++itOrder ){ - _attrOrderChar[ i ] = (char*)malloc( ((*itOrder).length()+1)*sizeof(char) ); - strcpy( _attrOrderChar[ i ], (*itOrder).latin1() ); - ++i; - } - _attrOrderChar[ i ] = NULL; - } - } - ~DNBeautifier() - { - int i=0; - for( QStringList::ConstIterator itOrder = _attrOrder.begin(); - itOrder != _attrOrder.end(); - ++itOrder ){ - free( _attrOrderChar[ i ] ); - ++i; - } - delete[] _attrOrderChar; - } - - QStringList attrOrder() const - { - return _attrOrder; - } - char** attrOrderChar() - { - return _attrOrderChar; - } - - UnknownAttrsHandling unknownAttrsHandling() const - { - return _unknownAttrsHandling; - } - const char* unknownAttrsHandlingChar() const - { - return _unknownAttrsHandlingChar; - } - - QValueList< QPair > reorder( const QValueList< QPair > & dn ) const - { - return reorder( dn, _attrOrder, _unknownAttrsHandling ); - } - - - static QValueList< QPair > reorder( - const QValueList< QPair > & dn, - QStringList attrOrder, - UnknownAttrsHandling unknownAttrsHandling ) - { - if( !attrOrder.isEmpty() ){ - QPtrList< QPair > unknownEntries; - QValueList< QPair > dnNew; - - QPair* unknownEntry; - QStringList::ConstIterator itOrder; - QValueList< QPair >::ConstIterator itDN; - bool bFound; - - if( unknownAttrsHandling != unknownAttrsHide ){ - // find all unknown entries in their order of appearance - for( itDN = dn.begin(); itDN != dn.end(); ++itDN ){ - bFound = false; - for( itOrder = attrOrder.begin(); itOrder != attrOrder.end(); ++itOrder ){ - if( (*itOrder) == (*itDN).first ){ - bFound = true; - break; - } - } - if( !bFound ) - unknownEntries.append( &(*itDN) ); - } - } - - // prepend the unknown attrs (if desired) - if( unknownAttrsHandling == unknownAttrsPrefix ){ - for( unknownEntry = unknownEntries.first(); unknownEntry; unknownEntry = unknownEntries.next() ){ - dnNew << *unknownEntry; - } - } - - // process the known attrs in the desired order - bool b_X_declared = false; - for( itOrder = attrOrder.begin(); itOrder != attrOrder.end(); ++itOrder ){ - if( (*itOrder) == "_X_" ){ - b_X_declared = true; - // insert the unknown attrs (if desired) - if( unknownAttrsHandling == unknownAttrsInfix ){ - for( unknownEntry = unknownEntries.first(); unknownEntry; unknownEntry = unknownEntries.next() ){ - dnNew << *unknownEntry; - } - } - }else{ - for( itDN = dn.begin(); itDN != dn.end(); ++itDN ){ - if( (*itOrder) == (*itDN).first ){ - dnNew << *itDN; - //kdDebug(5150) << QString((*itDN).first) <<" = " << QString((*itDN).second) << endl;; - } - } - } - } - - // append the unknown attrs (if desired) - if( unknownAttrsHandling == unknownAttrsPostfix || - ( unknownAttrsHandling == unknownAttrsInfix && ! b_X_declared ) ){ - for( unknownEntry = unknownEntries.first(); unknownEntry; unknownEntry = unknownEntries.next() ){ - dnNew << *unknownEntry; - } - } - - return dnNew; - } - return dn; - } - -private: - QStringList _attrOrder; - char** _attrOrderChar; - UnknownAttrsHandling _unknownAttrsHandling; - QCString _unknownAttrsHandlingChar; -}; - - - -/* special helper class to be used by signing/encrypting functions *******/ - - - -StructuringInfoWrapper::StructuringInfoWrapper( CryptPlugWrapper* wrapper ) - : _initDone( false ), _wrapper( wrapper ) -{ - initMe(); -} -StructuringInfoWrapper::~StructuringInfoWrapper() -{ - freeMe(); -} -void StructuringInfoWrapper::reset() -{ - freeMe(); - initMe(); -} -void StructuringInfoWrapper::initMe() -{ - if ( _wrapper && _wrapper->cryptPlug() ) { - _wrapper->cryptPlug()->init_StructuringInfo( &data ); - _initDone = true; - } -} -void StructuringInfoWrapper::freeMe() -{ - if( _wrapper && _wrapper->cryptPlug() && _initDone ) { - _wrapper->cryptPlug()->free_StructuringInfo( &data ); - _initDone = false; - } -} - -class CryptPlugWrapper::Config { -public: - Config( gpgme_protocol_t proto ); - ~Config(); - - const char* signatureKeyCertificate; - SignatureAlgorithm signatureAlgorithm; - SignatureCompoundMode signatureCompoundMode; - SendCertificates sendCertificates; - bool saveSentSignatures; - bool warnNoCertificate; - bool signatureUseCRLs; - EncryptionAlgorithm encryptionAlgorithm; - EncryptEmail encryptEmail; - bool saveMessagesEncrypted; - bool encryptionUseCRLs; - bool encryptionCRLExpiryNearWarning; - int encryptionCRLNearExpiryInterval; - CertificateSource certificateSource; - bool warnSendUnsigned; - bool signatureCertificateExpiryNearWarning; - int signatureCertificateExpiryNearInterval; - bool cACertificateExpiryNearWarning; - int cACertificateExpiryNearInterval; - bool rootCertificateExpiryNearWarning; - int rootCertificateExpiryNearInterval; - bool warnSendUnencrypted; - bool checkCertificatePath; - bool receiverCertificateExpiryNearWarning; - int receiverCertificateExpiryNearWarningInterval; - bool certificateInChainExpiryNearWarning; - int certificateInChainExpiryNearWarningInterval; - bool receiverEmailAddressNotInCertificateWarning; - const char* libVersion; /* a statically allocated string with the GPGME Version used */ -}; - -static const int NEAR_EXPIRY = 14; - -CryptPlugWrapper::Config::Config( gpgme_protocol_t proto ) -{ - signatureAlgorithm = SignAlg_SHA1; - if ( proto == GPGME_PROTOCOL_CMS ) - signatureCompoundMode = SignatureCompoundMode_Opaque; - else - signatureCompoundMode = SignatureCompoundMode_Detached; - sendCertificates = SendCert_SendChainWithRoot; - saveSentSignatures = true; - warnNoCertificate = true; - signatureUseCRLs = true; - encryptionAlgorithm = EncryptAlg_RSA; - encryptEmail = EncryptEmail_Ask; - saveMessagesEncrypted = true; - encryptionUseCRLs = true; - encryptionCRLExpiryNearWarning = false; - encryptionCRLNearExpiryInterval = NEAR_EXPIRY; - certificateSource = CertSrc_Server; - warnSendUnsigned = true; - signatureCertificateExpiryNearWarning = true; - signatureCertificateExpiryNearInterval = NEAR_EXPIRY; - cACertificateExpiryNearWarning = true; - cACertificateExpiryNearInterval = NEAR_EXPIRY; - rootCertificateExpiryNearWarning = true; - rootCertificateExpiryNearInterval = NEAR_EXPIRY; - warnSendUnencrypted = false; - checkCertificatePath = true; - receiverCertificateExpiryNearWarning = true; - receiverCertificateExpiryNearWarningInterval = NEAR_EXPIRY; - certificateInChainExpiryNearWarning = true; - certificateInChainExpiryNearWarningInterval = NEAR_EXPIRY; - receiverEmailAddressNotInCertificateWarning = true; - libVersion = gpgme_check_version (NULL); -} - -CryptPlugWrapper::Config::~Config() { -} - -/* Some multi purpose functions ******************************************/ - -QString CryptPlugWrapper::errorIdToText( int errId, bool & isPassphraseError ) { - const GpgME::Error err( errId ); - isPassphraseError = err.isCanceled() - || gpgme_err_code( errId ) == GPG_ERR_NO_SECKEY ; // FIXME: more? - return QString::fromLocal8Bit( err.asString() ); -} - -/* some special functions ************************************************/ - - -CryptPlugWrapper::CryptPlugWrapper( const QString& name, - const QString& libName, - const QString& update, - bool active ) - : Kleo::CryptoBackend::Protocol(), - _name( name ), - _libName( libName ), - _updateURL( update ), - _active( active ), - _initStatus( InitStatus_undef ), - _cp( 0 ), - _config( 0 ), - _cryptoConfig( 0 ) -{ - const bool ok = initialize( 0, 0 ); - assert( ok ); -} - - -CryptPlugWrapper::~CryptPlugWrapper() -{ - deinitialize(); -} - - -void CryptPlugWrapper::setActive( bool active ) -{ - _active = active; -} - - -bool CryptPlugWrapper::active() const -{ - return _active; -} - - - -bool CryptPlugWrapper::setLibName( const QString& libName ) -{ - bool bOk = ! _cp; // Changing the lib name is only allowed - if( bOk ) // when either no initialization took - _libName = libName; // place or 'deinitialize()' has been - return bOk; // called afterwards. -} - -QString CryptPlugWrapper::libName() const -{ - return _libName; -} - -QString CryptPlugWrapper::protocol() const -{ - if ( _libName.contains( "smime" ) ) - return "SMIME"; - if ( _libName.contains( "openpgp" ) ) - return "OpenPGP"; - return QString::null; -} - -void CryptPlugWrapper::setDisplayName( const QString& name ) -{ - _name = name; -} - - -QString CryptPlugWrapper::displayName() const -{ - if ( !_name.isEmpty() ) - return _name; - if ( _libName.contains( "smime" ) ) - return "gpgsm"; - if ( _libName.contains( "openpgp" ) ) - return "gpg"; - return i18n("(Unknown Protocol)"); -} - -bool CryptPlugWrapper::initialize( InitStatus* initStatus, QString* errorMsg ) -{ - if ( _cp ) - return true; - - _initStatus = InitStatus_undef; - /* make sure we have a lib name */ - if ( _libName.isEmpty() ) { - _initStatus = InitStatus_NoLibName; - kdDebug(5150) << "No library name was given.\n" << endl; - } else { - if ( _libName.contains( "smime" ) ) { - _cp = new SMIMECryptPlug(); - _config = new Config( GPGME_PROTOCOL_CMS ); - } else if ( _libName.contains( "openpgp" ) ) { - _cp = new OpenPGPCryptPlug(); - _config = new Config( GPGME_PROTOCOL_OpenPGP ); - } else { - _cp = 0; - _config = 0; - } - - if ( !_cp ) { - _initStatus = InitStatus_LoadError; - kdDebug(5150) << "Couldn't create '" << _libName.latin1() << "'" << endl; - } else { - /* now call the init function */ - if( !_cp->initialize() ) { - _initStatus = InitStatus_InitError; - kdDebug(5150) << "Error while executing function 'initialize' on plugin " << _libName << endl; - _lastError = i18n("Error while initializing plugin \"%1\"").arg( _libName ); - if ( errorMsg ) - *errorMsg = _lastError; - delete _cp; _cp = 0; - delete _config; _config = 0; - } else { - _initStatus = InitStatus_Ok; - } - } - } - if( initStatus ) - *initStatus = _initStatus; - return _initStatus == InitStatus_Ok; -} - - - -void CryptPlugWrapper::deinitialize() -{ - delete _cp; _cp = 0; - delete _config; _config = 0; - delete _cryptoConfig; _cryptoConfig = 0; -} - - -CryptPlugWrapper::InitStatus CryptPlugWrapper::initStatus( QString* errorMsg ) const -{ - if( errorMsg ) - *errorMsg = _lastError; - return _initStatus; -} - - -bool CryptPlugWrapper::hasFeature( Feature flag ) -{ - return _cp && _cp->hasFeature( flag ); -} - - -/* normal functions ******************************************************/ - -bool CryptPlugWrapper::checkMessageSignature( char** cleartext, - const char* signaturetext, - bool signatureIsBinary, - int signatureLen, - CryptPlug::SignatureMetaData* sigmeta ) -{ - DNBeautifier dnBeautifier( kapp->config(), - "DN", - "AttributeOrder", - "UnknownAttributes" ); - return _cp && _cp->checkMessageSignature( cleartext, - signaturetext, - signatureIsBinary, - signatureLen, - sigmeta, - dnBeautifier.attrOrderChar(), - dnBeautifier.unknownAttrsHandlingChar() ); -} - - -bool CryptPlugWrapper::decryptMessage( const char* ciphertext, - bool cipherIsBinary, - int cipherLen, - char** cleartext, - const char* certificate, - int* errId, - char** errTxt ) -{ - return _cp && _cp->decryptMessage( ciphertext, cipherIsBinary, cipherLen, - (const char**)cleartext, certificate, errId, errTxt ); -} - - -bool CryptPlugWrapper::decryptAndCheckMessage( - const char* ciphertext, - bool cipherIsBinary, - int cipherLen, - char** cleartext, - const char* certificate, - bool* signatureFound, - CryptPlug::SignatureMetaData* sigmeta, - int* errId, - char** errTxt ) -{ - DNBeautifier dnBeautifier( kapp->config(), - "DN", - "AttributeOrder", - "UnknownAttributes" ); - return _cp && _cp->decryptAndCheckMessage( ciphertext, - cipherIsBinary, - cipherLen, - (const char**)cleartext, - certificate, - signatureFound, - sigmeta, - errId, - errTxt, - dnBeautifier.attrOrderChar(), - dnBeautifier.unknownAttrsHandlingChar() ); -} - - - - -void CryptPlugWrapper::freeSignatureMetaData( CryptPlug::SignatureMetaData* sigmeta ) -{ - if ( !sigmeta ) - return; - free( sigmeta->status ); - for( int i = 0; i < sigmeta->extended_info_count; ++i ) { - free( sigmeta->extended_info[i].creation_time ); - free( (void*)sigmeta->extended_info[i].status_text ); - free( (void*)sigmeta->extended_info[i].keyid ); - free( (void*)sigmeta->extended_info[i].fingerprint ); - free( (void*)sigmeta->extended_info[i].algo ); - free( (void*)sigmeta->extended_info[i].userid ); - free( (void*)sigmeta->extended_info[i].name ); - free( (void*)sigmeta->extended_info[i].comment ); - if( sigmeta->extended_info[i].emailCount ){ - for( int j=0; j < sigmeta->extended_info[i].emailCount; ++j) - if( sigmeta->extended_info[i].emailList[j] ) - free( (void*)sigmeta->extended_info[i].emailList[j] ); - free( (void*)sigmeta->extended_info[i].emailList ); - } - } - free( sigmeta->extended_info ); -} - -GpgME::ImportResult CryptPlugWrapper::importCertificate( const char* data, size_t length ) -{ - if ( !_cp ) - return GpgME::ImportResult(); - - - return _cp->importCertificateFromMem( data, length ); -} - -Kleo::KeyListJob * CryptPlugWrapper::keyListJob( bool remote, bool includeSigs, bool validate ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - unsigned int mode = context->keyListMode(); - if ( remote ) { - mode |= GpgME::Context::Extern; - mode &= ~GpgME::Context::Local; - } else { - mode |= GpgME::Context::Local; - mode &= ~GpgME::Context::Extern; - } - if ( includeSigs ) mode |= GpgME::Context::Signatures; - if ( validate ) mode |= GpgME::Context::Validate; - context->setKeyListMode( mode ); - return new Kleo::QGpgMEKeyListJob( context ); -} - -Kleo::EncryptJob * CryptPlugWrapper::encryptJob( bool armor, bool textmode ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - context->setArmor( armor ); - context->setTextMode( textmode ); - return new Kleo::QGpgMEEncryptJob( context ); -} - -Kleo::DecryptJob * CryptPlugWrapper::decryptJob() const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - return new Kleo::QGpgMEDecryptJob( context ); -} - -Kleo::SignJob * CryptPlugWrapper::signJob( bool armor, bool textMode ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - context->setArmor( armor ); - context->setTextMode( textMode ); - - return new Kleo::QGpgMESignJob( context ); -} - -Kleo::VerifyDetachedJob * CryptPlugWrapper::verifyDetachedJob( bool textMode ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - context->setTextMode( textMode ); - - return new Kleo::QGpgMEVerifyDetachedJob( context ); -} - -Kleo::VerifyOpaqueJob * CryptPlugWrapper::verifyOpaqueJob( bool textMode ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - context->setTextMode( textMode ); - - return new Kleo::QGpgMEVerifyOpaqueJob( context ); -} - -Kleo::KeyGenerationJob * CryptPlugWrapper::keyGenerationJob() const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - return new Kleo::QGpgMEKeyGenerationJob( context ); -} - -Kleo::ImportJob * CryptPlugWrapper::importJob() const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - return new Kleo::QGpgMEImportJob( context ); -} - -Kleo::ExportJob * CryptPlugWrapper::publicKeyExportJob( bool armor ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - context->setArmor( armor ); - return new Kleo::QGpgMEExportJob( context ); -} - -Kleo::ExportJob * CryptPlugWrapper::secretKeyExportJob( bool armor ) const { - if ( !_cp || _cp->mProtocol != GpgME::Context::CMS ) // fixme: add support for gpg, too - return 0; - - // this operation is not supported by gpgme, so we have to call gpgsm ourselves: - return new Kleo::QGpgMESecretKeyExportJob( armor ); -} - -Kleo::RefreshKeysJob * CryptPlugWrapper::refreshKeysJob() const { - if ( !_cp || _cp->mProtocol != GpgME::Context::CMS ) // fixme: add support for gpg, too - return 0; - - // this operation is not supported by gpgme, so we have to call gpgsm ourselves: - return new Kleo::QGpgMERefreshKeysJob(); -} - -Kleo::DownloadJob * CryptPlugWrapper::downloadJob( bool armor ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - context->setArmor( armor ); - // this is the hackish interface for downloading from keyserers currently: - context->setKeyListMode( GpgME::Context::Extern ); - - return new Kleo::QGpgMEDownloadJob( context ); -} - -Kleo::DeleteJob * CryptPlugWrapper::deleteJob() const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - return new Kleo::QGpgMEDeleteJob( context ); -} - -Kleo::SignEncryptJob * CryptPlugWrapper::signEncryptJob( bool armor, bool textMode ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - context->setArmor( armor ); - context->setTextMode( textMode ); - - return new Kleo::QGpgMESignEncryptJob( context ); -} - -Kleo::DecryptVerifyJob * CryptPlugWrapper::decryptVerifyJob( bool textMode ) const { - if ( !_cp ) - return 0; - - GpgME::Context * context = GpgME::Context::createForProtocol( _cp->mProtocol ); - if ( !context ) - return 0; - - context->setTextMode( textMode ); - - return new Kleo::QGpgMEDecryptVerifyJob( context ); -} diff --git a/kleopatra/lib/cryptplugwrapper.h b/kleopatra/lib/cryptplugwrapper.h deleted file mode 100644 index 1cd851a69e..0000000000 --- a/kleopatra/lib/cryptplugwrapper.h +++ /dev/null @@ -1,839 +0,0 @@ -/** - * cryptplugwrapper.h - * - * Copyright (c) 2001 Karl-Heinz Zimmer, Klaraelvdalens Datakonsult AB - * - * This CRYPTPLUG wrapper interface is based on cryptplug.h by - * Karl-Heinz Zimmer which is based on 'The Aegypten Plugin API' as - * specified by Matthias Kalle Dalheimer, Klaraelvdalens Datakonsult AB, - * see file mua-integration.sgml located on Aegypten CVS: - * http://www.gnupg.org/aegypten/development.en.html - * - * purpose: Wrap up all Aegypten Plugin API functions in one C++ class - * for usage by KDE programs, e.g. KMail (or KMime, resp.) - * - * 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; version 2 of the License. - * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef cryptplugwrapper_h -#define cryptplugwrapper_h - -#include "cryptplug.h" - -#ifndef LIBKLEOPATRA_NO_COMPAT - -/* - * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * * - * This file's source comments are optimized for processing by Doxygen. * - * * - * To obtain best results please get an updated version of Doxygen, * - * for sources and binaries goto http://www.doxygen.org/index.html * - * * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - - * - */ -#include "kleo/cryptobackend.h" - -#include - -#include -#include -#include -#include -#include - - -class KConfigBase; -class QGpgMECryptoConfig; - -namespace GpgME { - class ImportResult; - class KeyGenerationResult; -} - -namespace Kleo { - class KeyListJob; - class EncryptJob; - class DecryptJob; - class SignJob; - class VerifyDetachedJob; - class VerifyOpaqueJob; - class KeyGenerationJob; - class ImportJob; - class ExportJob; - class DownloadJob; - class DeleteJob; - class SignEncryptJob; - class DecryptVerifyJob; - class CryptoConfig; - class RefreshKeysJob; - class SpecialJob; -} - -/*! \file cryptplugwrapper.h - \brief C++ wrapper for the CRYPTPLUG library API. - - This CRYPTPLUG wrapper interface is based on cryptplug.h by - Karl-Heinz Zimmer which is based on 'The Aegypten Plugin API' as - specified by Matthias Kalle Dalheimer, Klaraelvdalens Datakonsult AB, - see file mua-integration.sgml located on Aegypten CVS: - http://www.gnupg.org/aegypten/development.en.html - - purpose: Wrap up all Aegypten Plugin API functions in one C++ class - for usage by KDE programs, e.g. KMail (or KMime, resp.) - - CRYPTPLUG is an independent cryptography plug-in API - developed for Sphinx-enabeling KMail and Mutt. - - CRYPTPLUG was designed for the Aegypten project, but it may - be used by 3rd party developers as well to design pluggable - crypto backends for the above mentioned MUAs. - - \note All string parameters appearing in this API are to be - interpreted as UTF-8 encoded. - - \see cryptplugwrapper.cpp -*/ - -/*! \defgroup groupAdmin Constructor, destructor and setting of 'active' flag - - The functions in this section are used for general administration of - this CRYPTPLUG wrapper class and for maintaining a separate \c active flag - for environments using more than one CRYPTPLUG library simultaneously. -*/ - -/*! \defgroup groupGeneral Loading and Unloading the Plugin, General Functionality - - The functions in this section are used for loading and - unloading the respective CRYPTPLUG library, for (re)setting - it's internal data structures and for retrieving information - on the implementation state of all functions covered by the CRYPTPLUG API. -*/ - -/*! \defgroup groupDisplay Graphical Display Functionality - - The functions in this section return stationery that the - MUAs can use in order to display security functionality - graphically. This can be toolbar icons, shortcuts, tooltips, - etc. Not all MUAs will use all this functionality. -*/ - -/*! \defgroup groupConfig Configuration Support - - The functions in this section provide the necessary - functionality to configure the security functionality as well - as to query configuration settings. Since all configuration - settings will not be saved with the plugin, but rather with - the MUA, there are also functions to set configuration - settings programmatically; these will be used on startup of - the plugin when the MUA transfers the configuration values it - has read into the plugin. Usually, the functions to query and - set the configuration values are not needed for anything but - saving to and restoring from configuration files. -*/ - - -/*! \defgroup groupConfigSign Signature Configuration - \ingroup groupConfig - - The functions in this section provide the functionality - to configure signature handling and set and query the - signature configuration. -*/ - -/*! \defgroup groupConfigCrypt Encryption Configuration - \ingroup groupConfig - - The functions in this section provide the functionality - to configure encryption handling and set and query the - encryption configuration. - - \note Whenever the term encryption is used here, - it is supposed to mean both encryption and decryption, - unless otherwise specified. -*/ - -/*! \defgroup groupConfigDir Directory Service Configuration - \ingroup groupConfig - - This section contains messages for configuring the - directory service. -*/ - - -/*! \defgroup groupCertHand Certificate Handling - - The following methods are used to maintain and query certificates. -*/ - - -/*! \defgroup groupSignCryptAct Signing and Encrypting Actions - - This section describes methods and structures - used for signing and/or encrypting your mails. -*/ - - -/*! \defgroup groupSignAct Signature Actions - \ingroup groupSignCryptAct - - This section describes methods that are used for working - with signatures. -*/ - -/*! \defgroup groupCryptAct Encryption and Decryption - \ingroup groupSignCryptAct - - The following methods are used to encrypt and decrypt - email messages. -*/ - -/*! \defgroup groupCertAct Certificate Handling Actions - - The functions in this section provide local certificate management. -*/ - -/*! \defgroup groupCRLAct CRL Handling Actions - - This section describes functions for managing CRLs. -*/ - -/*! \defgroup groupAdUsoInterno Important functions to be used by plugin implementors ONLY. - - This section describes functions that have to be used by - plugin implementors but should not be used by plugin users - directly. - - If you are not planning to write your own cryptography - plugin you should ignore this section! -*/ - - - -class CryptPlugWrapper; -/*! \ingroup groupSignCryptAct - \brief This class provides C++ access to the StructuringInfo helper - struct that is specified in cryptplug.h to hold information - returned by signing and by encrypting functions. - - Use this information to compose a MIME object containing signed - and/or encrypted content (or to build a text frame around your - flat non-MIME message body, resp.) - - \note This class is different from the respective cryptplug.h class - because this one takes care for freeing the char** members' memory - automatically. You must not call the \c free function for - any of it's members - just ignore the advise given in the - cryptplug.h documentation! - - If value returned in \c makeMimeObject is TRUE the - text strings returned in \c contentTypeMain and \c contentDispMain - and \c contentTEncMain (and, if required, \c content[..]Version and - \c bodyTextVersion and \c content[..]Sig) should be used to compose - a respective MIME object.
- If FALSE the texts returned in \c flatTextPrefix and - \c flatTextSeparator and \c flatTextPostfix are to be used instead.
- Always either the \c content[..] and \c bodyTextVersion - parameters or the \c flatText[..] parameters are holding - valid data - never both of them may be used simultaneously - as plugins will just ignore the parameters not matching their - \c makeMimeObject setting. - - When creating your MIME object please observe these common rules: - \li Parameters named \c contentType[..] and \c contentDisp[..] and - \c contentTEnc[..] will return the values for the respective MIME - headers 'Content-Type' and 'Content-Disposition' and - 'Content-Transfer-Encoding'. The following applies to these parameters: - \li The relevant MIME part may only be created if the respective - \c contentType[..] parameter is holding a non-zero-length string. If the - \c contentType[..] parameter value is invalid or holding an empty string - the respective \c contentDisp[..] and \c contentTEnc[..] parameters - should be ignored. - \li If the respective \c contentDisp[..] or \c contentTEnc[..] parameter - is NULL or holding a zero-length string it is up to you whether you want - to add the relevant MIME header yourself, but since it in in the - responsibility of the plugin implementors to provide you with all - necessary 'Content-[..]' header information you should not need - to define them if they are not returned by the signing or encrypting - function - otherwise this may be considered as a bug in the plugin and - you could report the missing MIME header information to the address - returned by the \c bugURL() function. - - If \c makeMultiMime returns FALSE the \c contentTypeMain returned must - not be altered but used to specify a single part mime object holding the - code bloc, e.g. this is used for 'enveloped-data' single part MIME - objects. In this case you should ignore both the \c content[..]Version - and \c content[..]Code parameters. - - If \c makeMultiMime returns TRUE also the following rules apply: - \li If \c includeCleartext is TRUE you should include the cleartext - as first part of our multipart MIME object, typically this is TRUE - when signing mails but FALSE when encrypting. - \li The \c contentTypeMain returned typically starts with - "multipart/" while providing a "protocol" and a "micalg" parameter: just - add an appropriate \c "; boundary=[your \c boundary \c string]" to get - the complete Content-Type value to be used for the MIME object embedding - both the signed part and the signature part (or - in case of - encrypting - the version part and the code part, resp.). - \li If \c contentTypeVersion is holding a non-zero-length string an - additional MIME part must added immediately before the code part, this - version part's MIME headers must have the unaltered values of - \c contentTypeVersion and (if they are holding non-zero-length strings) - \c contentDispVersion and \c contentTEncVersion, the unaltered contents - of \c bodyTextVersion must be it's body. - \li The value returned in \c contentTypeCode is specifying the complete - Content-Type to be used for this multipart MIME object's signature part - (or - in case of encrypting - for the code part following after the - version part, resp.), you should not add/change/remove anything here - but just use it's unaltered value for specifying the Content-Type header - of the respective MIME part. - \li The same applies to the \c contentDispCode value: just use it's - unaltered value to specify the Content-Disposition header entry of - the respective MIME part. - \li The same applies to the \c contentTEncCode value: just use it's - unaltered value to specify the Content-Transfer-Encoding header of - the respective MIME part. - - If value returned in \c makeMimeObject is FALSE the - text strings returned in \c flatTextPrefix and \c flatTextPostfix - should be used to build a frame around the cleartext and the code - bloc holding the signature (or - in case of encrypting - the encoded - data bloc, resp.).
- If \c includeCleartext is TRUE this frame should also include the - cleartext as first bloc, this bloc should be divided from the code bloc - by the contents of \c flatTextSeparator - typically this is used for - signing but not when encrypting.
- If \c includeCleartext is FALSE you should ignore both the cleartext - and the \c flatTextSeparator parameter. - - How to use StructuringInfoWrapper data in your program: - \li To compose a signed message please act as described below. - \li For constructing an encrypted message just replace the - \c signMessage() call by the respective \c encryptMessage() call - and then proceed exactly the same way. - \li In any case make sure to free your \c ciphertext when - you are done with processing the data returned by the signing - (or encrypting, resp.) function. - -\verbatim - - char* ciphertext; - StructuringInfoWrapper structInf; - - if( ! signMessage( cleartext, &ciphertext, certificate, - structInf ) ) { - - myErrorDialog( "Error: could not sign the message!" ); - - } else { - if( structInf.data.makeMimeObject ) { - - // Build the main MIME object. - // This is done by - // using the header values returned in - // structInf.data.contentTypeMain and in - // structInf.data.contentDispMain and in - // structInf.data.contentTEncMain. - .. - - if( ! structInf.data.makeMultiMime ) { - - // Build the main MIME object's body. - // This is done by - // using the code bloc returned in - // ciphertext. - .. - - } else { - - // Build the encapsulated MIME parts. - if( structInf.data.includeCleartext ) { - - // Build a MIME part holding the cleartext. - // This is done by - // using the original cleartext's headers and by - // taking it's original body text. - .. - - } - if( structInf.data.contentTypeVersion - && 0 < strlen( structInf.data.contentTypeVersion ) ) { - - // Build a MIME part holding the version information. - // This is done by - // using the header values returned in - // structInf.data.contentTypeVersion and - // structInf.data.contentDispVersion and - // structInf.data.contentTEncVersion and by - // taking the body contents returned in - // structInf.data.bodyTextVersion. - .. - - } - if( structInf.data.contentTypeCode - && 0 < strlen( structInf.data.contentTypeCode ) ) { - - // Build a MIME part holding the code information. - // This is done by - // using the header values returned in - // structInf.data.contentTypeCode and - // structInf.data.contentDispCode and - // structInf.data.contentTEncCode and by - // taking the body contents returned in - // ciphertext. - .. - - } else { - - // Plugin error! - myErrorDialog( "Error: Cryptography plugin returned a main" - "Content-Type=Multipart/.. but did not " - "specify the code bloc's Content-Type header." - "\nYou may report this bug:" - "\n" + cryptplug.bugURL() ); - } - } - } else { - - // Build a plain message body - // based on the values returned in structInf. - // Note: We do _not_ insert line breaks between the parts since - // it is the plugin job to provide us with ready-to-use - // texts containing all necessary line breaks. - strcpy( myMessageBody, structInf.data.plainTextPrefix ); - if( structInf.data.includeCleartext ) { - strcat( myMessageBody, cleartext ); - strcat( myMessageBody, structInf.data.plainTextSeparator ); - } - strcat( myMessageBody, *ciphertext ); - strcat( myMessageBody, structInf.data.plainTextPostfix ); - } - - // free the memory that was allocated - // for the ciphertext - free( ciphertext ); - } - -\endverbatim - - \see signMessage, encryptMessage, encryptAndSignMessage -*/ -class StructuringInfoWrapper { -public: - StructuringInfoWrapper( CryptPlugWrapper* wrapper ); - ~StructuringInfoWrapper(); - void reset(); - CryptPlug::StructuringInfo data; -private: - void initMe(); - void freeMe(); - bool _initDone; - CryptPlugWrapper* _wrapper; -}; - - - -/*! - \brief This class provides C++ access to the CRYPTPLUG API. -*/ -class KDE_EXPORT CryptPlugWrapper : public Kleo::CryptoBackend::Protocol { -public: - static QString errorIdToText( int errId, bool & isPassphraseError ); - - /*! \ingroup groupGeneral - - \brief Current initialization state. - - This flag holding status of previous call of initialize function. - If initialize was not called before return value will be - \c CryptPlugInit_undef. - - \sa initStatus, initialize - */ - typedef enum { - InitStatus_undef = 0, - - InitStatus_Ok = 1, - InitStatus_NoLibName = 2, - InitStatus_LoadError = 0x1000, - InitStatus_InitError = 0x2000 - } InitStatus; - - /*! \ingroup groupSignAct - \brief Flags used to compose the SigStatusFlags value. - - This status flags are used to compose the SigStatusFlags value - returned in \c SignatureMetaDataExtendedInfo after trying to - verify a signed message part's signature status. - - The normal flags may not be used together with the - special SigStatus_NUMERICAL_CODE flag. When finding the special - SigStatus_NUMERICAL_CODE flag in a SigStatusFlags value you - can obtain the respective error code number by substracting - the SigStatusFlags value by SigStatus_NUMERICAL_CODE: this is - used to transport special status information NOT matching - any of the normal predefined status codes. - - \note to PlugIn developers: Implementations of the CryptPlug API - should try to express their signature states by bit-wise OR'ing - the normal SigStatusFlags values. Using the SigStatus_NUMERICAL_CODE - flag should only be used as for exceptional situations where no - other flag(s) could be used. By using the normal status flags your - PlugIn's users will be told an understandable description of the - status - when using (SigStatus_NUMERICAL_CODE + internalCode) they - will only be shown the respective code number and have to look - into your PlugIn's manual to learn about it's meaning... - */ - enum { - SigStatus_UNKNOWN = 0x0000, - SigStatus_VALID = SigStat_VALID, - SigStatus_GREEN = SigStat_GREEN, - SigStatus_RED = SigStat_RED, - SigStatus_KEY_REVOKED = SigStat_KEY_REVOKED, - SigStatus_KEY_EXPIRED = SigStat_KEY_EXPIRED, - SigStatus_SIG_EXPIRED = SigStat_SIG_EXPIRED, - SigStatus_KEY_MISSING = SigStat_KEY_MISSING, - SigStatus_CRL_MISSING = SigStat_CRL_MISSING, - SigStatus_CRL_TOO_OLD = SigStat_CRL_TOO_OLD, - SigStatus_BAD_POLICY = SigStat_BAD_POLICY, - SigStatus_SYS_ERROR = SigStat_SYS_ERROR, - - SigStatus_NUMERICAL_CODE = 0x8000 /* An other error occurred. */ - }; - typedef unsigned long SigStatusFlags; - - - enum { - CertStatus_EXPIRES_NEVER = CRYPTPLUG_CERT_DOES_NEVER_EXPIRE - }; - - - /*! \ingroup groupAdmin - \brief Constructor of CRYPTPLUG wrapper class. - - This constructor does not call the initialize() method - but just stores some information for later use. - - \note Since more than one crypto plug-in might be specified (using - multiple instances of the warpper class) it is necessary to - set \c active at least one them. Only wrappers that have been - activated may be initialized or configured or used to perform - crypto actions. - - \param name The external name that is visible in lists, messages, - etc. - \param libName Complete path+name of CRYPTPLUG library that is to - be used by this instance of CryptPlugWrapper. - \param update the URL from where updates can be downloaded - \param active Specify whether the relative library is to be used - or not. - - \sa ~CryptPlugWrapper, setActive, active, initialize, deinitialize - \sa initStatus - */ - CryptPlugWrapper( const QString& name=QString::null, - const QString& libName=QString::null, - const QString& update=QString::null, - bool active = false ); - - /*! \ingroup groupAdmin - \brief Destructor of CRYPTPLUG wrapper class. - - This destructor does call the deinitialize() method in case - this was not done by explicitly calling it before. - - \sa deinitialize, initialize, CryptPlugWrapper(), setActive, active - \sa - */ - ~CryptPlugWrapper(); - - QString protocol() const; - - QString name() const { - return protocol(); - } - - /*! \ingroup groupAdmin - \brief Set this CRYPTPLUG wrapper's internal \c active flag. - - Since more than one crypto plug-in might be specified (using - multiple instances of the warpper class) it is necessary to - set \c active at least one them. Only wrappers that have been - activated may be initialized or configured or used to perform - crypto actions. - - This flag may be set in the constructor or by calling setActive(). - - \note Deactivating does not mean resetting the internal - structures - if just prevents the normal functions from - being called erroneously. When deactivated only the following - functions are operational: constructor , destructor , - setActive , active, setLibName , libName , initStatus; - calling other functions will be ignored and their return - values will be undefined. - - \param active Specify whether the relative library is to be used - or not. - - \sa active, CryptPlugWrapper(), ~CryptPlugWrapper - \sa deinitialize, initialize, initStatus - */ - void setActive( bool active ); - - /*! \ingroup groupAdmin - \brief Returns this CRYPTPLUG wrapper's internal \c active flag. - - \return whether the relative library is to be used or not. - - \sa setActive - */ - bool active() const; - - - /*! \ingroup groupAdmin - \brief Set the CRYPTPLUG library name. - - Complete path+name of CRYPTPLUG library that is to - be used by this instance of CryptPlugWrapper. - - This name may be set in the constructor or by calling setLibName(). - - \note Setting/changing the library name may only be done when - the initStatus() is not \c InitStatus_Ok. - If you want to change the name of the library after - successfully having called initialize() please make - sure to unload it by calling the deinitialize() function. - - \param libName libName Complete path+name of CRYPTPLUG library - that is to be used by this CryptPlugWrapper. - - \return whether the library name could be changed; library name - can only be changed when library is not initialized - see - above 'note'. - - \sa libName, CryptPlugWrapper(), ~CryptPlugWrapper - \sa deinitialize, initialize, initStatus - */ - bool setLibName( const QString& libName ); - - /*! \ingroup groupAdmin - \brief Returns the CRYPTPLUG library name. - - \return the complete path+name of CRYPTPLUG library that is to - be used by this instance of CryptPlugWrapper. - - \sa setLibName - */ - QString libName() const; - - - /*! \ingroup groupAdmin - \brief Specifies the external name that is visible in lists, - messages, etc. - */ - void setDisplayName( const QString& name ); - - - /*! \ingroup groupAdmin - \brief Returns the external name. - \return the external name used for display purposes - */ - QString displayName() const; - -private: - /*! \ingroup groupGeneral - \brief This function does two things: (a) load the lib and (b) set up all internal structures. - - The method tries to load the CRYPTPLUG library specified - in the constructor and returns \c true if the both loading - and initializing the internal data structures was successful - and \c false otherwise. Before this function is called, - no other plugin functions should be called; the behavior is - undefined in this case, this rule does not apply to the functions - \c setActive() and \c setLibName(). - - \param initStatus will receive the resulting InitStatus if not NULL - \param errorMsg will receive the system error message if not NULL - - \sa initStatus, deinitialize, CryptPlugWrapper(), ~CryptPlugWrapper - \sa setActive, active - */ - bool initialize( InitStatus* initStatus, QString* errorMsg ); - -public: - /*! \ingroup groupGeneral - \brief This function unloads the lib and frees all internal structures. - - After this function has been called, no other plugin functions - should be called; the behavior is undefined in this case. - - \note Deinitializing sets the internal initStatus value back - to \c InitStatus_undef. - - \sa initStatus, initialize, CryptPlugWrapper, ~CryptPlugWrapper - \sa setActive, active - */ - void deinitialize(); - - /*! \ingroup groupGeneral - \brief Returns this CRYPTPLUG wrapper's initialization state. - - \param errorMsg receives the last system error message, this value - should be ignored if InitStatus value equals \c InitStatus_Ok. - - \return whether the relative library was loaded and initialized - correctly - - \sa initialize, deinitialize, CryptPlugWrapper(), ~CryptPlugWrapper - \sa setActive, active - */ - InitStatus initStatus( QString* errorMsg ) const; - - - /*! \ingroup groupGeneral - \brief This function returns \c true if the - specified feature is available in the plugin, and - \c false otherwise. - - Not all plugins will support all features; a complete Sphinx - implementation will support all features contained in the enum, - however. - - \note In case this function cannot be executed the system's error - message may be retrieved by calling initStatus( QString* ). - - \return whether the relative feature is implemented or not - */ - bool hasFeature( Feature ); - - - /* \ingroup groupSignAct - * Frees the members of a signature meta data struct, but not the - * signature meta data struct itself as this could be allocated on - * the stack. - */ - void freeSignatureMetaData( CryptPlug::SignatureMetaData* ); - - /*! \ingroup groupSignAct - \brief Checks whether the signature of a message is - valid. - - \c cleartext must never be 0 but be a valid pointer. - - If \c *cleartext > 0 then **cleartext specifies the message text - that was signed and \c signaturetext is the signature itself. - - If \c *cleartext == 0 is an empty string then \c signaturetext is - supposed to contain an opaque signed message part. After checking the - data and verifying the signature the cleartext of the message will be - returned in \c cleartext. The user must free the respective memory - occupied by *cleartext. - - Depending on the configuration, MUAs might not need to use this. - If \c sigmeta is non-null, the - \c SignatureMetaData object pointed to will - contain meta information about the signature after the - function call. - */ - bool checkMessageSignature( char** cleartext, - const char* signaturetext, - bool signatureIsBinary, - int signatureLen, - CryptPlug::SignatureMetaData* sigmeta ); - - /*! \ingroup groupCryptAct - \brief Tries to decrypt an email message - \c ciphertext and returns the decrypted - message in \c cleartext. - - The \c certificate is used for decryption. If - the message could be decrypted, the function returns - \c true, otherwise - \c false. - */ - bool decryptMessage( const char* ciphertext, - bool cipherIsBinary, - int cipherLen, - char** cleartext, - const char* certificate, - int* errId, - char** errTxt ); - - /*! \ingroup groupCryptAct - \brief Combines the functionality of - \c checkMessageSignature() and - \c decryptMessage(). - - If \c certificate is \c NULL, - the default certificate will be used. If - \c sigmeta is non-null, the - \c SignatureMetaData object pointed to will - contain meta information about the signature after the - function call. - */ - bool decryptAndCheckMessage( const char* ciphertext, - bool cipherIsBinary, - int cipherLen, - char** cleartext, - const char* certificate, - bool* signatureFound, - CryptPlug::SignatureMetaData* sigmeta, - int* errId, - char** errTxt ); - - Kleo::KeyListJob * keyListJob( bool remote=false, bool includeSigs=false, bool validate=true ) const; - Kleo::EncryptJob * encryptJob( bool armor=false, bool textmode=false ) const; - Kleo::DecryptJob * decryptJob() const; - Kleo::SignJob * signJob( bool armor=false, bool textMode=false ) const; - Kleo::VerifyDetachedJob * verifyDetachedJob( bool textmode=false) const; - Kleo::VerifyOpaqueJob * verifyOpaqueJob( bool textmode=false ) const; - Kleo::KeyGenerationJob * keyGenerationJob() const; - - Kleo::ImportJob * importJob() const; - Kleo::ExportJob * publicKeyExportJob( bool armor=false ) const; - Kleo::ExportJob * secretKeyExportJob( bool armor=false ) const; - Kleo::DownloadJob * downloadJob( bool armor=false ) const; - Kleo::DeleteJob * deleteJob() const; - - Kleo::SignEncryptJob * signEncryptJob( bool armor=false, bool textmode=false ) const; - Kleo::DecryptVerifyJob * decryptVerifyJob( bool textmode=false ) const; - Kleo::RefreshKeysJob * refreshKeysJob() const; - - Kleo::SpecialJob * specialJob( const char *, const QMap & ) const { return 0; } - - GpgME::ImportResult importCertificate( const char* data, size_t length ); - - CryptPlug * cryptPlug() const { return _cp; } - -private: - QString _name; - QString _libName; - QString _updateURL; - bool _active; - InitStatus _initStatus; - QString _lastError; - CryptPlug* _cp; - // local parameters without representation in cryptplug.h - bool mAlwaysEncryptToSelf; - class Config; - Config * _config; - QGpgMECryptoConfig * _cryptoConfig; -}; - -#endif // !LIBKLEOPATRA_NO_COMPAT - -#endif // cryptplugwrapper_h diff --git a/kleopatra/lib/cryptplugwrapperlist.cpp b/kleopatra/lib/cryptplugwrapperlist.cpp deleted file mode 100644 index 3ff38ddd8c..0000000000 --- a/kleopatra/lib/cryptplugwrapperlist.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* -*- c++ -*- - - CRYPTPLUG - an independent cryptography plug-in - API. CryptPlugWrapperList holds any number of crypto plug-ins. - - Copyright (C) 2001 by Klarlvdalens Datakonsult AB - - CRYPTPLUG is free software; you can redistribute it and/or modify - it under the terms of GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - CRYPTPLUG 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "cryptplugwrapperlist.h" - -CryptPlugWrapper * CryptPlugWrapperList::findForLibName( const QString & libName ) const -{ - for ( QPtrListIterator it( *this ) ; it.current() ; ++it ) - if ( (*it)->libName().find( libName, 0, false ) >= 0 ) - return *it; - return 0; -} diff --git a/kleopatra/lib/cryptplugwrapperlist.h b/kleopatra/lib/cryptplugwrapperlist.h deleted file mode 100644 index 3fab5799c1..0000000000 --- a/kleopatra/lib/cryptplugwrapperlist.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -*- Mode: C++ -*- - - CRYPTPLUG - an independent cryptography plug-in - API. CryptPlugWrapperList holds any number of crypto plug-ins. - - Copyright (C) 2001,2004 by Klarlvdalens Datakonsult AB - - CRYPTPLUG is free software; you can redistribute it and/or modify - it under the terms of GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - CRYPTPLUG 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ - -#ifndef __CRYPTPLUGWRAPPERLIST_H__ -#define __CRYPTPLUGWRAPPERLIST_H__ - -#include "cryptplugwrapper.h" - -#include - -class CryptPlugWrapperList : public QPtrList -{ -public: - CryptPlugWrapper * findForLibName( const QString & libName ) const; -}; - -typedef QPtrListIterator CryptPlugWrapperListIterator; - -#endif diff --git a/kleopatra/lib/kleo/Makefile.am b/kleopatra/lib/kleo/Makefile.am deleted file mode 100644 index 0465bb2daf..0000000000 --- a/kleopatra/lib/kleo/Makefile.am +++ /dev/null @@ -1,37 +0,0 @@ -INCLUDES = -I$(top_srcdir)/libkdenetwork \ - -I$(top_srcdir)/certmanager/lib \ - $(GPGME_CFLAGS) $(all_includes) - -noinst_LTLIBRARIES = libkleopatra_core.la - -libkleopatra_core_la_SOURCES = \ - cryptobackend.cpp \ - cryptobackendfactory.cpp \ - enum.cpp \ - dn.cpp \ - job.cpp \ - \ - multideletejob.cpp \ - hierarchicalkeylistjob.cpp \ - \ - kconfigbasedkeyfilter.cpp \ - keyfiltermanager.cpp - -kleodir = $(includedir)/kleo -kleo_HEADERS = \ - enum.h \ - cryptobackend.h \ - cryptobackendfactory.h \ - cryptoconfig.h \ - dn.h \ - job.h \ - keylistjob.h keygenerationjob.h importjob.h exportjob.h downloadjob.h deletejob.h \ - encryptjob.h decryptjob.h signjob.h verifydetachedjob.h verifyopaquejob.h \ - decryptverifyjob.h signencryptjob.h refreshkeysjob.h \ - multideletejob.h \ - hierarchicalkeylistjob.h \ - \ - keyfilter.h \ - keyfiltermanager.h - -METASOURCES = AUTO diff --git a/kleopatra/lib/kleo/cryptobackend.h b/kleopatra/lib/kleo/cryptobackend.h deleted file mode 100644 index 8d1f42e704..0000000000 --- a/kleopatra/lib/kleo/cryptobackend.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - kleo/cryptobackend.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_CRYPTOBACKEND_H__ -#define __KLEO_CRYPTOBACKEND_H__ - -namespace Kleo { - class CryptoConfig; - class KeyListJob; - class KeyGenerationJob; - class ImportJob; - class ExportJob; - class DownloadJob; - class DeleteJob; - class EncryptJob; - class DecryptJob; - class SignJob; - class VerifyDetachedJob; - class VerifyOpaqueJob; - class SignEncryptJob; - class DecryptVerifyJob; - class RefreshKeysJob; - class SpecialJob; -} - -class QString; -class QVariant; -template class QMap; - -namespace Kleo { - - class CryptoBackend { - public: - class Protocol; - - static const char OpenPGP[]; - static const char SMIME[]; - - virtual ~CryptoBackend() {} - - virtual QString name() const = 0; - virtual QString displayName() const = 0; - - virtual bool checkForOpenPGP( QString * reason=0 ) const = 0; - virtual bool checkForSMIME( QString * reason=0 ) const = 0; - virtual bool checkForProtocol( const char * name, QString * reason=0 ) const = 0; - - virtual bool supportsOpenPGP() const = 0; - virtual bool supportsSMIME() const = 0; - virtual bool supportsProtocol( const char * name ) const = 0; - - virtual CryptoConfig * config() const = 0; - - virtual Protocol * openpgp() const = 0; - virtual Protocol * smime() const = 0; - virtual Protocol * protocol( const char * name ) const = 0; - - virtual const char * enumerateProtocols( int i ) const = 0; - }; - - class CryptoBackend::Protocol { - public: - virtual ~Protocol() {} - - virtual QString name() const = 0; - - virtual QString displayName() const = 0; - - virtual KeyListJob * keyListJob( bool remote=false, bool includeSigs=false, bool validate=false ) const = 0; - virtual EncryptJob * encryptJob( bool armor=false, bool textmode=false ) const = 0; - virtual DecryptJob * decryptJob() const = 0; - virtual SignJob * signJob( bool armor=false, bool textMode=false ) const = 0; - virtual VerifyDetachedJob * verifyDetachedJob( bool textmode=false) const = 0; - virtual VerifyOpaqueJob * verifyOpaqueJob( bool textmode=false ) const = 0; - virtual KeyGenerationJob * keyGenerationJob() const = 0; - virtual ImportJob * importJob() const = 0; - virtual ExportJob * publicKeyExportJob( bool armor=false ) const = 0; - virtual ExportJob * secretKeyExportJob( bool armor=false ) const = 0; - virtual DownloadJob * downloadJob( bool armor=false ) const = 0; - virtual DeleteJob * deleteJob() const = 0; - virtual SignEncryptJob * signEncryptJob( bool armor=false, bool textMode=false ) const = 0; - virtual DecryptVerifyJob * decryptVerifyJob( bool textmode=false ) const = 0; - virtual RefreshKeysJob * refreshKeysJob() const = 0; - - virtual SpecialJob * specialJob( const char * type, const QMap & args ) const = 0; - }; - -} - -#endif // __KLEO_CRYPTOBACKEND_H__ diff --git a/kleopatra/lib/kleo/cryptobackendfactory.cpp b/kleopatra/lib/kleo/cryptobackendfactory.cpp deleted file mode 100644 index c56a7096f6..0000000000 --- a/kleopatra/lib/kleo/cryptobackendfactory.cpp +++ /dev/null @@ -1,275 +0,0 @@ -/* - cryptobackendfactory.cpp - - This file is part of libkleopatra, the KDE key management library - Copyright (c) 2001,2004,2005 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "cryptobackendfactory.h" - -#include -#if 0 // disabled for kde-3.3 -#include -#include -#include -#include -#endif -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#include - -Kleo::CryptoBackendFactory * Kleo::CryptoBackendFactory::mSelf = 0; - -static const char * availableProtocols[] = { - "Chiasmus", - "OpenPGP", "SMIME", -}; -static const unsigned int numAvailableProtocols = sizeof availableProtocols / sizeof *availableProtocols; - -Kleo::CryptoBackendFactory::CryptoBackendFactory() - : QObject( qApp, "CryptoBackendFactory::instance()" ), - mConfigObject( 0 ), - mAvailableProtocols( availableProtocols, availableProtocols + numAvailableProtocols ) -{ - mBackendList.push_back( new QGpgMEBackend() ); -#if 0 // disabled for kde-3.3 - mBackendList.push_back( new PGP2Backend() ); - mBackendList.push_back( new PGP5Backend() ); - mBackendList.push_back( new PGP6Backend() ); - mBackendList.push_back( new GPG1Backend() ); -#endif - mBackendList.push_back( new ChiasmusBackend() ); - scanForBackends(); - readConfig(); - - mSelf = this; // last! -} - -Kleo::CryptoBackendFactory::~CryptoBackendFactory() { - mSelf = 0; // first! - - for ( std::vector::iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { - delete *it; - *it = 0; - } - delete mConfigObject; - mConfigObject = 0; -} - -Kleo::CryptoBackendFactory * Kleo::CryptoBackendFactory::instance() { - if ( !mSelf ) - mSelf = new CryptoBackendFactory(); - return mSelf; -} - - -// const Kleo::CryptoBackend* Kleo::CryptoBackendFactory::smimeBackend() const { -// return mSMIMEBackend; -// } - -// const Kleo::CryptoBackend* Kleo::CryptoBackendFactory::openpgpBackend() const { -// return mOpenPGPBackend; -// } - -const Kleo::CryptoBackend::Protocol * Kleo::CryptoBackendFactory::smime() const { - const BackendMap::const_iterator it = mBackends.find( "SMIME" ); - if ( it == mBackends.end() ) - return 0; - if ( !it->second ) - return 0; - return it->second->smime(); -} - -const Kleo::CryptoBackend::Protocol * Kleo::CryptoBackendFactory::openpgp() const { - const BackendMap::const_iterator it = mBackends.find( "OpenPGP" ); - if ( it == mBackends.end() ) - return 0; - if ( !it->second ) - return 0; - return it->second->openpgp(); -} - -const Kleo::CryptoBackend::Protocol * Kleo::CryptoBackendFactory::protocol( const char * name ) const { - const BackendMap::const_iterator it = mBackends.find( name ); - if ( it == mBackends.end() ) - return 0; - if ( !it->second ) - return 0; - return it->second->protocol( name ); -} - -Kleo::CryptoConfig * Kleo::CryptoBackendFactory::config() const { - // ## should we use mSMIMEBackend? mOpenPGPBackend? backend(0) i.e. always qgpgme? - return backend( 0 ) ? backend( 0 )->config() : 0; -} - -bool Kleo::CryptoBackendFactory::hasBackends() const { - return !mBackendList.empty(); -} - -void Kleo::CryptoBackendFactory::scanForBackends( QStringList * reasons ) { - for ( std::vector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { - assert( *it ); - for ( int i = 0 ; const char * protocol = (*it)->enumerateProtocols( i ) ; ++i ) { - QString reason; - if ( (*it)->supportsProtocol( protocol ) && !(*it)->checkForProtocol( protocol, &reason ) ) { - if ( reasons ) { - reasons->push_back( i18n("While scanning for %1 support in backend %2:") - .arg( protocol, (*it)->displayName() ) ); - reasons->push_back( " " + reason ); - } - } - } - } -} - -const Kleo::CryptoBackend * Kleo::CryptoBackendFactory::backend( unsigned int idx ) const { - return ( idx < mBackendList.size() ) ? mBackendList[idx] : 0 ; -} - -const Kleo::CryptoBackend * Kleo::CryptoBackendFactory::backendByName( const QString& name ) const { - for ( std::vector::const_iterator it = mBackendList.begin() ; it != mBackendList.end() ; ++it ) { - if ( (*it)->name() == name ) - return *it; - } - return 0; -} - -Kleo::BackendConfigWidget * Kleo::CryptoBackendFactory::configWidget( QWidget * parent, const char * name ) const { - return new Kleo::BackendConfigWidget( mSelf, parent, name ); -} - -KConfig* Kleo::CryptoBackendFactory::configObject() const { - if ( !mConfigObject ) - // this is unsafe. We're a lib, used by concurrent apps. - mConfigObject = new KConfig( "libkleopatrarc" ); - return mConfigObject; -} - -void Kleo::CryptoBackendFactory::setSMIMEBackend( const CryptoBackend* backend ) { - setProtocolBackend( "SMIME", backend ); -} - -void Kleo::CryptoBackendFactory::setOpenPGPBackend( const CryptoBackend* backend ) { - setProtocolBackend( "OpenPGP", backend ); -} - -void Kleo::CryptoBackendFactory::setProtocolBackend( const char * protocol, const CryptoBackend * backend ) { - const QString name = backend ? backend->name() : QString::null ; - KConfigGroup group( configObject(), "Backends" ); - group.writeEntry( protocol, name ); - configObject()->sync(); - mBackends[protocol] = backend; -} - -static const char * defaultBackend( const char * proto ) { - static const struct { - const char * proto; - const char * backend; - } defaults[] = { - { "OpenPGP", "gpgme" }, - { "SMIME", "gpgme" }, - { "Chiasmus", "chiasmus" }, - }; - for ( unsigned int i = 0 ; i < sizeof defaults / sizeof *defaults ; ++i ) - if ( qstricmp( proto, defaults[i].proto ) == 0 ) - return defaults[i].backend; - return 0; -} - -void Kleo::CryptoBackendFactory::readConfig() { - mBackends.clear(); - const KConfigGroup group( configObject(), "Backends" ); - for ( ProtocolSet::const_iterator it = mAvailableProtocols.begin(), end = mAvailableProtocols.end() ; it != end ; ++it ) { - const QString backend = group.readEntry( *it, defaultBackend( *it ) ); - mBackends[*it] = backendByName( backend ); - } -} - -const char * Kleo::CryptoBackendFactory::enumerateProtocols( int i ) const { - if ( i < 0 || static_cast( i ) >= mAvailableProtocols.size() ) - return 0; - return mAvailableProtocols[i]; -} - -namespace { - class CaseInsensitiveString { - const char * m; - public: - CaseInsensitiveString( const char * s ) : m( s ) {} -#define make_operator( op ) \ - bool operator op( const CaseInsensitiveString & other ) const { \ - return qstricmp( m, other.m ) op 0; \ - } \ - bool operator op( const char * other ) const { \ - return qstricmp( m, other ) op 0; \ - } - make_operator( == ) - make_operator( != ) - make_operator( < ) - make_operator( > ) - make_operator( <= ) - make_operator( >= ) -#undef make_operator - operator const char *() const { return m; } - }; -#define make_ext_operator( op, inv_op ) \ - inline bool operator op( const char * lhs, const CaseInsensitiveString & rhs ) { \ - return rhs.operator inv_op( lhs ); \ - } - make_ext_operator( ==, == ) - make_ext_operator( !=, != ) - make_ext_operator( <, > ) - make_ext_operator( >, < ) - make_ext_operator( <=, >= ) - make_ext_operator( >=, <= ) -#undef make_ext_operator - -} - -bool Kleo::CryptoBackendFactory::knowsAboutProtocol( const char * name ) const { - return std::find( mAvailableProtocols.begin(), mAvailableProtocols.end(), - CaseInsensitiveString( name ) ) != mAvailableProtocols.end(); -} - -#include "cryptobackendfactory.moc" - diff --git a/kleopatra/lib/kleo/cryptobackendfactory.h b/kleopatra/lib/kleo/cryptobackendfactory.h deleted file mode 100644 index 7a54e9fd18..0000000000 --- a/kleopatra/lib/kleo/cryptobackendfactory.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - kleo/cryptobackendfactory.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_CRYPTOBACKENDFACTORY_H__ -#define __KLEO_CRYPTOBACKENDFACTORY_H__ - -#include - -#include "cryptobackend.h" -#include - -#include -#include - -namespace Kleo { - class BackendConfigWidget; -} - -class QString; -class KConfig; - -namespace Kleo { - - struct lt_i_str { - bool operator()( const char * one, const char * two ) const { - return qstricmp( one, two ) < 0; - } - }; - - class KDE_EXPORT CryptoBackendFactory : public QObject { - Q_OBJECT - protected: - CryptoBackendFactory(); - ~CryptoBackendFactory(); - public: - static CryptoBackendFactory * instance(); - - const CryptoBackend::Protocol * smime() const; - const CryptoBackend::Protocol * openpgp() const; - const CryptoBackend::Protocol * protocol( const char * name ) const; - CryptoConfig * config() const; - - const CryptoBackend * backend( unsigned int idx ) const; - - bool hasBackends() const; - - Kleo::BackendConfigWidget * configWidget( QWidget * parent=0, const char * name=0 ) const; - - KConfig* configObject() const; - - // The preferred backend for smime (can be 0) - currently unused - //const CryptoBackend* smimeBackend() const; - // The preferred backend for openpgp (can be 0) - currently unused - //const CryptoBackend* openpgpBackend() const; - - // For BackendConfigWidget to save the configuration - // 0 means no backend selected. - void setSMIMEBackend( const CryptoBackend* backend ); - void setOpenPGPBackend( const CryptoBackend* backend ); - void setProtocolBackend( const char * name, const CryptoBackend * backend ); - - void scanForBackends( QStringList * reasons=0 ); - - const char * enumerateProtocols( int i ) const; - - bool knowsAboutProtocol( const char * name ) const; - - protected: - std::vector mBackendList; - mutable KConfig* mConfigObject; - typedef std::map BackendMap; - BackendMap mBackends; - typedef std::vector ProtocolSet; - ProtocolSet mAvailableProtocols; - - private: - const CryptoBackend * backendByName( const QString& name ) const; - void readConfig(); - CryptoBackendFactory( const CryptoBackendFactory & ); - void operator=( const CryptoBackendFactory & ); - - static CryptoBackendFactory * mSelf; - }; - - -} - -#endif // __KLEO_CRYPTOBACKENDFACTORY_H__ diff --git a/kleopatra/lib/kleo/cryptoconfig.h b/kleopatra/lib/kleo/cryptoconfig.h deleted file mode 100644 index 6ed0cfec07..0000000000 --- a/kleopatra/lib/kleo/cryptoconfig.h +++ /dev/null @@ -1,382 +0,0 @@ -/* - cryptoconfig.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef CRYPTOCONFIG_H -#define CRYPTOCONFIG_H - -#ifdef __cplusplus -/* we read this file from a C compiler, and are only interested in the - * enums... */ - -#include - -/* Start reading this file from the bottom up :) */ - -namespace Kleo { - - /** - * Description of a single option - */ - class CryptoConfigEntry { - - public: -#endif /* __cplusplus */ - /** - @li basic This option should always be offered to the user. - @li advanced This option may be offered to advanced users. - @li expert This option should only be offered to expert users. - */ - enum Level { Level_Basic = 0, - Level_Advanced = 1, - Level_Expert = 2 }; - - /** - Type of the argument - @li ArgType_None The option is set or not set, but no argument. - @li ArgType_String An unformatted string. - @li ArgType_Int A signed integer number. - @li ArgType_UInt An unsigned integer number. - @li ArgType_Path A string that describes the pathname of a file. - The file does not necessarily need to exist. - Separated from string so that e.g. a KURLRequester can be used. - @li ArgType_DirPath A string that describes the pathname of a directory. - The directory does not necessarily need to exist. - Separated from path so that e.g. a KURLRequester can be used which only - allows directories to be selected. - @li ArgType_URL A URL - @li ArgType_LDAPURL A LDAP URL - Separated from URL so that a more specific widget can be shown, hiding the url syntax - */ - enum ArgType { ArgType_None = 0, - ArgType_String = 1, - ArgType_Int = 2, - ArgType_UInt = 3, - ArgType_Path = 4, - ArgType_URL = 5, - ArgType_LDAPURL = 6, - ArgType_DirPath = 7 }; - -#ifdef __cplusplus - virtual ~CryptoConfigEntry() {} - - /** - * Return the internal name of this entry - */ - virtual QString name() const = 0; - - /** - * @return user-visible description of this entry - */ - virtual QString description() const = 0; - - /** - * @return true if the argument is optional - */ - virtual bool isOptional() const = 0; - - /** - * @return true if the argument can be given multiple times - */ - virtual bool isList() const = 0; - - /** - * @return true if the argument can be changed at runtime - */ - virtual bool isRuntime() const = 0; - - /** - * User level - */ - virtual Level level() const = 0; - - /** - * Argument type - */ - virtual ArgType argType() const = 0; - - /** - * Return true if the option is set, i.e. different from default - */ - virtual bool isSet() const = 0; - - /** - * Return value as a bool (only allowed for ArgType_None) - */ - virtual bool boolValue() const = 0; - - /** - * Return value as a string (available for all argtypes) - * The returned string can be empty (explicitely set to empty) or null (not set). - */ - virtual QString stringValue() const = 0; - - /** - * Return value as a signed int - */ - virtual int intValue() const = 0; - - /** - * Return value as an unsigned int - */ - virtual unsigned int uintValue() const = 0; - - /** - * Return value as a URL (only meaningful for Path and URL argtypes) - */ - virtual KURL urlValue() const = 0; - - /** - * Return number of times the option is set (only valid for ArgType_None, if isList()) - */ - virtual unsigned int numberOfTimesSet() const = 0; - - /** - * Return value as a list of strings (mostly meaningful for String, Path and URL argtypes, if isList()) - */ - virtual QStringList stringValueList() const = 0; - - /** - * Return value as a list of signed ints - */ - virtual QValueList intValueList() const = 0; - - /** - * Return value as a list of unsigned ints - */ - virtual QValueList uintValueList() const = 0; - - /** - * Return value as a list of URLs (only meaningful for Path and URL argtypes, if isList()) - */ - virtual KURL::List urlValueList() const = 0; - - /** - * Reset an option to its default value - */ - virtual void resetToDefault() = 0; - - /** - * Define whether the option is set or not (only allowed for ArgType_None) - * #### TODO: and for options with optional args - */ - virtual void setBoolValue( bool ) = 0; - - /** - * Set string value (allowed for all argtypes) - */ - virtual void setStringValue( const QString& ) = 0; - - /** - * Set a new signed int value - */ - virtual void setIntValue( int ) = 0; - - /** - * Set a new unsigned int value - */ - virtual void setUIntValue( unsigned int ) = 0; - - /** - * Set value as a URL (only meaningful for Path (if local) and URL argtypes) - */ - virtual void setURLValue( const KURL& ) = 0; - - /** - * Set the number of times the option is set (only valid for ArgType_None, if isList()) - */ - virtual void setNumberOfTimesSet( unsigned int ) = 0; - - /** - * Set a new string-list value (only allowed for String, Path and URL argtypes, if isList()) - */ - virtual void setStringValueList( const QStringList& ) = 0; - - /** - * Set a new list of signed int values - */ - virtual void setIntValueList( const QValueList& ) = 0; - - /** - * Set a new list of unsigned int values - */ - virtual void setUIntValueList( const QValueList& ) = 0; - - /** - * Set value as a URL list (only meaningful for Path (if all URLs are local) and URL argtypes, if isList()) - */ - virtual void setURLValueList( const KURL::List& ) = 0; - - /** - * @return true if the value was changed - */ - virtual bool isDirty() const = 0; - }; - - /** - * Group containing a set of config options - */ - class CryptoConfigGroup { - - public: - virtual ~CryptoConfigGroup() {} - - /** - * Return the internal name of this group - */ - virtual QString name() const = 0; - - /** - * Return the name of the icon for this group - */ - virtual QString iconName() const = 0; - - /** - * @return user-visible description of this group - */ - virtual QString description() const = 0; - - /** - * User level - */ - virtual CryptoConfigEntry::Level level() const = 0; - - /** - * Returns the list of entries that are known by this group. - * - * @return list of group entry names. - **/ - virtual QStringList entryList() const = 0; - - /** - * @return the configuration object for a given entry in this group - * The object is owned by CryptoConfigGroup, don't delete it. - * Groups cannot be nested, so all entries returned here are pure entries, no groups. - */ - virtual CryptoConfigEntry* entry( const QString& name ) const = 0; - }; - - /** - * Crypto config for one component (e.g. gpg-agent, dirmngr etc.) - */ - class CryptoConfigComponent { - - public: - virtual ~CryptoConfigComponent() {} - - /** - * Return the internal name of this component - */ - virtual QString name() const = 0; - - /** - * Return the name of the icon for this component - */ - virtual QString iconName() const = 0; - - /** - * Return user-visible description of this component - */ - virtual QString description() const = 0; - - /** - * Returns the list of groups that are known about. - * - * @return list of group names. One of them can be "", which is the group where all - * "toplevel" options (belonging to no group) are. - */ - virtual QStringList groupList() const = 0; - - /** - * @return the configuration object for a given group - * The object is owned by CryptoConfigComponent, don't delete it. - */ - virtual CryptoConfigGroup* group( const QString& name ) const = 0; - - }; - - /** - * Main interface to crypto configuration. - */ - class CryptoConfig { - - public: - virtual ~CryptoConfig() {} - - /** - * Returns the list of known components (e.g. "gpg-agent", "dirmngr" etc.). - * Use @ref component() to retrieve more information about each one. - * @return list of component names. - **/ - virtual QStringList componentList() const = 0; - - /** - * @return the configuration object for a given component - * The object is owned by CryptoConfig, don't delete it. - */ - virtual CryptoConfigComponent* component( const QString& name ) const = 0; - - /** - * Convenience method to get hold of a single configuration entry when - * its component, group and name are known. This can be used to read - * the value and/or to set a value to it. - * - * @return the configuration object for a single configuration entry, 0 if not found. - * The object is owned by CryptoConfig, don't delete it. - */ - CryptoConfigEntry* entry( const QString& componentName, const QString& groupName, const QString& entryName ) const { - const Kleo::CryptoConfigComponent* comp = component( componentName ); - const Kleo::CryptoConfigGroup* group = comp ? comp->group( groupName ) : 0; - return group ? group->entry( entryName ) : 0; - } - - /** - * Write back changes - * - * @param runtime If this option is set, the changes will take effect at run-time, as - * far as this is possible. Otherwise, they will take effect at the next - * start of the respective backend programs. - */ - virtual void sync( bool runtime ) = 0; - - /** - * Tells the CryptoConfig to discard any cached information, including - * all components, groups and entries. - * Call this to free some memory when you won't be using the object - * for some time. - * DON'T call this if you're holding pointers to components, groups or entries. - */ - virtual void clear() = 0; - }; - -} -#endif /* __cplusplus */ -#endif /* CRYPTOCONFIG_H */ diff --git a/kleopatra/lib/kleo/decryptjob.h b/kleopatra/lib/kleo/decryptjob.h deleted file mode 100644 index e882152a0c..0000000000 --- a/kleopatra/lib/kleo/decryptjob.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - decryptjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_DECRYPTJOB_H__ -#define __KLEO_DECRYPTJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; - class Key; - class DecryptionResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous decrypters - - To use a DecryptJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the decryption with a - call to start(). This call might fail, in which case the - DecryptJob instance will have scheduled it's own destruction with - a call to QObject::deleteLater(). - - After result() is emitted, the DecryptJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class DecryptJob : public Job { - Q_OBJECT - protected: - DecryptJob( QObject * parent, const char * name ); - public: - ~DecryptJob(); - - /** - Starts the decryption operation. \a cipherText is the data to - decrypt. - */ - virtual GpgME::Error start( const QByteArray & cipherText ) = 0; - - virtual GpgME::DecryptionResult exec( const QByteArray & cipherText, - QByteArray & plainText ) = 0; - - signals: - void result( const GpgME::DecryptionResult & result, const QByteArray & plainText ); - }; - -} - -#endif // __KLEO_DECRYPTJOB_H__ diff --git a/kleopatra/lib/kleo/decryptverifyjob.h b/kleopatra/lib/kleo/decryptverifyjob.h deleted file mode 100644 index f7cdb81a1e..0000000000 --- a/kleopatra/lib/kleo/decryptverifyjob.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - decryptverifyjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_DECRYPTVERIFYJOB_H__ -#define __KLEO_DECRYPTVERIFYJOB_H__ - -#include "job.h" - -#include - -#include - -namespace GpgME { - class Error; - class Key; - class DecryptionResult; - class VerificationResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous combined decrypters and verifiers - - To use a DecryptVerifyJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the operation with a - call to start(). This call might fail, in which case the - DecryptVerifyJob instance will have scheduled it's own destruction with - a call to QObject::deleteLater(). - - After result() is emitted, the DecryptVerifyJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class DecryptVerifyJob : public Job { - Q_OBJECT - protected: - DecryptVerifyJob( QObject * parent, const char * name ); - public: - ~DecryptVerifyJob(); - - /** - Starts the combined decryption and verification operation. - \a cipherText is the data to decrypt and later verify. - */ - virtual GpgME::Error start( const QByteArray & cipherText ) = 0; - - /** Synchronous equivalent of start() */ - virtual std::pair - exec( const QByteArray & cipherText, QByteArray & plainText ) = 0; - - signals: - void result( const GpgME::DecryptionResult & decryptionresult, - const GpgME::VerificationResult & verificationresult, - const QByteArray & plainText ); - }; - -} - -#endif // __KLEO_DECRYPTVERIFYJOB_H__ diff --git a/kleopatra/lib/kleo/deletejob.h b/kleopatra/lib/kleo/deletejob.h deleted file mode 100644 index fd70ec513d..0000000000 --- a/kleopatra/lib/kleo/deletejob.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - deletejob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_DELETEJOB_H__ -#define __KLEO_DELETEJOB_H__ - -#include "job.h" - -namespace GpgME { - class Error; - class Key; -} - -namespace Kleo { - - /** - @short An abstract base class for asynchronous deleters - - To use a DeleteJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the delete with a call - to start(). This call might fail, in which case the DeleteJob - instance will have scheduled it's own destruction with a call to - QObject::deleteLater(). - - After result() is emitted, the DeleteJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class DeleteJob : public Job { - Q_OBJECT - protected: - DeleteJob( QObject * parent, const char * name ); - public: - ~DeleteJob(); - - /** - Starts the delete operation. \a key represents the key to - delete, \a allowSecretKeyDeletion specifies if a key may also - be deleted if the secret key part is available, too. - */ - virtual GpgME::Error start( const GpgME::Key & key, bool allowSecretKeyDeletion=false ) = 0; - - signals: - void result( const GpgME::Error & result ); - }; - -} - -#endif // __KLEO_DELETEJOB_H__ diff --git a/kleopatra/lib/kleo/dn.cpp b/kleopatra/lib/kleo/dn.cpp deleted file mode 100644 index 2ea0f6719f..0000000000 --- a/kleopatra/lib/kleo/dn.cpp +++ /dev/null @@ -1,512 +0,0 @@ -/* - dn.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - DN parsing: - Copyright (c) 2002 g10 Code GmbH - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "dn.h" - -#include "oidmap.h" -#include "ui/dnattributeorderconfigwidget.h" - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include - -struct Kleo::DN::Private { - Private() : mRefCount( 0 ) {} - Private( const Private & other ) - : attributes( other.attributes ), - reorderedAttributes( other.reorderedAttributes ), - mRefCount( 0 ) - { - - } - - int ref() { - return ++mRefCount; - } - - int unref() { - if ( --mRefCount <= 0 ) { - delete this; - return 0; - } else - return mRefCount; - } - - int refCount() const { return mRefCount; } - - DN::Attribute::List attributes; - DN::Attribute::List reorderedAttributes; -private: - int mRefCount; -}; - -namespace { - struct DnPair { - char * key; - char * value; - }; -} - -// copied from CryptPlug and adapted to work on DN::Attribute::List: - -#define digitp(p) (*(p) >= '0' && *(p) <= '9') -#define hexdigitp(a) (digitp (a) \ - || (*(a) >= 'A' && *(a) <= 'F') \ - || (*(a) >= 'a' && *(a) <= 'f')) -#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ - *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) -#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) - -static char * -trim_trailing_spaces( char *string ) -{ - char *p, *mark; - - for( mark = NULL, p = string; *p; p++ ) { - if( isspace( *p ) ) { - if( !mark ) - mark = p; - } - else - mark = NULL; - } - if( mark ) - *mark = '\0' ; - - return string ; -} - -/* Parse a DN and return an array-ized one. This is not a validating - parser and it does not support any old-stylish syntax; gpgme is - expected to return only rfc2253 compatible strings. */ -static const unsigned char * -parse_dn_part (DnPair *array, const unsigned char *string) -{ - const unsigned char *s, *s1; - size_t n; - char *p; - - /* parse attributeType */ - for (s = string+1; *s && *s != '='; s++) - ; - if (!*s) - return NULL; /* error */ - n = s - string; - if (!n) - return NULL; /* empty key */ - p = (char*)malloc (n+1); - - - memcpy (p, string, n); - p[n] = 0; - trim_trailing_spaces ((char*)p); - // map OIDs to their names: - for ( unsigned int i = 0 ; i < numOidMaps ; ++i ) - if ( !strcasecmp ((char*)p, oidmap[i].oid) ) { - free( p ); - p = strdup( oidmap[i].name ); - break; - } - array->key = p; - string = s + 1; - - if (*string == '#') - { /* hexstring */ - string++; - for (s=string; hexdigitp (s); s++) - s++; - n = s - string; - if (!n || (n & 1)) - return NULL; /* empty or odd number of digits */ - n /= 2; - array->value = p = (char*)malloc (n+1); - - - for (s1=string; n; s1 += 2, n--) - *p++ = xtoi_2 (s1); - *p = 0; - } - else - { /* regular v3 quoted string */ - for (n=0, s=string; *s; s++) - { - if (*s == '\\') - { /* pair */ - s++; - if (*s == ',' || *s == '=' || *s == '+' - || *s == '<' || *s == '>' || *s == '#' || *s == ';' - || *s == '\\' || *s == '\"' || *s == ' ') - n++; - else if (hexdigitp (s) && hexdigitp (s+1)) - { - s++; - n++; - } - else - return NULL; /* invalid escape sequence */ - } - else if (*s == '\"') - return NULL; /* invalid encoding */ - else if (*s == ',' || *s == '=' || *s == '+' - || *s == '<' || *s == '>' || *s == '#' || *s == ';' ) - break; - else - n++; - } - - array->value = p = (char*)malloc (n+1); - - - for (s=string; n; s++, n--) - { - if (*s == '\\') - { - s++; - if (hexdigitp (s)) - { - *p++ = xtoi_2 (s); - s++; - } - else - *p++ = *s; - } - else - *p++ = *s; - } - *p = 0; - } - return s; -} - - -/* Parse a DN and return an array-ized one. This is not a validating - parser and it does not support any old-stylish syntax; gpgme is - expected to return only rfc2253 compatible strings. */ -static Kleo::DN::Attribute::List -parse_dn( const unsigned char * string ) { - if ( !string ) - return QValueVector(); - - QValueVector result; - while (*string) - { - while (*string == ' ') - string++; - if (!*string) - break; /* ready */ - - DnPair pair = { 0, 0 }; - string = parse_dn_part (&pair, string); - if (!string) - goto failure; - if ( pair.key && pair.value ) - result.push_back( Kleo::DN::Attribute( QString::fromUtf8( pair.key ), - QString::fromUtf8( pair.value ) ) ); - free( pair.key ); - free( pair.value ); - - while (*string == ' ') - string++; - if (*string && *string != ',' && *string != ';' && *string != '+') - goto failure; /* invalid delimiter */ - if (*string) - string++; - } - return result; - -failure: - return QValueVector(); -} - -static QValueVector -parse_dn( const QString & dn ) { - return parse_dn( (const unsigned char*)dn.utf8().data() ); -} - -static QString -serialise( const QValueVector & dn ) { - QStringList result; - for ( QValueVector::const_iterator it = dn.begin() ; it != dn.end() ; ++it ) - if ( !(*it).name().isEmpty() && !(*it).value().isEmpty() ) - result.push_back( (*it).name().stripWhiteSpace() + '=' + (*it).value().stripWhiteSpace() ); - return result.join( "," ); -} - -static Kleo::DN::Attribute::List -reorder_dn( const Kleo::DN::Attribute::List & dn ) { - const QStringList & attrOrder = Kleo::DNAttributeMapper::instance()->attributeOrder(); - - Kleo::DN::Attribute::List unknownEntries; - Kleo::DN::Attribute::List result; - unknownEntries.reserve( dn.size() ); - result.reserve( dn.size() ); - - // find all unknown entries in their order of appearance - for ( Kleo::DN::const_iterator it = dn.begin(); it != dn.end(); ++it ) - if ( attrOrder.find( (*it).name() ) == attrOrder.end() ) - unknownEntries.push_back( *it ); - - // process the known attrs in the desired order - for ( QStringList::const_iterator oit = attrOrder.begin() ; oit != attrOrder.end() ; ++oit ) - if ( *oit == "_X_" ) { - // insert the unknown attrs - std::copy( unknownEntries.begin(), unknownEntries.end(), - std::back_inserter( result ) ); - unknownEntries.clear(); // don't produce dup's - } else { - for ( Kleo::DN::const_iterator dnit = dn.begin() ; dnit != dn.end() ; ++dnit ) - if ( (*dnit).name() == *oit ) - result.push_back( *dnit ); - } - - return result; -} - -// -// -// class DN -// -// - -Kleo::DN::DN() { - d = new Private(); - d->ref(); -} - -Kleo::DN::DN( const QString & dn ) { - d = new Private(); - d->ref(); - d->attributes = parse_dn( dn ); -} - -Kleo::DN::DN( const char * utf8DN ) { - d = new Private(); - d->ref(); - if ( utf8DN ) - d->attributes = parse_dn( (const unsigned char*)utf8DN ); -} - -Kleo::DN::DN( const DN & other ) - : d( other.d ) -{ - if ( d ) d->ref(); -} - -Kleo::DN::~DN() { - if ( d ) d->unref(); -} - -const Kleo::DN & Kleo::DN::operator=( const DN & that ) { - if ( this->d == that.d ) - return *this; - - if ( that.d ) - that.d->ref(); - if ( this->d ) - this->d->unref(); - - this->d = that.d; - - return *this; -} - -QString Kleo::DN::prettyDN() const { - if ( !d ) - return QString::null; - if ( d->reorderedAttributes.empty() ) - d->reorderedAttributes = reorder_dn( d->attributes ); - return serialise( d->reorderedAttributes ); -} - -QString Kleo::DN::dn() const { - return d ? serialise( d->attributes ) : QString::null ; -} - -void Kleo::DN::detach() { - if ( !d ) { - d = new Kleo::DN::Private(); - d->ref(); - } else if ( d->refCount() > 1 ) { - Kleo::DN::Private * d_save = d; - d = new Kleo::DN::Private( *d ); - d->ref(); - d_save->unref(); - } -} - -void Kleo::DN::append( const Attribute & attr ) { - detach(); - d->attributes.push_back( attr ); - d->reorderedAttributes.clear(); -} - -QString Kleo::DN::operator[]( const QString & attr ) const { - if ( !d ) - return QString::null; - const QString attrUpper = attr.upper(); - for ( QValueVector::const_iterator it = d->attributes.begin() ; - it != d->attributes.end() ; ++it ) - if ( (*it).name() == attrUpper ) - return (*it).value(); - return QString::null; -} - -static QValueVector empty; - -Kleo::DN::const_iterator Kleo::DN::begin() const { - return d ? d->attributes.begin() : empty.begin() ; -} - -Kleo::DN::const_iterator Kleo::DN::end() const { - return d ? d->attributes.end() : empty.end() ; -} - - -///////////////////// - -namespace { - struct ltstr { - bool operator()( const char * s1, const char * s2 ) const { - return qstrcmp( s1, s2 ) < 0 ; - } - }; -} - -static const char * defaultOrder[] = { - "CN", "L", "_X_", "OU", "O", "C" -}; - -std::pair attributeLabels[] = { -#define MAKE_PAIR(x,y) std::pair( x, y ) - MAKE_PAIR( "CN", I18N_NOOP("Common name") ), - MAKE_PAIR( "SN", I18N_NOOP("Surname") ), - MAKE_PAIR( "GN", I18N_NOOP("Given name") ), - MAKE_PAIR( "L", I18N_NOOP("Location") ), - MAKE_PAIR( "T", I18N_NOOP("Title") ), - MAKE_PAIR( "OU", I18N_NOOP("Organizational unit") ), - MAKE_PAIR( "O", I18N_NOOP("Organization") ), - MAKE_PAIR( "PC", I18N_NOOP("Postal code") ), - MAKE_PAIR( "C", I18N_NOOP("Country code") ), - MAKE_PAIR( "SP", I18N_NOOP("State or province") ), - MAKE_PAIR( "DC", I18N_NOOP("Domain component") ), - MAKE_PAIR( "BC", I18N_NOOP("Business category") ), - MAKE_PAIR( "EMAIL", I18N_NOOP("Email address") ), - MAKE_PAIR( "MAIL", I18N_NOOP("Mail address") ), - MAKE_PAIR( "MOBILE", I18N_NOOP("Mobile phone number") ), - MAKE_PAIR( "TEL", I18N_NOOP("Telephone number") ), - MAKE_PAIR( "FAX", I18N_NOOP("Fax number") ), - MAKE_PAIR( "STREET", I18N_NOOP("Street address") ), - MAKE_PAIR( "UID", I18N_NOOP("Unique ID") ) -#undef MAKE_PAIR -}; -static const unsigned int numAttributeLabels = sizeof attributeLabels / sizeof *attributeLabels ; - -class Kleo::DNAttributeMapper::Private { -public: - Private(); - std::map map; - QStringList attributeOrder; -}; - -Kleo::DNAttributeMapper::Private::Private() - : map( attributeLabels, attributeLabels + numAttributeLabels ) {} - -Kleo::DNAttributeMapper::DNAttributeMapper() { - d = new Private(); - const KConfigGroup config( kapp->config(), "DN" ); - d->attributeOrder = config.readListEntry( "AttributeOrder" ); - if ( d->attributeOrder.empty() ) - std::copy( defaultOrder, defaultOrder + sizeof defaultOrder / sizeof *defaultOrder, - std::back_inserter( d->attributeOrder ) ); - mSelf = this; -} - -Kleo::DNAttributeMapper::~DNAttributeMapper() { - mSelf = 0; - delete d; d = 0; -} - -Kleo::DNAttributeMapper * Kleo::DNAttributeMapper::mSelf = 0; - -const Kleo::DNAttributeMapper * Kleo::DNAttributeMapper::instance() { - if ( !mSelf ) - (void)new DNAttributeMapper(); - return mSelf; -} - -QString Kleo::DNAttributeMapper::name2label( const QString & s ) const { - const std::map::const_iterator it - = d->map.find( s.stripWhiteSpace().upper().latin1() ); - if ( it == d->map.end() ) - return QString::null; - return i18n( it->second ); -} - -QStringList Kleo::DNAttributeMapper::names() const { - QStringList result; - for ( std::map::const_iterator it = d->map.begin() ; it != d->map.end() ; ++it ) - result.push_back( it->first ); - return result; -} - -const QStringList & Kleo::DNAttributeMapper::attributeOrder() const { - return d->attributeOrder; -} - -void Kleo::DNAttributeMapper::setAttributeOrder( const QStringList & order ) { - d->attributeOrder = order; - if ( order.empty() ) - std::copy( defaultOrder, defaultOrder + sizeof defaultOrder / sizeof *defaultOrder, - std::back_inserter( d->attributeOrder ) ); - KConfigGroup config( kapp->config(), "DN" ); - config.writeEntry( "AttributeOrder", order ); -} - -Kleo::DNAttributeOrderConfigWidget * Kleo::DNAttributeMapper::configWidget( QWidget * parent, const char * name ) const { - return new DNAttributeOrderConfigWidget( mSelf, parent, name ); -} diff --git a/kleopatra/lib/kleo/dn.h b/kleopatra/lib/kleo/dn.h deleted file mode 100644 index f4bd78e8ec..0000000000 --- a/kleopatra/lib/kleo/dn.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - dn.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_DN_H__ -#define __KLEO_DN_H__ - -#include -#include -#include - -class QStringList; -class QWidget; - -namespace Kleo { - class DNAttributeOrderConfigWidget; -} - -namespace Kleo { - - /** - @short DN Attribute mapper - */ - class KDE_EXPORT DNAttributeMapper { - DNAttributeMapper(); - ~DNAttributeMapper(); - public: - static const DNAttributeMapper * instance(); - - QString name2label( const QString & s ) const; - QStringList names() const; - - const QStringList & attributeOrder() const; - - void setAttributeOrder( const QStringList & order ); - - DNAttributeOrderConfigWidget * configWidget( QWidget * parent=0, const char * name=0 ) const; - - private: - class Private; - Private * d; - static DNAttributeMapper * mSelf; - }; - - /** - @short DN parser and reorderer - */ - class KDE_EXPORT DN { - public: - class Attribute; - typedef QValueVector AttributeList; - typedef AttributeList::const_iterator const_iterator; - - DN(); - DN( const QString & dn ); - DN( const char * utf8DN ); - DN( const DN & other ); - ~DN(); - - const DN & operator=( const DN & other ); - - /** @return the DN in a reordered form, according to the settings in - the [DN] group of the application's config file */ - QString prettyDN() const; - /** @return the DN in the original form */ - QString dn() const; - - QString operator[]( const QString & attr ) const; - - void append( const Attribute & attr ); - - const_iterator begin() const; - const_iterator end() const; - - private: - void detach(); - private: - class Private; - Private * d; - }; - - class KDE_EXPORT DN::Attribute { - public: - typedef DN::AttributeList List; - - Attribute( const QString & name=QString::null, const QString & value=QString::null ) - : mName( name.upper() ), mValue( value ) {} - Attribute( const Attribute & other ) - : mName( other.name() ), mValue( other.value() ) {} - - const Attribute & operator=( const Attribute & other ) { - if ( this != &other ) { - mName = other.name(); - mValue = other.value(); - } - return *this; - } - - const QString & name() const { return mName; } - const QString & value() const { return mValue; } - - void setValue( const QString & value ) { mValue = value; } - - private: - QString mName; - QString mValue; - }; - -} - -#endif // __KLEO_DN_H__ diff --git a/kleopatra/lib/kleo/downloadjob.h b/kleopatra/lib/kleo/downloadjob.h deleted file mode 100644 index 006ab8ebd4..0000000000 --- a/kleopatra/lib/kleo/downloadjob.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - downloadjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_DOWNLOADJOB_H__ -#define __KLEO_DOWNLOADJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; -} - -class QStringList; - -namespace Kleo { - - /** - @short An abstract base class for asynchronous downloaders - - To use a DownloadJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the download with a call - to start(). This call might fail, in which case the DownloadJob - instance will have scheduled it's own destruction with a call to - QObject::deleteLater(). - - After result() is emitted, the DownloadJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class DownloadJob : public Job { - Q_OBJECT - protected: - DownloadJob( QObject * parent, const char * name ); - public: - ~DownloadJob(); - - /** - Starts the download operation. \a fingerprints is a list of - fingerprints used to specify the list of keys downloaded. Empty - patterns are ignored. If \a fingerprints is empty, contains - only empty strings or anything other than fingerprints, the - result is undefined. - */ - virtual GpgME::Error start( const QStringList & fingerprints ) = 0; - - signals: - void result( const GpgME::Error & result, const QByteArray & keyData ); - }; - -} - -#endif // __KLEO_DOWNLOADJOB_H__ diff --git a/kleopatra/lib/kleo/encryptjob.h b/kleopatra/lib/kleo/encryptjob.h deleted file mode 100644 index 02144656ff..0000000000 --- a/kleopatra/lib/kleo/encryptjob.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - encryptjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_ENCRYPTJOB_H__ -#define __KLEO_ENCRYPTJOB_H__ - -#include "job.h" - -#include - -#include - -namespace GpgME { - class Error; - class Key; - class EncryptionResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous encrypters - - To use a EncryptJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the encryption with a - call to start(). This call might fail, in which case the - EncryptJob instance will have scheduled it's own destruction with - a call to QObject::deleteLater(). - - After result() is emitted, the EncryptJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class EncryptJob : public Job { - Q_OBJECT - protected: - EncryptJob( QObject * parent, const char * name ); - public: - ~EncryptJob(); - - /** - Starts the encryption operation. \a recipients is the a list of - keys to encrypt \a plainText to. Empty (null) keys are ignored. - - If \a alwaysTrust is true, validity checking for the keys will - not be performed, but full validity assumed for all keys - without further checks. - */ - virtual GpgME::Error start( const std::vector & recipients, - const QByteArray & plainText, bool alwaysTrust=false ) = 0; - - virtual GpgME::EncryptionResult exec( const std::vector & recipients, - const QByteArray & plainText, - bool alwaysTrust, QByteArray & cipherText ) = 0; - - signals: - void result( const GpgME::EncryptionResult & result, const QByteArray & cipherText ); - }; - -} - -#endif // __KLEO_ENCRYPTJOB_H__ diff --git a/kleopatra/lib/kleo/enum.cpp b/kleopatra/lib/kleo/enum.cpp deleted file mode 100644 index efa4cfaa3d..0000000000 --- a/kleopatra/lib/kleo/enum.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - kleo/enum.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "enum.h" - -#include - -#include -#include - -static const struct { - Kleo::CryptoMessageFormat format; - const char * displayName; - const char * configName; -} cryptoMessageFormats[] = { - { Kleo::InlineOpenPGPFormat, - I18N_NOOP("Inline OpenPGP (deprecated)"), - "inline openpgp" }, - { Kleo::OpenPGPMIMEFormat, - I18N_NOOP("OpenPGP/MIME"), - "openpgp/mime" }, - { Kleo::SMIMEFormat, - I18N_NOOP("S/MIME"), - "s/mime" }, - { Kleo::SMIMEOpaqueFormat, - I18N_NOOP("S/MIME Opaque"), - "s/mime opaque" }, -}; -static const unsigned int numCryptoMessageFormats - = sizeof cryptoMessageFormats / sizeof *cryptoMessageFormats ; - -const char * Kleo::cryptoMessageFormatToString( Kleo::CryptoMessageFormat f ) { - if ( f == AutoFormat ) - return "auto"; - for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i ) - if ( f == cryptoMessageFormats[i].format ) - return cryptoMessageFormats[i].configName; - return 0; -} - -QStringList Kleo::cryptoMessageFormatsToStringList( unsigned int f ) { - QStringList result; - for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i ) - if ( f & cryptoMessageFormats[i].format ) - result.push_back( cryptoMessageFormats[i].configName ); - return result; -} - -QString Kleo::cryptoMessageFormatToLabel( Kleo::CryptoMessageFormat f ) { - if ( f == AutoFormat ) - return i18n("Any"); - for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i ) - if ( f == cryptoMessageFormats[i].format ) - return i18n( cryptoMessageFormats[i].displayName ); - return QString::null; -} - -Kleo::CryptoMessageFormat Kleo::stringToCryptoMessageFormat( const QString & s ) { - const QString t = s.lower(); - for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i ) - if ( t == cryptoMessageFormats[i].configName ) - return cryptoMessageFormats[i].format; - return AutoFormat; -} - -unsigned int Kleo::stringListToCryptoMessageFormats( const QStringList & sl ) { - unsigned int result = 0; - for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it ) - result |= stringToCryptoMessageFormat( *it ); - return result; -} - -// For the config values used below, see also kaddressbook/editors/cryptowidget.cpp - -const char* Kleo::encryptionPreferenceToString( EncryptionPreference pref ) -{ - switch( pref ) { - case UnknownPreference: - return 0; - case NeverEncrypt: - return "never"; - case AlwaysEncrypt: - return "always"; - case AlwaysEncryptIfPossible: - return "alwaysIfPossible"; - case AlwaysAskForEncryption: - return "askAlways"; - case AskWheneverPossible: - return "askWhenPossible"; - } - return 0; // keep the compiler happy -} - -Kleo::EncryptionPreference Kleo::stringToEncryptionPreference( const QString& str ) -{ - if ( str == "never" ) - return NeverEncrypt; - if ( str == "always" ) - return AlwaysEncrypt; - if ( str == "alwaysIfPossible" ) - return AlwaysEncryptIfPossible; - if ( str == "askAlways" ) - return AlwaysAskForEncryption; - if ( str == "askWhenPossible" ) - return AskWheneverPossible; - return UnknownPreference; -} - -QString Kleo::encryptionPreferenceToLabel( EncryptionPreference pref ) -{ - switch( pref ) { - case NeverEncrypt: - return i18n( "Never Encrypt" ); - case AlwaysEncrypt: - return i18n( "Always Encrypt" ); - case AlwaysEncryptIfPossible: - return i18n( "Always Encrypt If Possible" ); - case AlwaysAskForEncryption: - return i18n( "Ask" ); - case AskWheneverPossible: - return i18n( "Ask Whenever Possible" ); - default: - return i18n( "no specific preference", "" ); - } -} - -const char* Kleo::signingPreferenceToString( SigningPreference pref ) -{ - switch( pref ) { - case UnknownSigningPreference: - return 0; - case NeverSign: - return "never"; - case AlwaysSign: - return "always"; - case AlwaysSignIfPossible: - return "alwaysIfPossible"; - case AlwaysAskForSigning: - return "askAlways"; - case AskSigningWheneverPossible: - return "askWhenPossible"; - } - return 0; // keep the compiler happy -} - -Kleo::SigningPreference Kleo::stringToSigningPreference( const QString& str ) -{ - if ( str == "never" ) - return NeverSign; - if ( str == "always" ) - return AlwaysSign; - if ( str == "alwaysIfPossible" ) - return AlwaysSignIfPossible; - if ( str == "askAlways" ) - return AlwaysAskForSigning; - if ( str == "askWhenPossible" ) - return AskSigningWheneverPossible; - return UnknownSigningPreference; -} - -QString Kleo::signingPreferenceToLabel( SigningPreference pref ) -{ - switch( pref ) { - case NeverSign: - return i18n( "Never Sign" ); - case AlwaysSign: - return i18n( "Always Sign" ); - case AlwaysSignIfPossible: - return i18n( "Always Sign If Possible" ); - case AlwaysAskForSigning: - return i18n( "Ask" ); - case AskSigningWheneverPossible: - return i18n( "Ask Whenever Possible" ); - default: - return i18n( "no specific preference", "" ); - } -} diff --git a/kleopatra/lib/kleo/enum.h b/kleopatra/lib/kleo/enum.h deleted file mode 100644 index 29f8e2a661..0000000000 --- a/kleopatra/lib/kleo/enum.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - kleo/enum.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_ENUM_H__ -#define __KLEO_ENUM_H__ - -#include - -class QString; -class QStringList; - -namespace Kleo { - - enum CryptoMessageFormat { - InlineOpenPGPFormat = 1, - OpenPGPMIMEFormat = 2, - SMIMEFormat = 4, - SMIMEOpaqueFormat = 8, - AnyOpenPGP = InlineOpenPGPFormat|OpenPGPMIMEFormat, - AnySMIME = SMIMEOpaqueFormat|SMIMEFormat, - AutoFormat = AnyOpenPGP|AnySMIME - }; - - KDE_EXPORT QString cryptoMessageFormatToLabel( CryptoMessageFormat f ); - - KDE_EXPORT const char * cryptoMessageFormatToString( CryptoMessageFormat f ); - KDE_EXPORT QStringList cryptoMessageFormatsToStringList( unsigned int f ); - KDE_EXPORT CryptoMessageFormat stringToCryptoMessageFormat( const QString & s ); - KDE_EXPORT unsigned int stringListToCryptoMessageFormats( const QStringList & sl ); - - enum Action { - Conflict, DoIt, DontDoIt, Ask, AskOpportunistic, Impossible - }; - - enum EncryptionPreference { - UnknownPreference = 0, - NeverEncrypt = 1, - AlwaysEncrypt = 2, - AlwaysEncryptIfPossible = 3, - AlwaysAskForEncryption = 4, - AskWheneverPossible = 5, - MaxEncryptionPreference = AskWheneverPossible - }; - - KDE_EXPORT QString encryptionPreferenceToLabel( EncryptionPreference pref ); - KDE_EXPORT const char* encryptionPreferenceToString( EncryptionPreference pref ); - KDE_EXPORT EncryptionPreference stringToEncryptionPreference( const QString& str ); - - enum SigningPreference { - UnknownSigningPreference = 0, - NeverSign = 1, - AlwaysSign = 2, - AlwaysSignIfPossible = 3, - AlwaysAskForSigning = 4, - AskSigningWheneverPossible = 5, - MaxSigningPreference = AskSigningWheneverPossible - }; - - KDE_EXPORT QString signingPreferenceToLabel( SigningPreference pref ) KDE_EXPORT; - KDE_EXPORT const char* signingPreferenceToString( SigningPreference pref ) KDE_EXPORT; - KDE_EXPORT SigningPreference stringToSigningPreference( const QString& str ); -} - -#endif // __KLEO_CRYPTOBACKEND_H__ diff --git a/kleopatra/lib/kleo/exportjob.h b/kleopatra/lib/kleo/exportjob.h deleted file mode 100644 index d6a0db185b..0000000000 --- a/kleopatra/lib/kleo/exportjob.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - exportjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_EXPORTJOB_H__ -#define __KLEO_EXPORTJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; -} - -class QStringList; - -namespace Kleo { - - /** - @short An abstract base class for asynchronous exporters - - To use a ExportJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the export with a call - to start(). This call might fail, in which case the ExportJob - instance will have scheduled it's own destruction with a call to - QObject::deleteLater(). - - After result() is emitted, the ExportJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class ExportJob : public Job { - Q_OBJECT - protected: - ExportJob( QObject * parent, const char * name ); - public: - ~ExportJob(); - - /** - Starts the export operation. \a patterns is a list of patterns - used to restrict the list of keys exported. Empty patterns are - ignored. If \a patterns is empty or contains only empty - strings, all available keys are exported. - */ - virtual GpgME::Error start( const QStringList & patterns ) = 0; - - signals: - void result( const GpgME::Error & result, const QByteArray & keyData ); - }; - -} - -#endif // __KLEO_EXPORTJOB_H__ diff --git a/kleopatra/lib/kleo/hierarchicalkeylistjob.cpp b/kleopatra/lib/kleo/hierarchicalkeylistjob.cpp deleted file mode 100644 index a7a66b2fe8..0000000000 --- a/kleopatra/lib/kleo/hierarchicalkeylistjob.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* - hierarchicalkeylistjob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "hierarchicalkeylistjob.h" -#include "cryptobackend.h" -#include "keylistjob.h" - -#include - -#include -#include - -#include -#include -#include - -#include - -#include -#include - -#include - -Kleo::HierarchicalKeyListJob::HierarchicalKeyListJob( const CryptoBackend::Protocol * protocol, - bool remote, bool includeSigs, bool validating ) - : KeyListJob( 0, "Kleo::HierarchicalKeyListJob" ), - mProtocol( protocol ), - mRemote( remote ), - mIncludeSigs( includeSigs ), - mValidating( validating ), - mTruncated( false ), - mIntermediateResult(), - mJob( 0 ) -{ - assert( protocol ); -} - -Kleo::HierarchicalKeyListJob::~HierarchicalKeyListJob() { - -} - -GpgME::Error Kleo::HierarchicalKeyListJob::start( const QStringList & patterns, bool secretOnly ) { - if ( secretOnly || patterns.empty() ) - return gpg_err_make( GPG_ERR_SOURCE_GPGME, GPG_ERR_UNSUPPORTED_OPERATION ); - qCopy( patterns.begin(), patterns.end(), - std::inserter( mNextSet, mNextSet.begin() ) ); - const GpgME::Error err = startAJob(); - if ( err ) - deleteLater(); - return err; -} - -GpgME::KeyListResult Kleo::HierarchicalKeyListJob::exec( const QStringList &, bool, - std::vector & keys ) { - keys.clear(); - return GpgME::KeyListResult( gpg_err_make( GPG_ERR_SOURCE_GPGME, GPG_ERR_UNSUPPORTED_OPERATION ) ); -} - -void Kleo::HierarchicalKeyListJob::slotNextKey( const GpgME::Key & key ) { - if ( const char * chain_id = key.chainID() ) - mNextSet.insert( chain_id ); - if ( const char * fpr = key.primaryFingerprint() ) - if ( mSentSet.find( fpr ) == mSentSet.end() ) { - mSentSet.insert( fpr ); - emit nextKey( key ); - } -} - -void Kleo::HierarchicalKeyListJob::slotCancel() { - if ( mJob ) mJob->slotCancel(); - mNextSet.clear(); -} - -void Kleo::HierarchicalKeyListJob::slotResult( const GpgME::KeyListResult & res ) { - mJob = 0; - mIntermediateResult.mergeWith( res ); - std::set tmp; - std::set_difference( mNextSet.begin(), mNextSet.end(), - mScheduledSet.begin(), mScheduledSet.end(), - std::inserter( tmp, tmp.begin() ) ); - mNextSet.clear(); - std::set_difference( tmp.begin(), tmp.end(), - mSentSet.begin(), mSentSet.end(), - std::inserter( mNextSet, mNextSet.begin() ) ); - if ( mIntermediateResult.error() || mNextSet.empty() ) { - emit done(); - emit result( mIntermediateResult ); - deleteLater(); - return; - } - if ( const GpgME::Error error = startAJob() ) { // error starting the job for next keys - mIntermediateResult.mergeWith( GpgME::KeyListResult( error ) ); - emit done(); - emit result( mIntermediateResult ); - deleteLater(); - return; - } -#if 0 // FIXME - const int current = mIt - mKeys.begin(); - const int total = mKeys.size(); - emit progress( i18n("progress info: \"%1 of %2\"","%1/%2").arg( current ).arg( total ), current, total ); -#endif -} - -GpgME::Error Kleo::HierarchicalKeyListJob::startAJob() { - if ( mNextSet.empty() ) - return 0; - mJob = mProtocol->keyListJob( mRemote, mIncludeSigs, mValidating ); - assert( mJob ); // FIXME: we need a way to generate errors ourselves, - // but I don't like the dependency on gpg-error :/ - - connect( mJob, SIGNAL(nextKey(const GpgME::Key&)), SLOT(slotNextKey(const GpgME::Key&)) ); - connect( mJob, SIGNAL(result(const GpgME::KeyListResult&)), SLOT(slotResult(const GpgME::KeyListResult&)) ); - - QStringList patterns; - for ( std::set::const_iterator it = mNextSet.begin() ; it != mNextSet.end() ; ++it ) - patterns.push_back( *it ); - - mScheduledSet.insert( mNextSet.begin(), mNextSet.end() ); - mNextSet.clear(); - - return mJob->start( patterns, false ); -} - -#include "hierarchicalkeylistjob.moc" diff --git a/kleopatra/lib/kleo/hierarchicalkeylistjob.h b/kleopatra/lib/kleo/hierarchicalkeylistjob.h deleted file mode 100644 index a91ff6dc08..0000000000 --- a/kleopatra/lib/kleo/hierarchicalkeylistjob.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - hierarchicalkeylistjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_HIERARCHICALKEYLISTJOB_H__ -#define __KLEO_HIERARCHICALKEYLISTJOB_H__ - -#include -#include -#include - -#include - -#include -#include - -#include - -namespace GpgME { - class Error; - class Key; -} - -namespace Kleo { - class KeyListJob; -} - -namespace Kleo { - - /** - @short A convenience job that additionally fetches all available issuers. - - To use a HierarchicalKeyListJob, pass it a CryptoBackend - implementation, connect the progress() and result() signals to - suitable slots and then start the keylisting with a call to - start(). This call might fail, in which case the - HierarchicalKeyListJob instance will have scheduled it's own - destruction with a call to QObject::deleteLater(). - - After result() is emitted, the HierarchicalKeyListJob will - schedule its own destruction by calling QObject::deleteLater(). - */ - class KDE_EXPORT HierarchicalKeyListJob : public KeyListJob { - Q_OBJECT - public: - HierarchicalKeyListJob( const CryptoBackend::Protocol * protocol, - bool remote=false, bool includeSigs=false, bool validating=false ); - ~HierarchicalKeyListJob(); - - /** - Starts the keylist operation. \a patterns is a list of patterns - used to restrict the list of keys returned. Empty patterns are - ignored. \a patterns must not be empty or contain only empty - patterns; use the normal KeyListJob for a full listing. - - The \a secretOnly parameter is ignored by - HierarchicalKeyListJob and must be set to false. - */ - GpgME::Error start( const QStringList & patterns, bool secretOnly=false ); - - GpgME::KeyListResult exec( const QStringList & patterns, bool secretOnly, - std::vector & keys ); - - private slots: - void slotResult( const GpgME::KeyListResult & ); - void slotNextKey( const GpgME::Key & key ); - /*! \reimp from Job */ - void slotCancel(); - - private: - GpgME::Error startAJob(); - - private: - const CryptoBackend::Protocol * const mProtocol; - const bool mRemote; - const bool mIncludeSigs; - const bool mValidating; - bool mTruncated; - std::set mSentSet; // keys already sent (prevent duplicates even if the backend should return them) - std::set mScheduledSet; // keys already scheduled (by starting a job for them) - std::set mNextSet; // keys to schedule for the next iteraton - GpgME::KeyListResult mIntermediateResult; - QGuardedPtr mJob; - }; - -} - -#endif // __KLEO_HIERARCHICALKEYLISTJOB_H__ diff --git a/kleopatra/lib/kleo/importjob.h b/kleopatra/lib/kleo/importjob.h deleted file mode 100644 index 10aa903836..0000000000 --- a/kleopatra/lib/kleo/importjob.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - importjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_IMPORTJOB_H__ -#define __KLEO_IMPORTJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; - class Key; - class ImportResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous importers - - To use a ImportJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the import with a call - to start(). This call might fail, in which case the ImportJob - instance will have scheduled it's own destruction with a call to - QObject::deleteLater(). - - After result() is emitted, the ImportJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class ImportJob : public Job { - Q_OBJECT - protected: - ImportJob( QObject * parent, const char * name ); - public: - ~ImportJob(); - - /** - Starts the importing operation. \a keyData contains the data to - import from. - */ - virtual GpgME::Error start( const QByteArray & keyData ) = 0; - - virtual GpgME::ImportResult exec( const QByteArray & keyData ) = 0; - - signals: - void result( const GpgME::ImportResult & result ); - }; - -} - -#endif // __KLEO_IMPORTJOB_H__ diff --git a/kleopatra/lib/kleo/job.cpp b/kleopatra/lib/kleo/job.cpp deleted file mode 100644 index abccca7b38..0000000000 --- a/kleopatra/lib/kleo/job.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* - job.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "job.h" - -#include "keylistjob.h" -#include "encryptjob.h" -#include "decryptjob.h" -#include "decryptverifyjob.h" -#include "signjob.h" -#include "signencryptjob.h" -#include "verifydetachedjob.h" -#include "verifyopaquejob.h" -#include "keygenerationjob.h" -#include "importjob.h" -#include "exportjob.h" -#include "downloadjob.h" -#include "deletejob.h" -#include "refreshkeysjob.h" -#include "specialjob.h" - -#include -#include - -Kleo::Job::Job( QObject * parent, const char * name ) - : QObject( parent, name ) -{ - if ( qApp ) - connect( qApp, SIGNAL(aboutToQuit()), SLOT(slotCancel()) ); -} - -Kleo::Job::~Job() { - -} - -void Kleo::Job::showErrorDialog( QWidget *, const QString & ) const { - kdDebug() << "Kleo::Job::showErrorDialog() should be reimplemented in Kleo::Job subclasses!" << endl; -} - - - -#define make_job_subclass(x) \ - Kleo::x::x( QObject * parent, const char * name ) : Job( parent, name ) {} \ - Kleo::x::~x() {} - -make_job_subclass(KeyListJob) -make_job_subclass(EncryptJob) -make_job_subclass(DecryptJob) -make_job_subclass(DecryptVerifyJob) -make_job_subclass(SignJob) -make_job_subclass(SignEncryptJob) -make_job_subclass(VerifyDetachedJob) -make_job_subclass(VerifyOpaqueJob) -make_job_subclass(KeyGenerationJob) -make_job_subclass(ImportJob) -make_job_subclass(ExportJob) -make_job_subclass(DownloadJob) -make_job_subclass(DeleteJob) -make_job_subclass(RefreshKeysJob) -make_job_subclass(SpecialJob) - -#undef make_job_subclass - -#include "job.moc" - -#include "keylistjob.moc" -#include "encryptjob.moc" -#include "decryptjob.moc" -#include "decryptverifyjob.moc" -#include "signjob.moc" -#include "signencryptjob.moc" -#include "verifydetachedjob.moc" -#include "verifyopaquejob.moc" -#include "keygenerationjob.moc" -#include "importjob.moc" -#include "exportjob.moc" -#include "downloadjob.moc" -#include "deletejob.moc" -#include "refreshkeysjob.moc" -#include "specialjob.moc" diff --git a/kleopatra/lib/kleo/job.h b/kleopatra/lib/kleo/job.h deleted file mode 100644 index 6b762a04b3..0000000000 --- a/kleopatra/lib/kleo/job.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - job.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_JOB_H__ -#define __KLEO_JOB_H__ - -#include -#include - -class QWidget; - -namespace Kleo { - - /** - @short An abstract base class for asynchronous crypto operations - - During the operation, you might receive progress updates through - the progress() signal as they arrive, but an implementation is - free to not send progress information. You should show a busy - progressbar until the first progress() signal is received. - - The done() signal is emitted _before_ the result() signals of - subclasses and should be used to hide and/or reset progress bars, - not to learn of the end of the operation. Use the result() - signals for that. - - To cancel the operation, simply call slotCancel(). The result() - signal of subclasses will still be emitted, though, and will - carry the information that the operation was canceled. - */ - class Job : public QObject { - Q_OBJECT - protected: - Job( QObject * parent, const char * name ); - public: - ~Job(); - - virtual void showErrorDialog( QWidget * parent=0, const QString & caption=QString::null ) const; - - public slots: - virtual void slotCancel() = 0; - - signals: - void progress( const QString & what, int current, int total ); - void done(); - }; - -} - -#endif // __KLEO_JOB_H__ diff --git a/kleopatra/lib/kleo/kconfigbasedkeyfilter.cpp b/kleopatra/lib/kleo/kconfigbasedkeyfilter.cpp deleted file mode 100644 index 89d18e799b..0000000000 --- a/kleopatra/lib/kleo/kconfigbasedkeyfilter.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* - kconfigbasedkeyfilter.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "kconfigbasedkeyfilter.h" - -#include -#include - -static const struct { - const char * name; - GpgME::Key::OwnerTrust trust; - GpgME::UserID::Validity validity; -} ownerTrustAndValidityMap[] = { - { "unknown", GpgME::Key::Unknown, GpgME::UserID::Unknown }, - { "undefined", GpgME::Key::Undefined, GpgME::UserID::Undefined }, - { "never", GpgME::Key::Never, GpgME::UserID::Never }, - { "marginal", GpgME::Key::Marginal, GpgME::UserID::Marginal }, - { "full", GpgME::Key::Full, GpgME::UserID::Full }, - { "ultimate", GpgME::Key::Ultimate, GpgME::UserID::Ultimate }, -}; - -static GpgME::Key::OwnerTrust map2OwnerTrust( const QString & s ) { - for ( unsigned int i = 0 ; i < sizeof ownerTrustAndValidityMap / sizeof *ownerTrustAndValidityMap ; ++i ) - if ( s.lower() == ownerTrustAndValidityMap[i].name ) - return ownerTrustAndValidityMap[i].trust; - return ownerTrustAndValidityMap[0].trust; -} - -static GpgME::UserID::Validity map2Validity( const QString & s ) { - for ( unsigned int i = 0 ; i < sizeof ownerTrustAndValidityMap / sizeof *ownerTrustAndValidityMap ; ++i ) - if ( s.lower() == ownerTrustAndValidityMap[i].name ) - return ownerTrustAndValidityMap[i].validity; - return ownerTrustAndValidityMap[0].validity; -} - - -Kleo::KConfigBasedKeyFilter::KConfigBasedKeyFilter( const KConfigBase & config ) - : KeyFilter(), - mSpecificity( 0 ), - mItalic( false ), - mBold( false ), - mStrikeOut( false ), - mUseFullFont( false ), - mRevoked( DoesNotMatter ), - mExpired( DoesNotMatter ), - mDisabled( DoesNotMatter ), - mRoot( DoesNotMatter ), - mCanEncrypt( DoesNotMatter ), - mCanSign( DoesNotMatter ), - mCanCertify( DoesNotMatter ), - mCanAuthenticate( DoesNotMatter ), - mHasSecret( DoesNotMatter ), - mIsOpenPGP( DoesNotMatter ), - mWasValidated( DoesNotMatter ), - mOwnerTrust( LevelDoesNotMatter ), - mOwnerTrustReferenceLevel( GpgME::Key::Unknown ), - mValidity( LevelDoesNotMatter ), - mValidityReferenceLevel( GpgME::UserID::Unknown ) -{ - mFgColor = config.readColorEntry( "foreground-color" ); - mBgColor = config.readColorEntry( "background-color" ); - mName = config.readEntry( "name", i18n("") ); - mIcon = config.readEntry( "icon" ); - if ( config.hasKey( "font" ) ) { - mUseFullFont = true; - mFont = config.readFontEntry( "font" ); - } else { - mItalic = config.readBoolEntry( "font-italic", false ); - mBold = config.readBoolEntry( "font-bold", false ); - } - mStrikeOut = config.readBoolEntry( "font-strikeout", false ); -#ifdef SET -#undef SET -#endif -#define SET(member,key) \ - if ( config.hasKey( key ) ) { \ - member = config.readBoolEntry( key ) ? Set : NotSet ; \ - ++mSpecificity; \ - } - SET( mRevoked, "is-revoked" ); - SET( mExpired, "is-expired" ); - SET( mDisabled, "is-disabled" ); - SET( mRoot, "is-root-certificate" ); - SET( mCanEncrypt, "can-encrypt" ); - SET( mCanSign, "can-sign" ); - SET( mCanCertify, "can-certify" ); - SET( mCanAuthenticate, "can-authenticate" ); - SET( mHasSecret, "has-secret-key" ); - SET( mIsOpenPGP, "is-openpgp-key" ); - SET( mWasValidated, "was-validated" ); -#undef SET - static const struct { - const char * prefix; - LevelState state; - } prefixMap[] = { - { "is-", Is }, - { "is-not-", IsNot }, - { "is-at-least-", IsAtLeast }, - { "is-at-most-", IsAtMost }, - }; - for ( unsigned int i = 0 ; i < sizeof prefixMap / sizeof *prefixMap ; ++i ) { - const QString key = QString( prefixMap[i].prefix ) + "ownertrust"; - if ( config.hasKey( key ) ) { - mOwnerTrust = prefixMap[i].state; - mOwnerTrustReferenceLevel = map2OwnerTrust( config.readEntry( key ) ); - ++mSpecificity; - break; - } - } - for ( unsigned int i = 0 ; i < sizeof prefixMap / sizeof *prefixMap ; ++i ) { - const QString key = QString( prefixMap[i].prefix ) + "validity"; - if ( config.hasKey( key ) ) { - mValidity = prefixMap[i].state; - mValidityReferenceLevel = map2Validity( config.readEntry( key ) ); - ++mSpecificity; - break; - } - } -} - -Kleo::KConfigBasedKeyFilter::~KConfigBasedKeyFilter() { - -} - -bool Kleo::KConfigBasedKeyFilter::matches( const GpgME::Key & key ) const { -#ifdef MATCH -#undef MATCH -#endif -#define MATCH(member,method) \ - if ( member != DoesNotMatter && key.method() != bool( member == Set ) ) \ - return false -#define IS_MATCH(what) MATCH( m##what, is##what ) -#define CAN_MATCH(what) MATCH( mCan##what, can##what ) - IS_MATCH( Revoked ); - IS_MATCH( Expired ); - IS_MATCH( Disabled ); - IS_MATCH( Root ); - CAN_MATCH( Encrypt ); - CAN_MATCH( Sign ); - CAN_MATCH( Certify ); - CAN_MATCH( Authenticate ); - MATCH( mHasSecret, isSecret ); -#undef MATCH - if ( mIsOpenPGP != DoesNotMatter && - bool( key.protocol() == GpgME::Context::OpenPGP ) != bool( mIsOpenPGP == Set ) ) - return false; - if ( mWasValidated != DoesNotMatter && - bool( key.keyListMode() & GpgME::Context::Validate ) != bool( mWasValidated == Set ) ) - return false; - switch ( mOwnerTrust ) { - default: - case LevelDoesNotMatter: - break; - case Is: - if ( key.ownerTrust() != mOwnerTrustReferenceLevel ) - return false; - break; - case IsNot: - if ( key.ownerTrust() == mOwnerTrustReferenceLevel ) - return false; - break; - case IsAtLeast: - if ( (int)key.ownerTrust() < (int)mOwnerTrustReferenceLevel ) - return false; - break; - case IsAtMost: - if ( (int)key.ownerTrust() > (int)mOwnerTrustReferenceLevel ) - return false; - break; - } - const GpgME::UserID uid = key.userID(0); - switch ( mValidity ) { - default: - case LevelDoesNotMatter: - break; - case Is: - if ( uid.validity() != mValidityReferenceLevel ) - return false; - break; - case IsNot: - if ( uid.validity() == mValidityReferenceLevel ) - return false; - break; - case IsAtLeast: - if ( (int)uid.validity() < (int)mValidityReferenceLevel ) - return false; - break; - case IsAtMost: - if ( (int)uid.validity() > (int)mValidityReferenceLevel ) - return false; - break; - } - return true; -} - -static inline QFont resizedFont( QFont font, int pointSize, bool strike ) { - font.setPointSize( pointSize ); - if ( strike ) - font.setStrikeOut( true ); - return font; -} - -static inline QFont adapt( QFont font, bool it, bool b, bool strike ) { - if ( it ) - font.setItalic( true ); - if ( b ) - font.setBold( true ); - if ( strike ) - font.setStrikeOut( true ); - return font; -} - -QFont Kleo::KConfigBasedKeyFilter::font( const QFont & f ) const { - if ( mUseFullFont ) - return resizedFont( mFont, f.pointSize(), mStrikeOut ); - else - return adapt( f, mItalic, mBold, mStrikeOut ); -} diff --git a/kleopatra/lib/kleo/kconfigbasedkeyfilter.h b/kleopatra/lib/kleo/kconfigbasedkeyfilter.h deleted file mode 100644 index 42c0830809..0000000000 --- a/kleopatra/lib/kleo/kconfigbasedkeyfilter.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - kconfigbasedkeyfilter.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KCONFIGBASEDKEYFILTER_H__ -#define __KLEO_KCONFIGBASEDKEYFILTER_H__ - -#include "keyfilter.h" - -#include -#include -#include - -#include - -class KConfigBase; - -namespace Kleo { - - class KConfigBasedKeyFilter : public KeyFilter { - public: - explicit KConfigBasedKeyFilter( const KConfigBase & config ); - ~KConfigBasedKeyFilter(); - bool matches( const GpgME::Key & key ) const; - - unsigned int specificity() const { return mSpecificity; } - - QColor fgColor() const { return mFgColor; } - QColor bgColor() const { return mBgColor; } - QFont font( const QFont & ) const; - QString name() const { return mName; } - QString icon() const { return mIcon; } - - private: - QColor mFgColor, mBgColor; - QString mName; - QString mIcon; - unsigned int mSpecificity; - bool mItalic; - bool mBold; - bool mStrikeOut; - bool mUseFullFont; - QFont mFont; - - enum TriState { - DoesNotMatter = 0, - Set = 1, - NotSet = 2 - }; - TriState mRevoked; - TriState mExpired; - TriState mDisabled; - TriState mRoot; - TriState mCanEncrypt; - TriState mCanSign; - TriState mCanCertify; - TriState mCanAuthenticate; - TriState mHasSecret; - TriState mIsOpenPGP; - TriState mWasValidated; - enum LevelState { - LevelDoesNotMatter = 0, - Is = 1, - IsNot = 2, - IsAtLeast = 3, - IsAtMost = 4 - }; - LevelState mOwnerTrust; - GpgME::Key::OwnerTrust mOwnerTrustReferenceLevel; - LevelState mValidity; - GpgME::UserID::Validity mValidityReferenceLevel; - }; - -} - -#endif // __KLEO_KCONFIGBASEDKEYFILTER_H__ diff --git a/kleopatra/lib/kleo/keyfilter.h b/kleopatra/lib/kleo/keyfilter.h deleted file mode 100644 index f10fba9bf4..0000000000 --- a/kleopatra/lib/kleo/keyfilter.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - keyfilter.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KEYFILTER_H__ -#define __KLEO_KEYFILTER_H__ - -namespace GpgME { - class Key; -} - -class QFont; -class QColor; -class QString; - -namespace Kleo { - - /** - @short An abstract base class key filters - - */ - class KeyFilter { - public: - virtual ~KeyFilter() {} - virtual bool matches( const GpgME::Key & key ) const = 0; - - virtual unsigned int specificity() const = 0; - - // not sure if we want these here, but for the time being, it's - // the easiest way: - virtual QColor fgColor() const = 0; - virtual QColor bgColor() const = 0; - virtual QFont font( const QFont & ) const = 0; - virtual QString name() const = 0; - virtual QString icon() const = 0; - }; - -} - -#endif // __KLEO_KEYFILTER_H__ diff --git a/kleopatra/lib/kleo/keyfiltermanager.cpp b/kleopatra/lib/kleo/keyfiltermanager.cpp deleted file mode 100644 index 14932801c9..0000000000 --- a/kleopatra/lib/kleo/keyfiltermanager.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - keyfiltermanager.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "keyfiltermanager.h" -#include "kconfigbasedkeyfilter.h" - -#include "cryptobackendfactory.h" - -#include - -#include -#include -#include -#include - -#include - -namespace { - template - struct Delete { - void operator()( T * item ) { delete item; } - }; -} - -struct Kleo::KeyFilterManager::Private { - void clear() { - std::for_each( filters.begin(), filters.end(), Delete() ); - filters.clear(); - } - - QValueVector filters; -}; - -Kleo::KeyFilterManager * Kleo::KeyFilterManager::mSelf = 0; - -Kleo::KeyFilterManager::KeyFilterManager( QObject * parent, const char * name ) - : QObject( parent, name ), d( 0 ) -{ - mSelf = this; - d = new Private(); - // ### DF: doesn't a KStaticDeleter work more reliably? - if ( qApp ) - connect( qApp, SIGNAL(aboutToQuit()), SLOT(deleteLater()) ); - reload(); -} - -Kleo::KeyFilterManager::~KeyFilterManager() { - mSelf = 0; - if ( d ) - d->clear(); - delete d; d = 0; -} - -Kleo::KeyFilterManager * Kleo::KeyFilterManager::instance() { - if ( !mSelf ) - mSelf = new Kleo::KeyFilterManager(); - return mSelf; -} - -const Kleo::KeyFilter * Kleo::KeyFilterManager::filterMatching( const GpgME::Key & key ) const { - for ( QValueVector::const_iterator it = d->filters.begin() ; it != d->filters.end() ; ++it ) - if ( (*it)->matches( key ) ) - return *it; - return 0; -} - -static inline bool by_increasing_specificity( const Kleo::KeyFilter * left, const Kleo::KeyFilter * right ) { - return left->specificity() > right->specificity(); -} - -void Kleo::KeyFilterManager::reload() { - d->clear(); - - KConfig * config = Kleo::CryptoBackendFactory::instance()->configObject(); - if ( !config ) - return; - const QStringList groups = config->groupList().grep( QRegExp( "^Key Filter #\\d+$" ) ); - for ( QStringList::const_iterator it = groups.begin() ; it != groups.end() ; ++it ) { - const KConfigGroup cfg( config, *it ); - d->filters.push_back( new KConfigBasedKeyFilter( cfg ) ); - } - std::stable_sort( d->filters.begin(), d->filters.end(), by_increasing_specificity ); -} - -#include "keyfiltermanager.moc" diff --git a/kleopatra/lib/kleo/keyfiltermanager.h b/kleopatra/lib/kleo/keyfiltermanager.h deleted file mode 100644 index 25353d71aa..0000000000 --- a/kleopatra/lib/kleo/keyfiltermanager.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - keyfiltermanager.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KEYFILTERMANAGER_H__ -#define __KLEO_KEYFILTERMANAGER_H__ - -#include -#include -namespace GpgME { - class Key; -} - -namespace Kleo { - class KeyFilter; -} - -namespace Kleo { - - class KDE_EXPORT KeyFilterManager : public QObject { - Q_OBJECT - protected: - KeyFilterManager( QObject * parent=0, const char * name=0 ); - ~KeyFilterManager(); - - public: - static KeyFilterManager * instance(); - - const KeyFilter * filterMatching( const GpgME::Key & key ) const; - - void reload(); - - private: - class Private; - Private * d; - static KeyFilterManager * mSelf; - }; - -} - -#endif // __KLEO_KEYFILTERMANAGER_H__ diff --git a/kleopatra/lib/kleo/keygenerationjob.h b/kleopatra/lib/kleo/keygenerationjob.h deleted file mode 100644 index f78152c5c2..0000000000 --- a/kleopatra/lib/kleo/keygenerationjob.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - keygenerationjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KEYGENERATIONJOB_H__ -#define __KLEO_KEYGENERATIONJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; - class KeyGenerationResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous key generation - - To use a KeyGenerationJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the key generation with - a call to start(). This call might fail, in which case the - KeyGenerationJob instance will have scheduled it's own - destruction with a call to QObject::deleteLater(). - - After result() is emitted, the KeyGenerationJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class KeyGenerationJob : public Job { - Q_OBJECT - protected: - KeyGenerationJob( QObject * parent, const char * name ); - public: - ~KeyGenerationJob(); - - /** - Starts the key generation operation. \a parameters is a - backend-specific string containing the paramaters of the key to - create (length, capabilities, etc). - */ - virtual GpgME::Error start( const QString & parameters ) = 0; - - signals: - void result( const GpgME::KeyGenerationResult & result, const QByteArray & pubKeyData ); - }; - -} - -#endif // __KLEO_KEYGENERATIONJOB_H__ diff --git a/kleopatra/lib/kleo/keylistjob.h b/kleopatra/lib/kleo/keylistjob.h deleted file mode 100644 index c419ad47d7..0000000000 --- a/kleopatra/lib/kleo/keylistjob.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - keylistjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KEYLISTJOB_H__ -#define __KLEO_KEYLISTJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; - class Key; - class KeyListResult; -} - -class QStringList; - -namespace Kleo { - - /** - @short An abstract base class for asynchronous key listers - - To use a KeyListJob, first obtain an instance from the - CryptoBackend implementation, connect the nextKey(), progress() - and result() signals to suitable slots and then start the key - listing with a call to start(). This call might fail, in which - case the KeylistJob instance will have schedules it's own - destruction with a call to QObject::deleteLater(). - - During keylisting, you will receive new key objects through the - nextKey() signal as they arrive. After result() is emitted, the - KeyListJob will schedule it's own destruction by calling - QObject::deleteLater(). - */ - class KeyListJob : public Job { - Q_OBJECT - protected: - KeyListJob( QObject * parent, const char * name ); - - public: - ~KeyListJob(); - - /** - Starts the keylist operation. \a pattern is a list of patterns - used to restrict the list of keys returned. Empty patterns are - ignored. If \a pattern is empty or contains only empty strings, - all keys are returned (however, the backend is free to truncate - the result and should do so; when this happens, it will be - reported by the reult object). - - If \a secretOnly is true, only keys for which the secret key is - also available are returned. Use this if you need to select a - key for signing. - */ - virtual GpgME::Error start( const QStringList & patterns, bool secretOnly=false ) = 0; - - virtual GpgME::KeyListResult exec( const QStringList & patterns, bool secretOnly, std::vector & keys ) = 0; - - signals: - void nextKey( const GpgME::Key & key ); - void result( const GpgME::KeyListResult & result ); - }; - -} - -#endif // __KLEO_KEYLISTJOB_H__ diff --git a/kleopatra/lib/kleo/multideletejob.cpp b/kleopatra/lib/kleo/multideletejob.cpp deleted file mode 100644 index 32596e78f7..0000000000 --- a/kleopatra/lib/kleo/multideletejob.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* - multideletejob.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "multideletejob.h" -#include "cryptobackend.h" -#include "deletejob.h" - -#include - -#include -#include -#include - -#include - -#include - -Kleo::MultiDeleteJob::MultiDeleteJob( const CryptoBackend::Protocol * protocol ) - : Job( 0, "Kleo::MultiDeleteJob" ), - mProtocol( protocol ), - mJob( 0 ) -{ - assert( protocol ); -} - -Kleo::MultiDeleteJob::~MultiDeleteJob() { - -} - -GpgME::Error Kleo::MultiDeleteJob::start( const std::vector & keys, bool allowSecretKeyDeletion ) { - mKeys = keys; - mAllowSecretKeyDeletion = allowSecretKeyDeletion; - mIt = mKeys.begin(); - - const GpgME::Error err = startAJob(); - - if ( err ) - deleteLater(); - return err; -} - -void Kleo::MultiDeleteJob::slotCancel() { - if ( mJob ) mJob->slotCancel(); - mIt = mKeys.end(); -} - -void Kleo::MultiDeleteJob::slotResult( const GpgME::Error & err ) { - mJob = 0; - GpgME::Error error = err; - if ( error || // error in last op - mIt == mKeys.end() || // (shouldn't happen) - ++mIt == mKeys.end() || // was the last key - (error = startAJob()) ) { // error starting the job for the new key - emit done(); - emit result( error, error && mIt != mKeys.end() ? *mIt : GpgME::Key::null ); - deleteLater(); - return; - } - - const int current = mIt - mKeys.begin(); - const int total = mKeys.size(); - emit progress( i18n("progress info: \"%1 of %2\"","%1/%2").arg( current ).arg( total ), current, total ); -} - -GpgME::Error Kleo::MultiDeleteJob::startAJob() { - if ( mIt == mKeys.end() ) - return 0; - mJob = mProtocol->deleteJob(); - assert( mJob ); // FIXME: we need a way to generate errors ourselves, - // but I don't like the dependency on gpg-error :/ - - connect( mJob, SIGNAL(result(const GpgME::Error&)), SLOT(slotResult(const GpgME::Error&)) ); - - return mJob->start( *mIt, mAllowSecretKeyDeletion ); -} - -#include "multideletejob.moc" diff --git a/kleopatra/lib/kleo/multideletejob.h b/kleopatra/lib/kleo/multideletejob.h deleted file mode 100644 index 5b995adaf9..0000000000 --- a/kleopatra/lib/kleo/multideletejob.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - multideletejob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_MULTIDELETEJOB_H__ -#define __KLEO_MULTIDELETEJOB_H__ - -#include -#include - -#include -#include - -#include - -namespace GpgME { - class Error; - class Key; -} - -namespace Kleo { - class DeleteJob; -} - -namespace Kleo { - - /** - @short A convenience class bundling together multiple DeleteJobs. - - To use a MultiDeleteJob, pass it a CryptoBackend implementation, - connect the progress() and result() signals to suitable slots and - then start the delete with a call to start(). This call might - fail, in which case the MultiDeleteJob instance will have scheduled - it's own destruction with a call to QObject::deleteLater(). - - After result() is emitted, the MultiDeleteJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class KDE_EXPORT MultiDeleteJob : public Job { - Q_OBJECT - public: - MultiDeleteJob( const CryptoBackend::Protocol * protocol ); - ~MultiDeleteJob(); - - /** - Starts the delete operation. \a keys is the list of keys to - delete, \a allowSecretKeyDeletion specifies if a key may also - be deleted if the secret key part is available, too. - */ - GpgME::Error start( const std::vector & keys, bool allowSecretKeyDeletion=false ); - - signals: - void result( const GpgME::Error & result, const GpgME::Key & errorKey ); - - private slots: - void slotResult( const GpgME::Error & ); - /*! \reimp from Job */ - void slotCancel(); - - private: - GpgME::Error startAJob(); - - private: - const CryptoBackend::Protocol * mProtocol; - QGuardedPtr mJob; - std::vector mKeys; - std::vector::const_iterator mIt; - bool mAllowSecretKeyDeletion; - }; - -} - -#endif // __KLEO_MULTIDELETEJOB_H__ diff --git a/kleopatra/lib/kleo/oidmap.h b/kleopatra/lib/kleo/oidmap.h deleted file mode 100644 index 5962963329..0000000000 --- a/kleopatra/lib/kleo/oidmap.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - oidmap.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_OIDMAP_H__ -#define __KLEO_OIDMAP_H__ - -static struct { - const char * name; - const char * oid; -} oidmap[] = { - // keep them ordered by oid: - { "SP", "ST" }, // hack to show the Sphinx-required/desired SP for - // StateOrProvince, otherwise known as ST or even S - { "NameDistinguisher", "0.2.262.1.10.7.20" }, - { "EMAIL", "1.2.840.113549.1.9.1" }, - { "SN", "2.5.4.4" }, - { "SerialNumber", "2.5.4.5" }, - { "T", "2.5.4.12" }, - { "D", "2.5.4.13" }, - { "BC", "2.5.4.15" }, - { "ADDR", "2.5.4.16" }, - { "PC", "2.5.4.17" }, - { "GN", "2.5.4.42" }, - { "Pseudo", "2.5.4.65" }, -}; -static const unsigned int numOidMaps = sizeof oidmap / sizeof *oidmap; - -#endif // __KLEO_OIDMAP_H__ diff --git a/kleopatra/lib/kleo/refreshkeysjob.h b/kleopatra/lib/kleo/refreshkeysjob.h deleted file mode 100644 index dcf9cd516c..0000000000 --- a/kleopatra/lib/kleo/refreshkeysjob.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - refreshkeysjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_REFRESHKEYSJOB_H__ -#define __KLEO_REFRESHKEYSJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; - class Key; -} - -class QStringList; - -namespace Kleo { - - /** - @short An abstract base class for asynchronous key refreshers. - - To use a RefreshKeysJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the key refresh with a - call to start(). This call might fail, in which case the - RefreshKeysJob instance will have scheduled its own destruction - with a call to QObject::deleteLater(). - - After result() is emitted, the KeyListJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class RefreshKeysJob : public Job { - Q_OBJECT - protected: - RefreshKeysJob( QObject * parent, const char * name ); - - public: - ~RefreshKeysJob(); - - /** - Starts the keylist operation. \a pattern is a list of patterns - used to restrict the list of keys returned. Empty patterns are - ignored. If \a pattern is empty or contains only empty strings, - all keys are returned (however, the backend is free to truncate - the result and should do so; when this happens, it will be - reported by the reult object). - - If \a secretOnly is true, only keys for which the secret key is - also available are returned. Use this if you need to select a - key for signing. - */ - virtual GpgME::Error start( const QStringList & patterns ) = 0; - - signals: - void result( const GpgME::Error & error ); - }; - -} - -#endif // __KLEO_REFRESHKEYSJOB_H__ diff --git a/kleopatra/lib/kleo/signencryptjob.h b/kleopatra/lib/kleo/signencryptjob.h deleted file mode 100644 index 42d3a179f8..0000000000 --- a/kleopatra/lib/kleo/signencryptjob.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - signencryptjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_SIGNENCRYPTJOB_H__ -#define __KLEO_SIGNENCRYPTJOB_H__ - -#include // for Context::SignatureMode (or should - // we roll our own enum here?) -#include "job.h" -#include - -#include -#include - -namespace GpgME { - class Error; - class Key; - class SigningResult; - class EncryptionResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous combined signing and encrypting - - To use a SignEncryptJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the operation with a - call to start(). This call might fail, in which case the - SignEncryptJob instance will have scheduled it's own destruction - with a call to QObject::deleteLater(). - - After result() is emitted, the SignEncryptJob will schedule it's - own destruction by calling QObject::deleteLater(). - */ - class SignEncryptJob : public Job { - Q_OBJECT - protected: - SignEncryptJob( QObject * parent, const char * name ); - public: - ~SignEncryptJob(); - - /** - Starts the combined signing and encrypting operation. \a signers - is the list of keys to sign \a plainText with. \a recipients is - a list of keys to encrypt the signed \a plainText to. In both - lists, empty (null) keys are ignored. - - If \a alwaysTrust is true, validity checking for the - \em recipient keys will not be performed, but full validity - assumed for all \em recipient keys without further checks. - */ - virtual GpgME::Error start( const std::vector & signers, - const std::vector & recipients, - const QByteArray & plainText, - bool alwaysTrust=false ) = 0; - - virtual std::pair - exec( const std::vector & signers, - const std::vector & recipients, - const QByteArray & plainText, - bool alwaysTrust, QByteArray & cipherText ) = 0; - - signals: - void result( const GpgME::SigningResult & signingresult, - const GpgME::EncryptionResult & encryptionresult, - const QByteArray & cipherText ); - }; - -} - -#endif // __KLEO_SIGNENCRYPTJOB_H__ diff --git a/kleopatra/lib/kleo/signjob.h b/kleopatra/lib/kleo/signjob.h deleted file mode 100644 index 17ea3d9473..0000000000 --- a/kleopatra/lib/kleo/signjob.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - signjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_SIGNJOB_H__ -#define __KLEO_SIGNJOB_H__ - -#include // for Context::SignatureMode (or should - // we roll our own enum here?) -#include "job.h" -#include - -#include - -namespace GpgME { - class Error; - class Key; - class SigningResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous signing - - To use a SignJob, first obtain an instance from the CryptoBackend - implementation, connect the progress() and result() signals to - suitable slots and then start the signing with a call to - start(). This call might fail, in which case the SignJob instance - will have scheduled it's own destruction with a call to - QObject::deleteLater(). - - After result() is emitted, the SignJob will schedule it's own - destruction by calling QObject::deleteLater(). - */ - class SignJob : public Job { - Q_OBJECT - protected: - SignJob( QObject * parent, const char * name ); - public: - ~SignJob(); - - /** - Starts the signing operation. \a signers is the list of keys to - sign \a plainText with. Empty (null) keys are ignored. - */ - virtual GpgME::Error start( const std::vector & signers, - const QByteArray & plainText, - GpgME::Context::SignatureMode mode ) = 0; - virtual GpgME::SigningResult exec( const std::vector & signers, - const QByteArray & plainText, - GpgME::Context::SignatureMode mode, - QByteArray & signature ) = 0; - - signals: - void result( const GpgME::SigningResult & result, const QByteArray & signature ); - }; - -} - -#endif // __KLEO_SIGNJOB_H__ diff --git a/kleopatra/lib/kleo/verifydetachedjob.h b/kleopatra/lib/kleo/verifydetachedjob.h deleted file mode 100644 index f50fda546b..0000000000 --- a/kleopatra/lib/kleo/verifydetachedjob.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - verifydetachedjob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_VERIFYDETACHEDJOB_H__ -#define __KLEO_VERIFYDETACHEDJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; - class Key; - class VerificationResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous verification of detached signatures - - To use a VerifyDetachedJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the verification with a - call to start(). This call might fail, in which case the - VerifyDetachedJob instance will have scheduled it's own - destruction with a call to QObject::deleteLater(). - - After result() is emitted, the VerifyDetachedJob will schedule - it's own destruction by calling QObject::deleteLater(). - */ - class VerifyDetachedJob : public Job { - Q_OBJECT - protected: - VerifyDetachedJob( QObject * parent, const char * name ); - public: - ~VerifyDetachedJob(); - - /** - Starts the verification operation. \a signature contains the - signature data, while \a signedData contains the data over - which the signature was made. - */ - virtual GpgME::Error start( const QByteArray & signature, - const QByteArray & signedData ) = 0; - - virtual GpgME::VerificationResult exec( const QByteArray & signature, - const QByteArray & signedData ) = 0; - - signals: - void result( const GpgME::VerificationResult & result ); - }; - -} - -#endif // __KLEO_VERIFYDETACHEDJOB_H__ diff --git a/kleopatra/lib/kleo/verifyopaquejob.h b/kleopatra/lib/kleo/verifyopaquejob.h deleted file mode 100644 index b38b18de11..0000000000 --- a/kleopatra/lib/kleo/verifyopaquejob.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - verifyopaquejob.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_VERIFYOPAQUEJOB_H__ -#define __KLEO_VERIFYOPAQUEJOB_H__ - -#include "job.h" - -#include - -namespace GpgME { - class Error; - class Key; - class VerificationResult; -} - - -namespace Kleo { - - /** - @short An abstract base class for asynchronous verification of opaque signatures - - To use a VerifyOpaqueJob, first obtain an instance from the - CryptoBackend implementation, connect the progress() and result() - signals to suitable slots and then start the verification with a - call to start(). This call might fail, in which case the - VerifyOpaqueJob instance will have scheduled it's own - destruction with a call to QObject::deleteLater(). - - After result() is emitted, the VerifyOpaqueJob will schedule - it's own destruction by calling QObject::deleteLater(). - */ - class VerifyOpaqueJob : public Job { - Q_OBJECT - protected: - VerifyOpaqueJob( QObject * parent, const char * name ); - public: - ~VerifyOpaqueJob(); - - /** - Starts the verification operation. \a signature contains the - signature data, while \a signedData contains the data over - which the signature was made. - */ - virtual GpgME::Error start( const QByteArray & signedData ) = 0; - - /** Synchronous version of @ref start */ - virtual GpgME::VerificationResult exec( const QByteArray & signedData, QByteArray & plainText ) = 0; - - signals: - void result( const GpgME::VerificationResult & result, const QByteArray & plainText ); - }; - -} - -#endif // __KLEO_VERIFYOPAQUEJOB_H__ diff --git a/kleopatra/lib/libkleopatrarc.desktop b/kleopatra/lib/libkleopatrarc.desktop deleted file mode 100644 index 1e26c1ae51..0000000000 --- a/kleopatra/lib/libkleopatrarc.desktop +++ /dev/null @@ -1,190 +0,0 @@ -[Key Filter #0] -was-validated=false -Name=Not Validated Key -Name[bg]=Непроверен ключ -Name[ca]=Clau no validada -Name[cs]=Nevalidovaný klíč -Name[da]=Ikke godkendt nøgle -Name[de]=Ungeprüfter Schlüssel -Name[es]=Clave no validada -Name[et]=Võtme ehtsus kontrollimatu -Name[fr]=Clé non validée -Name[he]=מפתח לא מוודא -Name[hu]=Nem ellenőrzött kulcs -Name[is]=Ekki gildur hnappur -Name[it]=Chiave non validata -Name[nl]=Geen gevalideerde sleutel -Name[nn]=Ikkje-validert nøkkel -Name[pl]=Niesprawdzony klucz -Name[pt]=Chave Não Validada -Name[pt_BR]=Chave Não Validada -Name[ru]=Непроверенный ключ -Name[sl]=Nepreverjen ključ -Name[sr]=Неоверени кључ -Name[sr@Latn]=Neovereni ključ -Name[sv]=Nyckeln har inte validerats -Name[ta]=செல்லுபடியாகாத விசை -Name[tr]=Geçerli Olmayan Anahtar -Name[uk]=Неперевірений ключ -Name[zh_CN]=未校验的密钥 - -[Key Filter #1] -was-validated=true -is-expired=true -is-revoked=false -foreground-color=255,0,0 -Name=Expired Key -Name[bg]=Изтекъл ключ -Name[br]=Alc'hwez kabac'het -Name[ca]=Clau expirada -Name[cs]=Klíš s prošlou platností -Name[da]=Udløbet nøgle -Name[de]=Abgelaufener Schlüssel -Name[es]=Clave caducada -Name[et]=Aegunud võti -Name[fr]=Clé expirée -Name[he]=מפתח לא תקף -Name[hu]=Lejárt kulcs -Name[is]=Útrunninn lykill -Name[it]=Chiave scaduta -Name[nl]=Verlopen sleutel -Name[nn]=Forelda nøkkel -Name[pl]=Klucz, który stracił ważność -Name[pt]=Chave Expirada -Name[pt_BR]=Chave Expirada -Name[ru]=Утерявший силу ключ -Name[sl]=Pretečen ključ -Name[sr]=Истекли кључ -Name[sr@Latn]=Istekli ključ -Name[sv]=Utgången nyckel -Name[ta]=காலாவதியான விசை -Name[tr]=Süresi Dolmuş Anahtar -Name[uk]=Застарілий ключ -Name[zh_CN]=过期密钥 - -[Key Filter #2] -was-validated=true -is-revoked=true -Name=Revoked Key -Name[bg]=Анулиран ключ -Name[ca]=Clau revocada -Name[cs]=Odvolaný klíč -Name[da]=Fjernet nøgle -Name[de]=Widerrufener Schlüssel -Name[es]=Clave revocada -Name[et]=Tühistatud võti -Name[fr]=Clé révoquée -Name[he]=מפתח לא קביל -Name[hu]=Visszavont kulcs -Name[is]=Afturkallaður lykill -Name[it]=Chiave revocata -Name[nl]=Ingetrokken sleutel -Name[nn]=Tilbakekalla nøkkel -Name[pl]=Odwołany klucz -Name[pt]=Chave Revogada -Name[pt_BR]=Chave Revogada -Name[ru]=Отозванный ключ -Name[sl]=Preklican ključ -Name[sr]=Опозвани кључ -Name[sr@Latn]=Opozvani ključ -Name[sv]=Återkallad nyckel -Name[ta]=நீக்கிய விசை -Name[tr]=Geri Alınmış Anahtar -Name[uk]=Анульований ключ -Name[zh_CN]=吊销的密钥 - -[Key Filter #3] -was-validated=true -is-root-certificate=true -is-validity=ultimate -Name=Trusted Root Certificate -Name[bg]=Надеждно удостоверение -Name[ca]=Certificat arrel de confiança -Name[cs]=Důvěryhodný kořenový certifikát -Name[da]=Root-certifikat der stoles på -Name[de]=Vertrauenswürdiges Stammzertifikat -Name[es]=Certificado raíz de confianza -Name[et]=Usaldusväärne juursertifikaat -Name[fr]=Certificat racine de confiance -Name[hu]=Megbízható gyökértanúsítvány -Name[is]=Treyst rótarskilríki -Name[it]=Certificato radice affidabile -Name[nl]=Vertrouwd hoofdcertificaat -Name[nn]=Tiltrudd rotsertifikat -Name[pl]=Zaufany certyfikat bazowy -Name[pt]=Certificado Raiz de Confiança -Name[pt_BR]=Certificado Raiz Confiável -Name[ru]=Доверяемый корневой сертификат -Name[sl]=Zaupan korenski certifikat -Name[sr]=Корени сертификат од поверења -Name[sr@Latn]=Koreni sertifikat od poverenja -Name[sv]=Pålitligt rotcertifikat -Name[ta]=நம்பகமான மூல சான்றிதழ் -Name[tr]=Güvenilir Kök Sertifikası -Name[uk]=Кореневий сертифікат з довірою -Name[zh_CN]=可信任的根证书 - -[Key Filter #4] -was-validated=true -is-root-certificate=true -is-not-validity=ultimate -Name=Not Trusted Root Certificate -Name[bg]=Ненадеждно удостоверение -Name[ca]=Certificat arrel sense confiança -Name[cs]=Nedůvěryhodný kořenový certifikát -Name[da]=Root-certifikat der ikke stoles på -Name[de]=Nicht vertrauenswürdiges Stammzertifikat -Name[es]=Certificado raíz no de confianza -Name[et]=Ebausaldusväärne juursertifikaat -Name[fr]=Certificat racine non fiable -Name[hu]=Nem megbízható gyökértanúsítvány -Name[is]=Ekki traust rótarskilríki -Name[it]=Certificato radice non affidabile -Name[nl]=Niet vertrouwd hoofdcertificaat -Name[nn]=Ikkje tiltrudd rotsertifikat -Name[pl]=Nie zaufany certyfikat bazowy -Name[pt]=Certificado Raiz Não de Confiança -Name[pt_BR]=Certificado Raiz Não-Confiável -Name[ru]=Не доверяемый корневой сертификат -Name[sl]=Nezaupan korenski certifikat -Name[sr]=Корени сертификат који није од поверења -Name[sr@Latn]=Koreni sertifikat koji nije od poverenja -Name[sv]=Opålitligt rotcertifikat -Name[ta]=நம்பமுடியாத மூல சான்றிதழ் -Name[tr]=Güvenilmeyen Kök Sertifikası -Name[uk]=Кореневий сертифікат без довіри -Name[zh_CN]=未信任的根证书 - -[Key Filter #5] -was-validated=true -Name=Other Keys -Name[bg]=Други ключове -Name[br]=Alc'hwezioù all -Name[ca]=Altres claus -Name[cs]=Ostatní klíče -Name[da]=Andre nøgler -Name[de]=Andere Schlüssel -Name[es]=Otras claves -Name[et]=Muud võtmed -Name[fr]=Autres clés -Name[ga]=Eochracha Eile -Name[he]=מפתחות אחרים -Name[hu]=Egyéb kulcsok -Name[is]=Aðrir lyklar -Name[it]=Altre chiavi -Name[nl]=Andere sleutels -Name[nn]=Andre nøklar -Name[pa]=ਹੋਰ ਕੁੰਜੀਆਂ -Name[pl]=Inne klucze -Name[pt]=Outras Chaves -Name[pt_BR]=Outras Chaves -Name[ru]=Другие ключи -Name[sl]=Drugi ključi -Name[sr]=Други кључеви -Name[sr@Latn]=Drugi ključevi -Name[sv]=Andra nycklar -Name[ta]=மற்ற விசைகள் -Name[tr]=Diğer Anahtarlar -Name[uk]=Інші ключі -Name[zh_CN]=其它密钥 - diff --git a/kleopatra/lib/pics/Makefile.am b/kleopatra/lib/pics/Makefile.am deleted file mode 100644 index 33704d1b27..0000000000 --- a/kleopatra/lib/pics/Makefile.am +++ /dev/null @@ -1,4 +0,0 @@ -picsdir = $(kde_datadir)/libkleopatra/pics -pics_DATA = key.png key_ok.png key_bad.png key_unknown.png chiasmus_chi.png - -KDE_ICON = gpg gpgsm diff --git a/kleopatra/lib/tests/gnupgviewer.h b/kleopatra/lib/tests/gnupgviewer.h deleted file mode 100644 index efba1760bb..0000000000 --- a/kleopatra/lib/tests/gnupgviewer.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - gnupgviewer.h - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_TESTS_GNUPGVIEWER_H__ -#define __KLEO_TESTS_GNUPGVIEWER_H__ - -#include -#include - -namespace Kleo { - class GnuPGProcessBase; -} -class KProcess; -class QStringList; - -class GnuPGViewer : public QTextEdit { - Q_OBJECT -public: - GnuPGViewer( QWidget * parent=0, const char * name=0 ); - ~GnuPGViewer(); - - void setProcess( Kleo::GnuPGProcessBase * process ); - -private slots: - void slotStdout( KProcess *, char *, int ); - void slotStderr( KProcess *, char *, int ); - void slotStatus( Kleo::GnuPGProcessBase *, const QString &, const QStringList & ); - void slotProcessExited( KProcess * ); - -private: - Kleo::GnuPGProcessBase * mProcess; - QString mLastStdout, mLastStderr, mLastStatus; -}; - -#endif // __KLEO_TESTS_GNUPGVIEWER_H__ diff --git a/kleopatra/lib/tests/test_cryptoconfig.cpp b/kleopatra/lib/tests/test_cryptoconfig.cpp deleted file mode 100644 index fab91cff11..0000000000 --- a/kleopatra/lib/tests/test_cryptoconfig.cpp +++ /dev/null @@ -1,365 +0,0 @@ -/* - test_cryptoconfig.cpp - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include - -#include -#include -#include -#include -using namespace std; - -#include -#include - -int main( int argc, char** argv ) { - - KAboutData aboutData( "test_cryptoconfig", "CryptoConfig Test", "0.1" ); - KCmdLineArgs::init( argc, argv, &aboutData ); - KApplication app( false, false ); - - Kleo::CryptoConfig * config = new QGpgMECryptoConfig(); - - // Dynamic querying of the options - cout << "Components:" << endl; - QStringList components = config->componentList(); - - for( QStringList::Iterator compit = components.begin(); compit != components.end(); ++compit ) { - cout << "Component " << (*compit).local8Bit() << ":" << endl; - const Kleo::CryptoConfigComponent* comp = config->component( *compit ); - assert( comp ); - QStringList groups = comp->groupList(); - for( QStringList::Iterator groupit = groups.begin(); groupit != groups.end(); ++groupit ) { - const Kleo::CryptoConfigGroup* group = comp->group( *groupit ); - assert( group ); - cout << " Group " << (*groupit).local8Bit() << ": descr=\"" << group->description().local8Bit() << "\"" - << " level=" << group->level() << endl; - QStringList entries = group->entryList(); - for( QStringList::Iterator entryit = entries.begin(); entryit != entries.end(); ++entryit ) { - const Kleo::CryptoConfigEntry* entry = group->entry( *entryit ); - assert( entry ); - cout << " Entry " << (*entryit).local8Bit() << ":" - << " descr=\"" << entry->description().local8Bit() << "\"" - << " " << ( entry->isSet() ? "is set" : "is not set" ); - if ( !entry->isList() ) - switch( entry->argType() ) { - case Kleo::CryptoConfigEntry::ArgType_None: - break; - case Kleo::CryptoConfigEntry::ArgType_Int: - cout << " int value=" << entry->intValue(); - break; - case Kleo::CryptoConfigEntry::ArgType_UInt: - cout << " uint value=" << entry->uintValue(); - break; - case Kleo::CryptoConfigEntry::ArgType_LDAPURL: - case Kleo::CryptoConfigEntry::ArgType_URL: - cout << " URL value=" << entry->urlValue().prettyURL().local8Bit(); - // fallthrough - case Kleo::CryptoConfigEntry::ArgType_Path: - // fallthrough - case Kleo::CryptoConfigEntry::ArgType_DirPath: - // fallthrough - case Kleo::CryptoConfigEntry::ArgType_String: - - cout << " string value=" << entry->stringValue().local8Bit(); - break; - } - else // lists - { - switch( entry->argType() ) { - case Kleo::CryptoConfigEntry::ArgType_None: { - cout << " set " << entry->numberOfTimesSet() << " times"; - break; - } - case Kleo::CryptoConfigEntry::ArgType_Int: { - assert( entry->isOptional() ); // empty lists must be allowed (see issue121) - QValueList lst = entry->intValueList(); - QString str; - for( QValueList::Iterator it = lst.begin(); it != lst.end(); ++it ) { - str += QString::number( *it ); - } - cout << " int values=" << str.local8Bit(); - break; - } - case Kleo::CryptoConfigEntry::ArgType_UInt: { - assert( entry->isOptional() ); // empty lists must be allowed (see issue121) - QValueList lst = entry->uintValueList(); - QString str; - for( QValueList::Iterator it = lst.begin(); it != lst.end(); ++it ) { - str += QString::number( *it ); - } - cout << " uint values=" << str.local8Bit(); - break; - } - case Kleo::CryptoConfigEntry::ArgType_LDAPURL: - case Kleo::CryptoConfigEntry::ArgType_URL: { - assert( entry->isOptional() ); // empty lists must be allowed (see issue121) - KURL::List urls = entry->urlValueList(); - cout << " url values=" << urls.toStringList().join(" ").local8Bit() << "\n "; - } - // fallthrough - case Kleo::CryptoConfigEntry::ArgType_Path: - // fallthrough - case Kleo::CryptoConfigEntry::ArgType_DirPath: - // fallthrough - case Kleo::CryptoConfigEntry::ArgType_String: { - assert( entry->isOptional() ); // empty lists must be allowed (see issue121) - QStringList lst = entry->stringValueList(); - cout << " string values=" << lst.join(" ").local8Bit(); - break; - } - } - } - cout << endl; - } - // ... - } - } - - { - // Static querying of a single boolean option - static const char* s_groupName = "Monitor"; - static const char* s_entryName = "quiet"; - Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); - if ( entry ) { - assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_None ); - bool val = entry->boolValue(); - cout << "quiet option initially: " << ( val ? "is set" : "is not set" ) << endl; - - entry->setBoolValue( !val ); - assert( entry->isDirty() ); - config->sync( true ); - - // Clear cached values! - config->clear(); - - // Check new value - Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); - assert( entry ); - assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_None ); - cout << "quiet option now: " << ( val ? "is set" : "is not set" ) << endl; - assert( entry->boolValue() == !val ); - - // Set to default - entry->resetToDefault(); - assert( entry->boolValue() == false ); // that's the default - assert( entry->isDirty() ); - assert( !entry->isSet() ); - config->sync( true ); - config->clear(); - - // Check value - entry = config->entry( "dirmngr", s_groupName, s_entryName ); - assert( !entry->isDirty() ); - assert( !entry->isSet() ); - cout << "quiet option reset to default: " << ( entry->boolValue() ? "is set" : "is not set" ) << endl; - assert( entry->boolValue() == false ); - - // Reset old value - entry->setBoolValue( val ); - assert( entry->isDirty() ); - config->sync( true ); - - cout << "quiet option reset to initial: " << ( val ? "is set" : "is not set" ) << endl; - } - else - cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl; - } - - { - // Static querying and setting of a single int option - static const char* s_groupName = "LDAP"; - static const char* s_entryName = "ldaptimeout"; - Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); - if ( entry ) { - assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ); - uint val = entry->uintValue(); - cout << "LDAP timeout initially: " << val << " seconds." << endl; - - // Test setting the option directly, then querying again - //system( "echo 'ldaptimeout:0:101' | gpgconf --change-options dirmngr" ); - // Now let's do it with the C++ API instead - entry->setUIntValue( 101 ); - assert( entry->isDirty() ); - config->sync( true ); - - // Clear cached values! - config->clear(); - - // Check new value - Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); - assert( entry ); - assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ); - cout << "LDAP timeout now: " << entry->uintValue() << " seconds." << endl; - assert( entry->uintValue() == 101 ); - - // Set to default - entry->resetToDefault(); - assert( entry->uintValue() == 100 ); - assert( entry->isDirty() ); - assert( !entry->isSet() ); - config->sync( true ); - config->clear(); - - // Check value - entry = config->entry( "dirmngr", s_groupName, s_entryName ); - assert( !entry->isDirty() ); - assert( !entry->isSet() ); - cout << "LDAP timeout reset to default, " << entry->uintValue() << " seconds." << endl; - assert( entry->uintValue() == 100 ); - - // Reset old value - entry->setUIntValue( val ); - assert( entry->isDirty() ); - config->sync( true ); - - cout << "LDAP timeout reset to initial " << val << " seconds." << endl; - } - else - cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl; - } - - { - // Static querying and setting of a single string option - static const char* s_groupName = "Debug"; - static const char* s_entryName = "log-file"; - Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); - if ( entry ) { - assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path ); - QString val = entry->stringValue(); - cout << "Log-file initially: " << val.local8Bit() << endl; - - // Test setting the option, sync'ing, then querying again - entry->setStringValue( "/tmp/test:%e5" ); - assert( entry->isDirty() ); - config->sync( true ); - - // Let's see how it prints it - system( "gpgconf --list-options dirmngr | grep log-file" ); - - // Clear cached values! - config->clear(); - - // Check new value - Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); - assert( entry ); - assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path ); - cout << "Log-file now: " << entry->stringValue().local8Bit() << endl; - assert( entry->stringValue() == "/tmp/test:%e5" ); // (or even with %e5 decoded) - - // Reset old value -#if 0 - QString arg( val ); - if ( !arg.isEmpty() ) - arg.prepend( '"' ); - QCString sys; - sys.sprintf( "echo 'log-file:%s' | gpgconf --change-options dirmngr", arg.local8Bit().data() ); - system( sys.data() ); -#endif - entry->setStringValue( val ); - assert( entry->isDirty() ); - config->sync( true ); - - cout << "Log-file reset to initial " << val.local8Bit() << endl; - } - else - cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl; - } - - { - // Static querying and setting of the LDAP URL list option - static const char* s_groupName = "LDAP"; - static const char* s_entryName = "LDAP Server"; - Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); - if ( entry ) { - assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_LDAPURL ); - assert( entry->isList() ); - KURL::List val = entry->urlValueList(); - cout << "URL list initially: " << val.toStringList().join(", ").local8Bit() << endl; - - // Test setting the option, sync'ing, then querying again - KURL::List lst; - // We use non-empty paths to workaround a bug in KURL (kdelibs-3.2) - lst << KURL( "ldap://a:389/?b" ); - // Test with query containing a litteral ':' (KURL supports this) - // and a ' ' (KURL will escape it, see issue119) - lst << KURL( "ldap://foo:389/?a:b c" ); - lst << KURL( "ldap://server:389/?a%3db,c=DE" ); // the query contains a litteral ',' - //cout << " trying to set: " << lst.toStringList().join(", ").local8Bit() << endl; - assert( lst[0].query() == "?b" ); - assert( lst[1].query() == "?a:b%20c" ); // see, the space got escaped - entry->setURLValueList( lst ); - assert( entry->isDirty() ); - config->sync( true ); - - // Let's see how it prints it - system( "gpgconf --list-options dirmngr | grep 'LDAP Server'" ); - - // Clear cached values! - config->clear(); - - // Check new value - Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName ); - assert( entry ); - assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_LDAPURL ); - assert( entry->isList() ); - // Get raw a:b:c:d:e form - QStringList asStringList = entry->stringValueList(); - assert( asStringList.count() == 3 ); - cout << "asStringList[0]=" << asStringList[0].local8Bit() << endl; - cout << "asStringList[1]=" << asStringList[1].local8Bit() << endl; - cout << "asStringList[2]=" << asStringList[2].local8Bit() << endl; - assert( asStringList[0] == "a:389:::b" ); - assert( asStringList[1] == "foo:389:::a%3ab c" ); // the space must be decoded (issue119) - assert( asStringList[2] == "server:389:::a=b,c=DE" ); // all decoded - // Get KURL form - KURL::List newlst = entry->urlValueList(); - cout << "URL list now: " << newlst.toStringList().join(", ").local8Bit() << endl; - assert( newlst.count() == 3 ); - //cout << "newlst[0]=" << newlst[0].url().local8Bit() << endl; - //cout << "lst[0]=" << lst[0].url().local8Bit() << endl; - assert( newlst[0] == lst[0] ); - assert( newlst[1] == lst[1] ); - assert( newlst[2].url() == "ldap://server:389/?a=b,c=DE" ); // != lst[2] due to the encoded = - - // Reset old value - entry->setURLValueList( val ); - assert( entry->isDirty() ); - config->sync( true ); - - cout << "URL list reset to initial: " << val.toStringList().join(", ").local8Bit() << endl; - } - else - cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl; - } - - cout << "Done." << endl; -} diff --git a/kleopatra/lib/tests/test_gnupgprocessbase.cpp b/kleopatra/lib/tests/test_gnupgprocessbase.cpp deleted file mode 100644 index 37e961801f..0000000000 --- a/kleopatra/lib/tests/test_gnupgprocessbase.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - gnupgviewer.cpp - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "gnupgviewer.h" - -#include - -#include -#include -#include -#include -#include - -#include - -GnuPGViewer::GnuPGViewer( QWidget * parent, const char * name ) - : QTextEdit( parent, name ), mProcess( 0 ) -{ - setTextFormat( LogText ); - setMaxLogLines( 10000 ); -} - -GnuPGViewer::~GnuPGViewer() { - if ( mProcess ) - mProcess->kill(); -} - -void GnuPGViewer::setProcess( Kleo::GnuPGProcessBase * process ) { - if ( !process ) - return; - mProcess = process; - connect( mProcess, SIGNAL(processExited(KProcess*)), - SLOT(slotProcessExited(KProcess*)) ); - connect( mProcess, SIGNAL(receivedStdout(KProcess*,char*,int)), - SLOT(slotStdout(KProcess*,char*,int)) ); - connect( mProcess, SIGNAL(receivedStderr(KProcess*,char*,int)), - SLOT(slotStderr(KProcess*,char*,int)) ); - connect( mProcess, SIGNAL(status(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)), - SLOT(slotStatus(Kleo::GnuPGProcessBase*,const QString&,const QStringList&)) ); -} - -static QStringList split( char * buffer, int buflen, QString & old ) { - // when done right, this would need to use QTextCodec... - const QString str = old + QString::fromLocal8Bit( buffer, buflen ); - QStringList l = QStringList::split( '\n', str, true ); - if ( l.empty() ) - return l; - if ( str.endsWith( "\n" ) ) { - old = QString::null; - } else { - old = l.back(); - l.pop_back(); - } - return l; -} - -static QString escape( QString str ) { - return str.replace( '&', "&" ).replace( '<', "<" ).replace( '>', ">" ); -} - -void GnuPGViewer::slotStdout( KProcess *, char * buffer, int buflen ) { - const QStringList l = split( buffer, buflen, mLastStdout ); - for ( QStringList::const_iterator it = l.begin() ; it != l.end() ; ++it ) - append( "stdout: " + escape( *it ) ); -} - -void GnuPGViewer::slotStderr( KProcess *, char * buffer, int buflen ) { - const QStringList l = split( buffer, buflen, mLastStderr ); - for ( QStringList::const_iterator it = l.begin() ; it != l.end() ; ++it ) - append( "stderr: " + escape( *it ) + "" ); -} -void GnuPGViewer::slotStatus( Kleo::GnuPGProcessBase *, const QString & type, const QStringList & args ) { - append( "status: " + escape( type + ' ' + args.join( " " ) ) + "" ); -} -void GnuPGViewer::slotProcessExited( KProcess * proc ) { - if ( !proc ) - return; - if ( proc->normalExit() ) - append( QString( "Process exit: return code %1" ).arg ( proc->exitStatus() ) ); - else - append( "Process exit: killed" ); -} - -int main( int argc, char** argv ) { - if ( argc < 3 ) { - kdDebug() << "Need at least two arguments" << endl; - return 1; - } - KAboutData aboutData( "test_gnupgprocessbase", "GnuPGProcessBase Test", "0.1" ); - KCmdLineArgs::init( &aboutData ); - KApplication app; - - Kleo::GnuPGProcessBase gpg; - for ( int i = 1 ; i < argc ; ++i ) - gpg << argv[i]; - - gpg.setUseStatusFD( true ); - - GnuPGViewer * gv = new GnuPGViewer(); - gv->setProcess( &gpg ); - - app.setMainWidget( gv ); - gv->show(); - - gpg.start( KProcess::NotifyOnExit, KProcess::AllOutput ); - - return app.exec(); -} - -#include "gnupgviewer.moc" diff --git a/kleopatra/lib/tests/test_jobs.cpp b/kleopatra/lib/tests/test_jobs.cpp deleted file mode 100644 index 22d9136d4d..0000000000 --- a/kleopatra/lib/tests/test_jobs.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* - test_jobs.cpp - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include - -static const char * protocol = 0; - -static void testSign() -{ - const Kleo::CryptoBackend::Protocol * proto = protocol == "openpgp" ? Kleo::CryptoBackendFactory::instance()->openpgp() : Kleo::CryptoBackendFactory::instance()->smime() ; - assert( proto ); - - kdDebug() << "Using protocol " << proto->name() << endl; - - - std::vector signingKeys; - - std::auto_ptr listJob( proto->keyListJob( false, false, true ) ); // use validating keylisting - if ( listJob.get() ) { - // ##### Adjust this to your own identity - listJob->exec( "faure@kde.org", true /*secret*/, signingKeys ); - assert( !signingKeys.empty() ); - } else { - assert( 0 ); // job failed - } - - Kleo::SignJob* job = proto->signJob( true, true ); - - QCString cText = "Hallo Leute\n"; // like gpgme's t-sign.c - QByteArray plainText; - plainText.duplicate( cText.data(), cText.length() ); // hrmpf... - kdDebug() << k_funcinfo << "plainText=" << cText.data() << endl; - - kdDebug() << k_funcinfo << " signing with " << signingKeys[0].primaryFingerprint() << endl; - - QByteArray signature; - const GpgME::SigningResult res = - job->exec( signingKeys, plainText, GpgME::Context::Clearsigned, signature ); - if ( res.error().isCanceled() ) { - kdDebug() << "signing was canceled by user" << endl; - return; - } - if ( res.error() ) { - kdDebug() << "signing failed: " << res.error().asString() << endl; - return; - } - kdDebug() << k_funcinfo << "signing resulted in signature=" - << QCString( signature.data(), signature.size() + 1 ) << endl; -} - -int main( int argc, char** argv ) { - protocol = "openpgp"; - if ( argc == 2 ) { - protocol = argv[1]; - argc = 1; // hide from KDE - } - KAboutData aboutData( "test_jobs", "Signing Job Test", "0.1" ); - KCmdLineArgs::init( argc, argv, &aboutData ); - KApplication app; - - testSign(); -} diff --git a/kleopatra/lib/tests/test_keygen.cpp b/kleopatra/lib/tests/test_keygen.cpp deleted file mode 100644 index 9303b331cd..0000000000 --- a/kleopatra/lib/tests/test_keygen.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* - test_keygen.cpp - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "test_keygen.h" - -#include -#include -#include - -#include - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -static const char * keyParams[] = { - "Key-Type", "Key-Length", - "Subkey-Type", "Subkey-Length", - "Name-Real", "Name-Comment", "Name-Email", "Name-DN", - "Expire-Date", - "Passphrase" -}; -static const int numKeyParams = sizeof keyParams / sizeof *keyParams; - -static const char * protocol = 0; - -KeyGenerator::KeyGenerator( QWidget * parent, const char * name, WFlags ) - : KDialogBase( parent, name, true, "KeyGenerationJob test", - Close|User1, User1, true, KGuiItem( "Create" ) ) -{ - QWidget * w = new QWidget( this ); - setMainWidget( w ); - - QGridLayout * glay = new QGridLayout( w, numKeyParams+3, 2, marginHint(), spacingHint() ); - - int row = -1; - - ++row; - glay->addMultiCellWidget( new QLabel( "", w ), - row, row, 0, 1 ); - for ( int i = 0 ; i < numKeyParams ; ++i ) { - ++row; - glay->addWidget( new QLabel( keyParams[i], w ), row, 0 ); - glay->addWidget( mLineEdits[i] = new QLineEdit( w ), row, 1 ); - } - - ++row; - glay->addMultiCellWidget( new QLabel( "", w ), - row, row, 0, 1 ); - ++row; - glay->setRowStretch( row, 1 ); - glay->setColStretch( 1, 1 ); - - connect( this, SIGNAL(user1Clicked()), SLOT(slotStartKeyGeneration()) ); -} - -KeyGenerator::~KeyGenerator() {} - -void KeyGenerator::slotStartKeyGeneration() { - QString params = "\n"; - for ( int i = 0 ; i < numKeyParams ; ++i ) - if ( mLineEdits[i] && !mLineEdits[i]->text().stripWhiteSpace().isEmpty() ) - params += keyParams[i] + ( ": " + mLineEdits[i]->text().stripWhiteSpace() ) + '\n'; - params += "\n"; - - const Kleo::CryptoBackend::Protocol * proto = protocol == "openpgp" ? Kleo::CryptoBackendFactory::instance()->openpgp() : Kleo::CryptoBackendFactory::instance()->smime() ; - if ( !proto ) - proto = Kleo::CryptoBackendFactory::instance()->smime(); - assert( proto ); - - kdDebug() << "Using protocol " << proto->name() << endl; - - Kleo::KeyGenerationJob * job = proto->keyGenerationJob(); - assert( job ); - - connect( job, SIGNAL(result(const GpgME::KeyGenerationResult&,const QByteArray&)), - SLOT(slotResult(const GpgME::KeyGenerationResult&,const QByteArray&)) ); - - const GpgME::Error err = job->start( params ); - if ( err ) - showError( err ); - else - (void)new Kleo::ProgressDialog( job, "Generating key", this ); -} - -void KeyGenerator::showError( const GpgME::Error & err ) { - KMessageBox::error( this, "Could not start key generation: " + QString::fromLocal8Bit( err.asString() ), - "Key Generation Error" ); -} - -void KeyGenerator::slotResult( const GpgME::KeyGenerationResult & res, const QByteArray & keyData ) { - if ( res.error() ) - showError( res.error() ); - else - KMessageBox::information( this, QString("Key generated successfully, %1 bytes long").arg( keyData.size() ), - "Key Generation Finished" ); -} - -int main( int argc, char** argv ) { - if ( argc == 2 ) { - protocol = argv[1]; - argc = 1; // hide from KDE - } - KAboutData aboutData( "test_keygen", "KeyGenerationJob Test", "0.1" ); - KCmdLineArgs::init( argc, argv, &aboutData ); - KApplication app; - - KeyGenerator * keygen = new KeyGenerator( 0, "KeyGenerator top-level" ); - app.setMainWidget( keygen ); - keygen->show(); - - return app.exec(); -} - -#include "test_keygen.moc" diff --git a/kleopatra/lib/tests/test_keygen.h b/kleopatra/lib/tests/test_keygen.h deleted file mode 100644 index 0ba7138237..0000000000 --- a/kleopatra/lib/tests/test_keygen.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - test_keygen.h - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_TEST_KEYGEN_H__ -#define __KLEO_TEST_KEYGEN_H__ - -#include - -#include - -namespace GpgME { - class Error; - class KeyGenerationResult; -} - -class QLineEdit; - -class KeyGenerator : public KDialogBase { - Q_OBJECT -public: - KeyGenerator( QWidget * parent=0, const char * name=0, WFlags f=0 ); - ~KeyGenerator(); - -public slots: - void slotStartKeyGeneration(); - void slotResult( const GpgME::KeyGenerationResult & res, const QByteArray & keyData ); -private: - void showError( const GpgME::Error & err ); - -private: - QLineEdit * mLineEdits[20]; -}; - -#endif // __KLEO_TEST_KEYGEN_H__ diff --git a/kleopatra/lib/tests/test_keylister.cpp b/kleopatra/lib/tests/test_keylister.cpp deleted file mode 100644 index 9507221e77..0000000000 --- a/kleopatra/lib/tests/test_keylister.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* - test_keylister.cpp - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include - -#include "test_keylister.h" - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include - -namespace { - class TestColumnStrategy : public Kleo::KeyListView::ColumnStrategy { - public: - ~TestColumnStrategy() {} - QString title( int col ) const; - QString toolTip( const GpgME::Key & key, int col ) const; - QString text( const GpgME::Key & key, int col ) const; - }; - - QString TestColumnStrategy::title( int col ) const { - switch ( col ) { - case 0: return "Subject"; - case 1: return "EMail"; - case 2: return "Issuer"; - case 3: return "Serial"; - case 4: return "Protocol"; - case 5: return "Validity"; - default: return QString::null; - } - } - - QString TestColumnStrategy::toolTip( const GpgME::Key & key, int ) const { - return "Fingerprint: " + QString::fromUtf8( key.primaryFingerprint() ); - } - - QString TestColumnStrategy::text( const GpgME::Key & key, int col ) const { - if ( key.isNull() ) - return ""; - switch ( col ) { - case 0: return QString::fromUtf8( key.userID(0).id() ); - case 1: return QString::fromUtf8( key.userID(0).email() ); - case 2: return QString::fromUtf8( key.issuerName() ); - case 3: return key.issuerSerial(); - case 4: return key.protocolAsString(); - case 5: return QChar( key.userID(0).validityAsString() ); - default: return QString::null; - } - } -} - -CertListView::CertListView( QWidget * parent, const char * name, WFlags f ) - : Kleo::KeyListView( new TestColumnStrategy(), 0, parent, name, f ) -{ - setHierarchical( true ); - setRootIsDecorated( true ); -} - -void CertListView::slotResult( const GpgME::KeyListResult & result ) { - kdDebug() << "CertListView::slotResult()" << endl; - if ( result.isNull() ) - QMessageBox::information( this, "Key Listing Result", "KeyListResult is null!" ); - else if ( result.error() ) - QMessageBox::critical( this, "Key Listing Result", - QString("KeyListResult Error: %1").arg( result.error().asString() ) ); - else if ( result.isTruncated() ) - QMessageBox::information( this, "Key Listing Result", "KeyListResult is truncated!" ); - else - QMessageBox::information( this, "Key Listing Result", "Key listing successful" ); -} - -void CertListView::slotStart() { - kdDebug() << "CertListView::slotStart()" << endl; - Kleo::KeyListJob * job = Kleo::CryptoBackendFactory::instance()->smime()->keyListJob( false ); - assert( job ); - QObject::connect( job, SIGNAL(nextKey(const GpgME::Key&)), - this, SLOT(slotAddKey(const GpgME::Key&)) ); - QObject::connect( job, SIGNAL(result(const GpgME::KeyListResult&)), - this, SLOT(slotResult(const GpgME::KeyListResult&)) ); -#if 0 - QStringList l; - l << "Marc"; - job->start( l, false ); -#else - job->start( QStringList(), false ); -#endif -} - -int main( int argc, char** argv ) { - - KAboutData aboutData( "test_keylister", "KeyLister Test", "0.1" ); - KCmdLineArgs::init( argc, argv, &aboutData ); - KApplication app; - - CertListView * clv = new CertListView( 0, "CertListView top-level" ); - app.setMainWidget( clv ); - clv->show(); - - QTimer::singleShot( 5000, clv, SLOT(slotStart()) ); - - return app.exec(); -} - -#include "test_keylister.moc" diff --git a/kleopatra/lib/tests/test_keylister.h b/kleopatra/lib/tests/test_keylister.h deleted file mode 100644 index 348ec262ff..0000000000 --- a/kleopatra/lib/tests/test_keylister.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - test_keylister.h - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_TEST_KEYLISTER_H__ -#define __KLEO_TEST_KEYLISTER_H__ - -#include - -namespace GpgME { - class Key; - class KeyListResult; -} - -class CertListView : public Kleo::KeyListView { - Q_OBJECT -public: - CertListView( QWidget * parent=0, const char * name=0, WFlags f=0 ); - -public slots: - void slotResult( const GpgME::KeyListResult & result ); - void slotStart(); -}; - -#endif // __KLEO_TEST_KEYLISTER_H__ diff --git a/kleopatra/lib/tests/test_keyselectiondialog.cpp b/kleopatra/lib/tests/test_keyselectiondialog.cpp deleted file mode 100644 index e6c85fca0b..0000000000 --- a/kleopatra/lib/tests/test_keyselectiondialog.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - test_keygen.cpp - - This file is part of libkleopatra's test suite. - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -int main( int argc, char ** argv ) { - KAboutData aboutData( "test_keyselectiondialog", "KeySelectionDialog Test", "0.1" ); - KCmdLineArgs::init( argc, argv, &aboutData ); - KApplication app; - - KGlobal::iconLoader()->addAppDir( "libkleopatra" ); - - Kleo::KeySelectionDialog dlg( "Kleo::KeySelectionDialog Test", - "Please select a key:", - std::vector(), - Kleo::KeySelectionDialog::AllKeys, true, true ); - - if ( dlg.exec() == QDialog::Accepted ) { - kdDebug() << "accepted; selected key: " << (dlg.selectedKey().userID(0).id() ? dlg.selectedKey().userID(0).id() : "") << "\nselected _keys_:" << endl; - for ( std::vector::const_iterator it = dlg.selectedKeys().begin() ; it != dlg.selectedKeys().end() ; ++it ) - kdDebug() << (it->userID(0).id() ? it->userID(0).id() : "") << endl; - } else { - kdDebug() << "rejected" << endl; - } - - return 0; -} diff --git a/kleopatra/lib/ui/Makefile.am b/kleopatra/lib/ui/Makefile.am deleted file mode 100644 index 80c6e96dd5..0000000000 --- a/kleopatra/lib/ui/Makefile.am +++ /dev/null @@ -1,40 +0,0 @@ - -INCLUDES = -I$(top_srcdir)/libkdenetwork \ - -I$(top_srcdir)/libkpgp \ - -I$(top_srcdir)/certmanager/lib \ - $(GPGME_CFLAGS) $(all_includes) - -noinst_LTLIBRARIES = libkleopatra_ui.la - -libkleopatra_ui_la_SOURCES = \ - kdhorizontalline.cpp \ - progressbar.cpp \ - progressdialog.cpp \ - keylistview.cpp \ - keyselectiondialog.cpp \ - keyrequester.cpp \ - passphrasedialog.cpp \ - keyapprovaldialog.cpp \ - backendconfigwidget.cpp \ - dnattributeorderconfigwidget.cpp \ - cryptoconfigmodule.cpp \ - cryptoconfigdialog.cpp \ - directoryserviceswidgetbase.ui \ - directoryserviceswidget.cpp \ - adddirectoryservicedialog.ui \ - adddirectoryservicedialogimpl.cpp - -kleodir = $(includedir)/kleo -kleo_HEADERS = \ - kdhorizontalline.h \ - progressbar.h \ - progressdialog.h \ - keylistview.h \ - keyselectiondialog.h \ - keyrequester.h \ - passphrasedialog.h \ - keyapprovaldialog.h \ - backendconfigwidget.h \ - dnattributeorderconfigwidget.h - -METASOURCES = AUTO diff --git a/kleopatra/lib/ui/adddirectoryservicedialogimpl.cpp b/kleopatra/lib/ui/adddirectoryservicedialogimpl.cpp deleted file mode 100644 index 973266b161..0000000000 --- a/kleopatra/lib/ui/adddirectoryservicedialogimpl.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - adddirectoryservicedialogimpl.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "adddirectoryservicedialogimpl.h" - -#include -#include - -/* - * Constructs a AddDirectoryServiceDialogImpl which is 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. - */ -AddDirectoryServiceDialogImpl::AddDirectoryServiceDialogImpl( QWidget* parent, const char* name, bool modal, WFlags fl ) - : AddDirectoryServiceDialog( parent, name, modal, fl ) -{ - portED->setValidator( new QIntValidator( 0, 65535, portED ) ); -} - -/* - * Destroys the object and frees any allocated resources - */ -AddDirectoryServiceDialogImpl::~AddDirectoryServiceDialogImpl() -{ - // no need to delete child widgets, Qt does it all for us -} - -#include "adddirectoryservicedialogimpl.moc" diff --git a/kleopatra/lib/ui/adddirectoryservicedialogimpl.h b/kleopatra/lib/ui/adddirectoryservicedialogimpl.h deleted file mode 100644 index deee06439f..0000000000 --- a/kleopatra/lib/ui/adddirectoryservicedialogimpl.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - adddirectoryservicedialogimpl.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef ADDDIRECTORYSERVICEDIALOGIMPL_H -#define ADDDIRECTORYSERVICEDIALOGIMPL_H -#include "adddirectoryservicedialog.h" - -class AddDirectoryServiceDialogImpl : public AddDirectoryServiceDialog -{ - Q_OBJECT - -public: - AddDirectoryServiceDialogImpl( QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0 ); - ~AddDirectoryServiceDialogImpl(); - -}; - -#endif // ADDDIRECTORYSERVICEDIALOGIMPL_H diff --git a/kleopatra/lib/ui/backendconfigwidget.cpp b/kleopatra/lib/ui/backendconfigwidget.cpp deleted file mode 100644 index c40890a430..0000000000 --- a/kleopatra/lib/ui/backendconfigwidget.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/* -*- c++ -*- - backendconfigwidget.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2002,2004,2005 Klarlvdalens Datakonsult AB - Copyright (c) 2002,2003 Marc Mutz - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "backendconfigwidget.h" -#include "cryptoconfigdialog.h" - -#include "kleo/cryptobackendfactory.h" -#include "ui/keylistview.h" // for lvi_cast<> - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -namespace Kleo { - class BackendListView; -} - -class Kleo::BackendConfigWidget::Private { -public: - Kleo::BackendListView * listView; - QPushButton * configureButton; - QPushButton * rescanButton; - Kleo::CryptoBackendFactory * backendFactory; -}; - -namespace Kleo { - class BackendListViewItem; - class ProtocolCheckListItem; -} - -class Kleo::BackendListView : public KListView -{ -public: - BackendListView( BackendConfigWidget* parent, const char* name = 0 ) - : KListView( parent, name ) {} - - /// return backend for currently selected (/current) item. Used by Configure button. - const Kleo::CryptoBackend* currentBackend() const; - - /// return which protocol implementation was chosen (checked) for each type (used when saving) - const Kleo::CryptoBackend* chosenBackend( const char * protocol ); - - /// deselect all except one for a given protocol type (radiobutton-like exclusivity) - void deselectAll( const char * protocol, QCheckListItem* except ); - - void emitChanged() { static_cast( parentWidget() )->emitChanged( true ); } -}; - -// Toplevel listviewitem for a given backend (e.g. "GpgME", "Kgpg/gpg v2") -class Kleo::BackendListViewItem : public QListViewItem -{ -public: - BackendListViewItem( KListView* lv, QListViewItem *prev, const CryptoBackend *cryptoBackend ) - : QListViewItem( lv, prev, cryptoBackend->displayName() ), mCryptoBackend( cryptoBackend ) - {} - - const CryptoBackend *cryptoBackend() const { return mCryptoBackend; } - enum { RTTI = 0x2EAE3BE0, RTTI_MASK = 0xFFFFFFFF }; - int rtti() const { return RTTI; } - -private: - const CryptoBackend *mCryptoBackend; -}; - - -// Checklist item under a BackendListViewItem -// (e.g. "GpgME supports protocol OpenPGP") -class Kleo::ProtocolCheckListItem : public QCheckListItem -{ -public: - ProtocolCheckListItem( BackendListViewItem* blvi, - QListViewItem* prev, const char * protocolName, - const CryptoBackend::Protocol* protocol ) // can be 0 - : QCheckListItem( blvi, prev, itemText( protocolName, protocol ), - QCheckListItem::CheckBox ), - mProtocol( protocol ), mProtocolName( protocolName ) - {} - - enum { RTTI = 0x2EAE3BE1, RTTI_MASK = 0xFFFFFFFF }; - virtual int rtti() const { return RTTI; } - - // can be 0 - const CryptoBackend::Protocol* protocol() const { return mProtocol; } - const char * protocolName() const { return mProtocolName; } - -protected: - virtual void stateChange( bool b ) { - BackendListView* lv = static_cast( listView() ); - // "radio-button-like" behavior for the protocol checkboxes - if ( b ) - lv->deselectAll( mProtocolName, this ); - lv->emitChanged(); - QCheckListItem::stateChange( b ); - } - -private: - // Helper for the constructor. - static QString itemText( const char * protocolName, const CryptoBackend::Protocol* protocol ) { - // First one is the generic name (find a nice one for OpenPGP, SMIME) - const QString protoName = qstricmp( protocolName, "openpgp" ) != 0 - ? qstricmp( protocolName, "smime" ) != 0 - ? QString::fromLatin1( protocolName ) - : i18n( "S/MIME" ) - : i18n( "OpenPGP" ); - // second one is implementation name (gpg, gpgsm...) - const QString impName = protocol ? protocol->displayName() : i18n( "failed" ); - return i18n( "Items in Kleo::BackendConfigWidget listview (1: protocol; 2: implementation name)", - "%1 (%2)" ).arg( protoName, impName ); - } - - const CryptoBackend::Protocol* mProtocol; // can be 0 - const char * mProtocolName; -}; - -const Kleo::CryptoBackend* Kleo::BackendListView::currentBackend() const { - const QListViewItem* curItem = currentItem(); - if ( !curItem ) // can't happen - return 0; - if ( lvi_cast( curItem ) ) - curItem = curItem->parent(); - if ( const Kleo::BackendListViewItem * blvi = lvi_cast( curItem ) ) - return blvi->cryptoBackend(); - return 0; -} - -// can't be const method due to QListViewItemIterator (why?) -const Kleo::CryptoBackend* Kleo::BackendListView::chosenBackend( const char * protocolName ) -{ - for ( QListViewItemIterator it( this /*, QListViewItemIterator::Checked doesn't work*/ ) ; - it.current() ; ++it ) - if ( ProtocolCheckListItem * p = lvi_cast( it.current() ) ) - if ( p->isOn() && qstricmp( p->protocolName(), protocolName ) == 0 ) { - // OK that's the one. Now go up to the parent backend - // (need to do that in the listview since Protocol doesn't know it) - if ( const BackendListViewItem * parItem = lvi_cast( it.current()->parent() ) ) - return parItem->cryptoBackend(); - } - return 0; -} - -void Kleo::BackendListView::deselectAll( const char * protocolName, QCheckListItem* except ) -{ - for ( QListViewItemIterator it( this /*, QListViewItemIterator::Checked doesn't work*/ ) ; - it.current() ; ++it ) { - if ( it.current() == except ) continue; - if ( ProtocolCheckListItem * p = lvi_cast( it.current() ) ) - if ( p->isOn() && qstricmp( p->protocolName(), protocolName ) == 0 ) - p->setOn( false ); - } -} - -//// - -Kleo::BackendConfigWidget::BackendConfigWidget( CryptoBackendFactory * factory, QWidget * parent, const char * name, WFlags f ) - : QWidget( parent, name, f ), d( 0 ) -{ - assert( factory ); - d = new Private(); - d->backendFactory = factory; - - QHBoxLayout * hlay = - new QHBoxLayout( this, 0, KDialog::spacingHint() ); - - d->listView = new BackendListView( this, "d->listView" ); - d->listView->addColumn( i18n("Available Backends") ); - d->listView->setAllColumnsShowFocus( true ); - d->listView->setSorting( -1 ); - d->listView->header()->setClickEnabled( false ); - d->listView->setFullWidth( true ); - - hlay->addWidget( d->listView, 1 ); - - connect( d->listView, SIGNAL(selectionChanged(QListViewItem*)), - SLOT(slotSelectionChanged(QListViewItem*)) ); - - QVBoxLayout * vlay = new QVBoxLayout( hlay ); // inherits spacing - - d->configureButton = new QPushButton( i18n("Confi&gure..."), this ); - d->configureButton->setAutoDefault( false ); - vlay->addWidget( d->configureButton ); - - connect( d->configureButton, SIGNAL(clicked()), - SLOT(slotConfigureButtonClicked()) ); - - d->rescanButton = new QPushButton( i18n("Rescan"), this ); - d->rescanButton->setAutoDefault( false ); - vlay->addWidget( d->rescanButton ); - - connect( d->rescanButton, SIGNAL(clicked()), - SLOT(slotRescanButtonClicked()) ); - - vlay->addStretch( 1 ); -} - -Kleo::BackendConfigWidget::~BackendConfigWidget() { - delete d; d = 0; -} - -void Kleo::BackendConfigWidget::load() { - d->listView->clear(); - - unsigned int backendCount = 0; - - // populate the plugin list: - BackendListViewItem * top = 0; - for ( unsigned int i = 0 ; const CryptoBackend * b = d->backendFactory->backend( i ) ; ++i ) { - - top = new Kleo::BackendListViewItem( d->listView, top, b ); - - ProtocolCheckListItem * last = 0; - for ( int i = 0 ; const char * name = b->enumerateProtocols( i ) ; ++i ) { - const CryptoBackend::Protocol * protocol = b->protocol( name ); - - if ( protocol ) { - last = new ProtocolCheckListItem( top, last, name, protocol ); - last->setOn( protocol == d->backendFactory->protocol( name ) ); - } else if ( b->supportsProtocol( name ) ) { - last = new ProtocolCheckListItem( top, last, name, 0 ); - last->setOn( false ); - last->setEnabled( false ); - } - } - - top->setOpen( true ); - ++backendCount; - } - - if ( backendCount ) { - d->listView->setCurrentItem( d->listView->firstChild() ); - d->listView->setSelected( d->listView->firstChild(), true ); - } - - slotSelectionChanged( d->listView->firstChild() ); -} - -void Kleo::BackendConfigWidget::slotSelectionChanged( QListViewItem * ) { - const CryptoBackend* backend = d->listView->currentBackend(); - if ( backend && !backend->config() ) - kdDebug(5150) << "Backend w/o config object!" << endl; - d->configureButton->setEnabled( backend && backend->config() ); -} - - -void Kleo::BackendConfigWidget::slotRescanButtonClicked() { - QStringList reasons; - d->backendFactory->scanForBackends( &reasons ); - if ( !reasons.empty() ) - KMessageBox::informationList( this, - i18n("The following problems where encountered during scanning:"), - reasons, i18n("Scan Results") ); - load(); - emit changed( true ); -} - -void Kleo::BackendConfigWidget::slotConfigureButtonClicked() { - const CryptoBackend* backend = d->listView->currentBackend(); - if ( backend && backend->config() ) { - Kleo::CryptoConfigDialog dlg( backend->config(), this ); - int result = dlg.exec(); - if ( result == QDialog::Accepted ) { - // Tell other users of gpgconf (e.g. the s/mime page) that the gpgconf data might have changed - kapp->dcopClient()->emitDCOPSignal( "KPIM::CryptoConfig", "changed()", QByteArray() ); - // and schedule a rescan, in case the updates make a backend valid - QTimer::singleShot( 0, this, SLOT(slotRescanButtonClicked()) ); - } - } - else // shouldn't happen, button is disabled - kdWarning(5150) << "Can't configure backend, no config object available" << endl; -} - -void Kleo::BackendConfigWidget::save() const { - for ( int i = 0 ; const char * name = d->backendFactory->enumerateProtocols( i ) ; ++i ) - d->backendFactory->setProtocolBackend( name, d->listView->chosenBackend( name ) ); -} - -void Kleo::BackendConfigWidget::virtual_hook( int, void* ) {} - -#include "backendconfigwidget.moc" diff --git a/kleopatra/lib/ui/backendconfigwidget.h b/kleopatra/lib/ui/backendconfigwidget.h deleted file mode 100644 index 0e26655ce4..0000000000 --- a/kleopatra/lib/ui/backendconfigwidget.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -*- c++ -*- - backendconfigwidget.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2002,2004 Klarlvdalens Datakonsult AB - Copyright (c) 2002,2003 Marc Mutz - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - */ - -#ifndef __KLEO_UI_BACKENDCONFIGWIDGET_H__ -#define __KLEO_UI_BACKENDCONFIGWIDGET_H__ - -#include -#include - -namespace Kleo { - class CryptoBackendFactory; -} - -class QListViewItem; - -namespace Kleo { - - class KDE_EXPORT BackendConfigWidget : public QWidget { - Q_OBJECT - public: - BackendConfigWidget( CryptoBackendFactory * factory, QWidget * parent=0, const char * name=0, WFlags f=0 ); - ~BackendConfigWidget(); - - void load(); - void save() const; - - void emitChanged( bool b ) { emit changed( b ); } - - signals: - void changed( bool ); - - private slots: - void slotSelectionChanged( QListViewItem * ); - void slotRescanButtonClicked(); - void slotConfigureButtonClicked(); - - private: - class Private; - Private * d; - protected: - virtual void virtual_hook( int, void* ); - }; - -} - -#endif // __KLEO_UI_BACKENDCONFIGWIDGET_H__ diff --git a/kleopatra/lib/ui/cryptoconfigdialog.cpp b/kleopatra/lib/ui/cryptoconfigdialog.cpp deleted file mode 100644 index 3fa0a97ca8..0000000000 --- a/kleopatra/lib/ui/cryptoconfigdialog.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - cryptoconfigdialog.h - - This file is part of kgpgcertmanager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "cryptoconfigdialog.h" -#include "cryptoconfigmodule.h" -#include -#include - -Kleo::CryptoConfigDialog::CryptoConfigDialog( Kleo::CryptoConfig* config, QWidget *parent, const char* name ) - : KDialogBase( Swallow, - // Remove the "whats's this" button since we have no support for it - WStyle_Customize | WStyle_DialogBorder | WStyle_Maximize | WStyle_Title | WStyle_SysMenu, - parent, name, true /*modal*/, - i18n( "Configure" ), Default|Cancel|Apply|Ok|User1, - Ok, true /*separator*/, KGuiItem( i18n( "&Reset" ), "undo" ) ) -{ - mMainWidget = new CryptoConfigModule( config, this ); - setMainWidget( mMainWidget ); - connect( mMainWidget, SIGNAL( changed() ), SLOT( slotChanged() ) ); - enableButton( Apply, false ); - - // Automatically assign accelerators - KAcceleratorManager::manage( this ); -} - -void Kleo::CryptoConfigDialog::slotOk() -{ - slotApply(); - accept(); -} - -void Kleo::CryptoConfigDialog::slotCancel() -{ - mMainWidget->cancel(); - reject(); -} - -void Kleo::CryptoConfigDialog::slotDefault() -{ - mMainWidget->defaults(); - slotChanged(); -} - -void Kleo::CryptoConfigDialog::slotApply() -{ - mMainWidget->save(); - enableButton( Apply, false ); -} - -void Kleo::CryptoConfigDialog::slotUser1() // reset -{ - mMainWidget->reset(); - enableButton( Apply, false ); -} - -void Kleo::CryptoConfigDialog::slotChanged() -{ - enableButton( Apply, true ); -} - -#include "cryptoconfigdialog.moc" diff --git a/kleopatra/lib/ui/cryptoconfigdialog.h b/kleopatra/lib/ui/cryptoconfigdialog.h deleted file mode 100644 index 484c55ea48..0000000000 --- a/kleopatra/lib/ui/cryptoconfigdialog.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - cryptoconfigdialog.h - - This file is part of kgpgcertmanager - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef CRYPTOCONFIGDIALOG_H -#define CRYPTOCONFIGDIALOG_H - -#include -#include - -namespace Kleo { - - class CryptoConfig; - class CryptoConfigModule; - - /** - * Simple KDialogBase wrapper around CryptoConfigModule - */ - class KDE_EXPORT CryptoConfigDialog : public KDialogBase - { - Q_OBJECT - public: - CryptoConfigDialog( Kleo::CryptoConfig* config, QWidget *parent = 0, const char* name = 0 ); - - protected: - virtual void slotOk(); - virtual void slotCancel(); - virtual void slotDefault(); - virtual void slotApply(); - virtual void slotUser1(); // reset - - public slots: - void slotChanged(); - - private: - CryptoConfigModule* mMainWidget; - }; - -} - -#endif /* CRYPTOCONFIGDIALOG_H */ - diff --git a/kleopatra/lib/ui/cryptoconfigmodule.cpp b/kleopatra/lib/ui/cryptoconfigmodule.cpp deleted file mode 100644 index 6c2128de11..0000000000 --- a/kleopatra/lib/ui/cryptoconfigmodule.cpp +++ /dev/null @@ -1,572 +0,0 @@ -/* - cryptoconfigmodule.cpp - - This file is part of kgpgcertmanager - Copyright (c) 2004 Klar�vdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "cryptoconfigmodule.h" -#include "cryptoconfigmodule_p.h" -#include "directoryserviceswidget.h" -#include "kdhorizontalline.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -using namespace Kleo; - -inline QPixmap loadIcon( QString s ) { - return KGlobal::instance()->iconLoader() - ->loadIcon( s.replace( QRegExp( "[^a-zA-Z0-9_]" ), "_" ), KIcon::NoGroup, KIcon::SizeMedium ); -} - -static const KJanusWidget::Face determineJanusFace( const Kleo::CryptoConfig * config ) { - return config && config->componentList().size() < 2 - ? KJanusWidget::Plain - : KJanusWidget::IconList ; -} - -Kleo::CryptoConfigModule::CryptoConfigModule( Kleo::CryptoConfig* config, QWidget * parent, const char * name ) - : KJanusWidget( parent, name, determineJanusFace( config ) ), mConfig( config ) -{ - QWidget * vbox = 0; - if ( face() == Plain ) { - vbox = plainPage(); - QVBoxLayout * vlay = new QVBoxLayout( vbox, 0, KDialog::spacingHint() ); - vlay->setAutoAdd( true ); - } - - const QStringList components = config->componentList(); - for ( QStringList::const_iterator it = components.begin(); it != components.end(); ++it ) { - //kdDebug(5150) << "Component " << (*it).local8Bit() << ":" << endl; - Kleo::CryptoConfigComponent* comp = config->component( *it ); - Q_ASSERT( comp ); - if ( comp->groupList().empty() ) - continue; - if ( face() != Plain ) { - vbox = addVBoxPage( comp->description(), QString::null, loadIcon( comp->iconName() ) ); - } - CryptoConfigComponentGUI* compGUI = - new CryptoConfigComponentGUI( this, comp, vbox, (*it).local8Bit() ); - // KJanusWidget doesn't seem to have iterators, so we store a copy... - mComponentGUIs.append( compGUI ); - } -} - -void Kleo::CryptoConfigModule::save() -{ - bool changed = false; - QValueList::Iterator it = mComponentGUIs.begin(); - for( ; it != mComponentGUIs.end(); ++it ) { - if ( (*it)->save() ) - changed = true; - } - if ( changed ) - mConfig->sync(true /*runtime*/); -} - -void Kleo::CryptoConfigModule::reset() -{ - QValueList::Iterator it = mComponentGUIs.begin(); - for( ; it != mComponentGUIs.end(); ++it ) { - (*it)->load(); - } -} - -void Kleo::CryptoConfigModule::defaults() -{ - QValueList::Iterator it = mComponentGUIs.begin(); - for( ; it != mComponentGUIs.end(); ++it ) { - (*it)->defaults(); - } -} - -void Kleo::CryptoConfigModule::cancel() -{ - mConfig->clear(); -} - -//// - -Kleo::CryptoConfigComponentGUI::CryptoConfigComponentGUI( - CryptoConfigModule* module, Kleo::CryptoConfigComponent* component, - QWidget* parent, const char* name ) - : QWidget( parent, name ), - mComponent( component ) -{ - QGridLayout * glay = new QGridLayout( this, 1, 3, 0, KDialog::spacingHint() ); - const QStringList groups = mComponent->groupList(); - if ( groups.size() > 1 ) { - glay->setColSpacing( 0, KDHorizontalLine::indentHint() ); - for ( QStringList::const_iterator it = groups.begin(), end = groups.end() ; it != end; ++it ) { - Kleo::CryptoConfigGroup* group = mComponent->group( *it ); - Q_ASSERT( group ); - if ( !group ) - continue; - KDHorizontalLine * hl = new KDHorizontalLine( group->description(), this ); - const int row = glay->numRows(); - glay->addMultiCellWidget( hl, row, row, 0, 2 ); - mGroupGUIs.append( new CryptoConfigGroupGUI( module, group, glay, this ) ); - } - } else if ( !groups.empty() ) { - mGroupGUIs.append( new CryptoConfigGroupGUI( module, mComponent->group( groups.front() ), glay, this ) ); - } - glay->setRowStretch( glay->numRows(), 1 ); -} - - -bool Kleo::CryptoConfigComponentGUI::save() -{ - bool changed = false; - QValueList::Iterator it = mGroupGUIs.begin(); - for( ; it != mGroupGUIs.end(); ++it ) { - if ( (*it)->save() ) - changed = true; - } - return changed; -} - -void Kleo::CryptoConfigComponentGUI::load() -{ - QValueList::Iterator it = mGroupGUIs.begin(); - for( ; it != mGroupGUIs.end(); ++it ) - (*it)->load(); -} - -void Kleo::CryptoConfigComponentGUI::defaults() -{ - QValueList::Iterator it = mGroupGUIs.begin(); - for( ; it != mGroupGUIs.end(); ++it ) - (*it)->defaults(); -} - -//// - -Kleo::CryptoConfigGroupGUI::CryptoConfigGroupGUI( - CryptoConfigModule* module, Kleo::CryptoConfigGroup* group, - QGridLayout * glay, QWidget* widget, const char* name ) - : QObject( module, name ), mGroup( group ) -{ - const int startRow = glay->numRows(); - const QStringList entries = mGroup->entryList(); - for( QStringList::const_iterator it = entries.begin(), end = entries.end() ; it != end; ++it ) { - Kleo::CryptoConfigEntry* entry = group->entry( *it ); - Q_ASSERT( entry ); - if ( entry->level() > CryptoConfigEntry::Level_Advanced ) continue; - CryptoConfigEntryGUI* entryGUI = - CryptoConfigEntryGUIFactory::createEntryGUI( module, entry, *it, glay, widget ); - if ( entryGUI ) { - mEntryGUIs.append( entryGUI ); - entryGUI->load(); - } - } - const int endRow = glay->numRows() - 1; - if ( endRow < startRow ) - return; - - const QString iconName = group->iconName(); - if ( iconName.isEmpty() ) - return; - - QLabel * l = new QLabel( widget ); - l->setPixmap( loadIcon( iconName ) ); - glay->addMultiCellWidget( l, startRow, endRow, 0, 0, Qt::AlignTop ); -} - -bool Kleo::CryptoConfigGroupGUI::save() -{ - bool changed = false; - QValueList::Iterator it = mEntryGUIs.begin(); - for( ; it != mEntryGUIs.end(); ++it ) { - if ( (*it)->isChanged() ) { - (*it)->save(); - changed = true; - } - } - return changed; -} - -void Kleo::CryptoConfigGroupGUI::load() -{ - QValueList::Iterator it = mEntryGUIs.begin(); - for( ; it != mEntryGUIs.end(); ++it ) - (*it)->load(); -} - -void Kleo::CryptoConfigGroupGUI::defaults() -{ - QValueList::Iterator it = mEntryGUIs.begin(); - for( ; it != mEntryGUIs.end(); ++it ) - (*it)->resetToDefault(); -} - -//// - -CryptoConfigEntryGUI* Kleo::CryptoConfigEntryGUIFactory::createEntryGUI( CryptoConfigModule* module, Kleo::CryptoConfigEntry* entry, const QString& entryName, QGridLayout * glay, QWidget* widget, const char* name ) -{ - if ( entry->isList() ) { - switch( entry->argType() ) { - case Kleo::CryptoConfigEntry::ArgType_None: - // A list of options with no arguments (e.g. -v -v -v) is shown as a spinbox - return new CryptoConfigEntrySpinBox( module, entry, entryName, glay, widget, name ); - case Kleo::CryptoConfigEntry::ArgType_Int: - case Kleo::CryptoConfigEntry::ArgType_UInt: - // Let people type list of numbers (1,2,3....). Untested. - return new CryptoConfigEntryLineEdit( module, entry, entryName, glay, widget, name ); - case Kleo::CryptoConfigEntry::ArgType_URL: - case Kleo::CryptoConfigEntry::ArgType_Path: - case Kleo::CryptoConfigEntry::ArgType_DirPath: - case Kleo::CryptoConfigEntry::ArgType_String: - kdWarning(5150) << "No widget implemented for list of type " << entry->argType() << endl; - return 0; // TODO when the need arises :) - case Kleo::CryptoConfigEntry::ArgType_LDAPURL: - return new CryptoConfigEntryLDAPURL( module, entry, entryName, glay, widget, name ); - } - kdWarning(5150) << "No widget implemented for list of (unknown) type " << entry->argType() << endl; - return 0; - } - - switch( entry->argType() ) { - case Kleo::CryptoConfigEntry::ArgType_None: - return new CryptoConfigEntryCheckBox( module, entry, entryName, glay, widget, name ); - case Kleo::CryptoConfigEntry::ArgType_Int: - case Kleo::CryptoConfigEntry::ArgType_UInt: - return new CryptoConfigEntrySpinBox( module, entry, entryName, glay, widget, name ); - case Kleo::CryptoConfigEntry::ArgType_URL: - return new CryptoConfigEntryURL( module, entry, entryName, glay, widget, name ); - case Kleo::CryptoConfigEntry::ArgType_Path: - return new CryptoConfigEntryPath( module, entry, entryName, glay, widget, name ); - case Kleo::CryptoConfigEntry::ArgType_DirPath: - return new CryptoConfigEntryDirPath( module, entry, entryName, glay, widget, name ); - case Kleo::CryptoConfigEntry::ArgType_LDAPURL: - kdWarning(5150) << "No widget implemented for type " << entry->argType() << endl; - return 0; // TODO when the need arises :) - case Kleo::CryptoConfigEntry::ArgType_String: - return new CryptoConfigEntryLineEdit( module, entry, entryName, glay, widget, name ); - } - kdWarning(5150) << "No widget implemented for (unknown) type " << entry->argType() << endl; - return 0; -} - -//// - -Kleo::CryptoConfigEntryGUI::CryptoConfigEntryGUI( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, - const QString& entryName, - const char* name ) - : QObject( module, name ), mEntry( entry ), mName( entryName ), mChanged( false ) -{ - connect( this, SIGNAL( changed() ), module, SIGNAL( changed() ) ); -} - -QString Kleo::CryptoConfigEntryGUI::description() const -{ - QString descr = mEntry->description(); - if ( descr.isEmpty() ) // shouldn't happen - descr = QString( "<%1>" ).arg( mName ); - return descr; -} - -void Kleo::CryptoConfigEntryGUI::resetToDefault() -{ - mEntry->resetToDefault(); - load(); -} - -//// - -Kleo::CryptoConfigEntryLineEdit::CryptoConfigEntryLineEdit( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, const QString& entryName, - QGridLayout * glay, QWidget* widget, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, name ) -{ - const int row = glay->numRows(); - mLineEdit = new KLineEdit( widget ); - glay->addWidget( new QLabel( mLineEdit, description(), widget ), row, 1 ); - glay->addWidget( mLineEdit, row, 2 ); - connect( mLineEdit, SIGNAL( textChanged( const QString& ) ), SLOT( slotChanged() ) ); -} - -void Kleo::CryptoConfigEntryLineEdit::doSave() -{ - mEntry->setStringValue( mLineEdit->text() ); -} - -void Kleo::CryptoConfigEntryLineEdit::doLoad() -{ - mLineEdit->setText( mEntry->stringValue() ); -} - -//// - -Kleo::CryptoConfigEntryPath::CryptoConfigEntryPath( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, const QString& entryName, - QGridLayout * glay, QWidget* widget, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, name ) -{ - const int row = glay->numRows(); - mUrlRequester = new KURLRequester( widget ); - mUrlRequester->setMode( KFile::File | KFile::ExistingOnly | KFile::LocalOnly ); - glay->addWidget( new QLabel( mUrlRequester, description(), widget ), row, 1 ); - glay->addWidget( mUrlRequester, row, 2 ); - connect( mUrlRequester, SIGNAL( textChanged( const QString& ) ), SLOT( slotChanged() ) ); -} - -void Kleo::CryptoConfigEntryPath::doSave() -{ - KURL url; - url.setPath( mUrlRequester->url() ); - mEntry->setURLValue( url ); -} - -void Kleo::CryptoConfigEntryPath::doLoad() -{ - mUrlRequester->setURL( mEntry->urlValue().path() ); -} - -//// - -Kleo::CryptoConfigEntryDirPath::CryptoConfigEntryDirPath( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, const QString& entryName, - QGridLayout * glay, QWidget* widget, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, name ) -{ - const int row = glay->numRows(); - mUrlRequester = new KURLRequester( widget ); - mUrlRequester->setMode( KFile::Directory | KFile::ExistingOnly | KFile::LocalOnly ); - glay->addWidget( new QLabel( mUrlRequester, description(), widget ), row, 1 ); - glay->addWidget( mUrlRequester, row, 2 ); - connect( mUrlRequester, SIGNAL( textChanged( const QString& ) ), SLOT( slotChanged() ) ); -} - -void Kleo::CryptoConfigEntryDirPath::doSave() -{ - KURL url; - url.setPath( mUrlRequester->url() ); - mEntry->setURLValue( url ); - -} - -void Kleo::CryptoConfigEntryDirPath::doLoad() -{ - mUrlRequester->setURL( mEntry->urlValue().path() ); -} - -//// - -Kleo::CryptoConfigEntryURL::CryptoConfigEntryURL( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, const QString& entryName, - QGridLayout * glay, QWidget* widget, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, name ) -{ - const int row = glay->numRows(); - mUrlRequester = new KURLRequester( widget ); - mUrlRequester->setMode( KFile::File | KFile::ExistingOnly ); - glay->addWidget( new QLabel( mUrlRequester, description(), widget ), row, 1 ); - glay->addWidget( mUrlRequester, row, 2 ); - connect( mUrlRequester, SIGNAL( textChanged( const QString& ) ), SLOT( slotChanged() ) ); -} - -void Kleo::CryptoConfigEntryURL::doSave() -{ - mEntry->setURLValue( mUrlRequester->url() ); -} - -void Kleo::CryptoConfigEntryURL::doLoad() -{ - mUrlRequester->setURL( mEntry->urlValue().url() ); -} - -//// - -Kleo::CryptoConfigEntrySpinBox::CryptoConfigEntrySpinBox( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, const QString& entryName, - QGridLayout * glay, QWidget* widget, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, name ) -{ - - if ( entry->argType() == Kleo::CryptoConfigEntry::ArgType_None && entry->isList() ) { - mKind = ListOfNone; - } else if ( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ) { - mKind = UInt; - } else { - Q_ASSERT( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Int ); - mKind = Int; - } - - const int row = glay->numRows(); - mNumInput = new KIntNumInput( widget ); - glay->addWidget( new QLabel( mNumInput, description(), widget ), row, 1 ); - glay->addWidget( mNumInput, row, 2 ); - - if ( mKind == UInt || mKind == ListOfNone ) - mNumInput->setMinValue( 0 ); - connect( mNumInput, SIGNAL( valueChanged(int) ), SLOT( slotChanged() ) ); -} - -void Kleo::CryptoConfigEntrySpinBox::doSave() -{ - int value = mNumInput->value(); - switch ( mKind ) { - case ListOfNone: - mEntry->setNumberOfTimesSet( value ); - break; - case UInt: - mEntry->setUIntValue( value ); - break; - case Int: - mEntry->setIntValue( value ); - break; - } -} - -void Kleo::CryptoConfigEntrySpinBox::doLoad() -{ - int value = 0; - switch ( mKind ) { - case ListOfNone: - value = mEntry->numberOfTimesSet(); - break; - case UInt: - value = mEntry->uintValue(); - break; - case Int: - value = mEntry->intValue(); - break; - } - mNumInput->setValue( value ); -} - -//// - -Kleo::CryptoConfigEntryCheckBox::CryptoConfigEntryCheckBox( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, const QString& entryName, - QGridLayout * glay, QWidget* widget, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, name ) -{ - const int row = glay->numRows(); - mCheckBox = new QCheckBox( widget ); - glay->addMultiCellWidget( mCheckBox, row, row, 1, 2 ); - mCheckBox->setText( description() ); - connect( mCheckBox, SIGNAL( toggled(bool) ), SLOT( slotChanged() ) ); -} - -void Kleo::CryptoConfigEntryCheckBox::doSave() -{ - mEntry->setBoolValue( mCheckBox->isChecked() ); -} - -void Kleo::CryptoConfigEntryCheckBox::doLoad() -{ - mCheckBox->setChecked( mEntry->boolValue() ); -} - -Kleo::CryptoConfigEntryLDAPURL::CryptoConfigEntryLDAPURL( - CryptoConfigModule* module, - Kleo::CryptoConfigEntry* entry, - const QString& entryName, - QGridLayout * glay, QWidget* widget, const char* name ) - : CryptoConfigEntryGUI( module, entry, entryName, name ) -{ - mLabel = new QLabel( widget ); - mPushButton = new QPushButton( i18n( "Edit..." ), widget ); - - - const int row = glay->numRows(); - glay->addWidget( new QLabel( mPushButton, description(), widget ), row, 1 ); - QHBoxLayout * hlay = new QHBoxLayout; - glay->addLayout( hlay, row, 2 ); - hlay->addWidget( mLabel, 1 ); - hlay->addWidget( mPushButton ); - - connect( mPushButton, SIGNAL( clicked() ), SLOT( slotOpenDialog() ) ); -} - -void Kleo::CryptoConfigEntryLDAPURL::doLoad() -{ - setURLList( mEntry->urlValueList() ); -} - -void Kleo::CryptoConfigEntryLDAPURL::doSave() -{ - mEntry->setURLValueList( mURLList ); -} - -void Kleo::CryptoConfigEntryLDAPURL::slotOpenDialog() -{ - // I'm a bad boy and I do it all on the stack. Enough classes already :) - // This is just a simple dialog around the directory-services-widget - KDialogBase dialog( mPushButton->parentWidget(), 0, true /*modal*/, - i18n( "Configure LDAP Servers" ), - KDialogBase::Default|KDialogBase::Cancel|KDialogBase::Ok, - KDialogBase::Ok, true /*separator*/ ); - DirectoryServicesWidget* dirserv = new DirectoryServicesWidget( mEntry, &dialog ); - dirserv->load(); - dialog.setMainWidget( dirserv ); - connect( &dialog, SIGNAL( defaultClicked() ), dirserv, SLOT( defaults() ) ); - if ( dialog.exec() ) { - // Note that we just grab the urls from the dialog, we don't call its save method, - // since the user hasn't confirmed the big config dialog yet. - setURLList( dirserv->urlList() ); - slotChanged(); - } -} - -void Kleo::CryptoConfigEntryLDAPURL::setURLList( const KURL::List& urlList ) -{ - mURLList = urlList; - if ( mURLList.isEmpty() ) - mLabel->setText( i18n( "No server configured yet" ) ); - else - mLabel->setText( i18n( "1 server configured", "%n servers configured", mURLList.count() ) ); -} - -#include "cryptoconfigmodule.moc" -#include "cryptoconfigmodule_p.moc" diff --git a/kleopatra/lib/ui/cryptoconfigmodule.h b/kleopatra/lib/ui/cryptoconfigmodule.h deleted file mode 100644 index 1858145947..0000000000 --- a/kleopatra/lib/ui/cryptoconfigmodule.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - cryptoconfigmodule.h - - This file is part of libkleopatra - Copyright (c) 2004,2005 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef CRYPTOCONFIGMODULE_H -#define CRYPTOCONFIGMODULE_H - -#include - -#include - -namespace Kleo { - - class CryptoConfig; - class CryptoConfigComponentGUI; - - /** - * Crypto Config Module widget, dynamically generated from CryptoConfig - * It's a simple QWidget so that it can be embedded into a dialog or into a KCModule. - */ - class CryptoConfigModule : public KJanusWidget { - Q_OBJECT - public: - CryptoConfigModule( Kleo::CryptoConfig* config, QWidget * parent=0, const char * name=0 ); - - void save(); - void reset(); // i.e. reload current settings, discarding user input - void defaults(); - void cancel(); - - signals: - void changed(); - - private: - Kleo::CryptoConfig* mConfig; - QValueList mComponentGUIs; - }; - -} - -#endif diff --git a/kleopatra/lib/ui/directoryserviceswidget.cpp b/kleopatra/lib/ui/directoryserviceswidget.cpp deleted file mode 100644 index 76c1b3ddab..0000000000 --- a/kleopatra/lib/ui/directoryserviceswidget.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/* - directoryserviceswidget.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include - -#include "directoryserviceswidget.h" -#include "adddirectoryservicedialogimpl.h" -#include "cryptplugwrapper.h" - -#include -#include -#include -#include - -#include -#include -#include -#include - -using namespace Kleo; - -class QX500ListViewItem : public QListViewItem -{ -public: - QX500ListViewItem( QListView* lv, QListViewItem* prev, - const QString& serverName, - const QString& portNumber, - const QString& dn, - const QString& username, - const QString& password ) - : QListViewItem( lv, prev, serverName, portNumber, dn, username ) { - setPassword( password ); - } - - void setPassword( const QString& pass ) { - mPassword = pass; - setText( 4, pass.isEmpty() ? QString::null : QString::fromLatin1( "******" ) ); - } - - const QString& password() const { return mPassword; } - - void setData( const QString& serverName, - const QString& portNumber, - const QString& dn, - const QString& username, - const QString& password ) { - setText( 0, serverName ); - setText( 1, portNumber ); - setText( 2, dn ); - setText( 3, username ); - setPassword( password ); - } - - void copyItem( QX500ListViewItem* item ) { - for ( unsigned int i = 0; i < 4 ; ++i ) - setText( i, item->text( i ) ); - setPassword( item->password() ); - } - -private: - QString mPassword; -}; - -Kleo::DirectoryServicesWidget::DirectoryServicesWidget( - Kleo::CryptoConfigEntry* configEntry, - QWidget* parent, const char* name, WFlags fl ) - : DirectoryServicesWidgetBase( parent, name, fl ), - mConfigEntry( configEntry ) -{ - x500LV->setSorting( -1 ); - - // taken from kmail's configuredialog.cpp - upButton->setIconSet( BarIconSet( "up", KIcon::SizeSmall ) ); - upButton->setEnabled( false ); // b/c no item is selected yet - - downButton->setIconSet( BarIconSet( "down", KIcon::SizeSmall ) ); - downButton->setEnabled( false ); // b/c no item is selected yet -} - - -/* - * Destroys the object and frees any allocated resources - */ -DirectoryServicesWidget::~DirectoryServicesWidget() -{ - // no need to delete child widgets, Qt does it all for us -} - - -/** - Enables or disables the widgets in this dialog according to the - capabilities of the current plugin passed as a parameter. -*/ -void DirectoryServicesWidget::enableDisable( CryptPlugWrapper* cryptPlug ) // unused? -{ - // disable the whole page if the plugin does not support the use - // of directory services - setEnabled( cryptPlug->hasFeature( Feature_CertificateDirectoryService ) || - cryptPlug->hasFeature( Feature_CRLDirectoryService ) ); -} - - -/* - * protected slot, connected to selectionChanged() - */ -void DirectoryServicesWidget::slotServiceChanged( QListViewItem* item ) -{ - if( item ) - removeServicePB->setEnabled( true ); - else - removeServicePB->setEnabled( false ); - downButton->setEnabled( item && item->itemBelow() ); - upButton->setEnabled( item && item->itemAbove() ); -} - - -/* - * protected slot, connected to returnPressed/doubleClicked - */ -void DirectoryServicesWidget::slotServiceSelected( QListViewItem* item ) -{ - AddDirectoryServiceDialogImpl* dlg = new AddDirectoryServiceDialogImpl( this ); - dlg->serverNameED->setText( item->text( 0 ) ); - dlg->portED->setText( item->text( 1 ) ); - dlg->descriptionED->setText( item->text( 2 ) ); - dlg->usernameED->setText( item->text( 3 ) ); - QString pass = static_cast( item )->password(); - dlg->passwordED->setText( pass ); - - if( dlg->exec() == QDialog::Accepted ) { - item->setText( 0, dlg->serverNameED->text() ); - item->setText( 1, dlg->portED->text() ); - item->setText( 2, dlg->descriptionED->text() ); - item->setText( 3, dlg->usernameED->text() ); - static_cast( item )->setPassword( dlg->passwordED->text() ); - emit changed(); - } - delete dlg; -} - - -/* - * protected slot - */ -void DirectoryServicesWidget::slotAddService() -{ - AddDirectoryServiceDialogImpl* dlg = new AddDirectoryServiceDialogImpl( this ); - if( dlg->exec() == QDialog::Accepted ) { - QX500ListViewItem *item = new QX500ListViewItem( x500LV, x500LV->lastItem(), - dlg->serverNameED->text(), - dlg->portED->text(), - dlg->descriptionED->text(), - dlg->usernameED->text(), - dlg->passwordED->text() ); - slotServiceChanged(item); - emit changed(); - } - delete dlg; -} - -/* - * protected slot - */ -void DirectoryServicesWidget::slotDeleteService() -{ - QListViewItem* item = x500LV->selectedItem(); - Q_ASSERT( item ); - if( !item ) - return; - else - delete item; - x500LV->triggerUpdate(); - item = x500LV->currentItem(); - x500LV->setCurrentItem( item ); // seems necessary... - x500LV->setSelected( item, true ); - emit changed(); -} - - -void DirectoryServicesWidget::setInitialServices( const KURL::List& urls ) -{ - x500LV->clear(); - for( KURL::List::const_iterator it = urls.begin(); it != urls.end(); ++it ) { - QString dn = KURL::decode_string( (*it).query().mid( 1 ) ); // decode query and skip leading '?' - (void)new QX500ListViewItem( x500LV, x500LV->lastItem(), - (*it).host(), - QString::number( (*it).port() ), - dn, - (*it).user(), - (*it).pass()); - } -} - -KURL::List DirectoryServicesWidget::urlList() const -{ - KURL::List lst; - QListViewItemIterator it( x500LV ); - for ( ; it.current() ; ++it ) { - QListViewItem* item = it.current(); - KURL url; - url.setProtocol( "ldap" ); - url.setHost( item->text( 0 ) ); - url.setPort( item->text( 1 ).toInt() ); - url.setPath( "/" ); // workaround KURL parsing bug - url.setQuery( item->text( 2 ) ); - url.setUser( item->text( 3 ) ); - url.setPass( static_cast( item )->password() ); - kdDebug() << url << endl; - lst << url; - } - return lst; -} - -void DirectoryServicesWidget::clear() -{ - x500LV->clear(); - emit changed(); -} - -void DirectoryServicesWidget::load() -{ - if ( mConfigEntry ) { - setInitialServices( mConfigEntry->urlValueList() ); - } -} - -void DirectoryServicesWidget::save() -{ - if ( mConfigEntry ) { - mConfigEntry->setURLValueList( urlList() ); - } -} - -void DirectoryServicesWidget::defaults() -{ - if ( mConfigEntry ) { - // resetToDefault doesn't work since gpgconf doesn't know any defaults for this entry. - //mConfigEntry->resetToDefault(); - //load(); - clear(); // the default is an empty list. - } -} - -static void swapItems( QX500ListViewItem *item, QX500ListViewItem *other ) -{ - QString serverName = item->text( 0 ); - QString portNumber = item->text( 1 ); - QString dn = item->text( 2 ); - QString username = item->text( 3 ); - QString password = item->password(); - item->copyItem( other ); - other->setData( serverName, portNumber, dn, username, password ); -} - -void Kleo::DirectoryServicesWidget::slotMoveUp() -{ - QX500ListViewItem *item = static_cast( x500LV->selectedItem() ); - if ( !item ) return; - QX500ListViewItem *above = static_cast( item->itemAbove() ); - if ( !above ) return; - swapItems( item, above ); - x500LV->setCurrentItem( above ); - x500LV->setSelected( above, true ); - emit changed(); -} - -void Kleo::DirectoryServicesWidget::slotMoveDown() -{ - QX500ListViewItem *item = static_cast( x500LV->selectedItem() ); - if ( !item ) return; - QX500ListViewItem *below = static_cast( item->itemBelow() ); - if ( !below ) return; - swapItems( item, below ); - x500LV->setCurrentItem( below ); - x500LV->setSelected( below, true ); - emit changed(); -} - -#include "directoryserviceswidget.moc" diff --git a/kleopatra/lib/ui/directoryserviceswidget.h b/kleopatra/lib/ui/directoryserviceswidget.h deleted file mode 100644 index 02e428c954..0000000000 --- a/kleopatra/lib/ui/directoryserviceswidget.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - directoryserviceswidget.h - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef DIRECTORYSERVICESWIDGET_H -#define DIRECTORYSERVICESWIDGET_H -#include "directoryserviceswidgetbase.h" -#include -#include - -class CryptPlugWrapper; -namespace Kleo { - -class CryptoConfigEntry; - -class KDE_EXPORT DirectoryServicesWidget : public DirectoryServicesWidgetBase -{ - Q_OBJECT - -public: - DirectoryServicesWidget( - Kleo::CryptoConfigEntry* configEntry, - QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); - ~DirectoryServicesWidget(); - - void load(); - void save(); - - void enableDisable( CryptPlugWrapper* wrapper ); // unused? - void setInitialServices( const KURL::List& urls ); - KURL::List urlList() const; - void clear(); - -public slots: - void defaults(); - -signals: - void changed(); - -protected slots: - void slotServiceChanged( QListViewItem* ); - void slotServiceSelected( QListViewItem* ); - void slotAddService(); - void slotDeleteService(); - void slotMoveUp(); - void slotMoveDown(); - -private: - Kleo::CryptoConfigEntry* mConfigEntry; -}; - -} - -#endif // DIRECTORYSERVICESWIDGET_H diff --git a/kleopatra/lib/ui/dnattributeorderconfigwidget.cpp b/kleopatra/lib/ui/dnattributeorderconfigwidget.cpp deleted file mode 100644 index ad2ec69fe0..0000000000 --- a/kleopatra/lib/ui/dnattributeorderconfigwidget.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* -*- c++ -*- - dnattributeorderconfigwidget.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klar�vdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "dnattributeorderconfigwidget.h" - -#include "kleo/dn.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -struct Kleo::DNAttributeOrderConfigWidget::Private { - enum { UUp=0, Up=1, Left=2, Right=3, Down=4, DDown=5 }; - - QListView * availableLV; - QListView * currentLV; - QToolButton * navTB[6]; - - QListViewItem * placeHolderItem; - - Kleo::DNAttributeMapper * mapper; -}; - -static void prepare( QListView * lv ) { - lv->setAllColumnsShowFocus( true ); - lv->setResizeMode( QListView::LastColumn ); - lv->header()->setClickEnabled( false ); - lv->addColumn( QString::null ); - lv->addColumn( i18n("Description") ); -} - -Kleo::DNAttributeOrderConfigWidget::DNAttributeOrderConfigWidget( DNAttributeMapper * mapper, QWidget * parent, const char * name, WFlags f ) - : QWidget( parent, name, f ), d( 0 ) -{ - assert( mapper ); - d = new Private(); - d->mapper = mapper; - - QGridLayout * glay = new QGridLayout( this, 2, 3, 0, KDialog::spacingHint() ); - glay->setColStretch( 0, 1 ); - glay->setColStretch( 2, 1 ); - - int row = -1; - - ++row; - glay->addWidget( new QLabel( i18n("Available attributes:"), this ), row, 0 ); - glay->addWidget( new QLabel( i18n("Current attribute order:"), this ), row, 2 ); - - - ++row; - glay->setRowStretch( row, 1 ); - - d->availableLV = new QListView( this ); - prepare( d->availableLV ); - d->availableLV->setSorting( 0 ); - glay->addWidget( d->availableLV, row, 0 ); - - d->currentLV = new QListView( this ); - prepare( d->currentLV ); - d->currentLV->setSorting( -1 ); - glay->addWidget( d->currentLV, row, 2 ); - - connect( d->availableLV, SIGNAL(selectionChanged(QListViewItem*)), - SLOT(slotAvailableSelectionChanged(QListViewItem*)) ); - connect( d->currentLV, SIGNAL(selectionChanged(QListViewItem*)), - SLOT(slotCurrentOrderSelectionChanged(QListViewItem*)) ); - - d->placeHolderItem = new QListViewItem( d->availableLV, "_X_", i18n("All others") ); - - // the up/down/left/right arrow cross: - - QGridLayout * xlay = new QGridLayout( 5, 3, 0, "xlay" ); - xlay->setAlignment( AlignCenter ); - - static const struct { - const char * icon; - int row, col; - const char * tooltip; - const char * slot; - } navButtons[] = { - { "2uparrow", 0, 1, I18N_NOOP( "Move to top" ), SLOT(slotDoubleUpButtonClicked()) }, - { "1uparrow", 1, 1, I18N_NOOP( "Move one up" ), SLOT(slotUpButtonClicked()) }, - { "1leftarrow", 2, 0, I18N_NOOP( "Remove from current attribute order" ), SLOT(slotLeftButtonClicked()) }, - { "1rightarrow", 2, 2, I18N_NOOP( "Add to current attribute order" ), SLOT(slotRightButtonClicked()) }, - { "1downarrow", 3, 1, I18N_NOOP( "Move one down" ), SLOT(slotDownButtonClicked()) }, - { "2downarrow", 4, 1, I18N_NOOP( "Move to bottom" ), SLOT(slotDoubleDownButtonClicked()) } - }; - - for ( unsigned int i = 0 ; i < sizeof navButtons / sizeof *navButtons ; ++i ) { - QToolButton * tb = d->navTB[i] = new QToolButton( this ); - tb->setIconSet( SmallIconSet( navButtons[i].icon ) ); - tb->setEnabled( false ); - QToolTip::add( tb, i18n( navButtons[i].tooltip ) ); - xlay->addWidget( tb, navButtons[i].row, navButtons[i].col ); - connect( tb, SIGNAL(clicked()), navButtons[i].slot ); - } - - glay->addLayout( xlay, row, 1 ); -} - -Kleo::DNAttributeOrderConfigWidget::~DNAttributeOrderConfigWidget() { - delete d; d = 0; -} - -void Kleo::DNAttributeOrderConfigWidget::load() { - // save the _X_ item: - takePlaceHolderItem(); - // clear the rest: - d->availableLV->clear(); - d->currentLV->clear(); - - const QStringList order = d->mapper->attributeOrder(); - - // fill the RHS listview: - QListViewItem * last = 0; - for ( QStringList::const_iterator it = order.begin() ; it != order.end() ; ++it ) { - const QString attr = (*it).upper(); - if ( attr == "_X_" ) { - takePlaceHolderItem(); - d->currentLV->insertItem( d->placeHolderItem ); - d->placeHolderItem->moveItem( last ); - last = d->placeHolderItem; - } else - last = new QListViewItem( d->currentLV, last, attr, d->mapper->name2label( attr ) ); - } - - // fill the LHS listview with what's left: - - const QStringList all = Kleo::DNAttributeMapper::instance()->names(); - for ( QStringList::const_iterator it = all.begin() ; it != all.end() ; ++it ) - if ( order.find( *it ) == order.end() ) - (void)new QListViewItem( d->availableLV, *it, d->mapper->name2label( *it ) ); - - if ( !d->placeHolderItem->listView() ) - d->availableLV->insertItem( d->placeHolderItem ); -} - -void Kleo::DNAttributeOrderConfigWidget::takePlaceHolderItem() { - if ( QListView * lv = d->placeHolderItem->listView() ) - lv->takeItem( d->placeHolderItem ); -} - -void Kleo::DNAttributeOrderConfigWidget::save() const { - QStringList order; - for ( QListViewItemIterator it( d->currentLV ) ; it.current() ; ++it ) - order.push_back( it.current()->text( 0 ) ); - - d->mapper->setAttributeOrder( order ); -} - -void Kleo::DNAttributeOrderConfigWidget::defaults() { - kdDebug() << "Sorry, not implemented: Kleo::DNAttributeOrderConfigWidget::defaults()" << endl; -} - - - -void Kleo::DNAttributeOrderConfigWidget::slotAvailableSelectionChanged( QListViewItem * item ) { - d->navTB[Private::Right]->setEnabled( item ); -} - -void Kleo::DNAttributeOrderConfigWidget::slotCurrentOrderSelectionChanged( QListViewItem * item ) { - enableDisableButtons( item ); -} - -void Kleo::DNAttributeOrderConfigWidget::enableDisableButtons( QListViewItem * item ) { - d->navTB[Private::UUp ]->setEnabled( item && item->itemAbove() ); - d->navTB[Private::Up ]->setEnabled( item && item->itemAbove() ); - d->navTB[Private::Left ]->setEnabled( item ); - d->navTB[Private::Down ]->setEnabled( item && item->itemBelow() ); - d->navTB[Private::DDown]->setEnabled( item && item->itemBelow() ); -} - -void Kleo::DNAttributeOrderConfigWidget::slotUpButtonClicked() { - QListViewItem * item = d->currentLV->selectedItem(); - if ( !item ) - return; - QListViewItem * above = item->itemAbove(); - if ( !above ) - return; - above->moveItem( item ); // moves "above" to after "item", ie. "item" one up - enableDisableButtons( item ); - emit changed(); -} - -void Kleo::DNAttributeOrderConfigWidget::slotDoubleUpButtonClicked() { - QListViewItem * item = d->currentLV->selectedItem(); - if ( !item ) - return; - if ( item == d->currentLV->firstChild() ) - return; - d->currentLV->takeItem( item ); - d->currentLV->insertItem( item ); - d->currentLV->setSelected( item, true ); - enableDisableButtons( item ); - emit changed(); -} - -void Kleo::DNAttributeOrderConfigWidget::slotDownButtonClicked() { - QListViewItem * item = d->currentLV->selectedItem(); - if ( !item ) - return; - QListViewItem * below = item->itemBelow(); - if ( !below ) - return; - item->moveItem( below ); // moves "item" to after "below", ie. "item" one down - enableDisableButtons( item ); - emit changed(); -} - -void Kleo::DNAttributeOrderConfigWidget::slotDoubleDownButtonClicked() { - QListViewItem * item = d->currentLV->selectedItem(); - if ( !item ) - return; - QListViewItem * last = d->currentLV->lastItem(); - assert( last ); - if ( item == last ) - return; - item->moveItem( last ); // moves "item" to after "last", ie. to the bottom - enableDisableButtons( item ); - emit changed(); -} - -void Kleo::DNAttributeOrderConfigWidget::slotLeftButtonClicked() { - QListViewItem * right = d->currentLV->selectedItem(); - if ( !right ) - return; - QListViewItem * next = right->itemBelow(); - if ( !next ) - next = right->itemAbove(); - d->currentLV->takeItem( right ); - d->availableLV->insertItem( right ); - if ( next ) - d->currentLV->setSelected( next, true ); - enableDisableButtons( next ); - emit changed(); -} - -void Kleo::DNAttributeOrderConfigWidget::slotRightButtonClicked() { - QListViewItem * left = d->availableLV->selectedItem(); - if ( !left ) - return; - QListViewItem * next = left->itemBelow(); - if ( !next ) - next = left->itemAbove(); - d->availableLV->takeItem( left ); - d->currentLV->insertItem( left ); - if ( QListViewItem * right = d->currentLV->selectedItem() ) { - if ( QListViewItem * above = right->itemAbove() ) - left->moveItem( above ); // move new item immediately before old selected - d->currentLV->setSelected( right, false ); - } - d->currentLV->setSelected( left, true ); - enableDisableButtons( left ); - d->navTB[Private::Right]->setEnabled( next ); - if ( next ) - d->availableLV->setSelected( next, true ); - emit changed(); -} - - - -void Kleo::DNAttributeOrderConfigWidget::virtual_hook( int, void* ) {} - -#include "dnattributeorderconfigwidget.moc" diff --git a/kleopatra/lib/ui/dnattributeorderconfigwidget.h b/kleopatra/lib/ui/dnattributeorderconfigwidget.h deleted file mode 100644 index 11299ab374..0000000000 --- a/kleopatra/lib/ui/dnattributeorderconfigwidget.h +++ /dev/null @@ -1,87 +0,0 @@ -/* -*- c++ -*- - dnattributeorderconfigwidget.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - */ - -#ifndef __KLEO_UI_DNATTRIBUTEORDERCONFIGWIDGET_H__ -#define __KLEO_UI_DNATTRIBUTEORDERCONFIGWIDGET_H__ - -#include -#include -namespace Kleo { - class DNAttributeMapper; -} - -class QListViewItem; - -namespace Kleo { - - class KDE_EXPORT DNAttributeOrderConfigWidget : public QWidget { - Q_OBJECT - public: - /*! Use Kleo::DNAttributeMapper::instance()->configWidget( parent, name ) instead. */ - DNAttributeOrderConfigWidget( DNAttributeMapper * mapper, QWidget * parent=0, const char * name=0, WFlags f=0 ); - ~DNAttributeOrderConfigWidget(); - - void load(); - void save() const; - void defaults(); - - signals: - void changed(); - - // - // only boring stuff below... - // - - private slots: - void slotAvailableSelectionChanged( QListViewItem * ); - void slotCurrentOrderSelectionChanged( QListViewItem * ); - void slotDoubleUpButtonClicked(); - void slotUpButtonClicked(); - void slotDownButtonClicked(); - void slotDoubleDownButtonClicked(); - void slotLeftButtonClicked(); - void slotRightButtonClicked(); - - private: - void takePlaceHolderItem(); - void enableDisableButtons( QListViewItem * ); - - private: - class Private; - Private * d; - protected: - virtual void virtual_hook( int, void* ); - }; - -} - -#endif // __KLEO_UI_DNATTRIBUTEORDERCONFIGWIDGET_H__ diff --git a/kleopatra/lib/ui/keyapprovaldialog.cpp b/kleopatra/lib/ui/keyapprovaldialog.cpp deleted file mode 100644 index 7af85a0bbc..0000000000 --- a/kleopatra/lib/ui/keyapprovaldialog.cpp +++ /dev/null @@ -1,227 +0,0 @@ -/* -*- c++ -*- - keyapprovaldialog.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Based on kpgpui.h - Copyright (C) 2001,2002 the KPGP authors - See file libkdenetwork/AUTHORS.kpgp for details - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "keyapprovaldialog.h" - -#include "keyrequester.h" - -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -static Kleo::EncryptionPreference cb2pref( int i ) { - switch ( i ) { - default: - case 0: return Kleo::UnknownPreference; - case 1: return Kleo::NeverEncrypt; - case 2: return Kleo::AlwaysEncrypt; - case 3: return Kleo::AlwaysEncryptIfPossible; - case 4: return Kleo::AlwaysAskForEncryption; - case 5: return Kleo::AskWheneverPossible; - } -} - -static int pref2cb( Kleo::EncryptionPreference p ) { - switch ( p ) { - default: return 0; - case Kleo::NeverEncrypt: return 1; - case Kleo::AlwaysEncrypt: return 2; - case Kleo::AlwaysEncryptIfPossible: return 3; - case Kleo::AlwaysAskForEncryption: return 4; - case Kleo::AskWheneverPossible: return 5; - } -} - -static QStringList preferencesStrings() { - return QStringList() << i18n("") - << i18n("Never Encrypt with This Key") - << i18n("Always Encrypt with This Key") - << i18n("Encrypt Whenever Encryption is Possible") - << i18n("Always Ask") - << i18n("Ask Whenever Encryption is Possible"); -} - - -struct Kleo::KeyApprovalDialog::Private { - Private() : selfRequester( 0 ), prefsChanged( false ) {} - - Kleo::KeyRequester * selfRequester; - QStringList addresses; - std::vector requesters; - std::vector preferences; - bool prefsChanged; -}; - -Kleo::KeyApprovalDialog::KeyApprovalDialog( const std::vector & recipients, - const std::vector & sender, - QWidget * parent, const char * name, - bool modal ) - : KDialogBase( parent, name, modal, i18n("Encryption Key Approval"), Ok|Cancel, Ok ), - d( 0 ) -{ - assert( !recipients.empty() ); - - d = new Private(); - - QFrame *page = makeMainWidget(); - QVBoxLayout * vlay = new QVBoxLayout( page, 0, spacingHint() ); - - vlay->addWidget( new QLabel( i18n("The following keys will be used for encryption:"), page ) ); - - QScrollView * sv = new QScrollView( page ); - sv->setResizePolicy( QScrollView::AutoOneFit ); - vlay->addWidget( sv ); - - QWidget * view = new QWidget( sv->viewport() ); - - QGridLayout * glay = new QGridLayout( view, 3, 2, marginHint(), spacingHint() ); - glay->setColStretch( 1, 1 ); - sv->addChild( view ); - - int row = -1; - - if ( !sender.empty() ) { - ++row; - glay->addWidget( new QLabel( i18n("Your keys:"), view ), row, 0 ); - d->selfRequester = new EncryptionKeyRequester( true, EncryptionKeyRequester::AllProtocols, view ); - d->selfRequester->setKeys( sender ); - glay->addWidget( d->selfRequester, row, 1 ); - ++row; - glay->addMultiCellWidget( new KSeparator( Horizontal, view ), row, row, 0, 1 ); - } - - const QStringList prefs = preferencesStrings(); - - for ( std::vector::const_iterator it = recipients.begin() ; it != recipients.end() ; ++it ) { - ++row; - glay->addWidget( new QLabel( i18n("Recipient:"), view ), row, 0 ); - glay->addWidget( new QLabel( it->address, view ), row, 1 ); - d->addresses.push_back( it->address ); - - ++row; - glay->addWidget( new QLabel( i18n("Encryption keys:"), view ), row, 0 ); - KeyRequester * req = new EncryptionKeyRequester( true, EncryptionKeyRequester::AllProtocols, view ); - req->setKeys( it->keys ); - glay->addWidget( req, row, 1 ); - d->requesters.push_back( req ); - - ++row; - glay->addWidget( new QLabel( i18n("Encryption preference:"), view ), row, 0 ); - QComboBox * cb = new QComboBox( false, view ); - cb->insertStringList( prefs ); - glay->addWidget( cb, row, 1 ); - cb->setCurrentItem( pref2cb( it->pref ) ); - connect( cb, SIGNAL(activated(int)), SLOT(slotPrefsChanged()) ); - d->preferences.push_back( cb ); - } - - // calculate the optimal width for the dialog - const int dialogWidth = marginHint() - + sv->frameWidth() - + view->sizeHint().width() - + sv->verticalScrollBar()->sizeHint().width() - + sv->frameWidth() - + marginHint() - + 2; - // calculate the optimal height for the dialog - const int dialogHeight = marginHint() - + fontMetrics().height() - + spacingHint() - + sv->frameWidth() - + view->sizeHint().height() - + sv->horizontalScrollBar()->sizeHint().height() - + sv->frameWidth() - + spacingHint() - + actionButton( KDialogBase::Cancel )->sizeHint().height() - + marginHint() - + 2; - - // don't make the dialog too large - const QRect desk = KGlobalSettings::desktopGeometry( this ); - setInitialSize( QSize( kMin( dialogWidth, 3 * desk.width() / 4 ), - kMin( dialogHeight, 7 * desk.height() / 8 ) ) ); -} - -Kleo::KeyApprovalDialog::~KeyApprovalDialog() { - delete d; d = 0; -} - -std::vector Kleo::KeyApprovalDialog::senderKeys() const { - return d->selfRequester ? d->selfRequester->keys() : std::vector() ; -} - -std::vector Kleo::KeyApprovalDialog::items() const { - assert( d->requesters.size() == d->addresses.size() ); - assert( d->requesters.size() == d->preferences.size() ); - - std::vector result; - result.reserve( d->requesters.size() ); - QStringList::const_iterator ait = d->addresses.begin(); - std::vector::const_iterator rit = d->requesters.begin(); - std::vector::const_iterator cit = d->preferences.begin(); - while ( ait != d->addresses.end() ) - result.push_back( Item( *ait++, (*rit++)->keys(), cb2pref( (*cit++)->currentItem() ) ) ); - return result; -} - -bool Kleo::KeyApprovalDialog::preferencesChanged() const { - return d->prefsChanged; -} - -void Kleo::KeyApprovalDialog::slotPrefsChanged() { - d->prefsChanged = true; -} - -#include "keyapprovaldialog.moc" diff --git a/kleopatra/lib/ui/keyapprovaldialog.h b/kleopatra/lib/ui/keyapprovaldialog.h deleted file mode 100644 index 224530a719..0000000000 --- a/kleopatra/lib/ui/keyapprovaldialog.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -*- c++ -*- - keyselectiondialog.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Based on kpgpui.h - Copyright (C) 2001,2002 the KPGP authors - See file libkdenetwork/AUTHORS.kpgp for details - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KEYAPPROVALDIALOG_H__ -#define __KLEO_KEYAPPROVALDIALOG_H__ - -#include - -#include -#include - -#include // for EncryptPref -#include - -#include - -namespace GpgME { - class Key; -} - -class QStringList; - -namespace Kleo { - - class KDE_EXPORT KeyApprovalDialog : public KDialogBase { - Q_OBJECT - public: - struct Item { - Item() : pref( UnknownPreference ) {} - Item( const QString & a, const std::vector & k, - EncryptionPreference p=UnknownPreference ) - : address( a ), keys( k ), pref( p ) {} - QString address; - std::vector keys; - EncryptionPreference pref; - }; - - KeyApprovalDialog( const std::vector & recipients, - const std::vector & sender, - QWidget * parent=0, const char * name=0, - bool modal=true ); - ~KeyApprovalDialog(); - - std::vector items() const; - std::vector senderKeys() const; - - bool preferencesChanged() const; - - private slots: - void slotPrefsChanged(); - - private: - class Private; - Private * d; - }; - -} // namespace Kleo - -#endif // __KLEO_KEYAPPROVALDIALOG_H__ diff --git a/kleopatra/lib/ui/keylistview.cpp b/kleopatra/lib/ui/keylistview.cpp deleted file mode 100644 index 98534a4b73..0000000000 --- a/kleopatra/lib/ui/keylistview.cpp +++ /dev/null @@ -1,869 +0,0 @@ -/* - keylistview.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "keylistview.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include - -#include - -static const int updateDelayMilliSecs = 500; - -namespace { - - class ItemToolTip : public QToolTip { - public: - ItemToolTip( Kleo::KeyListView * parent ); - protected: - void maybeTip( const QPoint & p ); - private: - Kleo::KeyListView * mKeyListView; - }; - - ItemToolTip::ItemToolTip( Kleo::KeyListView * parent ) - : QToolTip( parent->viewport() ), mKeyListView( parent ) {} - - void ItemToolTip::maybeTip( const QPoint & p ) { - if ( !mKeyListView ) - return; - - const QListViewItem * item = mKeyListView->itemAt( p ); - if ( !item ) - return; - - const QRect itemRect = mKeyListView->itemRect( item ); - if ( !itemRect.isValid() ) - return; - - const int col = mKeyListView->header()->sectionAt( p.x() ); - if ( col == -1 ) - return; - - const QRect headerRect = mKeyListView->header()->sectionRect( col ); - if ( !headerRect.isValid() ) - return; - - const QRect cellRect( headerRect.left(), itemRect.top(), - headerRect.width(), itemRect.height() ); - - QString tipStr; - if ( const Kleo::KeyListViewItem * klvi = Kleo::lvi_cast( item ) ) - tipStr = klvi->toolTip( col ); - else - tipStr = item->text( col ) ; - - if ( !tipStr.isEmpty() ) - tip( cellRect, tipStr ); - } - -} // anon namespace - -struct Kleo::KeyListView::Private { - Private() : updateTimer( 0 ), itemToolTip( 0 ) {} - - std::vector keyBuffer; - QTimer * updateTimer; - QToolTip * itemToolTip; - std::map itemMap; -}; - -// a list of signals where we want to replace QListViewItem with -// Kleo:KeyListViewItem: -static const struct { - const char * source; - const char * target; -} signalReplacements[] = { - { SIGNAL(doubleClicked(QListViewItem*,const QPoint&,int)), - SLOT(slotEmitDoubleClicked(QListViewItem*,const QPoint&,int)) }, - { SIGNAL(returnPressed(QListViewItem*)), - SLOT(slotEmitReturnPressed(QListViewItem*)) }, - { SIGNAL(selectionChanged(QListViewItem*)), - SLOT(slotEmitSelectionChanged(QListViewItem*)) }, - { SIGNAL(contextMenu(KListView*, QListViewItem*,const QPoint&)), - SLOT(slotEmitContextMenu(KListView*, QListViewItem*,const QPoint&)) }, -}; -static const int numSignalReplacements = sizeof signalReplacements / sizeof *signalReplacements; - - -Kleo::KeyListView::KeyListView( const ColumnStrategy * columnStrategy, const DisplayStrategy * displayStrategy, QWidget * parent, const char * name, WFlags f ) - : KListView( parent, name ), - mColumnStrategy( columnStrategy ), - mDisplayStrategy ( displayStrategy ), - mHierarchical( false ) -{ - setWFlags( f ); - - d = new Private(); - - d->updateTimer = new QTimer( this ); - connect( d->updateTimer, SIGNAL(timeout()), SLOT(slotUpdateTimeout()) ); - - if ( !columnStrategy ) { - kdWarning(5150) << "Kleo::KeyListView: need a column strategy to work with!" << endl; - return; - } - - const QFontMetrics fm = fontMetrics(); - - for ( int col = 0 ; !columnStrategy->title( col ).isEmpty() ; ++col ) { - addColumn( columnStrategy->title( col ), columnStrategy->width( col, fm ) ); - setColumnWidthMode( col, columnStrategy->widthMode( col ) ); - } - - setAllColumnsShowFocus( true ); - setShowToolTips( false ); // we do it instead... - - for ( int i = 0 ; i < numSignalReplacements ; ++i ) - connect( this, signalReplacements[i].source, signalReplacements[i].target ); - - QToolTip::remove( this ); - QToolTip::remove( viewport() ); // make double sure :) - d->itemToolTip = new ItemToolTip( this ); -} - -Kleo::KeyListView::~KeyListView() { - d->updateTimer->stop(); - // need to clear here, since in ~QListView, our children won't have - // a valid listView() pointing to us anymore, and their dtors try to - // unregister from us. - clear(); - assert( d->itemMap.size() == 0 ); - // need to delete the tooltip ourselves, as ~QToolTip isn't virtual :o - delete d->itemToolTip; d->itemToolTip = 0; - delete d; d = 0; - delete mColumnStrategy; mColumnStrategy = 0; - delete mDisplayStrategy; mDisplayStrategy = 0; -} - -void Kleo::KeyListView::insertItem( QListViewItem * qlvi ) { - //kdDebug() << "Kleo::KeyListView::insertItem( " << qlvi << " )" << endl; - KListView::insertItem( qlvi ); - if ( KeyListViewItem * item = lvi_cast( qlvi ) ) - registerItem( item ); -} - -void Kleo::KeyListView::takeItem( QListViewItem * qlvi ) { - //kdDebug() << "Kleo::KeyListView::takeItem( " << qlvi << " )" << endl; - if ( KeyListViewItem * item = lvi_cast( qlvi ) ) - deregisterItem( item ); - KListView::takeItem( qlvi ); -} - - -void Kleo::KeyListView::setHierarchical( bool hier ) { - if ( hier == mHierarchical ) - return; - mHierarchical = hier; - if ( hier ) - gatherScattered(); - else - scatterGathered( firstChild() ); -} - -void Kleo::KeyListView::slotAddKey( const GpgME::Key & key ) { - if ( key.isNull() ) - return; - - d->keyBuffer.push_back( key ); - if ( !d->updateTimer->isActive() ) - d->updateTimer->start( updateDelayMilliSecs, true /* single-shot */ ); -} - -void Kleo::KeyListView::slotUpdateTimeout() { - if ( d->keyBuffer.empty() ) - return; - - const bool wasUpdatesEnabled = viewport()->isUpdatesEnabled(); - if ( wasUpdatesEnabled ) - viewport()->setUpdatesEnabled( false ); - kdDebug( 5150 ) << "Kleo::KeyListView::slotUpdateTimeout(): processing " - << d->keyBuffer.size() << " items en block" << endl; - if ( hierarchical() ) { - for ( std::vector::const_iterator it = d->keyBuffer.begin() ; it != d->keyBuffer.end() ; ++it ) - doHierarchicalInsert( *it ); - gatherScattered(); - } else { - for ( std::vector::const_iterator it = d->keyBuffer.begin() ; it != d->keyBuffer.end() ; ++it ) - (void)new KeyListViewItem( this, *it ); - } - if ( wasUpdatesEnabled ) - viewport()->setUpdatesEnabled( true ); - d->keyBuffer.clear(); -} - -void Kleo::KeyListView::clear() { - d->updateTimer->stop(); - d->keyBuffer.clear(); - KListView::clear(); -} - -void Kleo::KeyListView::registerItem( KeyListViewItem * item ) { - //kdDebug() << "registerItem( " << item << " )" << endl; - if ( !item ) - return; - const QCString fpr = item->key().primaryFingerprint(); - if ( !fpr.isEmpty() ) - d->itemMap.insert( std::make_pair( fpr, item ) ); -} - -void Kleo::KeyListView::deregisterItem( const KeyListViewItem * item ) { - //kdDebug() << "deregisterItem( KeyLVI: " << item << " )" << endl; - if ( !item ) - return; - std::map::iterator it - = d->itemMap.find( item->key().primaryFingerprint() ); - if ( it == d->itemMap.end() ) - return; - Q_ASSERT( it->second == item ); - if ( it->second != item ) - return; - d->itemMap.erase( it ); -} - -void Kleo::KeyListView::doHierarchicalInsert( const GpgME::Key & key ) { - const QCString fpr = key.primaryFingerprint(); - if ( fpr.isEmpty() ) - return; - KeyListViewItem * item = 0; - if ( !key.isRoot() ) - if ( KeyListViewItem * parent = itemByFingerprint( key.chainID() ) ) { - item = new KeyListViewItem( parent, key ); - parent->setOpen( true ); - } - if ( !item ) - item = new KeyListViewItem( this, key ); // top-level (for now) - - d->itemMap.insert( std::make_pair( fpr, item ) ); -} - -void Kleo::KeyListView::gatherScattered() { - KeyListViewItem * item = firstChild(); - while ( item ) { - KeyListViewItem * cur = item; - item = item->nextSibling(); - if ( cur->key().isRoot() ) - continue; - if ( KeyListViewItem * parent = itemByFingerprint( cur->key().chainID() ) ) { - // found a new parent... - // ### todo: optimize by suppressing removing/adding the item to the itemMap... - takeItem( cur ); - parent->insertItem( cur ); - parent->setOpen( true ); - } - } -} - -void Kleo::KeyListView::scatterGathered( QListViewItem * start ) { - QListViewItem * item = start; - while ( item ) { - QListViewItem * cur = item; - item = item->nextSibling(); - - scatterGathered( cur->firstChild() ); - assert( cur->childCount() == 0 ); - - // ### todo: optimize by suppressing removing/adding the item to the itemMap... - if ( cur->parent() ) - cur->parent()->takeItem( cur ); - else - takeItem( cur ); - insertItem( cur ); - } -} - -Kleo::KeyListViewItem * Kleo::KeyListView::itemByFingerprint( const QCString & s ) const { - if ( s.isEmpty() ) - return 0; - const std::map::const_iterator it = d->itemMap.find( s ); - if ( it == d->itemMap.end() ) - return 0; - return it->second; -} - - -void Kleo::KeyListView::slotRefreshKey( const GpgME::Key & key ) { - const char * fpr = key.primaryFingerprint(); - if ( !fpr ) - return; - if ( KeyListViewItem * item = itemByFingerprint( fpr ) ) - item->setKey ( key ); - else - // none found -> add it - slotAddKey( key ); -} - -// slots for the emission of covariant signals: - -void Kleo::KeyListView::slotEmitDoubleClicked( QListViewItem * item, const QPoint & p, int col ) { - if ( !item || lvi_cast( item ) ) - emit doubleClicked( static_cast( item ), p, col ); -} - -void Kleo::KeyListView::slotEmitReturnPressed( QListViewItem * item ) { - if ( !item || lvi_cast( item ) ) - emit returnPressed( static_cast( item ) ); -} - -void Kleo::KeyListView::slotEmitSelectionChanged( QListViewItem * item ) { - if ( !item || lvi_cast( item ) ) - emit selectionChanged( static_cast( item ) ); -} - -void Kleo::KeyListView::slotEmitContextMenu( KListView*, QListViewItem * item, const QPoint & p ) { - if ( !item || lvi_cast( item ) ) - emit contextMenu( static_cast( item ), p ); -} - -// -// -// KeyListViewItem -// -// - -Kleo::KeyListViewItem::KeyListViewItem( KeyListView * parent, const GpgME::Key & key ) - : QListViewItem( parent ) -{ - setKey( key ); -} - -Kleo::KeyListViewItem::KeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::Key & key ) - : QListViewItem( parent, after ) -{ - setKey( key ); -} - -Kleo::KeyListViewItem::KeyListViewItem( KeyListViewItem * parent, const GpgME::Key & key ) - : QListViewItem( parent ) -{ - setKey( key ); -} - -Kleo::KeyListViewItem::KeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::Key & key ) - : QListViewItem( parent, after ) -{ - setKey( key ); -} - -Kleo::KeyListViewItem::~KeyListViewItem() { - // delete the children first... When children are deleted in the - // QLVI dtor, they don't have listView() anymore, thus they don't - // call deregister( this ), leading to stale entries in the - // itemMap... - while ( QListViewItem * item = firstChild() ) - delete item; - // better do this here, too, since deletion is top-down and thus - // we're deleted when our parent item is no longer a - // KeyListViewItem, but a mere QListViewItem, so our takeItem() - // overload is gone by that time... - if ( KeyListView * lv = listView() ) - lv->deregisterItem( this ); -} - -void Kleo::KeyListViewItem::setKey( const GpgME::Key & key ) { - KeyListView * lv = listView(); - if ( lv ) - lv->deregisterItem( this ); - mKey = key; - if ( lv ) - lv->registerItem( this ); - - // the ColumnStrategy operations might be very slow, so cache their - // result here, where we're non-const :) - const Kleo::KeyListView::ColumnStrategy * cs = lv ? lv->columnStrategy() : 0 ; - if ( !cs ) - return; - const int numCols = lv ? lv->columns() : 0 ; - for ( int i = 0 ; i < numCols ; ++i ) { - setText( i, cs->text( key, i ) ); - if ( const QPixmap * pix = cs->pixmap( key, i ) ) - setPixmap( i, *pix ); - } - repaint(); -} - -QString Kleo::KeyListViewItem::toolTip( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->toolTip( key(), col ) - : QString::null ; -} - -int Kleo::KeyListViewItem::compare( QListViewItem * item, int col, bool ascending ) const { - if ( !item || item->rtti() != RTTI || !listView() || !listView()->columnStrategy() ) - return QListViewItem::compare( item, col, ascending ); - KeyListViewItem * that = static_cast( item ); - return listView()->columnStrategy()->compare( this->key(), that->key(), col ); -} - -void Kleo::KeyListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { - const KeyListView::DisplayStrategy * ds = listView() ? listView()->displayStrategy() : 0 ; - if ( !ds ) { - QListViewItem::paintCell( p, cg, column, width, alignment ); - return; - } - const QColor fg = ds->keyForeground( key(), cg.text() ); - const QColor bg = ds->keyBackground( key(), cg.base() ); - const QFont f = ds->keyFont( key(), p->font() ); - - QColorGroup _cg = cg; - p->setFont( f ); - _cg.setColor( QColorGroup::Text, fg ); - _cg.setColor( QColorGroup::Base, bg ); - - QListViewItem::paintCell( p, _cg, column, width, alignment ); -} - -void Kleo::KeyListViewItem::insertItem( QListViewItem * qlvi ) { - //kdDebug() << "Kleo::KeyListViewItem::insertItem( " << qlvi << " )" << endl; - QListViewItem::insertItem( qlvi ); - if ( KeyListViewItem * item = lvi_cast( qlvi ) ) - listView()->registerItem( item ); -} - -void Kleo::KeyListViewItem::takeItem( QListViewItem * qlvi ) { - //kdDebug() << "Kleo::KeyListViewItem::takeItem( " << qlvi << " )" << endl; - if ( KeyListViewItem * item = lvi_cast( qlvi ) ) - listView()->deregisterItem( item ); - QListViewItem::takeItem( qlvi ); -} - - -// -// -// SubkeyKeyListViewItem -// -// - -Kleo::SubkeyKeyListViewItem::SubkeyKeyListViewItem( KeyListView * parent, const GpgME::Subkey & subkey ) - : KeyListViewItem( parent, subkey.parent() ), mSubkey( subkey ) -{ - -} - -Kleo::SubkeyKeyListViewItem::SubkeyKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::Subkey & subkey ) - : KeyListViewItem( parent, after, subkey.parent() ), mSubkey( subkey ) -{ - -} - -Kleo::SubkeyKeyListViewItem::SubkeyKeyListViewItem( KeyListViewItem * parent, const GpgME::Subkey & subkey ) - : KeyListViewItem( parent, subkey.parent() ), mSubkey( subkey ) -{ - -} - -Kleo::SubkeyKeyListViewItem::SubkeyKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::Subkey & subkey ) - : KeyListViewItem( parent, after, subkey.parent() ), mSubkey( subkey ) -{ - -} - -void Kleo::SubkeyKeyListViewItem::setSubkey( const GpgME::Subkey & subkey ) { - mSubkey = subkey; - setKey( subkey.parent() ); -} - -QString Kleo::SubkeyKeyListViewItem::text( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->subkeyText( subkey(), col ) - : QString::null ; -} - -QString Kleo::SubkeyKeyListViewItem::toolTip( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->subkeyToolTip( subkey(), col ) - : QString::null ; -} - -const QPixmap * Kleo::SubkeyKeyListViewItem::pixmap( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->subkeyPixmap( subkey(), col ) : 0 ; -} - -int Kleo::SubkeyKeyListViewItem::compare( QListViewItem * item, int col, bool ascending ) const { - if ( !item || item->rtti() != RTTI || !listView() || !listView()->columnStrategy() ) - return KeyListViewItem::compare( item, col, ascending ); - SubkeyKeyListViewItem * that = static_cast( item ); - return listView()->columnStrategy()->subkeyCompare( this->subkey(), that->subkey(), col ); -} - -void Kleo::SubkeyKeyListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { - const KeyListView::DisplayStrategy * ds = listView() ? listView()->displayStrategy() : 0 ; - if ( !ds ) { - QListViewItem::paintCell( p, cg, column, width, alignment ); - return; - } - const QColor fg = ds->subkeyForeground( subkey(), cg.text() ); - const QColor bg = ds->subkeyBackground( subkey(), cg.base() ); - const QFont f = ds->subkeyFont( subkey(), p->font() ); - - QColorGroup _cg = cg; - p->setFont( f ); - _cg.setColor( QColorGroup::Text, fg ); - _cg.setColor( QColorGroup::Base, bg ); - - QListViewItem::paintCell( p, _cg, column, width, alignment ); -} - - -// -// -// UserIDKeyListViewItem -// -// - -Kleo::UserIDKeyListViewItem::UserIDKeyListViewItem( KeyListView * parent, const GpgME::UserID & userID ) - : KeyListViewItem( parent, userID.parent() ), mUserID( userID ) -{ - -} - -Kleo::UserIDKeyListViewItem::UserIDKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::UserID & userID ) - : KeyListViewItem( parent, after, userID.parent() ), mUserID( userID ) -{ - -} - -Kleo::UserIDKeyListViewItem::UserIDKeyListViewItem( KeyListViewItem * parent, const GpgME::UserID & userID ) - : KeyListViewItem( parent, userID.parent() ), mUserID( userID ) -{ - -} - -Kleo::UserIDKeyListViewItem::UserIDKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::UserID & userID ) - : KeyListViewItem( parent, after, userID.parent() ), mUserID( userID ) -{ - -} - -void Kleo::UserIDKeyListViewItem::setUserID( const GpgME::UserID & userID ) { - mUserID = userID; - setKey( userID.parent() ); -} - -QString Kleo::UserIDKeyListViewItem::text( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->userIDText( userID(), col ) - : QString::null ; -} - -QString Kleo::UserIDKeyListViewItem::toolTip( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->userIDToolTip( userID(), col ) - : QString::null ; -} - -const QPixmap * Kleo::UserIDKeyListViewItem::pixmap( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->userIDPixmap( userID(), col ) : 0 ; -} - -int Kleo::UserIDKeyListViewItem::compare( QListViewItem * item, int col, bool ascending ) const { - if ( !item || item->rtti() != RTTI || !listView() || !listView()->columnStrategy() ) - return KeyListViewItem::compare( item, col, ascending ); - UserIDKeyListViewItem * that = static_cast( item ); - return listView()->columnStrategy()->userIDCompare( this->userID(), that->userID(), col ); -} - - -void Kleo::UserIDKeyListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { - const KeyListView::DisplayStrategy * ds = listView() ? listView()->displayStrategy() : 0 ; - if ( !ds ) { - QListViewItem::paintCell( p, cg, column, width, alignment ); - return; - } - const QColor fg = ds->useridForeground( userID(), cg.text() ); - const QColor bg = ds->useridBackground( userID(), cg.base() ); - const QFont f = ds->useridFont( userID(), p->font() ); - - QColorGroup _cg = cg; - p->setFont( f ); - _cg.setColor( QColorGroup::Text, fg ); - _cg.setColor( QColorGroup::Base, bg ); - - QListViewItem::paintCell( p, _cg, column, width, alignment ); -} - - -// -// -// SignatureKeyListViewItem -// -// - -Kleo::SignatureKeyListViewItem::SignatureKeyListViewItem( KeyListView * parent, const GpgME::UserID::Signature & signature ) - : KeyListViewItem( parent, signature.parent().parent() ), mSignature( signature ) -{ - -} - -Kleo::SignatureKeyListViewItem::SignatureKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::UserID::Signature & signature ) - : KeyListViewItem( parent, after, signature.parent().parent() ), mSignature( signature ) -{ - -} - -Kleo::SignatureKeyListViewItem::SignatureKeyListViewItem( KeyListViewItem * parent, const GpgME::UserID::Signature & signature ) - : KeyListViewItem( parent, signature.parent().parent() ), mSignature( signature ) -{ - -} - -Kleo::SignatureKeyListViewItem::SignatureKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::UserID::Signature & signature ) - : KeyListViewItem( parent, after, signature.parent().parent() ), mSignature( signature ) -{ - -} - -void Kleo::SignatureKeyListViewItem::setSignature( const GpgME::UserID::Signature & signature ) { - mSignature = signature; - setKey( signature.parent().parent() ); -} - -QString Kleo::SignatureKeyListViewItem::text( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->signatureText( signature(), col ) - : QString::null ; -} - -QString Kleo::SignatureKeyListViewItem::toolTip( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->signatureToolTip( signature(), col ) - : QString::null ; -} - -const QPixmap * Kleo::SignatureKeyListViewItem::pixmap( int col ) const { - return listView() && listView()->columnStrategy() - ? listView()->columnStrategy()->signaturePixmap( signature(), col ) : 0 ; -} - -int Kleo::SignatureKeyListViewItem::compare( QListViewItem * item, int col, bool ascending ) const { - if ( !item || item->rtti() != RTTI || !listView() || !listView()->columnStrategy() ) - return KeyListViewItem::compare( item, col, ascending ); - SignatureKeyListViewItem * that = static_cast( item ); - return listView()->columnStrategy()->signatureCompare( this->signature(), that->signature(), col ); -} - -void Kleo::SignatureKeyListViewItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ) { - const KeyListView::DisplayStrategy * ds = listView() ? listView()->displayStrategy() : 0 ; - if ( !ds ) { - QListViewItem::paintCell( p, cg, column, width, alignment ); - return; - } - const QColor fg = ds->signatureForeground( signature(), cg.text() ); - const QColor bg = ds->signatureBackground( signature(), cg.base() ); - const QFont f = ds->signatureFont( signature(), p->font() ); - - QColorGroup _cg = cg; - p->setFont( f ); - _cg.setColor( QColorGroup::Text, fg ); - _cg.setColor( QColorGroup::Base, bg ); - - QListViewItem::paintCell( p, _cg, column, width, alignment ); -} - - -// -// -// ColumnStrategy -// -// - -Kleo::KeyListView::ColumnStrategy::~ColumnStrategy() {} - -int Kleo::KeyListView::ColumnStrategy::compare( const GpgME::Key & key1, const GpgME::Key & key2, int col ) const { - return QString::localeAwareCompare( text( key1, col ), text( key2, col ) ); -} - -int Kleo::KeyListView::ColumnStrategy::width( int col, const QFontMetrics & fm ) const { - return fm.width( title( col ) ) * 2; -} - -int Kleo::KeyListView::ColumnStrategy::subkeyCompare( const GpgME::Subkey & sub1, const GpgME::Subkey & sub2, int col ) const { - return QString::localeAwareCompare( subkeyText( sub1, col ), subkeyText( sub2, col ) ); -} - -int Kleo::KeyListView::ColumnStrategy::userIDCompare( const GpgME::UserID & uid1, const GpgME::UserID & uid2, int col ) const { - return QString::localeAwareCompare( userIDText( uid1, col ), userIDText( uid2, col ) ); -} - -int Kleo::KeyListView::ColumnStrategy::signatureCompare( const GpgME::UserID::Signature & sig1, const GpgME::UserID::Signature & sig2, int col ) const { - return QString::localeAwareCompare( signatureText( sig1, col ), signatureText( sig2, col ) ); -} - -QString Kleo::KeyListView::ColumnStrategy::toolTip( const GpgME::Key & key, int col ) const { - return text( key, col ); -} - -QString Kleo::KeyListView::ColumnStrategy::subkeyToolTip( const GpgME::Subkey & sub, int col ) const { - return subkeyText( sub, col ); -} - -QString Kleo::KeyListView::ColumnStrategy::userIDToolTip( const GpgME::UserID & uid, int col ) const { - return userIDText( uid, col ); -} - -QString Kleo::KeyListView::ColumnStrategy::signatureToolTip( const GpgME::UserID::Signature & sig, int col ) const { - return signatureText( sig, col ); -} - -// -// -// DisplayStrategy -// -// - -Kleo::KeyListView::DisplayStrategy::~DisplayStrategy() {} - - -//font -QFont Kleo::KeyListView::DisplayStrategy::keyFont( const GpgME::Key &, const QFont & font ) const { - return font; -} - -QFont Kleo::KeyListView::DisplayStrategy::subkeyFont( const GpgME::Subkey &, const QFont & font ) const { - return font; -} - -QFont Kleo::KeyListView::DisplayStrategy::useridFont( const GpgME::UserID &, const QFont & font ) const { - return font; -} - -QFont Kleo::KeyListView::DisplayStrategy::signatureFont( const GpgME::UserID::Signature &, const QFont & font ) const { - return font; -} - -//foreground -QColor Kleo::KeyListView::DisplayStrategy::keyForeground( const GpgME::Key &, const QColor & fg )const { - return fg; -} - -QColor Kleo::KeyListView::DisplayStrategy::subkeyForeground( const GpgME::Subkey &, const QColor & fg ) const { - return fg; -} - -QColor Kleo::KeyListView::DisplayStrategy::useridForeground( const GpgME::UserID &, const QColor & fg ) const { - return fg; -} - -QColor Kleo::KeyListView::DisplayStrategy::signatureForeground( const GpgME::UserID::Signature &, const QColor & fg ) const { - return fg; -} - -//background -QColor Kleo::KeyListView::DisplayStrategy::keyBackground( const GpgME::Key &, const QColor & bg )const { - return bg; -} - -QColor Kleo::KeyListView::DisplayStrategy::subkeyBackground( const GpgME::Subkey &, const QColor & bg ) const { - return bg; -} - -QColor Kleo::KeyListView::DisplayStrategy::useridBackground( const GpgME::UserID &, const QColor & bg ) const { - return bg; -} - -QColor Kleo::KeyListView::DisplayStrategy::signatureBackground( const GpgME::UserID::Signature &, const QColor & bg ) const { - return bg; -} - - -// -// -// Collection of covariant return reimplementations of QListView(Item) -// members: -// -// - -Kleo::KeyListView * Kleo::KeyListViewItem::listView() const { - return static_cast( QListViewItem::listView() ); -} - -Kleo::KeyListViewItem * Kleo::KeyListViewItem::nextSibling() const { - return static_cast( QListViewItem::nextSibling() ); -} - -Kleo::KeyListViewItem * Kleo::KeyListView::firstChild() const { - return static_cast( KListView::firstChild() ); -} - -Kleo::KeyListViewItem * Kleo::KeyListView::selectedItem() const { - return static_cast( KListView::selectedItem() ); -} - -static void selectedItems( QPtrList & result, QListViewItem * start ) { - for ( QListViewItem * item = start ; item ; item = item->nextSibling() ) { - if ( item->isSelected() ) - if ( Kleo::KeyListViewItem * i = Kleo::lvi_cast( item ) ) - result.append( i ); - selectedItems( result, item->firstChild() ); - } -} - -QPtrList Kleo::KeyListView::selectedItems() const { - QPtrList result; - ::selectedItems( result, firstChild() ); - return result; -} - -static bool hasSelection( QListViewItem * start ) { - for ( QListViewItem * item = start ; item ; item = item->nextSibling() ) - if ( item->isSelected() || hasSelection( item->firstChild() ) ) - return true; - return false; -} - -bool Kleo::KeyListView::hasSelection() const { - return ::hasSelection( firstChild() ); -} - -#include "keylistview.moc" diff --git a/kleopatra/lib/ui/keylistview.h b/kleopatra/lib/ui/keylistview.h deleted file mode 100644 index 3ef7087710..0000000000 --- a/kleopatra/lib/ui/keylistview.h +++ /dev/null @@ -1,323 +0,0 @@ -/* - keylistview.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_KEYLISTVIEW_H__ -#define __KLEO_KEYLISTVIEW_H__ - -#include - -#include -#include - -class QPainter; -class QColorGroup; -class QFont; -class QColor; - -namespace Kleo { - - // work around moc parser bug... -#define TEMPLATE_TYPENAME(T) template - TEMPLATE_TYPENAME(T) - inline T * lvi_cast( QListViewItem * item ) { - return item && (item->rtti() & T::RTTI_MASK) == T::RTTI - ? static_cast( item ) : 0 ; - } - - TEMPLATE_TYPENAME(T) - inline const T * lvi_cast( const QListViewItem * item ) { - return item && (item->rtti() & T::RTTI_MASK) == T::RTTI - ? static_cast( item ) : 0 ; - } -#undef TEMPLATE_TYPENAME - - class KeyListView; - - class KDE_EXPORT KeyListViewItem : public QListViewItem { - public: - KeyListViewItem( KeyListView * parent, const GpgME::Key & key ); - KeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::Key & key ); - KeyListViewItem( KeyListViewItem * parent, const GpgME::Key & key ); - KeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::Key & key ); - ~KeyListViewItem(); - - void setKey( const GpgME::Key & key ); - const GpgME::Key & key() const { return mKey; } - - enum { RTTI_MASK = 0xFFFFFFF0, RTTI = 0x2C1362E0 }; - - // - // only boring stuff below: - // - virtual QString toolTip( int column ) const; - - /*! \reimp for covariant return */ - KeyListView * listView() const; - /*! \reimp for covariant return */ - KeyListViewItem * nextSibling() const; - /*! \reimp */ - int compare( QListViewItem * other, int col, bool ascending ) const; - /*! \reimp to allow for key() overload above */ - QString key( int col, bool ascending ) const { return QListViewItem::key( col, ascending ); } - /*! \reimp */ - int rtti() const { return RTTI; } - /*! \reimp */ - void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); - /*! \reimp */ - void insertItem( QListViewItem * item ); - /*! \reimp */ - void takeItem( QListViewItem * item ); - - private: - GpgME::Key mKey; - }; - - class KDE_EXPORT SubkeyKeyListViewItem : public KeyListViewItem { - public: - SubkeyKeyListViewItem( KeyListView * parent, const GpgME::Subkey & subkey ); - SubkeyKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::Subkey & subkey ); - SubkeyKeyListViewItem( KeyListViewItem * parent, const GpgME::Subkey & subkey ); - SubkeyKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::Subkey & subkey ); - - void setSubkey( const GpgME::Subkey & subkey ); - const GpgME::Subkey & subkey() const { return mSubkey; } - - enum { RTTI = KeyListViewItem::RTTI + 1 }; - - // - // only boring stuff below: - // - /*! \reimp */ - QString toolTip( int col ) const; - /*! \reimp */ - QString text( int col ) const; - /*! \reimp */ - const QPixmap * pixmap( int col ) const; - /*! \reimp */ - int compare( QListViewItem * other, int col, bool ascending ) const; - /*! \reimp */ - int rtti() const { return RTTI; } - /*! \reimp */ - void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); - - private: - GpgME::Subkey mSubkey; - }; - - class KDE_EXPORT UserIDKeyListViewItem : public KeyListViewItem { - public: - UserIDKeyListViewItem( KeyListView * parent, const GpgME::UserID & userid ); - UserIDKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::UserID & userid ); - UserIDKeyListViewItem( KeyListViewItem * parent, const GpgME::UserID & userid ); - UserIDKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::UserID & userid ); - - void setUserID( const GpgME::UserID & userid ); - const GpgME::UserID userID() const { return mUserID; } - - enum { RTTI = KeyListViewItem::RTTI + 2 }; - - // - // only boring stuff below: - // - /*! \reimp */ - QString toolTip( int col ) const; - /*! \reimp */ - QString text( int col ) const; - /*! \reimp */ - const QPixmap * pixmap( int col ) const; - /*! \reimp */ - int compare( QListViewItem * other, int col, bool ascending ) const; - /*! \reimp */ - int rtti() const { return RTTI; } - /*! \reimp */ - void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); - - private: - GpgME::UserID mUserID; - }; - - class KDE_EXPORT SignatureKeyListViewItem : public KeyListViewItem { - public: - SignatureKeyListViewItem( KeyListView * parent, const GpgME::UserID::Signature & sig ); - SignatureKeyListViewItem( KeyListView * parent, KeyListViewItem * after, const GpgME::UserID::Signature & sig ); - SignatureKeyListViewItem( KeyListViewItem * parent, const GpgME::UserID::Signature & sig ); - SignatureKeyListViewItem( KeyListViewItem * parent, KeyListViewItem * after, const GpgME::UserID::Signature & sig ); - - void setSignature( const GpgME::UserID::Signature & sig ); - const GpgME::UserID::Signature & signature() const { return mSignature; } - - enum { RTTI = KeyListViewItem::RTTI + 3 }; - - // - // only boring stuff below: - // - /*! \reimp */ - QString toolTip( int col ) const; - /*! \reimp */ - QString text( int col ) const; - /*! \reimp */ - const QPixmap * pixmap( int col ) const; - /*! \reimp */ - int compare( QListViewItem * other, int col, bool ascending ) const; - /*! \reimp */ - int rtti() const { return RTTI; } - /*! \reimp */ - void paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int alignment ); - - private: - GpgME::UserID::Signature mSignature; - }; - - - class KDE_EXPORT KeyListView : public KListView { - Q_OBJECT - friend class KeyListViewItem; - public: - - class KDE_EXPORT ColumnStrategy { - public: - virtual ~ColumnStrategy(); - virtual QString title( int column ) const = 0; - virtual int width( int column, const QFontMetrics & fm ) const; - virtual QListView::WidthMode widthMode( int ) const { return QListView::Manual; } - - virtual QString text( const GpgME::Key & key, int column ) const = 0; - virtual QString toolTip( const GpgME::Key & key, int column ) const; - virtual const QPixmap * pixmap( const GpgME::Key &, int ) const { return 0; } - virtual int compare( const GpgME::Key & key1, const GpgME::Key & key2, const int column ) const; - - virtual QString subkeyText( const GpgME::Subkey &, int ) const { return QString::null; } - virtual QString subkeyToolTip( const GpgME::Subkey & subkey, int column ) const; - virtual const QPixmap * subkeyPixmap( const GpgME::Subkey &, int ) const { return 0; } - virtual int subkeyCompare( const GpgME::Subkey & subkey1, const GpgME::Subkey & subkey2, const int column ) const; - - virtual QString userIDText( const GpgME::UserID &, int ) const { return QString::null; } - virtual QString userIDToolTip( const GpgME::UserID & userID, int column ) const; - virtual const QPixmap * userIDPixmap( const GpgME::UserID &, int ) const { return 0; } - virtual int userIDCompare( const GpgME::UserID & userID1, const GpgME::UserID & userID2, const int column ) const; - - virtual QString signatureText( const GpgME::UserID::Signature &, int ) const { return QString::null; } - virtual QString signatureToolTip( const GpgME::UserID::Signature & sig, int column ) const; - virtual const QPixmap * signaturePixmap( const GpgME::UserID::Signature &, int ) const { return 0; } - virtual int signatureCompare( const GpgME::UserID::Signature & sig1, const GpgME::UserID::Signature & sig2, const int column ) const; - }; - - class KDE_EXPORT DisplayStrategy { - public: - virtual ~DisplayStrategy(); - //font - virtual QFont keyFont( const GpgME::Key &, const QFont & ) const; - virtual QFont subkeyFont( const GpgME::Subkey &, const QFont & ) const; - virtual QFont useridFont( const GpgME::UserID &, const QFont & ) const; - virtual QFont signatureFont( const GpgME::UserID::Signature & , const QFont & ) const; - //foreground - virtual QColor keyForeground( const GpgME::Key & , const QColor & ) const; - virtual QColor subkeyForeground( const GpgME::Subkey &, const QColor & ) const; - virtual QColor useridForeground( const GpgME::UserID &, const QColor & ) const; - virtual QColor signatureForeground( const GpgME::UserID::Signature &, const QColor & ) const; - //background - virtual QColor keyBackground( const GpgME::Key &, const QColor & ) const; - virtual QColor subkeyBackground( const GpgME::Subkey &, const QColor & ) const; - virtual QColor useridBackground( const GpgME::UserID &, const QColor & ) const; - virtual QColor signatureBackground( const GpgME::UserID::Signature &, const QColor & ) const; - }; - - KeyListView( const ColumnStrategy * strategy, - const DisplayStrategy * display=0, - QWidget * parent=0, const char * name=0, WFlags f=0 ); - - ~KeyListView(); - - const ColumnStrategy * columnStrategy() const { return mColumnStrategy; } - const DisplayStrategy * displayStrategy() const { return mDisplayStrategy; } - - bool hierarchical() const { return mHierarchical; } - virtual void setHierarchical( bool hier ); - - void flushKeys() { slotUpdateTimeout(); } - - bool hasSelection() const; - - KeyListViewItem * itemByFingerprint( const QCString & ) const; - - signals: - void doubleClicked( Kleo::KeyListViewItem*, const QPoint&, int ); - void returnPressed( Kleo::KeyListViewItem* ); - void selectionChanged( Kleo::KeyListViewItem* ); - void contextMenu( Kleo::KeyListViewItem*, const QPoint& ); - - public slots: - virtual void slotAddKey( const GpgME::Key & key ); - virtual void slotRefreshKey( const GpgME::Key & key ); - - // - // Only boring stuff below: - // - private slots: - void slotEmitDoubleClicked( QListViewItem*, const QPoint&, int ); - void slotEmitReturnPressed( QListViewItem* ); - void slotEmitSelectionChanged( QListViewItem* ); - void slotEmitContextMenu( KListView*, QListViewItem*, const QPoint& ); - void slotUpdateTimeout(); - - public: - /*! \reimp for covariant return */ - KeyListViewItem * selectedItem() const; - /*! \reimp */ - QPtrList selectedItems() const; - /*! \reimp for covariant return */ - KeyListViewItem * firstChild() const; - /*! \reimp */ - void clear(); - /*! \reimp */ - void insertItem( QListViewItem * ); - /*! \reimp */ - void takeItem( QListViewItem * ); - - private: - void doHierarchicalInsert( const GpgME::Key & ); - void gatherScattered(); - void scatterGathered( QListViewItem * ); - void registerItem( KeyListViewItem * ); - void deregisterItem( const KeyListViewItem * ); - - private: - const ColumnStrategy * mColumnStrategy; - const DisplayStrategy * mDisplayStrategy; - bool mHierarchical; - - class Private; - Private * d; - }; -} - -#endif // __KLEO_KEYLISTVIEW_H__ diff --git a/kleopatra/lib/ui/keyrequester.cpp b/kleopatra/lib/ui/keyrequester.cpp deleted file mode 100644 index d537affc5e..0000000000 --- a/kleopatra/lib/ui/keyrequester.cpp +++ /dev/null @@ -1,481 +0,0 @@ -/* -*- c++ -*- - keyrequester.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klar�vdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - - - Based on kpgpui.cpp - Copyright (C) 2001,2002 the KPGP authors - See file libkdenetwork/AUTHORS.kpgp for details - - This file is part of KPGP, the KDE PGP/GnuPG support library. - - KPGP 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. - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "keyrequester.h" - -#include "keyselectiondialog.h" - -#include -#include -#include - -// gpgme++ -#include -#include - -// KDE -#include -#include -#include -#include -#include -#include - -// Qt -#include -#include -#include -#include -#include -#include -#include - -#include - -Kleo::KeyRequester::KeyRequester( unsigned int allowedKeys, bool multipleKeys, - QWidget * parent, const char * name ) - : QWidget( parent, name ), - mOpenPGPBackend( 0 ), - mSMIMEBackend( 0 ), - mMulti( multipleKeys ), - mKeyUsage( allowedKeys ), - mJobs( 0 ), - d( 0 ) -{ - init(); -} - -Kleo::KeyRequester::KeyRequester( QWidget * parent, const char * name ) - : QWidget( parent, name ), - mOpenPGPBackend( 0 ), - mSMIMEBackend( 0 ), - mMulti( false ), - mKeyUsage( 0 ), - mJobs( 0 ), - d( 0 ) -{ - init(); -} - -void Kleo::KeyRequester::init() -{ - QHBoxLayout * hlay = new QHBoxLayout( this, 0, KDialog::spacingHint() ); - - // the label where the key id is to be displayed: - mLabel = new QLabel( this ); - mLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken ); - - // the button to unset any key: - mEraseButton = new KPushButton( this ); - mEraseButton->setAutoDefault( false ); - mEraseButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, - QSizePolicy::Minimum ) ); - mEraseButton->setIconSet( SmallIconSet( QApplication::reverseLayout() ? "locationbar_erase" : "clear_left" ) ); - QToolTip::add( mEraseButton, i18n("Clear") ); - - // the button to call the KeySelectionDialog: - mDialogButton = new QPushButton( i18n("Change..."), this ); - mDialogButton->setAutoDefault( false ); - - hlay->addWidget( mLabel, 1 ); - hlay->addWidget( mEraseButton ); - hlay->addWidget( mDialogButton ); - - connect( mEraseButton, SIGNAL(clicked()), SLOT(slotEraseButtonClicked()) ); - connect( mDialogButton, SIGNAL(clicked()), SLOT(slotDialogButtonClicked()) ); - - setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, - QSizePolicy::Fixed ) ); - - setAllowedKeys( mKeyUsage ); -} - -Kleo::KeyRequester::~KeyRequester() { - -} - -const std::vector & Kleo::KeyRequester::keys() const { - return mKeys; -} - -const GpgME::Key & Kleo::KeyRequester::key() const { - if ( mKeys.empty() ) - return GpgME::Key::null; - else - return mKeys.front(); -} - -void Kleo::KeyRequester::setKeys( const std::vector & keys ) { - mKeys.clear(); - for ( std::vector::const_iterator it = keys.begin() ; it != keys.end() ; ++it ) - if ( !it->isNull() ) - mKeys.push_back( *it ); - updateKeys(); -} - -void Kleo::KeyRequester::setKey( const GpgME::Key & key ) { - mKeys.clear(); - if ( !key.isNull() ) - mKeys.push_back( key ); - updateKeys(); -} - -QString Kleo::KeyRequester::fingerprint() const { - if ( mKeys.empty() ) - return QString::null; - else - return mKeys.front().primaryFingerprint(); -} - -QStringList Kleo::KeyRequester::fingerprints() const { - QStringList result; - for ( std::vector::const_iterator it = mKeys.begin() ; it != mKeys.end() ; ++it ) - if ( !it->isNull() ) - if ( const char * fpr = it->primaryFingerprint() ) - result.push_back( fpr ); - return result; -} - -void Kleo::KeyRequester::setFingerprint( const QString & fingerprint ) { - startKeyListJob( fingerprint ); -} - -void Kleo::KeyRequester::setFingerprints( const QStringList & fingerprints ) { - startKeyListJob( fingerprints ); -} - -void Kleo::KeyRequester::updateKeys() { - if ( mKeys.empty() ) { - mLabel->clear(); - return; - } - if ( mKeys.size() > 1 ) - setMultipleKeysEnabled( true ); - - QStringList labelTexts; - QString toolTipText; - for ( std::vector::const_iterator it = mKeys.begin() ; it != mKeys.end() ; ++it ) { - if ( it->isNull() ) - continue; - const QString fpr = it->primaryFingerprint(); - labelTexts.push_back( fpr.right(8) ); - toolTipText += fpr.right(8) + ": "; - if ( const char * uid = it->userID(0).id() ) - if ( it->protocol() == GpgME::Context::OpenPGP ) - toolTipText += QString::fromUtf8( uid ); - else - toolTipText += Kleo::DN( uid ).prettyDN(); - else - toolTipText += i18n(""); - toolTipText += '\n'; - } - - mLabel->setText( labelTexts.join(", ") ); - QToolTip::remove( mLabel ); - QToolTip::add( mLabel, toolTipText ); -} - -#ifndef __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ -#define __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ -static void showKeyListError( QWidget * parent, const GpgME::Error & err ) { - assert( err ); - const QString msg = i18n( "

An error occurred while fetching " - "the keys from the backend:

" - "

%1

" ) - .arg( QString::fromLocal8Bit( err.asString() ) ); - - KMessageBox::error( parent, msg, i18n( "Key Listing Failed" ) ); -} -#endif // __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ - -void Kleo::KeyRequester::startKeyListJob( const QStringList & fingerprints ) { - if ( !mSMIMEBackend && !mOpenPGPBackend ) - return; - - mTmpKeys.clear(); - mJobs = 0; - - unsigned int count = 0; - for ( QStringList::const_iterator it = fingerprints.begin() ; it != fingerprints.end() ; ++it ) - if ( !(*it).stripWhiteSpace().isEmpty() ) - ++count; - - if ( !count ) { - // don't fall into the trap that an empty pattern means - // "return all keys" :) - setKey( GpgME::Key::null ); - return; - } - - if ( mOpenPGPBackend ) { - KeyListJob * job = mOpenPGPBackend->keyListJob( false ); // local, no sigs - if ( !job ) { - KMessageBox::error( this, - i18n("The OpenPGP backend does not support listing keys. " - "Check your installation."), - i18n("Key Listing Failed") ); - } else { - connect( job, SIGNAL(result(const GpgME::KeyListResult&)), - SLOT(slotKeyListResult(const GpgME::KeyListResult&)) ); - connect( job, SIGNAL(nextKey(const GpgME::Key&)), - SLOT(slotNextKey(const GpgME::Key&)) ); - - const GpgME::Error err = job->start( fingerprints, - mKeyUsage & Kleo::KeySelectionDialog::SecretKeys && - !( mKeyUsage & Kleo::KeySelectionDialog::PublicKeys ) ); - - if ( err ) - showKeyListError( this, err ); - else - ++mJobs; - } - } - - if ( mSMIMEBackend ) { - KeyListJob * job = mSMIMEBackend->keyListJob( false ); // local, no sigs - if ( !job ) { - KMessageBox::error( this, - i18n("The S/MIME backend does not support listing keys. " - "Check your installation."), - i18n("Key Listing Failed") ); - } else { - connect( job, SIGNAL(result(const GpgME::KeyListResult&)), - SLOT(slotKeyListResult(const GpgME::KeyListResult&)) ); - connect( job, SIGNAL(nextKey(const GpgME::Key&)), - SLOT(slotNextKey(const GpgME::Key&)) ); - - const GpgME::Error err = job->start( fingerprints, - mKeyUsage & Kleo::KeySelectionDialog::SecretKeys && - !( mKeyUsage & Kleo::KeySelectionDialog::PublicKeys ) ); - - if ( err ) - showKeyListError( this, err ); - else - ++mJobs; - } - } - - if ( mJobs > 0 ) { - mEraseButton->setEnabled( false ); - mDialogButton->setEnabled( false ); - } -} - -void Kleo::KeyRequester::slotNextKey( const GpgME::Key & key ) { - if ( !key.isNull() ) - mTmpKeys.push_back( key ); -} - -void Kleo::KeyRequester::slotKeyListResult( const GpgME::KeyListResult & res ) { - if ( res.error() ) - showKeyListError( this, res.error() ); - - if ( --mJobs <= 0 ) { - mEraseButton->setEnabled( true ); - mDialogButton->setEnabled( true ); - - setKeys( mTmpKeys ); - mTmpKeys.clear(); - } -} - - -void Kleo::KeyRequester::slotDialogButtonClicked() { - KeySelectionDialog * dlg = mKeys.empty() - ? new KeySelectionDialog( mDialogCaption, mDialogMessage, mInitialQuery, mKeyUsage, mMulti, false, this ) - : new KeySelectionDialog( mDialogCaption, mDialogCaption, mKeys, mKeyUsage, mMulti, false, this ) ; - - if ( dlg->exec() == QDialog::Accepted ) { - if ( mMulti ) - setKeys( dlg->selectedKeys() ); - else - setKey( dlg->selectedKey() ); - emit changed(); - } - - delete dlg; -} - -void Kleo::KeyRequester::slotEraseButtonClicked() { - if ( !mKeys.empty() ) - emit changed(); - mKeys.clear(); - updateKeys(); -} - -void Kleo::KeyRequester::setDialogCaption( const QString & caption ) { - mDialogCaption = caption; -} - -void Kleo::KeyRequester::setDialogMessage( const QString & msg ) { - mDialogMessage = msg; -} - -bool Kleo::KeyRequester::isMultipleKeysEnabled() const { - return mMulti; -} - -void Kleo::KeyRequester::setMultipleKeysEnabled( bool multi ) { - if ( multi == mMulti ) return; - - if ( !multi && !mKeys.empty() ) - mKeys.erase( mKeys.begin() + 1, mKeys.end() ); - - mMulti = multi; - updateKeys(); -} - -unsigned int Kleo::KeyRequester::allowedKeys() const { - return mKeyUsage; -} - -void Kleo::KeyRequester::setAllowedKeys( unsigned int keyUsage ) { - mKeyUsage = keyUsage; - mOpenPGPBackend = 0; - mSMIMEBackend = 0; - - if ( mKeyUsage & KeySelectionDialog::OpenPGPKeys ) - mOpenPGPBackend = Kleo::CryptoBackendFactory::instance()->openpgp(); - if ( mKeyUsage & KeySelectionDialog::SMIMEKeys ) - mSMIMEBackend = Kleo::CryptoBackendFactory::instance()->smime(); - - if ( mOpenPGPBackend && !mSMIMEBackend ) { - mDialogCaption = i18n("OpenPGP Key Selection"); - mDialogMessage = i18n("Please select an OpenPGP key to use."); - } else if ( !mOpenPGPBackend && mSMIMEBackend ) { - mDialogCaption = i18n("S/MIME Key Selection"); - mDialogMessage = i18n("Please select an S/MIME key to use."); - } else { - mDialogCaption = i18n("Key Selection"); - mDialogMessage = i18n("Please select an (OpenPGP or S/MIME) key to use."); - } -} - -QPushButton * Kleo::KeyRequester::dialogButton() { - return mDialogButton; -} - -QPushButton * Kleo::KeyRequester::eraseButton() { - return mEraseButton; -} - -static inline unsigned int foo( bool openpgp, bool smime, bool trusted, bool valid ) { - unsigned int result = 0; - if ( openpgp ) - result |= Kleo::KeySelectionDialog::OpenPGPKeys; - if ( smime ) - result |= Kleo::KeySelectionDialog::SMIMEKeys; - if ( trusted ) - result |= Kleo::KeySelectionDialog::TrustedKeys; - if ( valid ) - result |= Kleo::KeySelectionDialog::ValidKeys; - return result; -} - -static inline unsigned int encryptionKeyUsage( bool openpgp, bool smime, bool trusted, bool valid ) { - return foo( openpgp, smime, trusted, valid ) | Kleo::KeySelectionDialog::EncryptionKeys | Kleo::KeySelectionDialog::PublicKeys; -} - -static inline unsigned int signingKeyUsage( bool openpgp, bool smime, bool trusted, bool valid ) { - return foo( openpgp, smime, trusted, valid ) | Kleo::KeySelectionDialog::SigningKeys | Kleo::KeySelectionDialog::SecretKeys; -} - -Kleo::EncryptionKeyRequester::EncryptionKeyRequester( bool multi, unsigned int proto, - QWidget * parent, const char * name, - bool onlyTrusted, bool onlyValid ) - : KeyRequester( encryptionKeyUsage( proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid ), multi, - parent, name ) -{ -} - -Kleo::EncryptionKeyRequester::EncryptionKeyRequester( QWidget * parent, const char * name ) - : KeyRequester( 0, false, parent, name ) -{ -} - -Kleo::EncryptionKeyRequester::~EncryptionKeyRequester() {} - - -void Kleo::EncryptionKeyRequester::setAllowedKeys( unsigned int proto, bool onlyTrusted, bool onlyValid ) -{ - KeyRequester::setAllowedKeys( encryptionKeyUsage( proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid ) ); -} - -Kleo::SigningKeyRequester::SigningKeyRequester( bool multi, unsigned int proto, - QWidget * parent, const char * name, - bool onlyTrusted, bool onlyValid ) - : KeyRequester( signingKeyUsage( proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid ), multi, - parent, name ) -{ -} - -Kleo::SigningKeyRequester::SigningKeyRequester( QWidget * parent, const char * name ) - : KeyRequester( 0, false, parent, name ) -{ -} - -Kleo::SigningKeyRequester::~SigningKeyRequester() {} - -void Kleo::SigningKeyRequester::setAllowedKeys( unsigned int proto, bool onlyTrusted, bool onlyValid ) -{ - KeyRequester::setAllowedKeys( signingKeyUsage( proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid ) ); -} - -void Kleo::KeyRequester::virtual_hook( int, void* ) {} -void Kleo::EncryptionKeyRequester::virtual_hook( int id, void * data ) { - KeyRequester::virtual_hook( id, data ); -} -void Kleo::SigningKeyRequester::virtual_hook( int id, void * data ) { - KeyRequester::virtual_hook( id, data ); -} - -#include "keyrequester.moc" diff --git a/kleopatra/lib/ui/keyrequester.h b/kleopatra/lib/ui/keyrequester.h deleted file mode 100644 index 3de9c508bf..0000000000 --- a/kleopatra/lib/ui/keyrequester.h +++ /dev/null @@ -1,227 +0,0 @@ -/* -*- c++ -*- - keyrequester.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - - - Based on kpgpui.h - Copyright (C) 2001,2002 the KPGP authors - See file libkdenetwork/AUTHORS.kpgp for details - - This file is part of KPGP, the KDE PGP/GnuPG support library. - - KPGP 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. - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ - -#ifndef __KLEO_UI_KEYREQUESTER_H__ -#define __KLEO_UI_KEYREQUESTER_H__ - -#include -#include - -#include -#include - -namespace Kleo { - class KeyListView; - class KeyListViewItem; -} - -namespace GpgME { - class Key; - class KeyListResult; -} - -class QStringList; -class QString; -class QPushButton; -class QLabel; - -namespace Kleo { - - /// Base class for SigningKeyRequester and EncryptionKeyRequester - class KDE_EXPORT KeyRequester : public QWidget { - Q_OBJECT - public: - KeyRequester( unsigned int allowedKeys, bool multipleKeys=false, - QWidget * parent=0, const char * name=0 ); - // Constructor for Qt Designer - KeyRequester( QWidget * parent=0, const char * name=0 ); - ~KeyRequester(); - - const GpgME::Key & key() const; - /** Preferred method to set a key for - non-multi-KeyRequesters. Doesn't start a backend - KeyListJob. - */ - void setKey( const GpgME::Key & key ); - - const std::vector & keys() const; - /** Preferred method to set a key for multi-KeyRequesters. Doesn't - start a backend KeyListJob. - */ - void setKeys( const std::vector & keys ); - - QString fingerprint() const; - /** Set the key by fingerprint. Starts a background KeyListJob to - retrive the complete GpgME::Key object - */ - void setFingerprint( const QString & fingerprint ); - - QStringList fingerprints() const; - /** Set the keys by fingerprint. Starts a background KeyListJob to - retrive the complete GpgME::Key objects - */ - void setFingerprints( const QStringList & fingerprints ); - - - QPushButton * eraseButton(); - QPushButton * dialogButton(); - - void setDialogCaption( const QString & caption ); - void setDialogMessage( const QString & message ); - - bool isMultipleKeysEnabled() const; - void setMultipleKeysEnabled( bool enable ); - - unsigned int allowedKeys() const; - void setAllowedKeys( unsigned int allowed ); - - void setInitialQuery( const QString & s ) { mInitialQuery = s; } - const QString & initialQuery() const { return mInitialQuery; } - - signals: - void changed(); - - private: - void init(); - void startKeyListJob( const QStringList & fingerprints ); - void updateKeys(); - - private slots: - void slotNextKey( const GpgME::Key & key ); - void slotKeyListResult( const GpgME::KeyListResult & result ); - void slotDialogButtonClicked(); - void slotEraseButtonClicked(); - - private: - const CryptoBackend::Protocol * mOpenPGPBackend; - const CryptoBackend::Protocol * mSMIMEBackend; - QLabel * mLabel; - QPushButton * mEraseButton; - QPushButton * mDialogButton; - QString mDialogCaption, mDialogMessage, mInitialQuery; - bool mMulti; - unsigned int mKeyUsage; - int mJobs; - std::vector mKeys; - std::vector mTmpKeys; - - private: - class Private; - Private * d; - protected: - virtual void virtual_hook( int, void* ); - }; - - - class KDE_EXPORT EncryptionKeyRequester : public KeyRequester { - Q_OBJECT - public: - enum { OpenPGP = 1, SMIME = 2, AllProtocols = OpenPGP|SMIME }; - - /** - * Preferred constructor - */ - EncryptionKeyRequester( bool multipleKeys=false, unsigned int proto=AllProtocols, - QWidget * parent=0, const char * name=0, - bool onlyTrusted=true, bool onlyValid=true ); - /** - * Constructor for Qt designer - */ - EncryptionKeyRequester( QWidget * parent=0, const char * name=0 ); - ~EncryptionKeyRequester(); - - void setAllowedKeys( unsigned int proto, bool onlyTrusted=true, bool onlyValid=true ); - - private: - class Private; - Private * d; - protected: - virtual void virtual_hook( int, void* ); - }; - - - class KDE_EXPORT SigningKeyRequester : public KeyRequester { - Q_OBJECT - public: - enum { OpenPGP = 1, SMIME = 2, AllProtocols = OpenPGP|SMIME }; - - /** - * Preferred constructor - * @param multipleKeys whether multiple keys can be selected - * - * @param proto the allowed protocols, OpenPGP and/or SMIME - * @param onlyTrusted only show trusted keys - * @param onlyValid only show valid keys - */ - SigningKeyRequester( bool multipleKeys=false, unsigned int proto=AllProtocols, - QWidget * parent=0, const char * name=0, - bool onlyTrusted=true, bool onlyValid=true ); - /** - * Constructor for Qt designer - */ - SigningKeyRequester( QWidget * parent=0, const char * name=0 ); - ~SigningKeyRequester(); - - /* - * Those parameters affect the parameters given to the key selection dialog. - * @param proto the allowed protocols, OpenPGP and/or SMIME - * @param onlyTrusted only show trusted keys - * @param onlyValid only show valid keys - */ - void setAllowedKeys( unsigned int proto, bool onlyTrusted=true, bool onlyValid=true ); - - private: - class Private; - Private * d; - protected: - virtual void virtual_hook( int, void* ); - }; - -} - -#endif // __KLEO_UI_KEYREQUESTER_H__ diff --git a/kleopatra/lib/ui/keyselectiondialog.cpp b/kleopatra/lib/ui/keyselectiondialog.cpp deleted file mode 100644 index b544711bba..0000000000 --- a/kleopatra/lib/ui/keyselectiondialog.cpp +++ /dev/null @@ -1,779 +0,0 @@ -/* -*- c++ -*- - keyselectiondialog.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Based on kpgpui.cpp - Copyright (C) 2001,2002 the KPGP authors - See file libkdenetwork/AUTHORS.kpgp for details - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "keyselectiondialog.h" - -#include "keylistview.h" -#include "progressdialog.h" - -#include -#include -#include - -// gpgme++ -#include -#include - -// KDE -#include -#include -#include -#include -#include -#include -#include -#include - -// Qt -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -static bool checkKeyUsage( const GpgME::Key & key, unsigned int keyUsage ) { - - if ( keyUsage & Kleo::KeySelectionDialog::ValidKeys ) { - if ( key.isInvalid() ) - kdDebug() << "key is invalid - ignoring" << endl; - if ( key.isExpired() ) { - kdDebug() << "key is expired" << endl; - return false; - } else if ( key.isRevoked() ) { - kdDebug() << "key is revoked" << endl; - return false; - } else if ( key.isDisabled() ) { - kdDebug() << "key is disabled" << endl; - return false; - } - } - - if ( keyUsage & Kleo::KeySelectionDialog::EncryptionKeys && - !key.canEncrypt() ) { - kdDebug() << "key can't encrypt" << endl; - return false; - } - if ( keyUsage & Kleo::KeySelectionDialog::SigningKeys && - !key.canSign() ) { - kdDebug() << "key can't sign" << endl; - return false; - } - if ( keyUsage & Kleo::KeySelectionDialog::CertificationKeys && - !key.canCertify() ) { - kdDebug() << "key can't certify" << endl; - return false; - } - if ( keyUsage & Kleo::KeySelectionDialog::AuthenticationKeys && - !key.canAuthenticate() ) { - kdDebug() << "key can't authenticate" << endl; - return false; - } - - if ( keyUsage & Kleo::KeySelectionDialog::SecretKeys && - !( keyUsage & Kleo::KeySelectionDialog::PublicKeys ) && - !key.isSecret() ) { - kdDebug() << "key isn't secret" << endl; - return false; - } - - if ( keyUsage & Kleo::KeySelectionDialog::TrustedKeys && - key.protocol() == GpgME::Context::OpenPGP && - // only check this for secret keys for now. - // Seems validity isn't checked for secret keylistings... - !key.isSecret() ) { - std::vector uids = key.userIDs(); - for ( std::vector::const_iterator it = uids.begin() ; it != uids.end() ; ++it ) - if ( !it->isRevoked() && it->validity() >= GpgME::UserID::Marginal ) - return true; - kdDebug() << "key has no UIDs with validity >= Marginal" << endl; - return false; - } - // X.509 keys are always trusted, else they won't be the keybox. - // PENDING(marc) check that this ^ is correct - - return true; -} - -static bool checkKeyUsage( const std::vector & keys, unsigned int keyUsage ) { - for ( std::vector::const_iterator it = keys.begin() ; it != keys.end() ; ++it ) - if ( !checkKeyUsage( *it, keyUsage ) ) - return false; - return true; -} - -static inline QString time_t2string( time_t t ) { - QDateTime dt; - dt.setTime_t( t ); - return dt.toString(); -} - -namespace { - - class ColumnStrategy : public Kleo::KeyListView::ColumnStrategy { - public: - ColumnStrategy( unsigned int keyUsage ); - - QString title( int col ) const; - int width( int col, const QFontMetrics & fm ) const; - - QString text( const GpgME::Key & key, int col ) const; - QString toolTip( const GpgME::Key & key, int col ) const; - const QPixmap * pixmap( const GpgME::Key & key, int col ) const; - - private: - const QPixmap mKeyGoodPix, mKeyBadPix, mKeyUnknownPix, mKeyValidPix; - const unsigned int mKeyUsage; - }; - - ColumnStrategy::ColumnStrategy( unsigned int keyUsage ) - : Kleo::KeyListView::ColumnStrategy(), - mKeyGoodPix( UserIcon( "key_ok" ) ), - mKeyBadPix( UserIcon( "key_bad" ) ), - mKeyUnknownPix( UserIcon( "key_unknown" ) ), - mKeyValidPix( UserIcon( "key" ) ), - mKeyUsage( keyUsage ) - { - kdWarning( keyUsage == 0, 5150 ) - << "KeySelectionDialog: keyUsage == 0. You want to use AllKeys instead." << endl; - } - - QString ColumnStrategy::title( int col ) const { - switch ( col ) { - case 0: return i18n("Key ID"); - case 1: return i18n("User ID"); - default: return QString::null; - } - } - - int ColumnStrategy::width( int col, const QFontMetrics & fm ) const { - if ( col == 0 ) { - static const char hexchars[] = "0123456789ABCDEF"; - int maxWidth = 0; - for ( unsigned int i = 0 ; i < 16 ; ++i ) - maxWidth = kMax( fm.width( QChar( hexchars[i] ) ), maxWidth ); - return 8 * maxWidth + 2 * mKeyGoodPix.width(); - } - return Kleo::KeyListView::ColumnStrategy::width( col, fm ); - } - - QString ColumnStrategy::text( const GpgME::Key & key, int col ) const { - switch ( col ) { - case 0: - { - if ( key.shortKeyID() ) - return QString::fromUtf8( key.shortKeyID() ); - else - return i18n(""); - } - break; - case 1: - { - const char * uid = key.userID(0).id(); - if ( key.protocol() == GpgME::Context::OpenPGP ) - return uid && *uid ? QString::fromUtf8( uid ) : QString::null ; - else // CMS - return Kleo::DN( uid ).prettyDN(); - } - break; - default: return QString::null; - } - } - - QString ColumnStrategy::toolTip( const GpgME::Key & key, int ) const { - const char * uid = key.userID(0).id(); - const char * fpr = key.primaryFingerprint(); - const char * issuer = key.issuerName(); - const GpgME::Subkey subkey = key.subkey(0); - const QString expiry = subkey.neverExpires() ? i18n("never") : time_t2string( subkey.expirationTime() ) ; - const QString creation = time_t2string( subkey.creationTime() ); - if ( key.protocol() == GpgME::Context::OpenPGP ) - return i18n( "OpenPGP key for %1\n" - "Created: %2\n" - "Expiry: %3\n" - "Fingerprint: %4" ) - .arg( uid ? QString::fromUtf8( uid ) : i18n("unknown"), - creation, expiry, - fpr ? QString::fromLatin1( fpr ) : i18n("unknown") ); - else - return i18n( "S/MIME key for %1\n" - "Created: %2\n" - "Expiry: %3\n" - "Fingerprint: %4\n" - "Issuer: %5" ) - .arg( uid ? Kleo::DN( uid ).prettyDN() : i18n("unknown"), - creation, expiry, - fpr ? QString::fromLatin1( fpr ) : i18n("unknown") ) - .arg( issuer ? Kleo::DN( issuer ).prettyDN() : i18n("unknown") ); - } - - const QPixmap * ColumnStrategy::pixmap( const GpgME::Key & key, int col ) const { - if ( col != 0 ) - return 0; - // this key did not undergo a validating keylisting yet: - if ( !( key.keyListMode() & GpgME::Context::Validate ) ) - return &mKeyUnknownPix; - - if ( !checkKeyUsage( key, mKeyUsage ) ) - return &mKeyBadPix; - - if ( key.protocol() == GpgME::Context::CMS ) - return &mKeyGoodPix; - - switch ( key.userID(0).validity() ) { - default: - case GpgME::UserID::Unknown: - case GpgME::UserID::Undefined: - return &mKeyUnknownPix; - case GpgME::UserID::Never: - return &mKeyValidPix; - case GpgME::UserID::Marginal: - case GpgME::UserID::Full: - case GpgME::UserID::Ultimate: - return &mKeyGoodPix; - } - } - -} - - -static const int sCheckSelectionDelay = 250; - -Kleo::KeySelectionDialog::KeySelectionDialog( const QString & title, - const QString & text, - const std::vector & selectedKeys, - unsigned int keyUsage, - bool extendedSelection, - bool rememberChoice, - QWidget * parent, const char * name, - bool modal ) - : KDialogBase( parent, name, modal, title, Default|Ok|Cancel, Ok ), - mOpenPGPBackend( 0 ), - mSMIMEBackend( 0 ), - mRememberCB( 0 ), - mSelectedKeys( selectedKeys ), - mKeyUsage( keyUsage ), - mCurrentContextMenuItem( 0 ) -{ - init( rememberChoice, extendedSelection, text, QString::null ); -} - -Kleo::KeySelectionDialog::KeySelectionDialog( const QString & title, - const QString & text, - const QString & initialQuery, - unsigned int keyUsage, - bool extendedSelection, - bool rememberChoice, - QWidget * parent, const char * name, - bool modal ) - : KDialogBase( parent, name, modal, title, Default|Ok|Cancel, Ok ), - mOpenPGPBackend( 0 ), - mSMIMEBackend( 0 ), - mRememberCB( 0 ), - mKeyUsage( keyUsage ), - mSearchText( initialQuery ), - mCurrentContextMenuItem( 0 ) -{ - init( rememberChoice, extendedSelection, text, initialQuery ); -} - -void Kleo::KeySelectionDialog::init( bool rememberChoice, bool extendedSelection, - const QString & text, const QString & initialQuery ) { - if ( mKeyUsage & OpenPGPKeys ) - mOpenPGPBackend = Kleo::CryptoBackendFactory::instance()->openpgp(); - if ( mKeyUsage & SMIMEKeys ) - mSMIMEBackend = Kleo::CryptoBackendFactory::instance()->smime(); - - QSize dialogSize( 580, 400 ); - if ( kapp ) { - KWin::setIcons( winId(), kapp->icon(), kapp->miniIcon() ); - - KConfigGroup dialogConfig( KGlobal::config(), "Key Selection Dialog" ); - dialogSize = dialogConfig.readSizeEntry( "Dialog size", &dialogSize ); - } - resize( dialogSize ); - - mCheckSelectionTimer = new QTimer( this ); - mStartSearchTimer = new QTimer( this ); - - QFrame *page = makeMainWidget(); - QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() ); - - if ( !text.isEmpty() ) - topLayout->addWidget( new QLabel( text, page ) ); - - QHBoxLayout * hlay = new QHBoxLayout( topLayout ); // inherits spacing - QLineEdit * le = new QLineEdit( page ); - le->setText( initialQuery ); - QToolButton *clearButton = new QToolButton( page ); - clearButton->setIconSet( KGlobal::iconLoader()->loadIconSet( - KApplication::reverseLayout() ? "clear_left":"locationbar_erase", KIcon::Small, 0 ) ); - hlay->addWidget( clearButton ); - hlay->addWidget( new QLabel( le, i18n("&Search for:"), page ) ); - hlay->addWidget( le, 1 ); - le->setFocus(); - - connect( clearButton, SIGNAL( clicked() ), le, SLOT( clear() ) ); - connect( le, SIGNAL(textChanged(const QString&)), - this, SLOT(slotSearch(const QString&)) ); - connect( mStartSearchTimer, SIGNAL(timeout()), SLOT(slotFilter()) ); - - mKeyListView = new KeyListView( new ColumnStrategy( mKeyUsage ), 0, page, "mKeyListView" ); - mKeyListView->setResizeMode( QListView::LastColumn ); - mKeyListView->setRootIsDecorated( true ); - mKeyListView->setShowSortIndicator( true ); - mKeyListView->setSorting( 1, true ); // sort by User ID - mKeyListView->setShowToolTips( true ); - if ( extendedSelection ) - mKeyListView->setSelectionMode( QListView::Extended ); - topLayout->addWidget( mKeyListView, 10 ); - - if ( rememberChoice ) { - mRememberCB = new QCheckBox( i18n("&Remember choice"), page ); - topLayout->addWidget( mRememberCB ); - QWhatsThis::add( mRememberCB, - i18n("

If you check this box your choice will " - "be stored and you will not be asked again." - "

") ); - } - - connect( mCheckSelectionTimer, SIGNAL(timeout()), - SLOT(slotCheckSelection()) ); - connectSignals(); - - connect( mKeyListView, - SIGNAL(doubleClicked(Kleo::KeyListViewItem*,const QPoint&,int)), - SLOT(slotTryOk()) ); - connect( mKeyListView, - SIGNAL(contextMenu(Kleo::KeyListViewItem*,const QPoint&)), - SLOT(slotRMB(Kleo::KeyListViewItem*,const QPoint&)) ); - - setButtonText( KDialogBase::Default, i18n("&Reread Keys") ); - connect( this, SIGNAL(defaultClicked()), - this, SLOT(slotRereadKeys()) ); - - slotRereadKeys(); -} - -Kleo::KeySelectionDialog::~KeySelectionDialog() { - KConfigGroup dialogConfig( KGlobal::config(), "Key Selection Dialog" ); - dialogConfig.writeEntry( "Dialog size", size() ); - dialogConfig.sync(); -} - - -void Kleo::KeySelectionDialog::connectSignals() { - if ( mKeyListView->isMultiSelection() ) - connect( mKeyListView, SIGNAL(selectionChanged()), - SLOT(slotSelectionChanged()) ); - else - connect( mKeyListView, SIGNAL(selectionChanged(Kleo::KeyListViewItem*)), - SLOT(slotCheckSelection(Kleo::KeyListViewItem*)) ); -} - -void Kleo::KeySelectionDialog::disconnectSignals() { - if ( mKeyListView->isMultiSelection() ) - disconnect( mKeyListView, SIGNAL(selectionChanged()), - this, SLOT(slotSelectionChanged()) ); - else - disconnect( mKeyListView, SIGNAL(selectionChanged(Kleo::KeyListViewItem*)), - this, SLOT(slotCheckSelection(Kleo::KeyListViewItem*)) ); -} - -const GpgME::Key & Kleo::KeySelectionDialog::selectedKey() const { - if ( mKeyListView->isMultiSelection() || !mKeyListView->selectedItem() ) - return GpgME::Key::null; - return mKeyListView->selectedItem()->key(); -} - -QString Kleo::KeySelectionDialog::fingerprint() const { - return selectedKey().primaryFingerprint(); -} - -QStringList Kleo::KeySelectionDialog::fingerprints() const { - QStringList result; - for ( std::vector::const_iterator it = mSelectedKeys.begin() ; it != mSelectedKeys.end() ; ++it ) - if ( const char * fpr = it->primaryFingerprint() ) - result.push_back( fpr ); - return result; -} - -QStringList Kleo::KeySelectionDialog::pgpKeyFingerprints() const { - QStringList result; - for ( std::vector::const_iterator it = mSelectedKeys.begin() ; it != mSelectedKeys.end() ; ++it ) - if ( it->protocol() == GpgME::Context::OpenPGP ) - if ( const char * fpr = it->primaryFingerprint() ) - result.push_back( fpr ); - return result; -} - -QStringList Kleo::KeySelectionDialog::smimeFingerprints() const { - QStringList result; - for ( std::vector::const_iterator it = mSelectedKeys.begin() ; it != mSelectedKeys.end() ; ++it ) - if ( it->protocol() == GpgME::Context::CMS ) - if ( const char * fpr = it->primaryFingerprint() ) - result.push_back( fpr ); - return result; -} - -void Kleo::KeySelectionDialog::slotRereadKeys() { - mKeyListView->clear(); - mListJobCount = 0; - mTruncated = 0; - mSavedOffsetY = mKeyListView->contentsY(); - - disconnectSignals(); - mKeyListView->setEnabled( false ); - - // FIXME: save current selection - if ( mOpenPGPBackend ) - startKeyListJobForBackend( mOpenPGPBackend, std::vector(), false /*non-validating*/ ); - if ( mSMIMEBackend ) - startKeyListJobForBackend( mSMIMEBackend, std::vector(), false /*non-validating*/ ); - - if ( mListJobCount == 0 ) { - mKeyListView->setEnabled( true ); - KMessageBox::information( this, - i18n("No backends found for listing keys. " - "Check your installation."), - i18n("Key Listing Failed") ); - connectSignals(); - } -} - -#ifndef __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ -#define __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ -static void showKeyListError( QWidget * parent, const GpgME::Error & err ) { - assert( err ); - const QString msg = i18n( "

An error occurred while fetching " - "the keys from the backend:

" - "

%1

" ) - .arg( QString::fromLocal8Bit( err.asString() ) ); - - KMessageBox::error( parent, msg, i18n( "Key Listing Failed" ) ); -} -#endif // __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ - -namespace { - struct ExtractFingerprint { - QString operator()( const GpgME::Key & key ) { - return key.primaryFingerprint(); - } - }; -} - -void Kleo::KeySelectionDialog::startKeyListJobForBackend( const CryptoBackend::Protocol * backend, const std::vector & keys, bool validate ) { - assert( backend ); - KeyListJob * job = backend->keyListJob( false, false, validate ); // local, w/o sigs, validation as givem - if ( !job ) - return; - - connect( job, SIGNAL(result(const GpgME::KeyListResult&)), - SLOT(slotKeyListResult(const GpgME::KeyListResult&)) ); - connect( job, SIGNAL(nextKey(const GpgME::Key&)), - mKeyListView, validate ? - SLOT(slotRefreshKey(const GpgME::Key&)) : - SLOT(slotAddKey(const GpgME::Key&)) ); - - QStringList fprs; - std::transform( keys.begin(), keys.end(), std::back_inserter( fprs ), ExtractFingerprint() ); - const GpgME::Error err = job->start( fprs, mKeyUsage & SecretKeys && !( mKeyUsage & PublicKeys ) ); - - if ( err ) - return showKeyListError( this, err ); - - // FIXME: create a MultiProgressDialog: - (void)new ProgressDialog( job, validate ? i18n( "Checking selected keys..." ) : i18n( "Fetching keys..." ), this ); - ++mListJobCount; -} - -static void selectKeys( Kleo::KeyListView * klv, const std::vector & selectedKeys ) { - klv->clearSelection(); - if ( selectedKeys.empty() ) - return; - for ( std::vector::const_iterator it = selectedKeys.begin() ; it != selectedKeys.end() ; ++it ) - if ( Kleo::KeyListViewItem * item = klv->itemByFingerprint( it->primaryFingerprint() ) ) - item->setSelected( true ); -} - -void Kleo::KeySelectionDialog::slotKeyListResult( const GpgME::KeyListResult & res ) { - if ( res.error() ) - showKeyListError( this, res.error() ); - else if ( res.isTruncated() ) - ++mTruncated; - - if ( --mListJobCount > 0 ) - return; // not yet finished... - - if ( mTruncated > 0 ) - KMessageBox::information( this, - i18n("One backend returned truncated output.
" - "Not all available keys are shown
", - "%n backends returned truncated output.
" - "Not all available keys are shown
", - mTruncated), - i18n("Key List Result") ); - - mKeyListView->flushKeys(); - - mKeyListView->setEnabled( true ); - mListJobCount = mTruncated = 0; - mKeysToCheck.clear(); - - selectKeys( mKeyListView, mSelectedKeys ); - - slotFilter(); - - connectSignals(); - - slotSelectionChanged(); - - // restore the saved position of the contents - mKeyListView->setContentsPos( 0, mSavedOffsetY ); mSavedOffsetY = 0; -} - -void Kleo::KeySelectionDialog::slotSelectionChanged() { - kdDebug(5150) << "KeySelectionDialog::slotSelectionChanged()" << endl; - - // (re)start the check selection timer. Checking the selection is delayed - // because else drag-selection doesn't work very good (checking key trust - // is slow). - mCheckSelectionTimer->start( sCheckSelectionDelay ); -} - -namespace { - struct AlreadyChecked { - bool operator()( const GpgME::Key & key ) const { - return key.keyListMode() & GpgME::Context::Validate ; - } - }; -} - -void Kleo::KeySelectionDialog::slotCheckSelection( KeyListViewItem * item ) { - kdDebug(5150) << "KeySelectionDialog::slotCheckSelection()\n"; - - mCheckSelectionTimer->stop(); - - mSelectedKeys.clear(); - - if ( !mKeyListView->isMultiSelection() ) { - if ( item ) - mSelectedKeys.push_back( item->key() ); - } - - for ( KeyListViewItem * it = mKeyListView->firstChild() ; it ; it = it->nextSibling() ) - if ( it->isSelected() ) - mSelectedKeys.push_back( it->key() ); - - mKeysToCheck.clear(); - std::remove_copy_if( mSelectedKeys.begin(), mSelectedKeys.end(), - std::back_inserter( mKeysToCheck ), - AlreadyChecked() ); - if ( mKeysToCheck.empty() ) { - enableButtonOK( !mSelectedKeys.empty() && - checkKeyUsage( mSelectedKeys, mKeyUsage ) ); - return; - } - - // performed all fast checks - now for validating key listing: - startValidatingKeyListing(); -} - -void Kleo::KeySelectionDialog::startValidatingKeyListing() { - if ( mKeysToCheck.empty() ) - return; - - mListJobCount = 0; - mTruncated = 0; - mSavedOffsetY = mKeyListView->contentsY(); - - disconnectSignals(); - mKeyListView->setEnabled( false ); - - std::vector smime, openpgp; - for ( std::vector::const_iterator it = mKeysToCheck.begin() ; it != mKeysToCheck.end() ; ++it ) - if ( it->protocol() == GpgME::Context::OpenPGP ) - openpgp.push_back( *it ); - else - smime.push_back( *it ); - - if ( !openpgp.empty() ) { - assert( mOpenPGPBackend ); - startKeyListJobForBackend( mOpenPGPBackend, openpgp, true /*validate*/ ); - } - if ( !smime.empty() ) { - assert( mSMIMEBackend ); - startKeyListJobForBackend( mSMIMEBackend, smime, true /*validate*/ ); - } - - assert( mListJobCount > 0 ); -} - -bool Kleo::KeySelectionDialog::rememberSelection() const { - return mRememberCB && mRememberCB->isChecked() ; -} - -void Kleo::KeySelectionDialog::slotRMB( Kleo::KeyListViewItem * item, const QPoint & p ) { - if ( !item ) return; - - mCurrentContextMenuItem = item; - - QPopupMenu menu; - menu.insertItem( i18n( "Recheck Key" ), this, SLOT(slotRecheckKey()) ); - menu.exec( p ); -} - -void Kleo::KeySelectionDialog::slotRecheckKey() { - if ( !mCurrentContextMenuItem || mCurrentContextMenuItem->key().isNull() ) - return; - - mKeysToCheck.clear(); - mKeysToCheck.push_back( mCurrentContextMenuItem->key() ); -} - -void Kleo::KeySelectionDialog::slotTryOk() { - if ( actionButton( Ok )->isEnabled() ) - slotOk(); -} - -void Kleo::KeySelectionDialog::slotOk() { - if ( mCheckSelectionTimer->isActive() ) - slotCheckSelection(); - mStartSearchTimer->stop(); - accept(); -} - - -void Kleo::KeySelectionDialog::slotCancel() { - mCheckSelectionTimer->stop(); - mStartSearchTimer->stop(); - reject(); -} - -void Kleo::KeySelectionDialog::slotSearch( const QString & text ) { - mSearchText = text.stripWhiteSpace().upper(); - slotSearch(); -} - -void Kleo::KeySelectionDialog::slotSearch() { - mStartSearchTimer->start( sCheckSelectionDelay, true /*single-shot*/ ); -} - -void Kleo::KeySelectionDialog::slotFilter() { - if ( mSearchText.isEmpty() ) { - showAllItems(); - return; - } - - // OK, so we need to filter: - QRegExp keyIdRegExp( "(?:0x)?[A-F0-9]{1,8}", false /*case-insens.*/ ); - if ( keyIdRegExp.exactMatch( mSearchText ) ) { - if ( mSearchText.startsWith( "0X" ) ) - // search for keyID only: - filterByKeyID( mSearchText.mid( 2 ) ); - else - // search for UID and keyID: - filterByKeyIDOrUID( mSearchText ); - } else { - // search in UID: - filterByUID( mSearchText ); - } -} - -void Kleo::KeySelectionDialog::filterByKeyID( const QString & keyID ) { - assert( keyID.length() <= 8 ); - assert( !keyID.isEmpty() ); // regexp in slotFilter should prevent these - if ( keyID.isEmpty() ) - showAllItems(); - else - for ( KeyListViewItem * item = mKeyListView->firstChild() ; item ; item = item->nextSibling() ) - item->setVisible( item->text( 0 ).upper().startsWith( keyID ) ); -} - -static bool anyUIDMatches( const Kleo::KeyListViewItem * item, QRegExp & rx ) { - if ( !item ) - return false; - - const std::vector uids = item->key().userIDs(); - for ( std::vector::const_iterator it = uids.begin() ; it != uids.end() ; ++it ) - if ( it->id() && rx.search( QString::fromUtf8( it->id() ) ) >= 0 ) - return true; - return false; -} - -void Kleo::KeySelectionDialog::filterByKeyIDOrUID( const QString & str ) { - assert( !str.isEmpty() ); - - // match beginnings of words: - QRegExp rx( "\\b" + QRegExp::escape( str ), false ); - - for ( KeyListViewItem * item = mKeyListView->firstChild() ; item ; item = item->nextSibling() ) - item->setVisible( item->text( 0 ).upper().startsWith( str ) || anyUIDMatches( item, rx ) ); - -} - -void Kleo::KeySelectionDialog::filterByUID( const QString & str ) { - assert( !str.isEmpty() ); - - // match beginnings of words: - QRegExp rx( "\\b" + QRegExp::escape( str ), false ); - - for ( KeyListViewItem * item = mKeyListView->firstChild() ; item ; item = item->nextSibling() ) - item->setVisible( anyUIDMatches( item, rx ) ); -} - - -void Kleo::KeySelectionDialog::showAllItems() { - for ( KeyListViewItem * item = mKeyListView->firstChild() ; item ; item = item->nextSibling() ) - item->setVisible( true ); -} - -#include "keyselectiondialog.moc" diff --git a/kleopatra/lib/ui/keyselectiondialog.h b/kleopatra/lib/ui/keyselectiondialog.h deleted file mode 100644 index 0f7607ebc9..0000000000 --- a/kleopatra/lib/ui/keyselectiondialog.h +++ /dev/null @@ -1,168 +0,0 @@ -/* -*- c++ -*- - keyselectiondialog.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Based on kpgpui.h - Copyright (C) 2001,2002 the KPGP authors - See file libkdenetwork/AUTHORS.kpgp for details - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_UI_KEYSELECTIONDIALOG_H__ -#define __KLEO_UI_KEYSELECTIONDIALOG_H__ - -#include - -#include -#include -#include -#include - -class QCheckBox; -class QPixmap; -class QTimer; -class QListViewItem; -class QRegExp; -class QPoint; - -namespace Kleo { - class KeyListView; - class KeyListViewItem; -} - -namespace GpgME { - class KeyListResult; -} - -namespace Kleo { - - class KDE_EXPORT KeySelectionDialog : public KDialogBase { - Q_OBJECT - public: - - enum KeyUsage { - PublicKeys = 1, - SecretKeys = 2, - EncryptionKeys = 4, - SigningKeys = 8, - ValidKeys = 16, - TrustedKeys = 32, - CertificationKeys = 64, - AuthenticationKeys = 128, - OpenPGPKeys = 256, - SMIMEKeys = 512, - AllKeys = PublicKeys | SecretKeys | OpenPGPKeys | SMIMEKeys, - ValidTrustedEncryptionKeys = AllKeys | EncryptionKeys | ValidKeys | TrustedKeys - }; - - KeySelectionDialog( const QString & title, - const QString & text, - const std::vector & selectedKeys=std::vector(), - unsigned int keyUsage=AllKeys, - bool extendedSelection=false, - bool rememberChoice=false, - QWidget * parent=0, const char * name=0, - bool modal=true ); - KeySelectionDialog( const QString & title, - const QString & text, - const QString & initialPattern, - unsigned int keyUsage=AllKeys, - bool extendedSelection=false, - bool rememberChoice=false, - QWidget * parent=0, const char * name=0, - bool modal=true ); - ~KeySelectionDialog(); - - /** Returns the key ID of the selected key in single selection mode. - Otherwise it returns a null key. */ - const GpgME::Key & selectedKey() const; - - QString fingerprint() const; - - /** Returns a list of selected key IDs. */ - const std::vector & selectedKeys() const { return mSelectedKeys; } - - /// Return all the selected fingerprints - QStringList fingerprints() const; - - /// Return the selected openpgp fingerprints - QStringList pgpKeyFingerprints() const; - /// Return the selected smime fingerprints - QStringList smimeFingerprints() const; - - bool rememberSelection() const; - - private slots: - void slotRereadKeys(); - void slotKeyListResult( const GpgME::KeyListResult & ); - void slotSelectionChanged(); - void slotCheckSelection() { slotCheckSelection( 0 ); } - void slotCheckSelection( Kleo::KeyListViewItem * ); - void slotRMB( Kleo::KeyListViewItem *, const QPoint & ); - void slotRecheckKey(); - void slotTryOk(); - void slotOk(); - void slotCancel(); - void slotSearch( const QString & text ); - void slotSearch(); - void slotFilter(); - - private: - void filterByKeyID( const QString & keyID ); - void filterByKeyIDOrUID( const QString & keyID ); - void filterByUID( const QString & uid ); - void showAllItems(); - bool anyChildMatches( const Kleo::KeyListViewItem * item, QRegExp & rx ) const; - - void connectSignals(); - void disconnectSignals(); - - void startKeyListJobForBackend( const Kleo::CryptoBackend::Protocol *, const std::vector &, bool ); - void startValidatingKeyListing(); - - void init( bool, bool, const QString &, const QString & ); - - private: - Kleo::KeyListView * mKeyListView; - const Kleo::CryptoBackend::Protocol * mOpenPGPBackend; - const Kleo::CryptoBackend::Protocol * mSMIMEBackend; - QCheckBox * mRememberCB; - std::vector mSelectedKeys, mKeysToCheck; - unsigned int mKeyUsage; - QTimer * mCheckSelectionTimer; - QTimer * mStartSearchTimer; - // cross-eventloop temporaries: - QString mSearchText; - Kleo::KeyListViewItem * mCurrentContextMenuItem; - int mTruncated, mListJobCount, mSavedOffsetY; - }; - -} - -#endif // __KLEO_UI_KEYSELECTIONDIALOG_H__ diff --git a/kleopatra/lib/ui/passphrasedialog.cpp b/kleopatra/lib/ui/passphrasedialog.cpp deleted file mode 100644 index 5915387f5d..0000000000 --- a/kleopatra/lib/ui/passphrasedialog.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* -*- c++ -*- - passphrasedialog.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - - - Based on kpgpui.cpp - Copyright (C) 2001,2002 the KPGP authors - See file libkdenetwork/AUTHORS.kpgp for details - - This file is part of KPGP, the KDE PGP/GnuPG support library. - - KPGP 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. - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ - -#ifndef HAVE_CONFIG_H -#include -#endif - -#include "passphrasedialog.h" - -#include -#include -#include - -#include -#include -#include - -struct Kleo::PassphraseDialog::Private { - KPasswordEdit * lineedit; -}; - - -Kleo::PassphraseDialog::PassphraseDialog( const QString & msg, const QString & caption, - QWidget * parent, const char * name, bool modal ) - : KDialogBase( parent, name, modal, caption, Ok|Cancel, Ok ), d( 0 ) -{ - d = new Private(); - - QWidget * w = new QWidget( this ); - setMainWidget( w ); - - QHBoxLayout * hlay = new QHBoxLayout( w, 0, spacingHint() ); - - QLabel * label = new QLabel( w ); - label->setPixmap( DesktopIcon( "pgp-keys", KIcon::SizeMedium ) ); - hlay->addWidget( label, 0, AlignTop ); - - QVBoxLayout * vlay = new QVBoxLayout( hlay ); // inherits spacing - - vlay->addWidget( new QLabel( msg.isEmpty() ? i18n("Please enter your passphrase:") : msg, w ) ); - - d->lineedit = new KPasswordEdit( KPasswordEdit::OneStar, w, "d->lineedit" ); - d->lineedit->setMinimumWidth( fontMetrics().width("*") * 20 ); - d->lineedit->setFocus(); - - vlay->addWidget( d->lineedit ); - - connect( d->lineedit, SIGNAL(returnPressed()), SLOT(slotOk()) ); - - disableResize(); -} - - -Kleo::PassphraseDialog::~PassphraseDialog() { - delete d; d = 0; -} - -const char * Kleo::PassphraseDialog::passphrase() const { - return d->lineedit->password(); -} - -void Kleo::PassphraseDialog::slotOk() { - const char * pass = passphrase(); - emit finished( pass ? pass : "" ); - KDialogBase::slotOk(); -} - -void Kleo::PassphraseDialog::slotCancel() { - emit canceled(); - KDialogBase::slotCancel(); -} - - -void Kleo::PassphraseDialog::virtual_hook( int id, void * data ) { - return KDialogBase::virtual_hook( id, data ); -} - -#include "passphrasedialog.moc" diff --git a/kleopatra/lib/ui/passphrasedialog.h b/kleopatra/lib/ui/passphrasedialog.h deleted file mode 100644 index 12a434e13a..0000000000 --- a/kleopatra/lib/ui/passphrasedialog.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -*- c++ -*- - passphrasedialog.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. - - - Based on kpgpui.h - Copyright (C) 2001,2002 the KPGP authors - See file libkdenetwork/AUTHORS.kpgp for details - - This file is part of KPGP, the KDE PGP/GnuPG support library. - - KPGP 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. - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ - -#ifndef __KLEO_UI_PASSPHRASEDIALOG_H__ -#define __KLEO_UI_PASSPHRASEDIALOG_H__ - -#include - -namespace Kleo { - - class PassphraseDialog : public KDialogBase { - Q_OBJECT - public: - PassphraseDialog( const QString & description, - const QString & caption=QString::null, - QWidget * parent=0, const char * name=0, - bool modal=true ); - ~PassphraseDialog(); - - const char * passphrase() const; - - signals: - /** emitted when the user clicks Ok. \a pass is never NULL. - \c pass only valid inside slots connected to this signal. - */ - void finished( const char * pass ); - /** emitted when the user clicks Cancel. */ - void canceled(); - - protected slots: - /*! \reimp */ - void slotOk(); - /*! \reimp */ - void slotCancel(); - - private: - class Private; - Private * d; - protected: - /*! \reimp */ - void virtual_hook( int, void* ); - }; - -} // namespace Kleo - -#endif // __KLEO_UI_PASSPHRASEDIALOG_H__ diff --git a/kleopatra/lib/ui/progressbar.cpp b/kleopatra/lib/ui/progressbar.cpp deleted file mode 100644 index 96f51fa8a1..0000000000 --- a/kleopatra/lib/ui/progressbar.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - progressbar.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "config.h" -#include "progressbar.h" - -#include -#include - -static const int busyTimerTickInterval = 100; -static const int busyTimerTickIncrement = 5; - -Kleo::ProgressBar::ProgressBar( QWidget * parent, const char * name, WFlags f ) - : QProgressBar( 0, parent, name, f ), - mRealProgress( -1 ) -{ - mBusyTimer = new QTimer( this ); - connect( mBusyTimer, SIGNAL(timeout()), SLOT(slotBusyTimerTick()) ); - fixup( true ); -} - -void Kleo::ProgressBar::slotProgress( const QString &, int cur, int tot ) { - setProgress( cur, tot ); -} - -void Kleo::ProgressBar::slotProgress( const QString &, int, int cur, int tot ) { - setProgress( cur, tot ); -} - -void Kleo::ProgressBar::setTotalSteps( int total ) { - kdDebug() << "Kleo::ProgressBar::setTotalSteps( " << total << " )" << endl; - if ( total == totalSteps() ) - return; - QProgressBar::setTotalSteps( 0 ); - fixup( false ); -} - -void Kleo::ProgressBar::setProgress( int p ) { - kdDebug() << "Kleo::ProgressBar::setProgress( " << p << " )" << endl; - mRealProgress = p; - fixup( true ); -} - -void Kleo::ProgressBar::reset() { - mRealProgress = -1; - fixup( true ); -} - -void Kleo::ProgressBar::slotBusyTimerTick() { - fixup( false ); - if ( mBusyTimer->isActive() ) - QProgressBar::setProgress( QProgressBar::progress() + busyTimerTickIncrement ); -} - -void Kleo::ProgressBar::fixup( bool newValue ) { - const int cur = QProgressBar::progress(); - const int tot = QProgressBar::totalSteps(); - - kdDebug() << "Kleo::ProgressBar::startStopBusyTimer() cur = " << cur << "; tot = " << tot << "; real = " << mRealProgress << endl; - - if ( ( newValue && mRealProgress < 0 ) || ( !newValue && cur < 0 ) ) { - kdDebug() << "(new value) switch to reset" << endl; - mBusyTimer->stop(); - if ( newValue ) - QProgressBar::reset(); - mRealProgress = -1; - } else if ( tot == 0 ) { - kdDebug() << "(new value) switch or stay in busy" << endl; - if ( !mBusyTimer->isActive() ) { - mBusyTimer->start( busyTimerTickInterval ); - if ( newValue ) - QProgressBar::setProgress( mRealProgress ); - } - } else { - kdDebug() << "(new value) normal progress" << endl; - mBusyTimer->stop(); - if ( QProgressBar::progress() != mRealProgress ) - QProgressBar::setProgress( mRealProgress ); - } -} - -#include "progressbar.moc" diff --git a/kleopatra/lib/ui/progressbar.h b/kleopatra/lib/ui/progressbar.h deleted file mode 100644 index 41d96796d5..0000000000 --- a/kleopatra/lib/ui/progressbar.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - progressbar.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_PROGRESSBAR_H__ -#define __KLEO_PROGRESSBAR_H__ - -#include -#include -class QTimer; - -namespace Kleo { - - /** - @short A QProgressBar with self-powered busy indicator - */ - class KDE_EXPORT ProgressBar : public QProgressBar { - Q_OBJECT - public: - ProgressBar( QWidget * parent=0, const char * name=0, WFlags f=0 ); - - public slots: - void slotProgress( const QString & message, int type, int current, int total ); - void slotProgress( const QString & message, int current, int total ); - /*! reimplementation to support self-powered busy indicator */ - void setProgress( int progress ); - /*! reimplementation to support self-powered busy indicator */ - void setTotalSteps( int total ); - /*! reimplementation to support self-powered busy indicator */ - void reset(); - /*! reimplementation to preserve visibility */ - void setProgress( int cur, int tot ) { QProgressBar::setProgress( cur, tot ); } - - private slots: - void slotBusyTimerTick(); - - private: - void fixup( bool ); - - private: - QTimer * mBusyTimer; - int mRealProgress; - }; -} - -#endif // __KLEO_PROGRESSBAR_H__ diff --git a/kleopatra/lib/ui/progressdialog.cpp b/kleopatra/lib/ui/progressdialog.cpp deleted file mode 100644 index bb66aca173..0000000000 --- a/kleopatra/lib/ui/progressdialog.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - progressdialog.cpp - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#include "progressdialog.h" - -#include "progressbar.h" - -#include - -#include -#include - -#include - -#include - -Kleo::ProgressDialog::ProgressDialog( Job * job, const QString & baseText, - QWidget * creator, const char * name, WFlags f ) - : QProgressDialog( creator, name, false, f ), mBaseText( baseText ) -{ - assert( job ); - setBar( new ProgressBar( this, "replacement progressbar in Kleo::ProgressDialog" ) ); - - setMinimumDuration( 2000 /*ms*/ ); - setAutoReset( false ); - setAutoClose( false ); - setLabelText( baseText ); - setProgress( 0, 0 ); // activate busy indicator - - connect( job, SIGNAL(progress(const QString&,int,int)), - SLOT(slotProgress(const QString&,int,int)) ); - connect( job, SIGNAL(done()), SLOT(slotDone()) ); - connect( this, SIGNAL(canceled()), - job, SLOT(slotCancel()) ); - - QTimer::singleShot( minimumDuration(), this, SLOT(forceShow()) ); -} - -Kleo::ProgressDialog::~ProgressDialog() { - -} - -void Kleo::ProgressDialog::setMinimumDuration( int ms ) { - if ( 0 < ms && ms < minimumDuration() ) - QTimer::singleShot( ms, this, SLOT(forceShow()) ); - QProgressDialog::setMinimumDuration( ms ); -} - -void Kleo::ProgressDialog::slotProgress( const QString & what, int current, int total ) { - kdDebug(5150) << "Kleo::ProgressDialog::slotProgress( \"" << what << "\", " - << current << ", " << total << " )" << endl; - if ( mBaseText.isEmpty() ) - setLabelText( what ); - else if ( what.isEmpty() ) - setLabelText( mBaseText ); - else - setLabelText( i18n( "%1: %2" ).arg( mBaseText, what ) ); - setProgress( current, total ); -} - -void Kleo::ProgressDialog::slotDone() { - kdDebug(5150) << "Kleo::ProgressDialog::slotDone()" << endl; - hide(); - deleteLater(); -} - - -#include "progressdialog.moc" - diff --git a/kleopatra/lib/ui/progressdialog.h b/kleopatra/lib/ui/progressdialog.h deleted file mode 100644 index 0b419aabba..0000000000 --- a/kleopatra/lib/ui/progressdialog.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - progressdialog.h - - This file is part of libkleopatra, the KDE keymanagement library - Copyright (c) 2004 Klarlvdalens Datakonsult AB - - Libkleopatra 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. - - Libkleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifndef __KLEO_PROGRESSDIALOG_H__ -#define __KLEO_PROGRESSDIALOG_H__ - -#include -#include -#include -namespace Kleo { - - class Job; - - /** - @short A progress dialog for Kleo::Jobs - */ - class KDE_EXPORT ProgressDialog : public QProgressDialog { - Q_OBJECT - public: - ProgressDialog( Job * job, const QString & baseText, - QWidget * creator=0, const char * name=0, WFlags f=0 ); - ~ProgressDialog(); - - public slots: - /*! reimplementation */ - void setMinimumDuration( int ms ); - - private slots: - void slotProgress( const QString & what, int current, int total ); - void slotDone(); - private: - QString mBaseText; - }; - -} - -#endif // __KLEO_PROGRESSDIALOG_H__ diff --git a/kleopatra/main.cpp b/kleopatra/main.cpp deleted file mode 100644 index 37545502d1..0000000000 --- a/kleopatra/main.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - main.cpp - - This file is part of Kleopatra, the KDE keymanager - Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB - - Kleopatra 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. - - Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - In addition, as a special exception, the copyright holders give - permission to link the code of this program with any edition of - the Qt library by Trolltech AS, Norway (or with modified versions - of Qt that use the same license as Qt), and distribute linked - combinations including the two. You must obey the GNU General - Public License in all respects for all of the code used other than - Qt. If you modify this file, you may extend this exception to - your version of the file, but you are not obligated to do so. If - you do not wish to do so, delete this exception statement from - your version. -*/ - -#ifdef HAVE_CONFIG_H -#include -#endif - -#include "aboutdata.h" -#include "certmanager.h" - -#include - -#include -#include -#include -#include -#include -#include - -int main( int argc, char** argv ) -{ - AboutData aboutData; - - KCmdLineArgs::init(argc, argv, &aboutData); - static const KCmdLineOptions options[] = { - { "external" , I18N_NOOP("Search for external certificates initially"), 0 }, - { "query " , I18N_NOOP("Initial query string"), 0 }, - { "import-certificate ", I18N_NOOP("Name of certificate file to import"), 0 }, - KCmdLineLastOption// End of options. - }; - KCmdLineArgs::addCmdLineOptions( options ); - - KApplication app; - - KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); - - KGlobal::locale()->insertCatalogue( "libkleopatra" ); - KGlobal::iconLoader()->addAppDir( "libkleopatra" ); - - if( !Kleo::CryptoBackendFactory::instance()->smime() ) { - KMessageBox::error(0, - i18n( "The crypto plugin could not be initialized.
" - "Certificate Manager will terminate now.
") ); - return -2; - } - - CertManager* manager = new CertManager( args->isSet("external"), - QString::fromLocal8Bit(args->getOption("query")), - QString::fromLocal8Bit(args->getOption("import-certificate")) ); - - args->clear(); - manager->show(); - - return app.exec(); -} diff --git a/kleopatra/storedtransferjob.cpp b/kleopatra/storedtransferjob.cpp deleted file mode 100644 index 589acd702b..0000000000 --- a/kleopatra/storedtransferjob.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - Copyright (C) 2004 David Faure - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "storedtransferjob.h" - -using namespace KIOext; - -#define KIO_ARGS QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream - -StoredTransferJob::StoredTransferJob(const KURL& url, int command, - const QByteArray &packedArgs, - const QByteArray &_staticData, - bool showProgressInfo) - : KIO::TransferJob( url, command, packedArgs, _staticData, showProgressInfo ), - m_uploadOffset( 0 ) -{ - connect( this, SIGNAL( data( KIO::Job *, const QByteArray & ) ), - SLOT( slotData( KIO::Job *, const QByteArray & ) ) ); - connect( this, SIGNAL( dataReq( KIO::Job *, QByteArray & ) ), - SLOT( slotDataReq( KIO::Job *, QByteArray & ) ) ); -} - -void StoredTransferJob::setData( const QByteArray& arr ) -{ - Q_ASSERT( m_data.isNull() ); // check that we're only called once - Q_ASSERT( m_uploadOffset == 0 ); // no upload started yet - m_data = arr; -} - -void StoredTransferJob::slotData( KIO::Job *, const QByteArray &data ) -{ - // check for end-of-data marker: - if ( data.size() == 0 ) - return; - unsigned int oldSize = m_data.size(); - m_data.resize( oldSize + data.size(), QGArray::SpeedOptim ); - memcpy( m_data.data() + oldSize, data.data(), data.size() ); -} - -void StoredTransferJob::slotDataReq( KIO::Job *, QByteArray &data ) -{ - // Inspired from kmail's KMKernel::byteArrayToRemoteFile - // send the data in 64 KB chunks - const int MAX_CHUNK_SIZE = 64*1024; - int remainingBytes = m_data.size() - m_uploadOffset; - if( remainingBytes > MAX_CHUNK_SIZE ) { - // send MAX_CHUNK_SIZE bytes to the receiver (deep copy) - data.duplicate( m_data.data() + m_uploadOffset, MAX_CHUNK_SIZE ); - m_uploadOffset += MAX_CHUNK_SIZE; - //kdDebug() << "Sending " << MAX_CHUNK_SIZE << " bytes (" - // << remainingBytes - MAX_CHUNK_SIZE << " bytes remain)\n"; - } else { - // send the remaining bytes to the receiver (deep copy) - data.duplicate( m_data.data() + m_uploadOffset, remainingBytes ); - m_data = QByteArray(); - m_uploadOffset = 0; - //kdDebug() << "Sending " << remainingBytes << " bytes\n"; - } -} - -//// - -StoredTransferJob *KIOext::storedGet( const KURL& url, bool reload, bool showProgressInfo ) -{ - // Send decoded path and encoded query - KIO_ARGS << url; - StoredTransferJob * job = new StoredTransferJob( url, KIO::CMD_GET, packedArgs, QByteArray(), showProgressInfo ); - if (reload) - job->addMetaData("cache", "reload"); - return job; -} - -StoredTransferJob *KIOext::put( const QByteArray& arr, const KURL& url, int permissions, - bool overwrite, bool resume, bool showProgressInfo ) -{ - KIO_ARGS << url << Q_INT8( overwrite ? 1 : 0 ) << Q_INT8( resume ? 1 : 0 ) << permissions; - StoredTransferJob * job = new StoredTransferJob( url, KIO::CMD_PUT, packedArgs, QByteArray(), showProgressInfo ); - job->setData( arr ); - return job; -} - -#include "storedtransferjob.moc" diff --git a/kleopatra/storedtransferjob.h b/kleopatra/storedtransferjob.h deleted file mode 100644 index 85b591c6b8..0000000000 --- a/kleopatra/storedtransferjob.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - Copyright (C) 2004 David Faure - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef STOREDTRANSFERJOB_H -#define STOREDTRANSFERJOB_H - -#include - -// To be moved to KIO? -namespace KIOext { - -/** - * StoredTransferJob is a TransferJob (for downloading or uploading data) that - * also stores a QByteArray with the data, making it simpler to use than the - * standard TransferJob. - * - * For KIO::get it puts the data into the member QByteArray, so the user - * of this class can get hold of the whole data at once by calling data() - * when the result signal is emitted. - * You should only use StoredTransferJob to download data if you cannot - * process the data by chunks while it's being downloaded, since storing - * everything in a QByteArray can potentially require a lot of memory. - * - * For KIO::put the user of this class simply provides the bytearray from - * the start, and the job takes care of uploading it. - * You should only use StoredTransferJob to upload data if you cannot - * provide the in chunks while it's being uploaded, since storing - * everything in a QByteArray can potentially require a lot of memory. - * - */ -class StoredTransferJob : public KIO::TransferJob { - Q_OBJECT - -public: - /** - * Do not create a StoredTransferJob. Use storedGet() or storedPut() - * instead. - * @param url the url to get or put - * @param command the command to issue - * @param packedArgs the arguments - * @param _staticData additional data to transmit (e.g. in a HTTP Post) - * @param showProgressInfo true to show progress information to the user - */ - StoredTransferJob(const KURL& url, int command, - const QByteArray &packedArgs, - const QByteArray &_staticData, - bool showProgressInfo); - - /** - * Set data to be uploaded. This is for put jobs. - * Automatically called by KIOext::put(const QByteArray &, ...), do not call this yourself. - */ - void setData( const QByteArray& arr ); - - /** - * Get hold of the downloaded data. This is for get jobs. - * You're supposed to call this only from the slot connected to the result() signal. - */ - QByteArray data() const { return m_data; } - -private slots: - void slotData( KIO::Job *job, const QByteArray &data ); - void slotDataReq( KIO::Job *job, QByteArray &data ); -private: - QByteArray m_data; - int m_uploadOffset; -}; - - /** - * Get (a.k.a. read), into a single QByteArray. - * @see StoredTransferJob - * - * @param url the URL of the file - * @param reload true to reload the file, false if it can be taken from the cache - * @param showProgressInfo true to show progress information - * @return the job handling the operation. - */ - StoredTransferJob *storedGet( const KURL& url, bool reload=false, bool showProgressInfo = true ); - - /** - * Put (a.k.a. write) data from a single QByteArray. - * @see StoredTransferJob - * - * @param url Where to write data. - * @param permissions May be -1. In this case no special permission mode is set. - * @param overwrite If true, any existing file will be overwritten. - * @param resume true to resume, false otherwise - * @param showProgressInfo true to show progress information - * @return the job handling the operation. - * @see multi_get() - */ - StoredTransferJob *put( const QByteArray& arr, const KURL& url, int permissions, - bool overwrite, bool resume, bool showProgressInfo = true ); - -} // namespace - -#endif diff --git a/konsolekalendar/COPYING b/konsolekalendar/COPYING index 2e3f0efad4..54754ab4ba 100644 --- a/konsolekalendar/COPYING +++ b/konsolekalendar/COPYING @@ -1,341 +1,341 @@ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy 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 + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. diff --git a/konsolekalendar/Makefile.am b/konsolekalendar/Makefile.am index 429832b1c1..fdb9ae9139 100644 --- a/konsolekalendar/Makefile.am +++ b/konsolekalendar/Makefile.am @@ -1,24 +1,24 @@ SUBDIRS = pixmaps INCLUDES= -I$(top_srcdir)/libkcal \ -I$(top_srcdir)/libemailfunctions \ -I$(top_srcdir) $(all_includes) METASOURCES = AUTO bin_PROGRAMS = konsolekalendar konsolekalendar_SOURCES = konsolekalendarepoch.cpp konsolekalendardelete.cpp \ konsolekalendarchange.cpp konsolekalendarvariables.cpp \ konsolekalendaradd.cpp konsolekalendarexports.cpp konsolekalendar.cpp \ main.cpp konsolekalendar_LDADD = $(top_builddir)/libkcal/libkcal.la $(top_builddir)/libkdepim/libkdepim.la konsolekalendar_LDFLAGS = $(all_libraries) $(KDE_RPATH) appsdir = $(kde_appsdir)/Utilities xdg_apps_DATA = konsolekalendar.desktop messages: rc.cpp $(XGETTEXT) *.cpp -o $(podir)/konsolekalendar.pot -include $(top_srcdir)/doc/api/Doxyfile.am +include $(top_srcdir)/admin/Doxyfile.am diff --git a/konsolekalendar/konsolekalendar.cpp b/konsolekalendar/konsolekalendar.cpp index 6bcb26e17b..4e011a1420 100644 --- a/konsolekalendar/konsolekalendar.cpp +++ b/konsolekalendar/konsolekalendar.cpp @@ -1,463 +1,463 @@ /******************************************************************************* * konsolekalendar.cpp * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ /** * @file konsolekalendar.cpp * Provides the KonsoleKalendar class definition. * @author Tuukka Pasanen * @author Allen Winter */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "konsolekalendar.h" #include "konsolekalendaradd.h" #include "konsolekalendarchange.h" #include "konsolekalendardelete.h" #include "konsolekalendarexports.h" using namespace KCal; using namespace std; KonsoleKalendar::KonsoleKalendar( KonsoleKalendarVariables *variables ) { m_variables = variables; // m_Calendar = new ResourceCalendar; } KonsoleKalendar::~KonsoleKalendar() { } bool KonsoleKalendar::importCalendar() { KonsoleKalendarAdd add( m_variables ); kdDebug() << "konsolecalendar.cpp::importCalendar() | importing now!" << endl; return( add.addImportedCalendar() ); } bool KonsoleKalendar::createCalendar() { bool status = false; CalendarLocal newCalendar( QString::fromLatin1("UTC") ); if ( m_variables->isDryRun() ) { cout << i18n( "Create Calendar : %1" ). arg( m_variables->getCalendarFile() ).local8Bit() << endl; } else { kdDebug() << "konsolekalendar.cpp::createCalendar() | " << "Creating calendar file: " << m_variables->getCalendarFile().local8Bit() << endl; if ( m_variables->isVerbose() ) { cout << i18n( "Create Calendar : %1" ). arg( m_variables->getCalendarFile() ).local8Bit() << endl; } if ( newCalendar.save( m_variables->getCalendarFile() ) ) { newCalendar.close(); status = true; } } return status; } bool KonsoleKalendar::showInstance() { bool status = true; QFile f; QString title; Event::List *eventList; Event *event; if ( m_variables->isDryRun() ) { cout << i18n( "View Events :" ).local8Bit() << endl; printSpecs(); } else { kdDebug() << "konsolekalendar.cpp::showInstance() | " << "open export file" << endl; if ( m_variables->isExportFile() ) { f.setName( m_variables->getExportFile() ); if ( !f.open( IO_WriteOnly ) ) { status = false; kdDebug() << "konsolekalendar.cpp::showInstance() | " << "unable to open export file " << m_variables->getExportFile() << endl; } } else { f.open( IO_WriteOnly, stdout ); } if ( status ) { kdDebug() << "konsolekalendar.cpp::showInstance() | " << "opened successful" << endl; if ( m_variables->isVerbose() ) { cout << i18n( "View Event :" ).local8Bit() << endl; printSpecs(); } QTextStream ts( &f ); if ( m_variables->getExportType() != ExportTypeHTML && m_variables->getExportType() != ExportTypeMonthHTML ) { if ( m_variables->getAll() ) { kdDebug() << "konsolekalendar.cpp::showInstance() | " << "view all events sorted list" << endl; Event::List sortedList = m_variables->getCalendar()->events( EventSortStartDate ); QDate dt, firstdate, lastdate; firstdate = sortedList.first()->dtStart().date(); lastdate = sortedList.last()->dtStart().date(); for ( dt = firstdate; dt <= lastdate && status != false; dt = dt.addDays(1) ) { Event::List events = m_variables->getCalendar()->events( dt, EventSortStartDate, SortDirectionAscending ); status = printEventList( &ts, &events, dt ); } } else if ( m_variables->isUID() ) { kdDebug() << "konsolekalendar.cpp::showInstance() | " << "view events by uid list" << endl; //TODO: support a list of UIDs event = m_variables->getCalendar()->event( m_variables->getUID() ); //If this UID represents a recurring Event, //only the first day of the Event will be printed status = printEvent ( &ts, event, event->dtStart().date() ); } else if ( m_variables->isNext() ) { kdDebug() << "konsolekalendar.cpp::showInstance() | " << "Show next activity in calendar" << endl; QDateTime datetime = m_variables->getStartDateTime(); datetime = datetime.addDays( 720 ); QDate dt; for ( dt = m_variables->getStartDateTime().date(); dt <= datetime.date() && status != false; dt = dt.addDays(1) ) { Event::List events = m_variables->getCalendar()->events( dt, EventSortStartDate, SortDirectionAscending ); status = printEventList( &ts, &events, dt ); // when we get next event we exit.. if ( events.count() ) { kdDebug() << "konsolekalendar.cpp::showInstance() | " << "Next event" << endl; return true; } } } else { kdDebug() << "konsolekalendar.cpp::showInstance() | " << "view raw events within date range list" << endl; QDate dt; for ( dt = m_variables->getStartDateTime().date(); dt <= m_variables->getEndDateTime().date() && status != false; dt = dt.addDays(1) ) { Event::List events = m_variables->getCalendar()->events( dt, EventSortStartDate, SortDirectionAscending ); status = printEventList( &ts, &events, dt ); } } } else { QDate firstdate, lastdate; if ( m_variables->getAll() ) { // TODO: this is broken since the date on last() may not be last date // (this is the case for me) kdDebug() << "konsolekalendar.cpp::showInstance() | " << "HTML view all events sorted list" << endl; eventList = new Event::List ( m_variables->getCalendar()->rawEvents() ); firstdate = eventList->first()->dtStart().date(); lastdate = eventList->last()->dtStart().date(); delete eventList; } else if ( m_variables->isUID() ) { // TODO kdDebug() << "konsolekalendar.cpp::showInstance() | " << "HTML view events by uid list" << endl; cout << i18n("Sorry, export to HTML by UID is not supported yet") .local8Bit() << endl; return( false ); } else { kdDebug() << "konsolekalendar.cpp::showInstance() | " << "HTML view raw events within date range list" << endl; firstdate = m_variables->getStartDateTime().date(); lastdate = m_variables->getEndDateTime().date(); } HTMLExportSettings htmlSettings( "Konsolekalendar" ); //TODO: get progname and url from the values set in main htmlSettings.setCreditName( "KonsoleKalendar" ); htmlSettings.setCreditURL( "http://pim.kde.org/components/konsolekalendar.php" ); htmlSettings.setExcludePrivate( true ); htmlSettings.setExcludeConfidential( true ); htmlSettings.setEventView( false ); htmlSettings.setMonthView( false ); if ( m_variables->getExportType() == ExportTypeMonthHTML ) { title = i18n( "Events:" ); htmlSettings.setMonthView( true ); } else { if ( firstdate == lastdate ) { title = i18n( "Events: %1" ) .arg( firstdate.toString( Qt::TextDate ) ); } else { title = i18n( "Events: %1 - %2" ) .arg( firstdate.toString( Qt::TextDate ) ) .arg( lastdate.toString( Qt::TextDate ) ); } htmlSettings.setEventView( true ); } htmlSettings.setEventTitle( title ); htmlSettings.setEventAttendees( true ); // Not supporting Todos yet // title = "To-Do List for " + firstdate.toString(Qt::TextDate); // if ( firstdate != lastdate ) { // title += " - " + lastdate.toString(Qt::TextDate); // } htmlSettings.setTodoListTitle( title ); htmlSettings.setTodoView( false ); // htmlSettings.setTaskCategories( false ); // htmlSettings.setTaskAttendees( false ); // htmlSettings.setTaskDueDate( true ); htmlSettings.setDateStart( QDateTime( firstdate ) ); htmlSettings.setDateEnd( QDateTime( lastdate ) ) ; KCal::HtmlExport *Export; if ( !m_variables->isCalendarResources() ) { Export = new HtmlExport( m_variables->getCalendar(), &htmlSettings ); } else { Export = new HtmlExport( m_variables->getCalendarResources(), &htmlSettings ); } status = Export->save( &ts ); delete Export; } f.close(); } } return status; } bool KonsoleKalendar::printEventList( QTextStream *ts, Event::List *eventList, QDate date ) { bool status = true; if ( eventList->count() ) { Event *singleEvent; Event::List::ConstIterator it; for ( it = eventList->begin(); it != eventList->end() && status != false; ++it ) { singleEvent = *it; status = printEvent( ts, singleEvent, date ); } } return( status ); } bool KonsoleKalendar::printEvent( QTextStream *ts, Event *event, QDate dt ) { bool status = false; bool sameDay = true; KonsoleKalendarExports exports; if ( event ) { switch ( m_variables->getExportType() ) { case ExportTypeCSV: kdDebug() << "konsolekalendar.cpp::printEvent() | " << "CSV export" << endl; status = exports.exportAsCSV( ts, event, dt ); break; case ExportTypeTextShort: kdDebug() << "konsolekalendar.cpp::printEvent() | " << "TEXT-SHORT export" << endl; if ( dt.daysTo( m_saveDate ) ) { sameDay = false; m_saveDate = dt; } status = exports.exportAsTxtShort( ts, event, dt, sameDay ); break; case ExportTypeHTML: // this is handled separately for now break; default:// Default export-type is ExportTypeText kdDebug() << "konsolekalendar.cpp::printEvent() | " << "TEXT export" << endl; status = exports.exportAsTxt( ts, event, dt ); break; } } return( status ); } bool KonsoleKalendar::addEvent() { kdDebug() << "konsolecalendar.cpp::addEvent() | " << "Create Adding" << endl; KonsoleKalendarAdd add( m_variables ); kdDebug() << "konsolecalendar.cpp::addEvent() | " << "Adding Event now!" << endl; return( add.addEvent() ); } bool KonsoleKalendar::changeEvent() { kdDebug() << "konsolecalendar.cpp::changeEvent() | " << "Create Changing" << endl; KonsoleKalendarChange change( m_variables ); kdDebug() << "konsolecalendar.cpp::changeEvent() | " << "Changing Event now!" << endl; return( change.changeEvent() ); } bool KonsoleKalendar::deleteEvent() { kdDebug() << "konsolecalendar.cpp::deleteEvent() | " << "Create Deleting" << endl; KonsoleKalendarDelete del( m_variables ); kdDebug() << "konsolecalendar.cpp::deleteEvent() | " << "Deleting Event now!" << endl; return( del.deleteEvent() ); } bool KonsoleKalendar::isEvent( QDateTime startdate, QDateTime enddate, QString summary ) { // Search for an event with specified start and end datetime stamp and summary Event *event; Event::List::ConstIterator it; bool found = false; Event::List eventList( m_variables->getCalendar()-> rawEventsForDate( startdate.date(), EventSortStartDate, SortDirectionAscending ) ); for ( it = eventList.begin(); it != eventList.end(); ++it ) { event = *it; if ( event->dtEnd() == enddate && event->summary() == summary ) { found = true; break; } } return found; } void KonsoleKalendar::printSpecs() { cout << i18n( " What: %1" ). arg( m_variables->getSummary() ).local8Bit() << endl; cout << i18n( " Begin: %1" ). arg( m_variables->getStartDateTime().toString( Qt::TextDate ) ).local8Bit() << endl; cout << i18n( " End: %1" ). arg( m_variables->getEndDateTime().toString( Qt::TextDate ) ).local8Bit() << endl; if ( m_variables->getFloating() == true ) { cout << i18n( " No Time Associated with Event" ).local8Bit() << endl; } cout << i18n( " Desc: %1" ). arg( m_variables->getDescription() ).local8Bit() << endl; cout << i18n( " Location: %1" ). arg( m_variables->getLocation() ).local8Bit() << endl; } diff --git a/konsolekalendar/konsolekalendar.h b/konsolekalendar/konsolekalendar.h index 305abd9c8e..f41ed4ccb2 100644 --- a/konsolekalendar/konsolekalendar.h +++ b/konsolekalendar/konsolekalendar.h @@ -1,144 +1,144 @@ /******************************************************************************* * konsolekalendar.h * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ #ifndef _KONSOLEKALENDAR_H #define _KONSOLEKALENDAR_H #include #include #include #include #include #include "konsolekalendarvariables.h" /** * @file konsolekalendar.h * Provides the KonsoleKalendar class definition. */ namespace KCal { /** * The base class of the project. * @author Tuukka Pasanen */ class KonsoleKalendar { public: /** * Constructs a KonsoleKalendar object from command line arguments. */ KonsoleKalendar( KonsoleKalendarVariables *variables ); /** * Destructor */ ~KonsoleKalendar(); /** * Visualize what we need. */ bool showInstance(); /** * Imports calendar file */ bool importCalendar(); /** * Add event to calendar */ bool addEvent(); /** * Change event */ bool changeEvent(); /** * Delete event */ bool deleteEvent(); /** * Detect if event already exists * * @param startdate Starting date * @param enddate Ending date * @param summary Which summary event should have have */ bool isEvent( QDateTime startdate, QDateTime enddate, QString summary ); /** * Creates calendar file (If it doesn't exists) */ bool createCalendar(); private: /** * Print event specs for dryrun and verbose options */ void printSpecs(); /** * Prints event list in many formats * * @param eventlist which event we should print * @param dt is the date to use when printing the event for recurring events */ bool printEventList( QTextStream *ts, Event::List *eventList, QDate dt ); /** * Prints a single event in many formats * * @param event which we should print * @param dt is the date to use when printing the event for recurring events */ bool printEvent( QTextStream *ts, Event *event, QDate dt ); /** * Variables that changes stuff in programm */ KonsoleKalendarVariables *m_variables; /** * Calendar file itself */ ResourceCalendar *m_Calendar; /** * This is usefull if we like to have same day events to same system */ QDate m_saveDate; }; } #endif diff --git a/konsolekalendar/konsolekalendaradd.cpp b/konsolekalendar/konsolekalendaradd.cpp index 42eee7bb60..becbf29125 100644 --- a/konsolekalendar/konsolekalendaradd.cpp +++ b/konsolekalendar/konsolekalendaradd.cpp @@ -1,169 +1,167 @@ /******************************************************************************* * konsolekalendaradd.cpp * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ /** * @file konsolekalendaradd.cpp * Provides the KonsoleKalendarAdd class definition. * @author Tuukka Pasanen * @author Allen Winter */ #include #include #include #include #include #include #include #include #include #include "konsolekalendaradd.h" using namespace KCal; using namespace std; KonsoleKalendarAdd::KonsoleKalendarAdd( KonsoleKalendarVariables *vars ) { m_variables = vars; } KonsoleKalendarAdd::~KonsoleKalendarAdd() { } /** * Adds event to Calendar */ bool KonsoleKalendarAdd::addEvent() { bool status = true; kdDebug() << "konsolekalendaradd.cpp::addEvent()" << endl; if ( m_variables->isDryRun() ) { cout << i18n( "Insert Event :" ).local8Bit() << endl; printSpecs(); } else { if ( m_variables->isVerbose() ) { cout << i18n( "Insert Event :" ).local8Bit() << endl; printSpecs(); } Event *event = new Event(); event->setDtStart( m_variables->getStartDateTime() ); event->setDtEnd( m_variables->getEndDateTime() ); event->setSummary( m_variables->getSummary() ); event->setFloats( m_variables->getFloating() ); event->setDescription( m_variables->getDescription() ); event->setLocation( m_variables->getLocation() ); if ( m_variables->getCalendar()->addEvent( event ) ) { cout << i18n( "Success: \"%1\" inserted" ). arg( m_variables->getSummary() ).local8Bit() << endl; if ( !m_variables->isCalendarResources() ) { status = m_variables->getCalendar()->save( m_variables->getCalendarFile() ); } else { m_variables->getCalendar()->save(); } } else { cout << i18n( "Failure: \"%1\" not inserted" ). arg( m_variables->getSummary() ).local8Bit() << endl; status = false; } } kdDebug() << "konsolekalendaradd.cpp::addEvent() | Done " << endl; return status; } bool KonsoleKalendarAdd::addImportedCalendar() { - // TODO: reimplement this please.. - - /*if ( !m_variables->getCalendar()->load( m_variables->getImportFile() ) ) { + if ( !m_variables->getCalendar()->load( m_variables->getImportFile() ) ) { kdDebug() << "konsolekalendaradd.cpp::importCalendar() | " << "Can't import file: " << m_variables->getImportFile() << endl; return false; } else { kdDebug() << "konsolekalendaradd.cpp::importCalendar() | " << "Successfully imported file: " << m_variables->getImportFile() << endl; } if ( !m_variables->isCalendarResources() ) { m_variables->getCalendar()->save( m_variables->getCalendarFile() ); } else { m_variables->getCalendar()->save(); - }*/ + } return true; } void KonsoleKalendarAdd::printSpecs() { cout << i18n( " What: %1" ). arg( m_variables->getSummary() ).local8Bit() << endl; cout << i18n( " Begin: %1" ). arg( m_variables->getStartDateTime().toString( Qt::TextDate ) ).local8Bit() << endl; cout << i18n( " End: %1" ). arg( m_variables->getEndDateTime().toString( Qt::TextDate ) ).local8Bit() << endl; if ( m_variables->getFloating() == true ) { cout << i18n( " No Time Associated with Event" ).local8Bit() << endl; } cout << i18n( " Desc: %1" ). arg( m_variables->getDescription() ).local8Bit() << endl; cout << i18n( " Location: %1" ). arg( m_variables->getLocation() ).local8Bit() << endl; } diff --git a/konsolekalendar/konsolekalendaradd.h b/konsolekalendar/konsolekalendaradd.h index 1a01000b73..d1c9a29601 100644 --- a/konsolekalendar/konsolekalendaradd.h +++ b/konsolekalendar/konsolekalendaradd.h @@ -1,83 +1,83 @@ /******************************************************************************* * konsolekalendaradd.h * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ #ifndef _KONSOLEKALENDARADD_H_ #define _KONSOLEKALENDARADD_H_ #include "konsolekalendarvariables.h" /** * @file konsolekalendaradd.h * Provides the KonsoleKalendarAdd class definition. */ namespace KCal { /** * Class to manage the Event insertion capability. * @author Tuukka Pasanen * @author Allen Winter */ class KonsoleKalendarAdd { public: /** * Constructs a KonsoleKalendarAdd object from command line arguments. * @param vars is a KonsoleKalendarVariable object with Event information. */ KonsoleKalendarAdd( KonsoleKalendarVariables *vars ); /** * Destructor */ ~KonsoleKalendarAdd(); /** * Add the Event. */ bool addEvent(); /** * Imports calendar file to current Calendar. */ bool addImportedCalendar(); private: /** * Print event specs for dryrun and verbose options */ void printSpecs(); /** * Variable to how to make it */ KonsoleKalendarVariables *m_variables; }; } #endif diff --git a/konsolekalendar/konsolekalendarchange.cpp b/konsolekalendar/konsolekalendarchange.cpp index 1377a67c2b..b2970a662a 100644 --- a/konsolekalendar/konsolekalendarchange.cpp +++ b/konsolekalendar/konsolekalendarchange.cpp @@ -1,185 +1,185 @@ /******************************************************************************* * konsolekalendarchange.cpp * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ /** * @file konsolekalendarchange.cpp * Provides the KonsoleKalendarChange class definition. * @author Tuukka Pasanen * @author Allen Winter */ #include #include #include #include #include "konsolekalendarchange.h" using namespace KCal; using namespace std; KonsoleKalendarChange::KonsoleKalendarChange( KonsoleKalendarVariables *vars ) { m_variables = vars; } KonsoleKalendarChange::~KonsoleKalendarChange() { } bool KonsoleKalendarChange::changeEvent() { bool status = false; kdDebug() << "konsolekalendarchange.cpp::changeEvent()" << endl; /* * Retrieve event on the basis of the unique string ID */ Event *event = m_variables->getCalendar()->event( m_variables->getUID() ); if ( event ) { if ( m_variables->isDryRun() ) { cout << i18n( "Change Event :" ).local8Bit() << endl; printSpecs( event ); cout << i18n( "To Event :" ).local8Bit() << endl; printSpecs(); } else { kdDebug() << "konsolekalendarchange.cpp:changeEvent() : " << m_variables->getUID().local8Bit() << endl; if ( m_variables->isVerbose() ) { cout << i18n( "Change Event :" ).local8Bit() << endl; printSpecs( event ); cout << i18n( "To Event :" ).local8Bit() << endl; printSpecs(); } if ( m_variables->isStartDateTime() ) { event->setDtStart( m_variables->getStartDateTime() ); } if ( m_variables->isEndDateTime() ) { event->setDtEnd( m_variables->getEndDateTime() ); } event->setFloats( m_variables->getFloating() ); if ( m_variables->isSummary() ) { event->setSummary( m_variables->getSummary() ); } if ( m_variables->isDescription() ) { event->setDescription( m_variables->getDescription() ); } if ( m_variables->isLocation() ) { event->setLocation( m_variables->getLocation() ); } if ( m_variables->getCalendar()->addEvent( event ) ) { cout << i18n( "Success: \"%1\" changed" ) .arg( event->summary() ).local8Bit() << endl; if ( !m_variables->isCalendarResources() ) { status = m_variables->getCalendar()->save( m_variables->getCalendarFile() ); } else { m_variables->getCalendar()->save(); status = true; } } else { cout << i18n( "Failure: \"%1\" not changed" ) .arg( event->summary() ).local8Bit() << endl; } } } kdDebug() << "konsolekalendarchange.cpp::changeEvent() | Done " << endl; return status; } void KonsoleKalendarChange::printSpecs( Event *event ) { cout << i18n( " UID: %1" ). arg( event->uid() ).local8Bit() << endl; cout << i18n( " What: %1" ). arg( event->summary() ).local8Bit() << endl; cout << i18n( " Begin: %1" ). arg( event->dtStart().toString( Qt::TextDate ) ).local8Bit() << endl; cout << i18n( " End: %1" ). arg( event->dtEnd().toString( Qt::TextDate ) ).local8Bit() << endl; cout << i18n( " Desc: %1" ). arg( event->description() ).local8Bit() << endl; cout << i18n( " Location: %1" ). arg( event->location() ).local8Bit() << endl; } void KonsoleKalendarChange::printSpecs() { cout << i18n( " UID: %1" ). arg( m_variables->getUID() ).local8Bit() << endl; cout << i18n( " What: %1" ). arg( m_variables->getSummary() ).local8Bit() << endl; cout << i18n( " Begin: %1" ). arg( m_variables->getStartDateTime().toString( Qt::TextDate ) ).local8Bit() << endl; cout << i18n( " End: %1" ). arg( m_variables->getEndDateTime().toString( Qt::TextDate ) ).local8Bit() << endl; cout << i18n( " Desc: %1" ). arg( m_variables->getDescription() ).local8Bit() << endl; cout << i18n( " Location: %1" ). arg( m_variables->getLocation() ).local8Bit() << endl; } diff --git a/konsolekalendar/konsolekalendarchange.h b/konsolekalendar/konsolekalendarchange.h index d21208fb6f..80e8f8c2ea 100644 --- a/konsolekalendar/konsolekalendarchange.h +++ b/konsolekalendar/konsolekalendarchange.h @@ -1,83 +1,83 @@ /******************************************************************************* * konsolekalendarchange.h * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ #ifndef _KONSOLEKALENDARCHANGE_H_ #define _KONSOLEKALENDARCHANGE_H_ #include "konsolekalendarvariables.h" /** * @file konsolekalendarchange.h * Provides the KonsoleKalendarChange class definition. */ namespace KCal { /** * Class to manage the Event modification capability. * @author Tuukka Pasanen * @author Allen Winter */ class KonsoleKalendarChange { public: /** * Constructs a KonsoleKalendarChange object from command line arguments. * @param vars is a KonsoleKalendarVariable object with Event information. */ KonsoleKalendarChange( KonsoleKalendarVariables *vars ); /** * Destructor */ ~KonsoleKalendarChange(); /** * Modify the Event. */ bool changeEvent(); private: /** * Print Event specs for dryrun and verbose options. * @param event is the Event to print. */ void printSpecs( Event *event ); /* * Print Event specs as provided from the command line arguments. */ void printSpecs(); /** * Variables are here */ KonsoleKalendarVariables *m_variables; }; } #endif diff --git a/konsolekalendar/konsolekalendardelete.cpp b/konsolekalendar/konsolekalendardelete.cpp index 0416b6bfc1..1dd09a99cf 100644 --- a/konsolekalendar/konsolekalendardelete.cpp +++ b/konsolekalendar/konsolekalendardelete.cpp @@ -1,123 +1,123 @@ /******************************************************************************* * konsolekalendardelete.cpp * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ /** * @file konsolekalendardelete.cpp * Provides the KonsoleKalendarDelete class definition. * @author Tuukka Pasanen * @author Allen Winter */ #include #include #include #include #include "konsolekalendardelete.h" using namespace KCal; using namespace std; KonsoleKalendarDelete::KonsoleKalendarDelete( KonsoleKalendarVariables *vars ) { m_variables = vars; } KonsoleKalendarDelete::~KonsoleKalendarDelete() { } bool KonsoleKalendarDelete::deleteEvent() { bool status = false; kdDebug() << "konsolekalendardelete.cpp::deleteEvent()" << endl; /* * Retrieve event on the basis of the unique string ID */ Event *event = m_variables->getCalendar()->event( m_variables->getUID() ); if ( event ) { if ( m_variables->isDryRun() ) { cout << i18n( "Delete Event :" ).local8Bit() << endl; printSpecs( event ); } else { kdDebug() << "konsolekalendardelete.cpp:deleteEvent() : " << m_variables->getUID().local8Bit() << endl; if ( m_variables->isVerbose() ) { cout << i18n( "Delete Event :" ).local8Bit() << endl; printSpecs( event ); } m_variables->getCalendar()->deleteEvent( event ); cout << i18n( "Success: \"%1\" deleted" ) .arg( event->summary() ).local8Bit() << endl; if ( !m_variables->isCalendarResources() ) { status = m_variables->getCalendar()->save( m_variables->getCalendarFile() ); } else { m_variables->getCalendar()->save(); status = true; } } } kdDebug() << "konsolekalendardelete.cpp::deleteEvent() | Done " << endl; return status; } void KonsoleKalendarDelete::printSpecs( Event *event ) { cout << i18n( " UID: %1" ). arg( m_variables->getUID() ).local8Bit() << endl; cout << i18n( " What: %1" ). arg( event->summary() ).local8Bit() << endl; cout << i18n( " Begin: %1" ). arg( event->dtStart().toString( Qt::TextDate ) ).local8Bit() << endl; cout << i18n( " End: %1" ). arg( event->dtEnd().toString( Qt::TextDate ) ).local8Bit() << endl; cout << i18n( " Desc: %1" ). arg( event->description() ).local8Bit() << endl; cout << i18n( " Location: %1" ). arg( event->location() ).local8Bit() << endl; } diff --git a/konsolekalendar/konsolekalendardelete.h b/konsolekalendar/konsolekalendardelete.h index c895529ff2..2a01990f0a 100644 --- a/konsolekalendar/konsolekalendardelete.h +++ b/konsolekalendar/konsolekalendardelete.h @@ -1,77 +1,77 @@ /******************************************************************************* * konsolekalendardelete.h * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ #ifndef _KONSOLEKALENDARDELETE_H_ #define _KONSOLEKALENDARDELETE_H_ #include "konsolekalendarvariables.h" /** * @file konsolekalendardelete.h * Provides the KonsoleKalendarDelete class definition. */ namespace KCal { /** * Class to manage the Event removal capability. * @author Tuukka Pasanen * @author Allen Winter */ class KonsoleKalendarDelete { public: /** * Constructs a KonsoleKalendarDelete object from command line arguments. */ KonsoleKalendarDelete( KonsoleKalendarVariables *vars ); /** * Destructor */ ~KonsoleKalendarDelete(); /** * Delete the Event. */ bool deleteEvent(); private: /** * Print event specs for dryrun and verbose options. */ void printSpecs( Event *event ); /** * What we need to delete */ KonsoleKalendarVariables *m_variables; }; } #endif diff --git a/konsolekalendar/konsolekalendarepoch.cpp b/konsolekalendar/konsolekalendarepoch.cpp index 748145c65a..c070d25320 100644 --- a/konsolekalendar/konsolekalendarepoch.cpp +++ b/konsolekalendar/konsolekalendarepoch.cpp @@ -1,176 +1,176 @@ /******************************************************************************* * konsolekalendarepoch.cpp * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ /** * @file konsolekalendarepoch.cpp * Provides the KonsoleKalendarEpoch class definition. * @author Tuukka Pasanen * @author Allen Winter */ #include #include #include #include "konsolekalendarepoch.h" using namespace KCal; using namespace std; KonsoleKalendarEpoch::KonsoleKalendarEpoch() { } KonsoleKalendarEpoch::~KonsoleKalendarEpoch() { } // By "epoch" we mean the number of seconds since 00:00:00 UTC on January 1 1970 // Function to convert an epoch value into a QDateTime QDateTime KonsoleKalendarEpoch::epoch2QDateTime( uint epoch ) { QDateTime dt; dt.setTime_t( epoch, Qt::UTC ); return( dt ); } // Function to convert a QDateTime value into an epoch uint KonsoleKalendarEpoch::QDateTime2epoch( QDateTime dt ) { // THIS FUNCTION CAN BE OFF BY 1 HOUR DUE TO DAYLIGHT SAVINGS TIME. // SORRY QT DOESN'T HANDLE DAYLIGHT SAVINGS TIME. // Compute #seconds to subtract for local timezone difference from UTC. int offset = QDateTime::currentDateTime( Qt::UTC ).toTime_t() - QDateTime::currentDateTime( Qt::LocalTime ).toTime_t(); return( dt.toTime_t() - offset ); } #if defined (TEST) // Pass -DTEST to the compile command to create the test program, e.g: // cc -DTEST -I/usr/local/KDE/include konsolekalendarepoch.cpp // -L/usr/local/KDE/lib -lqt-mt -pthread main() { uint epoch; QDateTime dt; cout << endl; cout << "NOTE: Some tests may be off by 1 hour (3600 secs) " << "due to daylight savings time" << endl << endl; // Test1 epoch = 0; dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); cout << "TEST 1:" << endl; cout << "epoch=" << epoch << " converts to " << dt.toString( Qt::TextDate ) << endl; epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); cout << "date=" << dt.toString( Qt::TextDate ) << " converts to " << "epoch=" << epoch << endl; // Test2 epoch = 100000; dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); cout << "TEST 2:" << endl; cout << "epoch=" << epoch << " converts to " << dt.toString( Qt::TextDate ) << endl; epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); cout << "date=" << dt.toString( Qt::TextDate ) << " converts to " << "epoch=" << epoch << endl; // Test3 epoch = 10000000; dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); cout << "TEST 3:" << endl; cout << "epoch=" << epoch << " converts to " << dt.toString( Qt::TextDate ) << endl; epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); cout << "date=" << dt.toString( Qt::TextDate ) << " converts to " << "epoch=" << epoch << endl; // Test4 epoch = 1000000000; dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); cout << "TEST 4:" << endl; cout << "epoch=" << epoch << " converts to " << dt.toString( Qt::TextDate ) << endl; epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); cout << "date=" << dt.toString( Qt::TextDate ) << " converts to " << "epoch=" << epoch << endl; // Test5 epoch = 10000000000; dt = KonsoleKalendarEpoch::epoch2QDateTime( epoch ); cout << "TEST 5:" << endl; cout << "epoch=" << epoch << " converts to " << dt.toString( Qt::TextDate ) << endl; epoch = KonsoleKalendarEpoch::QDateTime2epoch( dt ); cout << "date=" << dt.toString( Qt::TextDate ) << " converts to " << "epoch=" << epoch << endl; } #endif diff --git a/konsolekalendar/konsolekalendarepoch.h b/konsolekalendar/konsolekalendarepoch.h index 57ea8369d7..e6db6d77e1 100644 --- a/konsolekalendar/konsolekalendarepoch.h +++ b/konsolekalendar/konsolekalendarepoch.h @@ -1,72 +1,72 @@ /******************************************************************************* * konsolekalendarepoch.h * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ #ifndef _KONSOLEKALENDAREPOCH_H_ #define _KONSOLEKALENDAREPOCH_H_ #include /** * @file konsolekalendarepoch.h * Provides the KonsoleKalendarEpoch class definition. */ namespace KCal { /** * Class for timestamps expressed as epochs. * @author Allen Winter */ class KonsoleKalendarEpoch { public: /** * Constructor. */ KonsoleKalendarEpoch(); /** * Destructor */ ~KonsoleKalendarEpoch(); /** * Converts epoch time to QDateTime format. * @param epoch epoch time. */ static QDateTime epoch2QDateTime( uint epoch ); /** * Converts QT DateTime to epoch format. * @param dt is a QDateTime to convert to an epoch. */ static uint QDateTime2epoch( QDateTime dt ); }; } #endif diff --git a/konsolekalendar/konsolekalendarexports.cpp b/konsolekalendar/konsolekalendarexports.cpp index 6f4e740243..cad79964a4 100644 --- a/konsolekalendar/konsolekalendarexports.cpp +++ b/konsolekalendar/konsolekalendarexports.cpp @@ -1,243 +1,243 @@ /******************************************************************************* * konsolekalendarexports.cpp * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ /** * @file konsolekalendarexports.cpp * Provides the KonsoleKalendarExports class definition. * @author Tuukka Pasanen * @author Allen Winter */ #include #include #include #include #include #include #include #include #include "konsolekalendarexports.h" using namespace KCal; using namespace std; KonsoleKalendarExports::KonsoleKalendarExports( KonsoleKalendarVariables *vars ) { m_variables = vars; m_firstEntry = true; } KonsoleKalendarExports::~KonsoleKalendarExports() { } bool KonsoleKalendarExports::exportAsTxt( QTextStream *ts, Event *event, QDate date ) { // Export "Text" Format: // // Date:\t(dddd yyyy-MM-dd) // [\t(hh:mm) - (hh:mm)] // Summary: // \t // Location: // \t // Description: // \t // UID: // \t // -------------------------------------------------- // Print Event Date (in user's prefered format) *ts << i18n( "Date:" ) << "\t" << KGlobal::locale()->formatDate( date ) << endl; // Print Event Starttime - Endtime, for Non-Floating Events Only if ( !event->doesFloat() ) { *ts << "\t" << KGlobal::locale()->formatTime( event->dtStart().time() ) << " - " << KGlobal::locale()->formatTime( event->dtEnd().time() ); } *ts << endl; // Print Event Summary *ts << i18n( "Summary:" ) << endl; if ( !event->summary().isEmpty() ) { *ts << "\t" << event->summary() << endl; } else { *ts << "\t" << i18n( "(no summary available)" ) << endl; } // Print Event Location *ts << i18n( "Location:" ) << endl; if ( !event->location().isEmpty() ) { *ts << "\t" <location() << endl; } else { *ts << "\t" << i18n( "(no location available)" ) << endl; } // Print Event Description *ts << i18n( "Description:" ) << endl; if ( !event->description().isEmpty() ) { *ts << "\t" << event->description() << endl; } else { *ts << "\t" << i18n( "(no description available)" ) << endl; } // Print Event UID *ts << i18n( "UID:" ) << endl << "\t" << event->uid() << endl; // Print Line Separator *ts << "--------------------------------------------------" << endl; return true; } bool KonsoleKalendarExports::exportAsTxtShort( QTextStream *ts, Event *event, QDate date, bool sameday ) { // Export "Text-Short" Format: // // [--------------------------------------------------] // {(dddd yyyy-MM-dd)] // [(hh:mm) - (hh:mm) | "\t"] // \t[, ] // \t\t if ( !sameday ) { // If a new date, then Print the Event Date (in user's prefered format) *ts << KGlobal::locale()->formatDate( date ) << ":" << endl; } // Print Event Starttime - Endtime if ( !event->doesFloat() ) { *ts << KGlobal::locale()->formatTime( event->dtStart().time() ) << " - " << KGlobal::locale()->formatTime( event->dtEnd().time() ); } else { *ts << i18n( "[all day]\t" ); } *ts << "\t"; // Print Event Summary *ts << event->summary().replace( QChar( '\n' ), QChar( ' ' ) ); // Print Event Location if ( !event->location().isEmpty() ) { if ( !event->summary().isEmpty() ) { *ts << ", "; } *ts << event->location().replace( QChar( '\n' ), QChar( ' ' ) ); } *ts << endl; // Print Event Description if ( !event->description().isEmpty() ) { *ts << "\t\t\t" << event->description().replace( QChar( '\n' ), QChar( ' ' ) ) << endl; } // By user request, no longer print UIDs if export-type==short return true; } QString KonsoleKalendarExports::processField( QString field, QString dquote ) { // little function that processes a field for CSV compliance: // 1. Replaces double quotes by a pair of consecutive double quotes // 2. Surrounds field with double quotes QString double_dquote = dquote + dquote; QString retField = dquote + field.replace( dquote, double_dquote ) + dquote; return retField; } #define pF( x ) processField( ( x ), dquote ) bool KonsoleKalendarExports::exportAsCSV( QTextStream *ts, Event *event, QDate date ) { // Export "CSV" Format: // // startdate,starttime,enddate,endtime,summary,location,description,UID QString delim = i18n( "," ); // character to use as CSV field delimiter QString dquote = i18n( "\"" ); // character to use to quote CSV fields if ( !event->doesFloat() ) { *ts << pF( KGlobal::locale()->formatDate( date ) ) << delim << pF( KGlobal::locale()->formatTime( event->dtStart().time() ) ) << delim << pF( KGlobal::locale()->formatDate( date ) ) << delim << pF( KGlobal::locale()->formatTime( event->dtEnd().time() ) ); } else { *ts << pF( KGlobal::locale()->formatDate( date ) ) << delim << pF( "" ) << delim << pF( KGlobal::locale()->formatDate( date ) ) << delim << pF( "" ); } *ts << delim << pF( event->summary().replace( QChar('\n'), QChar(' ') ) ) << delim << pF( event->location().replace( QChar('\n'), QChar(' ') ) ) << delim << pF( event->description().replace( QChar('\n'), QChar(' ') ) ) << delim << pF( event->uid() ) << endl; return true; } diff --git a/konsolekalendar/konsolekalendarexports.h b/konsolekalendar/konsolekalendarexports.h index efb1b5f37b..dc2f44ecaf 100644 --- a/konsolekalendar/konsolekalendarexports.h +++ b/konsolekalendar/konsolekalendarexports.h @@ -1,101 +1,101 @@ /******************************************************************************* * konsolekalendarexports.h * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ #ifndef _KONSOLEKALENDAREXPORTS_H_ #define _KONSOLEKALENDAREXPORTS_H_ #include #include "konsolekalendarvariables.h" /** * @file konsolekalendarexports.h * Provides the KonsoleKalendarExports class definition. */ namespace KCal { /** * Class to manage the Export functionality. * @author Tuukka Pasanen * @author Allen Winter */ class KonsoleKalendarExports { public: /** * Constructs a KonsoleKalendarChange object from command line arguments. * @param vars is a KonsoleKalendarVariable object with Event information. */ KonsoleKalendarExports( KonsoleKalendarVariables *vars = 0 ); /** * Destructor */ ~KonsoleKalendarExports(); /** * Export the Event in Text Mode. * @param ts pointer to the output QTextStream. * @param event pointer to the Event to export. * @param date is the QDate to be exported for. */ bool exportAsTxt( QTextStream *ts, Event *event, QDate date ); /** * Export the Event in Short Text Mode. * @param ts pointer to the output QTextStream. * @param event pointer to the Event to export. * @param date is the QDate to be exported for. * @param sameday flags that this Event is on the same date as the * previously exported Event. */ bool exportAsTxtShort( QTextStream *ts, Event *event, QDate date, bool sameday ); /** * Export the Event in Comma-Separated Values (CSV) Mode. * @param ts pointer to the output QTextStream. * @param event pointer to the Event to export. * @param date is the QDate to be exported for. */ bool exportAsCSV( QTextStream *ts, Event *event, QDate date ); private: KonsoleKalendarVariables *m_variables; bool m_firstEntry; /** * Processes a field for Comma-Separated Value (CSV) compliance: * 1. Replaces double quotes by a pair of consecutive double quotes * 2. Surrounds field with double quotes * @param field is the field value to be processed. * @param dquote is a QString containing the double quote character. */ QString processField( QString field, QString dquote ); }; } #endif diff --git a/konsolekalendar/konsolekalendarvariables.cpp b/konsolekalendar/konsolekalendarvariables.cpp index 01966a7954..0b1364bc39 100644 --- a/konsolekalendar/konsolekalendarvariables.cpp +++ b/konsolekalendar/konsolekalendarvariables.cpp @@ -1,472 +1,472 @@ /******************************************************************************* * konsolekalendarvariables.cpp * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ /** * @file konsolekalendarvariables.cpp * Provides the KonsoleKalendarVariables class definition. * @author Tuukka Pasanen * @author Allen Winter */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "konsolekalendarvariables.h" using namespace KCal; using namespace std; KonsoleKalendarVariables::KonsoleKalendarVariables() { m_TimeZoneId = ""; m_bIsTimeZoneId = false; m_bIsUID = false; m_bIsStartDateTime = false; m_bIsEndDateTime = false; m_bNext = false; m_bVerbose = false; m_bDryRun = false; m_bUseEvents = false; m_bUseTodos = false; m_bUseJournals = false; m_bDescription = false; m_description = ""; m_bSummary = false; m_summary = "Default summary"; m_bFloating = true; m_exportType = ExportTypeText; m_bIsExportFile = false; m_bIsDefault = false; m_bIsCalendarResources = false; } void KonsoleKalendarVariables::setTimeZoneId() { m_bIsTimeZoneId = true; m_TimeZoneId = KPimPrefs::timezone(); } QString KonsoleKalendarVariables::getTimeZoneId() { return m_TimeZoneId; } bool KonsoleKalendarVariables::isTimeZoneId() { return m_bIsTimeZoneId; } KonsoleKalendarVariables::~KonsoleKalendarVariables() { // delete m_resource; } void KonsoleKalendarVariables::setUID( QString uid ) { m_bIsUID = true; m_UID = uid; } QString KonsoleKalendarVariables::getUID() { return m_UID; } bool KonsoleKalendarVariables::isUID() { return m_bIsUID; } void KonsoleKalendarVariables::setStartDateTime( QDateTime start ) { m_bIsStartDateTime = true; m_startDateTime = start; } QDateTime KonsoleKalendarVariables::getStartDateTime() { return m_startDateTime; } bool KonsoleKalendarVariables::isStartDateTime() { return m_bIsStartDateTime; } void KonsoleKalendarVariables::setEndDateTime( QDateTime end ) { m_bIsEndDateTime = true; m_endDateTime = end; } QDateTime KonsoleKalendarVariables::getEndDateTime() { return m_endDateTime; } bool KonsoleKalendarVariables::isEndDateTime() { return m_bIsEndDateTime; } void KonsoleKalendarVariables::setNext( bool next ) { m_bNext = next; } bool KonsoleKalendarVariables::isNext() { return m_bNext; } void KonsoleKalendarVariables::setVerbose( bool verbose ) { m_bVerbose = verbose; } bool KonsoleKalendarVariables::isVerbose() { return m_bVerbose; } void KonsoleKalendarVariables::setDryRun( bool dryrun ) { m_bDryRun = dryrun; } bool KonsoleKalendarVariables::isDryRun() { return m_bDryRun; } void KonsoleKalendarVariables::setUseEvents( bool useEvents ) { m_bUseEvents = useEvents; } bool KonsoleKalendarVariables::getUseEvents() { return( m_bUseEvents ); } void KonsoleKalendarVariables::setUseTodos( bool useTodos ) { m_bUseTodos = useTodos; } bool KonsoleKalendarVariables::getUseTodos() { return( m_bUseTodos ); } void KonsoleKalendarVariables::setUseJournals( bool useJournals ) { m_bUseJournals = useJournals; } bool KonsoleKalendarVariables::getUseJournals() { return( m_bUseJournals ); } void KonsoleKalendarVariables::setCalendarFile( QString calendar ) { m_calendar = calendar; } QString KonsoleKalendarVariables::getCalendarFile() { return m_calendar; } void KonsoleKalendarVariables::setImportFile( QString calendar ) { m_import = calendar; } QString KonsoleKalendarVariables::getImportFile() { return m_import; } void KonsoleKalendarVariables::setCalendar( CalendarLocal *calendar ) { m_calendarLocal = calendar; } CalendarLocal *KonsoleKalendarVariables::getCalendar() { return m_calendarLocal; } void KonsoleKalendarVariables::setExportType( ExportType exportType ) { m_exportType = exportType; } ExportType KonsoleKalendarVariables::getExportType() { return m_exportType; } void KonsoleKalendarVariables::setExportFile( QString export_file ) { m_exportFile = export_file; m_bIsExportFile = true; } bool KonsoleKalendarVariables::isExportFile() { return m_bIsExportFile; } QString KonsoleKalendarVariables::getExportFile() { return m_exportFile; } bool KonsoleKalendarVariables::isAll() { return m_bAll; } void KonsoleKalendarVariables::setAll( bool all ) { m_bAll = all; } bool KonsoleKalendarVariables::getAll() { return m_bAll; } void KonsoleKalendarVariables::setDefault( bool def ) { m_bIsDefault = def; } bool KonsoleKalendarVariables::isDefault() { return m_bIsDefault; } void KonsoleKalendarVariables::setDescription( QString description ) { m_bDescription = true; m_description = description; } QString KonsoleKalendarVariables::getDescription() { return m_description; } bool KonsoleKalendarVariables::isDescription() { return m_bDescription; } void KonsoleKalendarVariables::setLocation( QString location ) { m_bLocation = true; m_location = location; } QString KonsoleKalendarVariables::getLocation() { return m_location; } bool KonsoleKalendarVariables::isLocation() { return m_bLocation; } void KonsoleKalendarVariables::setSummary( QString summary ) { m_bSummary = true; m_summary = summary; } QString KonsoleKalendarVariables::getSummary() { return m_summary; } bool KonsoleKalendarVariables::isSummary() { return m_bSummary; } void KonsoleKalendarVariables::setFloating( bool floating ) { m_bFloating = floating; } bool KonsoleKalendarVariables::getFloating() { return m_bFloating; } void KonsoleKalendarVariables::setDaysCount( int count ) { m_daysCount = count; m_bDaysCount = true; } int KonsoleKalendarVariables::getDaysCount() { return m_daysCount; } bool KonsoleKalendarVariables::isDaysCount() { return m_bDaysCount; } bool KonsoleKalendarVariables::addCalendarResources( ResourceCalendar *resource ) { if ( m_resource ) { // In current state we support only one calendar // that's a fact and we have to live with that! kdDebug() << "konsolekalendarvariables.cpp::addCalendarResources() | " << "Add to calendar resource!" << endl; CalendarResourceManager::ActiveIterator it; CalendarResourceManager *manager = getCalendarResourceManager(); QString fileName = NULL; for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) { kdDebug() << "Resource name: " + (*it)->resourceName() << endl; if ( !strcmp( (*it)->resourceName().local8Bit(), getCalendarFile().local8Bit() ) ) { kdDebug() << "konsolekalendarvariables.cpp::addCalendarResources() | " << "We allready have this resource" << endl; return true; } } manager->add( resource ); if ( isDefault() ) { kdDebug() << "konsolekalendarvariables.cpp::addCalendarResources() | " << "Make it default" << endl; manager->setStandardResource( resource ); } } else { kdDebug() << "konsolekalendarvariables.cpp::addCalendarResources() | " << "Cannot add to calendar resources (Not created!)" << endl; return false; } return true; } bool KonsoleKalendarVariables::isCalendarResources() { return m_bIsCalendarResources; } void KonsoleKalendarVariables::setCalendarResources( CalendarResources *resource ) { m_resource = resource; setCalendar( (CalendarLocal *) m_resource ); m_bIsCalendarResources = true; } CalendarResources *KonsoleKalendarVariables::getCalendarResources() { return m_resource; } CalendarResourceManager *KonsoleKalendarVariables::getCalendarResourceManager( ) { return m_resource->resourceManager(); } bool KonsoleKalendarVariables::loadCalendarResources( KConfig *config ) { if ( m_resource ) { kdDebug() << "konsolekalendarvariables.cpp::loadCalendarResources() | " << "loading resources" << endl; CalendarResourceManager *manager = m_resource->resourceManager(); if ( manager->isEmpty() == true ) { config->setGroup( "General" ); QString fileName = config->readPathEntry( "Active Calendar" ); QString resourceName; if ( fileName.isEmpty() ) { fileName = locateLocal( "appdata", "std.ics" ); resourceName = i18n( "Default KOrganizer resource" ); } else { resourceName = i18n( "Active Calendar" ); } kdDebug() << "konsolekalendarvariables.cpp::loadCalendarResources() | " << "Using as default resource: '" << fileName << "'" << endl; ResourceCalendar *defaultResource = new ResourceLocal( fileName ); //defaultResource->setTimeZoneId); defaultResource->setResourceName( resourceName ); manager->add( defaultResource ); manager->setStandardResource( defaultResource ); } } return true; } diff --git a/konsolekalendar/konsolekalendarvariables.h b/konsolekalendar/konsolekalendarvariables.h index d022b773ae..cfc419a6ea 100644 --- a/konsolekalendar/konsolekalendarvariables.h +++ b/konsolekalendar/konsolekalendarvariables.h @@ -1,467 +1,467 @@ /******************************************************************************* * konsolekalendarvariables.h * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ #ifndef _KONSOLEKALENDARVARIABLES_H_ #define _KONSOLEKALENDARVARIABLES_H_ #include #include #include #include #include #include #include /** * @file konsolekalendarvariables.h * Provides the KonsoleKalendarVariables class definition. */ namespace KCal { /** * ExportType is the type of Export output */ enum ExportType { /** Export none */ ExportTypeNone, /** Export as text (default) */ ExportTypeText, /** Export as compact text */ ExportTypeTextShort, /** Export HTML for the specified time span */ ExportTypeHTML, /** Export HTML for the time span on month boundaries */ ExportTypeMonthHTML, /** Export XHTML (NOT AVAILABLE YET) */ ExportTypeXHTML, /** Export XML (NOT AVAILABLE YET) */ ExportTypeXML, /** Export Comma-Separated Values */ ExportTypeCSV, /** Export VCard (NOT AVAILABLE YET) */ ExportTypeVCard }; /** * This class provides all the variables for the program. * @author Tuukka Pasanen * @author Allen Winter */ class KonsoleKalendarVariables { public: /** * Construct an empty KonsoleKalendarVariables object. */ KonsoleKalendarVariables(); /** * Destructor */ ~KonsoleKalendarVariables(); /** * Set switch to use Events. * @param useEvents if true, operation uses Events. */ void setUseEvents( bool useEvents ); /** * Get use Events switch. * @return true if operation using Events is specified. */ bool getUseEvents(); /** * Set switch to use Todos. * @param useTodos if true, operation uses Todos. */ void setUseTodos( bool useTodos ); /** * Get use Todos switch. * @return true if operation using Todos is specified. */ bool getUseTodos(); /** * Set switch to use Journals. * @param useJournals if true, operation uses Journals. */ void setUseJournals( bool useJournals ); /** * Get use Journals switch. * @return true if operation using Journals is specified. */ bool getUseJournals(); /** * Sets start date. * @param start is the start date. */ void setStartDateTime( QDateTime start ); /** * Get start date. * @return start date. */ QDateTime getStartDateTime(); /** * Is there start date? * @return true if there is false is there isn't. */ bool isStartDateTime(); /** * Sets end date. * @param end is the enddate. */ void setEndDateTime( QDateTime end ); /** * Get end date. * @return end date. */ QDateTime getEndDateTime(); /** * Is there end date? * @return true if there is false is there isn't. */ bool isEndDateTime(); /** * Sets the timezone from the user or system environment. */ void setTimeZoneId(); /** * Get timezone id string. * @return timezone id string. */ QString getTimeZoneId(); /** * Is there a timezone set? * @return true if there is false if there isn't. */ bool isTimeZoneId(); /** * Sets the UID, the unique tag for VCard entry. * @param uid unique tag for VCard entry. */ void setUID( QString uid ); /** * Get UID, the unique tag for VCard entry. * @return UID number. */ QString getUID(); /** * Is there UID set? * @return true there is UID false there isn't. */ bool isUID(); /** * Show only next activity and exit. * @param next true or false. */ void setNext( bool next ); /** * Should we show only next activity and exit? */ bool isNext(); /** * Should program be more verbose? * @param verbose a flag to set verbosity. */ void setVerbose( bool verbose ); /** * Should program be more verbose? */ bool isVerbose(); /** * Should we only try to run it and do nothing? * @param dryrun false no and true just test it. */ void setDryRun( bool dryrun ); /** * Is this program only in testing mode? * @return true yes false no. */ bool isDryRun(); /** * Set calendar file (Kinda obsolete!) * @param calendar Calendar files full path. */ void setCalendarFile( QString calendar ); /** * Returns fullpath to calendar file. * @return calendar file. */ QString getCalendarFile(); /** * Set file to import active calendar. * @param calendar Calendar file to import. */ void setImportFile( QString calendar ); /** * Return import filename. * @return File that should be imported. */ QString getImportFile(); /** * Add description. * @param description to event. */ void setDescription( QString description ); /** * Return description. * @return description of event. */ QString getDescription(); /** * Is there an event description? * @return true is there is description false there isn't. */ bool isDescription(); /** * Add location information. * @param location location where the event occurs. */ void setLocation( QString location ); /** - * Return location information.. + * Return location information. * @return location where event is occurring. */ QString getLocation(); /** * Is there event location information available? * @return true is there is description false there isn't. */ bool isLocation(); /** * Add summary. * @param summary event summary. */ void setSummary( QString summary ); /** * Get summary. * @return summary. */ QString getSummary(); /** * Is there an event summary? * @return true there is false there isn't. */ bool isSummary(); /** * View all option. * @param all flag to view all Events. */ void setAll( bool all ); /** * Return all option. */ bool getAll(); /** * Is the all option set? */ bool isAll(); /** * Set if Event is floating. * @param floating if true then the Event is floating. */ void setFloating( bool floating ); /** * Return if Event is floating. */ bool getFloating(); /** * Set is calendar default resource. */ void setDefault( bool def ); /** * Return if calendar is default resource. */ bool isDefault(); /** * Set calendar file for global use. */ void setCalendar( CalendarLocal *calendar ); /** * Get global calendar. */ CalendarLocal *getCalendar(); /** * Set output file. */ void setExportFile( QString export_file ); /** * To what file we'll output. */ QString getExportFile(); /** * Has an Export File been set? */ bool isExportFile(); /** * Set export type that'll we use. */ void setExportType( ExportType exportType ); /** * What export type to use. */ ExportType getExportType(); /** * Do we use CalendarResources or LocalCalendar? */ bool isCalendarResources(); /** * Add to Calendar Resources. */ CalendarResourceManager *getCalendarResourceManager(); /** * Add to Calendar Resources. */ bool addCalendarResources( ResourceCalendar *cal ); /** * Calendar resource is the new way. */ void setCalendarResources( CalendarResources *resource ); /** * Calendar resource is the new way. */ CalendarResources *getCalendarResources(); /** * Loads calendar resources. */ bool loadCalendarResources( KConfig *config ); /** * Set how many day should be seen. */ void setDaysCount( int count ); /** * Is there some cound of days should be seen. */ bool isDaysCount(); /** * Get how many day should be seen. */ int getDaysCount(); private: bool m_bIsTimeZoneId; QString m_TimeZoneId; QDateTime m_startDateTime; QDateTime m_endDateTime; bool m_bIsStartDateTime; bool m_bIsEndDateTime; QString m_calendar; QString m_import; QString m_description; QString m_location; QString m_summary; QString m_export_file; QString m_UID; bool m_bUseEvents; bool m_bUseTodos; bool m_bUseJournals; bool m_bSummary; bool m_bNext; bool m_bVerbose; bool m_bDryRun; bool m_bAll; bool m_bDescription; bool m_bLocation; bool m_bFloating; bool m_bDaysCount; bool m_bIsUID; int str_length; ExportType m_exportType; int m_daysCount; QString m_exportFile; bool m_bIsExportFile; bool m_bIsDefault; bool m_bIsCalendarResources; // New resource stuff will over-ride old pne CalendarResources *m_resource; // We can use this from everywhere CalendarLocal *m_calendarLocal; Event::List m_eventList; Todo::List m_todoList; }; } #endif diff --git a/konsolekalendar/main.cpp b/konsolekalendar/main.cpp index 0db4ed1b8d..f2198449b4 100644 --- a/konsolekalendar/main.cpp +++ b/konsolekalendar/main.cpp @@ -1,965 +1,976 @@ /******************************************************************************* * main.cpp * * * * KonsoleKalendar is a command line interface to KDE calendars * * Copyright (C) 2002-2004 Tuukka Pasanen * * Copyright (C) 2003-2005 Allen Winter * * * * 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. * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. * * * ******************************************************************************/ /** * @file main.cpp * KonsoleKalendar main program. * @author Tuukka Pasanen * @author Allen Winter */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #if TIME_WITH_SYS_TIME # include # include #else # if HAVE_SYS_TIME_H # include # else # include # endif #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include "konsolekalendar.h" #include "konsolekalendarepoch.h" #include "konsolekalendarvariables.h" using namespace KCal; using namespace std; static const char progName[] = "konsolekalendar"; static const char progDisplay[] = "KonsoleKalendar"; -static const char progVersion[] = "1.3.4"; +static const char progVersion[] = "1.3.5"; static const char progDesc[] = "A command line interface to KDE calendars"; static const char progURL[] = "pim.kde.org/components/konsolekalendar.php"; static KCmdLineOptions options[] = { { "verbose", I18N_NOOP( "Print helpful runtime messages" ), 0 }, { "dry-run", I18N_NOOP( "Print what would have been done, but do not execute" ), 0 }, { "file ", I18N_NOOP( "Specify which calendar you want to use" ), 0 }, { ":", I18N_NOOP( "Incidence types (these options can be combined):" ), 0 }, { "event", I18N_NOOP( " Operate for Events only (Default)" ), 0 }, { "todo", I18N_NOOP( " Operate for To-dos only [NOT WORKING YET]" ), 0 }, { "journal", I18N_NOOP( " Operate for Journals only [NOT WORKING YET]" ), 0 }, { ":", I18N_NOOP( "Major operation modes:" ), 0 }, { "view", I18N_NOOP( " Print incidences in specified export format" ), 0 }, { "add", I18N_NOOP( " Insert an incidence into the calendar" ), 0 }, { "change", I18N_NOOP( " Modify an existing incidence" ), 0 }, { "delete", I18N_NOOP( " Remove an existing incidence" ), 0 }, { "create", I18N_NOOP( " Create new calendar file if one does not exist" ), 0 }, { "import ", I18N_NOOP( " Import this calendar to main calendar" ), 0 }, { ":", I18N_NOOP( "Operation modifiers:" ), 0 }, { "all", I18N_NOOP( " View all calendar entries" ), 0 }, { "next", I18N_NOOP( " View next activity in calendar" ), 0 }, { "show-next ", I18N_NOOP( " From start date show next # days' activities" ), 0 }, { "uid ", I18N_NOOP( " Incidence Unique-string identifier" ), 0 }, { "date ", I18N_NOOP( " Start from this day [YYYY-MM-DD]" ), 0 }, { "time ", I18N_NOOP( " Start from this time [HH:MM:SS]" ), 0 }, { "end-date ", I18N_NOOP( " End at this day [YYYY-MM-DD]" ), 0 }, { "end-time ", I18N_NOOP( " End at this time [HH:MM:SS]" ), 0 }, { "epoch-start ", I18N_NOOP( " Start from this time [secs since epoch]" ), 0 }, { "epoch-end ", I18N_NOOP( " End at this time [secs since epoch]" ), 0 }, { "summary ", I18N_NOOP( " Add summary to incidence (for add/change modes)" ), 0 }, { "description ", I18N_NOOP( "Add description to incidence (for add/change modes)" ), 0 }, { "location ", I18N_NOOP( " Add location to incidence (for add/change modes)" ), 0 }, { ":", I18N_NOOP( "Export options:" ), 0 }, { "export-type ", I18N_NOOP( "Export file type (Default: text)" ), 0 }, { "export-file ", I18N_NOOP( "Export to file (Default: stdout)" ), 0 }, { "export-list", I18N_NOOP( " Print list of export types supported and exit" ), 0 }, { "", I18N_NOOP( "Examples:\n" " konsolekalendar --view\n" " konsolekalendar --add --date 2003-06-04 " "--time 10:00 --end-time 12:00 \\\n" " --summary \"Doctor Visit\" " "--description \"Get My Head Examined\"\n" " konsolekalendar --delete --uid KOrganizer-1740326.803" ), 0 }, { "", I18N_NOOP( "For more information visit the program home page at:\n" " http://pim.kde.org/components/konsolekalendar.php" ), 0 }, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( progName, // internal program name I18N_NOOP( progDisplay ), // displayable program name. progVersion, // version string I18N_NOOP( progDesc ), // short porgram description KAboutData::License_GPL, // license type "(c) 2002-2005, Tuukka Pasanen and Allen Winter", // copyright statement 0, // any free form text progURL, // program home page address "bugs.kde.org" // bug report email address ); aboutData.addAuthor( "Tuukka Pasanen", // developer's name I18N_NOOP( "Primary Author" ), // task or role "illuusio@mailcity.com", // email address 0 // home page or relevant link ); aboutData.addAuthor( "Allen Winter", // developer's name I18N_NOOP( "Author" ), // task or role "winter@kde.org", // email address 0 // home page or relevant link ); // KCmdLineArgs::init() final 'true' argument indicates no commandline options // for QApplication/KApplication (no KDE or Qt options) KCmdLineArgs::init( argc, argv, &aboutData, true ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KInstance ins( progName ); // Replace the KApplication call below with the three lines above // will make this a pure non-GUI application // -- thanks for the info Stephan Kulow. // KApplication app( // false, //do not allowstyles - disable the loading on plugin based styles // false //GUI is not enabled - disable all GUI stuff // ); KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); // Default values for start date/time (today at 07:00) QDate startdate = QDate::currentDate(); QTime starttime( 7, 0 ); // Default values for end date/time (today at 17:00) QDate enddate = QDate::currentDate(); QTime endtime( 17, 0 ); // Default values for switches bool view = true; bool add = false; bool change = false; bool del = false; bool create = false; bool calendarFile = false; bool importFile = false; QString option; KonsoleKalendarVariables variables; KonsoleKalendarEpoch epochs; variables.setFloating( false ); // by default, new events do NOT float if ( args->isSet( "verbose" ) ) { variables.setVerbose( true ); } if ( args->isSet( "dry-run" ) ) { variables.setDryRun( true ); } /* * Switch on export list */ if ( args->isSet( "export-list" ) ) { - cout << i18n( - "\nKonsoleKalendar supports these export formats:\n" - " Text [Default]\n" - " Short (like Text, but more compact)\n" - " HTML\n" - " HTMLmonth (like HTML, but in a month view)\n" - " CSV (Comma-Separated Values)\n" - ).local8Bit() + cout << endl; + cout << i18n( "%1 supports these export formats:" ). + arg( progDisplay ).local8Bit() + << endl; + cout << i18n( " %1 [Default]" ). + arg( "Text" ).local8Bit() + << endl; + cout << i18n( " %1 (like %2, but more compact)" ). + arg( "Short", "Text" ).local8Bit() + << endl; + cout << i18n( " %1" ). + arg( "HTML" ).local8Bit() + << endl; + cout << i18n( " %1 (like %2, but in a month view)" ). + arg( "HTMLmonth", "HTML" ).local8Bit() + << endl; + cout << i18n( " %1 (Comma-Separated Values)" ). + arg( "CSV" ).local8Bit() << endl; + cout << endl; return 0; } /* * Set incidence type(s) */ if ( args->isSet( "event" ) ) { variables.setUseEvents( true ); kdDebug() << "main | parse options | use Events" << endl; } if ( args->isSet( "todo" ) ) { variables.setUseTodos( true ); kdDebug() << "main | parse options | use To-dos" << endl; cout << i18n( "Sorry, To-dos are not working yet." ).local8Bit() << endl; return 1; } if ( args->isSet( "journal" ) ) { variables.setUseJournals( true ); kdDebug() << "main | parse options | use Journals" << endl; cout << i18n( "Sorry, Journals are not working yet." ).local8Bit() << endl; return 1; } // Use Events if no incidence type is specified on the command line if ( !args->isSet( "event" ) && !args->isSet( "todo" ) && !args->isSet( "journal" ) ) { variables.setUseEvents( true ); kdDebug() << "main | parse options | use Events (Default)" << endl; } /* * Switch on exporting */ variables.setExportType( ExportTypeText ); if ( args->isSet( "export-type" ) ) { option = args->getOption( "export-type" ); if ( option.upper() == "HTML" ) { kdDebug() << "main | export-type | Export to HTML" << endl; variables.setExportType( ExportTypeHTML ); } else if ( option.upper() == "HTMLMONTH" ) { kdDebug() << "main | export-type | Export to HTML by Month" << endl; variables.setExportType( ExportTypeMonthHTML ); } else if ( option.upper() == "CSV" ) { kdDebug() << "main | export-type | Export to CSV" << endl; variables.setExportType( ExportTypeCSV ); } else if ( option.upper() == "TEXT" ) { kdDebug() << "main | export-type | Export to TEXT (default)" << endl; variables.setExportType( ExportTypeText ); } else if ( option.upper() == "SHORT" ) { kdDebug() << "main | export-type | Export to TEXT-SHORT" << endl; variables.setExportType( ExportTypeTextShort ); } else { cout << i18n( "Invalid Export Type Specified: %1" ). arg( option ).local8Bit() << endl; return 1; } } /* * Switch on export file name */ if ( args->isSet( "export-file" ) ) { option = args->getOption( "export-file" ); kdDebug() << "main | parse options | " << "Export File: " << "(" << option << ")" << endl; variables.setExportFile( option ); } /* * Switch on View (Print Entries). This is the default mode of operation. */ if ( args->isSet( "view" ) ) { view = true; kdDebug() << "main | parse options | " << "Mode: (Print incidences)" << endl; } /* * Switch on Add (Insert Entry) */ if ( args->isSet( "add" ) ) { view = false; add = true; kdDebug() << "main | parse options | " << "Mode: (Add incidence)" << endl; } /* * Switch on Change (Modify Entry) */ if ( args->isSet( "change" ) ) { view = false; change = true; kdDebug() << "main | parse options | " << "Mode: (Change incidence)" << endl; } /* * Switch on Delete (Remove Entry) */ if ( args->isSet( "delete" ) ) { view = false; del = true; kdDebug() << "main | parse options | " << "Mode: (Delete incidence)" << endl; } /* * Switch on Create */ if ( args->isSet( "create" ) ) { view = false; create = true; kdDebug() << "main | parse options | " << "Calendar File: (Create)" << endl; } /* * If there is summary attached. */ if ( args->isSet( "summary" ) ) { option = args->getOption( "summary" ); kdDebug() << "main | parse options | " << "Summary: " << "(" << option << ")" << endl; variables.setSummary( option ); } /* * If there is description attached. */ if ( args->isSet( "description" ) ) { option = args->getOption( "description" ); kdDebug() << "main | parse options | " << "Description: " << "(" << option << ")" << endl; variables.setDescription( option ); } /* * If there is location information */ if ( args->isSet( "location" ) ) { option = args->getOption( "location" ); kdDebug() << "main | parse options | " << "Location: " << "(" << option << ")" << endl; variables.setLocation( option ); } /* * Show next happening and exit */ if ( args->isSet( "next" ) ) { kdDebug() << "main | parse options | " << "Show next incidence only" << endl; variables.setNext( true ); } /* * Set incidence unique string identifier */ if ( args->isSet( "uid" ) ) { option = args->getOption( "uid" ); kdDebug() << "main | parse options | " << "incidence UID: " << "(" << option << ")" << endl; variables.setUID( option ); } /* * Set starting date for calendar */ if ( args->isSet( "date" ) ) { option = args->getOption( "date" ); kdDebug() << "main | parse options | " << "Start date before conversion: " << "(" << option << ")" << endl; startdate = QDate::fromString( option, Qt::ISODate ); if ( !startdate.isValid() ) { cout << i18n( "Invalid Start Date Specified: %1" ). arg( option ).local8Bit() << endl; return 1; } kdDebug() << "main | parse options | " << "Start date after conversion: " << "(" << startdate.toString() << ")" << endl; } /* * Set starting time */ if ( args->isSet( "time" ) ) { option = args->getOption( "time" ); kdDebug() << "main | parse options | " << "Start time before conversion : " << "(" << option << ")" << endl; if ( option.upper() != "FLOAT" ) { starttime = QTime::fromString( option, Qt::ISODate ); if ( !starttime.isValid() ) { cout << i18n( "Invalid Start Time Specified: %1" ). arg( option ).local8Bit() << endl; return 1; } kdDebug() << "main | parse options | " << "Start time after conversion: " << "(" << starttime.toString() << ")" << endl; } else { variables.setFloating( true ); kdDebug() << "main | parse options | " << "Floating event time specified" << endl; } } /* * Set end date for calendar */ if ( args->isSet( "end-date" ) ) { QString option = args->getOption( "end-date" ); kdDebug() << "main | parse options | " << "End date before conversion: " << "(" << option << ")" << endl; enddate = QDate::fromString( option, Qt::ISODate ); if ( !enddate.isValid() ) { cout << i18n( "Invalid End Date Specified: %1" ). arg( option ).local8Bit() << endl; return 1; } kdDebug() << "main | parse options | " << "End date after conversion: " << "(" << enddate.toString() << ")" << endl; } /* * Show next # days and exit */ if ( args->isSet( "show-next" ) ) { bool ok; option = args->getOption( "show-next" ); kdDebug() << "main | parse options | " << "Show " << option << " days ahead" << endl; variables.setDaysCount( option.toInt( &ok, 10 ) ); if ( !ok ) { cout << i18n( "Invalid Date Count Specified: %1" ). arg( option ).local8Bit() << endl; return 1; } enddate = startdate; enddate = enddate.addDays( variables.getDaysCount() ); kdDebug() << "main | parse options | " << "End date after conversion: " << "(" << enddate.toString() << ")" << endl; } /* * Set ending time */ if ( args->isSet( "end-time" ) ) { option = args->getOption( "end-time" ); kdDebug() << "main | parse options | " << "End time before conversion: " << "(" << option << ")" << endl; if ( option.upper() != "FLOAT" ) { endtime = QTime::fromString( option, Qt::ISODate ); if ( !endtime.isValid() ) { cout << i18n( "Invalid End Time Specified: %1" ). arg( option ).local8Bit() << endl; return 1; } kdDebug() << "main | parse options | " << "End time after conversion: " << "(" << endtime.toString() << ")" << endl; } else { variables.setFloating( true ); kdDebug() << "main | parse options | " << "Floating event time specified" << endl; } } /* * Set start date/time from epoch */ time_t epochstart = 0; if ( args->isSet( "epoch-start" ) ) { option = args->getOption( "epoch-start" ); kdDebug() << "main | parse options | " << "Epoch start: " << "(" << option << ")" << endl; epochstart = ( time_t ) option.toULong( 0, 10 ); } /* * Set end date/time from epoch */ time_t epochend = 0; if ( args->isSet( "epoch-end" ) ) { option = args->getOption( "epoch-end" ); kdDebug() << "main | parse options | " << "Epoch end: " << "(" << option << ")" << endl; epochend = ( time_t ) option.toULong( 0, 10 ); } if ( args->isSet( "all" ) ) { variables.setAll( true ); } else { variables.setAll( false ); } if ( args->isSet( "import" ) ) { view = false; importFile = true; option = args->getOption( "import" ); variables.setImportFile( option ); kdDebug() << "main | parse options | " << "importing file from: " << "(" << option << ")" << endl; } KonsoleKalendar *konsolekalendar = new KonsoleKalendar( &variables ); if ( args->isSet( "file" ) ) { calendarFile = true; option = args->getOption( "file" ); variables.setCalendarFile( option ); /* * All modes need to know if the calendar file exists * This must be done before we get to opening biz */ bool exists = QFile::exists( variables.getCalendarFile() ); if ( create ) { kdDebug() << "main | createcalendar | " << "check if calendar file already exists" << endl; if ( exists ) { cout << i18n( "Calendar %1 already exists" ). arg( variables.getCalendarFile() ).local8Bit() << endl; return 1; } if ( konsolekalendar->createCalendar() ) { cout << i18n( "Calendar %1 successfully created" ). arg( variables.getCalendarFile() ).local8Bit() << endl; return 0; } else { cout << i18n( "Unable to create calendar: %1" ). arg( variables.getCalendarFile() ).local8Bit() << endl; return 1; } } if ( !exists ) { cout << i18n( "Calendar file not found %1" ). arg( option ).local8Bit() << endl; cout << i18n( "Try --create to create new calendar file" ).local8Bit() << endl; return 1; } } CalendarResources *calendarResource = NULL; CalendarLocal *localCalendar = NULL; /* * Should we use local calendar or resource? */ variables.setTimeZoneId(); if ( args->isSet( "file" ) ) { localCalendar = new CalendarLocal( variables.getTimeZoneId() ); localCalendar->load( variables.getCalendarFile() ); variables.setCalendar( localCalendar ); } else { calendarResource = new CalendarResources( variables.getTimeZoneId() ); calendarResource->readConfig(); calendarResource->load(); variables.setCalendarResources( calendarResource ); } /*************************************************************************** * Glorious date/time checking and setting code * ***************************************************************************/ QDateTime startdatetime, enddatetime; // Handle case with either date or end-date unspecified if ( !args->isSet( "end-date" ) && !args->isSet( "show-next" ) && args->isSet( "date" ) ) { enddate = startdate; kdDebug() << "main | datetimestamp | " << "setting enddate to startdate" << endl; } else if ( args->isSet( "end-date" ) && !args->isSet( "date" ) ) { startdate = enddate; kdDebug() << "main | datetimestamp | " << "setting startdate to enddate" << endl; } // NOTE: If neither date nor end-date specified, then event will be today. // Case: // End time (or epoch) unspecified, and start time (or epoch) IS specified. // In this case, set the ending to 1 hour after starting. if ( !args->isSet( "end-time" ) && !args->isSet( "epoch-end" ) ) { if ( args->isSet( "time" ) ) { endtime = starttime.addSecs( 60 * 60 ); // end is 1 hour after start kdDebug() << "main | datetimestamp | " << "setting endtime 1 hour after starttime" << endl; } else if ( args->isSet( "epoch-start" ) ) { startdatetime = epochs.epoch2QDateTime( epochstart ); enddatetime = startdatetime.addSecs( 60 * 60 ); kdDebug() << "main | datetimestamp | " << "setting endtime 1 hour after epochstart" << endl; } } // Case: // Time (or epoch) unspecified, and end-time (or epoch) IS specified. // In this case, set the starting to 1 hour before ending. if ( !args->isSet( "time" ) && !args->isSet( "epoch-start" ) ) { if ( args->isSet( "end-time" ) ) { starttime = endtime.addSecs( -60 * 60 ); // start is 1 hour before end kdDebug() << "main | datetimestamp | " << "setting starttime 1 hour before endtime" << endl; } else if ( args->isSet( "epoch-end" ) ) { enddatetime = epochs.epoch2QDateTime( epochend ); startdatetime = enddatetime.addSecs( -60 * 60 ); kdDebug() << "main | datetimestamp | " << "setting starttime 1 before after epochend" << endl; } } // Case: // Time (or epoch) unspecified, and end-time (or epoch) unspecified. if ( !args->isSet( "time" ) && !args->isSet( "epoch-start" ) && !args->isSet( "end-time" ) && !args->isSet( "epoch-end" ) ) { // set default start date/time startdatetime = QDateTime::QDateTime( startdate, starttime ); kdDebug() << "main | datetimestamp | " << "setting startdatetime from " << "default startdate (today) and starttime" << endl; // set default end date/time enddatetime = QDateTime::QDateTime( enddate, endtime ); kdDebug() << "main | datetimestamp | " << "setting enddatetime from " << "default enddate (today) and endtime" << endl; } // Set startdatetime, enddatetime if still necessary if ( startdatetime.isNull() ) { startdatetime = QDateTime::QDateTime( startdate, starttime ); kdDebug() << "main | datetimestamp | " << "setting startdatetime from startdate and starttime" << endl; } if ( enddatetime.isNull() ) { enddatetime = QDateTime::QDateTime( enddate, endtime ); kdDebug() << "main | datetimestamp | " << "setting enddatetime from enddate and endtime" << endl; } // Float check for add mode: // Events float if time AND end-time AND epoch times are UNspecified if ( add ) { if ( !args->isSet( "time" ) && !args->isSet( "end-time" ) && !args->isSet( "epoch-start" ) && !args->isSet( "epoch-end" ) ) { variables.setFloating( true ); kdDebug() << "main | floatingcheck | " << "turn-on floating event" << endl; } } // Finally! Set the start/end date times if ( !change ) { variables.setStartDateTime( startdatetime ); variables.setEndDateTime( enddatetime ); } else { // Do NOT set start/end datetimes in change mode, // unless they were specified on commandline if ( args->isSet( "time" ) || args->isSet( "epoch-start" ) || args->isSet( "end-time" ) || args->isSet( "epoch-end" ) ) { variables.setStartDateTime( startdatetime ); variables.setEndDateTime( enddatetime ); } } // Some more debug prints kdDebug() << "main | datetimestamp | StartDate=" << startdatetime.toString( Qt::TextDate ) << endl; kdDebug() << "main | datetimestamp | EndDate=" << enddatetime.toString( Qt::TextDate ) << endl; /*************************************************************************** * Sanity checks * ***************************************************************************/ // Cannot combine modes if ( create + view + add + change + del > 1 ) { cout << i18n( "Only 1 operation mode " "(view, add, change, delete, create) " "permitted at any one time" ).local8Bit() << endl; return 1; } // Cannot have a ending before starting if ( startdatetime > enddatetime ) { cout << i18n( "Ending Date/Time occurs before the Starting Date/Time" ).local8Bit() << endl; return 1; } /*************************************************************************** * And away we go with the real work... * ***************************************************************************/ args->clear(); // Free up some memory. /* * Set our application name for use in unique IDs and error messages, * and product ID for incidence PRODID property */ QString prodId = "-//K Desktop Environment//NONSGML %1 %2//EN"; CalFormat::setApplication( progDisplay, prodId.arg( progDisplay ).arg( progVersion ) ); if ( importFile ) { if ( konsolekalendar->importCalendar() ) { cout << i18n( "Calendar %1 successfully imported" ). arg( variables.getImportFile() ).local8Bit() << endl; return 0; } else { cout << i18n( "Unable to import calendar: %1" ). arg( variables.getImportFile() ).local8Bit() << endl; return 1; } } if ( add ) { if ( !konsolekalendar->isEvent( startdatetime, enddatetime, variables.getSummary() ) ) { kdDebug() << "main | modework | " << "calling addEvent()" << endl; konsolekalendar->addEvent(); } else { cout << i18n( "Attempting to insert an event that already exists" ).local8Bit() << endl; return 1; } } if ( change ) { kdDebug() << "main | modework | " << "calling changeEvent()" << endl; if ( !variables.isUID() ) { cout << i18n( "Missing event UID: " "use --uid command line option" ).local8Bit() << endl; return 1; } if ( konsolekalendar->changeEvent() != true ) { cout << i18n( "No such event UID: change event failed" ).local8Bit() << endl; return 1; } kdDebug() << "main | modework | " << "successful changeEvent()" << endl; } if ( del ) { kdDebug() << "main | modework | " << "calling deleteEvent()" << endl; if ( !variables.isUID() ) { cout << i18n( "Missing event UID: " "use --uid command line option" ).local8Bit() << endl; return 1; } if ( konsolekalendar->deleteEvent() != true ) { cout << i18n( "No such event UID: delete event failed").local8Bit() << endl; return 1; } kdDebug() << "main | modework | " << "successful deleteEvent()" << endl; } if ( view ) { kdDebug() << "main | modework | " << "calling showInstance() to view events" << endl; if ( !konsolekalendar->showInstance() ) { cout << i18n( "Cannot open specified export file: %1" ). arg( variables.getExportFile() ).local8Bit() << endl; return 1; } } delete konsolekalendar; if ( calendarFile ) { localCalendar->close(); delete localCalendar; } else { calendarResource->close(); delete calendarResource; } kdDebug() << "main | exiting" << endl; return 0; } diff --git a/ktimetracker/BUGS b/ktimetracker/BUGS deleted file mode 100644 index 8084680e9e..0000000000 --- a/ktimetracker/BUGS +++ /dev/null @@ -1,6 +0,0 @@ - -BUGS ----- -Lots. - -please report bugs to taj@kde.org or at http://buglist.kde.org. diff --git a/ktimetracker/ChangeLog b/ktimetracker/ChangeLog deleted file mode 100644 index f42b61e1c2..0000000000 --- a/ktimetracker/ChangeLog +++ /dev/null @@ -1,3 +0,0 @@ -0.2 - Now supports floating toolbar - Documentation converted to linuxdoc diff --git a/ktimetracker/DESCRIPTION b/ktimetracker/DESCRIPTION deleted file mode 100644 index 2d4a384442..0000000000 --- a/ktimetracker/DESCRIPTION +++ /dev/null @@ -1,3 +0,0 @@ -KArm is a time tracker for busy people who need -to keep track of the amount of time they spend -on various tasks. diff --git a/ktimetracker/Makefile.am b/ktimetracker/Makefile.am deleted file mode 100644 index 4aa0e0ca4c..0000000000 --- a/ktimetracker/Makefile.am +++ /dev/null @@ -1,67 +0,0 @@ - -############ Autoconf-generated variables ################### -INCLUDES = -I$(top_srcdir)/libkcal -I$(top_srcdir)/kresources/remote -I$(top_srcdir) $(all_includes) - -bin_PROGRAMS = karm -SUBDIRS = support pics test - -METASOURCES = AUTO - -COMPILE_BEFORE_karm = libkdepim kresources - -noinst_LTLIBRARIES = libkarm_shared.la - -libkarm_shared_la_SOURCES = kaccelmenuwatch.cpp desktoptracker.cpp \ - edittaskdialog.cpp idletimedetector.cpp \ - printdialog.cpp timekard.cpp karmutility.cpp ktimewidget.cpp \ - karmstorage.cpp mainwindow.cpp preferences.cpp print.cpp \ - task.cpp taskview.cpp tray.cpp \ - csvexportdialog_base.ui csvexportdialog.cpp plannerparser.cpp \ - karmdcopiface.skel -libkarm_shared_la_LIBADD = -lkdeprint $(top_builddir)/libkcal/libkcal.la \ - $(top_builddir)/kresources/remote/libkcal_resourceremote.la \ - $(top_builddir)/libkdepim/libkdepim.la $(LIBXSS) -karm_SOURCES = main.cpp -karm_LDADD = libkarm_shared.la -karm_LDFLAGS = $(all_libraries) $(KDE_RPATH) -noinst_HEADERS = desktoptracker.h edittaskdialog.h printdialog.h \ - idletimedetector.h kaccelmenuwatch.h timekard.h \ - karmutility.h ktimewidget.h karmstorage.h mainwindow.h \ - preferences.h print.h task.h taskview.h toolicons.h \ - tray.h version.h csvexportdialog.h plannerparser.h - -KDE_ICON = karm - -rcdir = $(kde_datadir)/karm -rc_DATA = karmui.rc - -install-data-local: uninstall.desktop - $(mkinstalldirs) $(DESTDIR)$(kde_appsdir)/Utilities - $(INSTALL_DATA) $(srcdir)/uninstall.desktop $(DESTDIR)$(kde_appsdir)/Utilities/karm.desktop - -messages: rc.cpp - $(XGETTEXT) *.cpp -o $(podir)/karm.pot - -srcdoc: - kdoc -a -p -H -d $(HOME)/web/src/karm karm *.h -lkdecore -lkdeui -lqt - -DOXYGEN_REFERENCES = kdeui -include $(top_srcdir)/admin/Doxyfile.am - -######################################################################### -# KPART SECTION -######################################################################### -kde_module_LTLIBRARIES = libkarmpart.la - -# the Part's source, library search path, and link libraries -libkarmpart_la_SOURCES = karm_part.cpp -libkarmpart_la_LDFLAGS = -module -avoid-version -no-undefined $(KDE_PLUGIN) $(all_libraries) -libkarmpart_la_LIBADD = libkarm_shared.la $(LIB_KPARTS) - -# this is where the desktop file will go -partdesktopdir = $(kde_servicesdir) -partdesktop_DATA = karm_part.desktop - -# this is where the part's XML-GUI resource file goes -partrcdir = $(kde_datadir)/karmpart -partrc_DATA = karmui.rc diff --git a/ktimetracker/README b/ktimetracker/README deleted file mode 100644 index d1d05b06f9..0000000000 --- a/ktimetracker/README +++ /dev/null @@ -1,34 +0,0 @@ -KArm 0.6 --------- -- It is now possible to type in the time like 3:20, or 3:20 + 1:10 -- The two QListBoxes with time and description has been replaced with one - QListView. This makes the interface nicer, and simplifies a lot internally. - -KArm 0.3 --------- - -Fixes edit task bugs -Complies to new FSSTND - -KArm 0.2 --------- - -In my day, I may have to work on several different projects and keep track -separately of how much time I spent working on each project. If you are -like me, then KArm is for you. - -KArm is a time tracker. You can enter a list of "tasks", start KArm's clock, -and it will count the number of minutes you spend on the highlighted task. - - -KArm was inspired by Harald Tveit Alvestrand's very useful utility called -titrax, the only failing of which is that it is based on the Xt toolkit. One -day KArm will do all that titrax does, but not today. - -The word "karm", in my mother tongue Punjabi, means "work". - - -There is a screenshot at - http://www.ph.unimelb.edu.au/~ssk/kde/karm/karm.gif - -and is installed with the included (sparse) documentation. diff --git a/ktimetracker/TODO b/ktimetracker/TODO deleted file mode 100644 index 12df8f5c65..0000000000 --- a/ktimetracker/TODO +++ /dev/null @@ -1,90 +0,0 @@ -* KarmWindow::makeMenus -> export KAction? KarmWindow::contextMenuRequest -* QPopupMenu should be static! put connect( ..contextMenu at the right place -* mainwindow: move tray signals into tray.cpp add mouse double-click action -* (start new timer, stop old) to "Configure - Shortcuts" dialog. - -Mark - Sooner ... -------------------------- - - * 2005-05-24: Modify test scripts for change in dcop iface. - - * 2005-05-24: Update docs for new dcop methods. - - * 2003-09-24: Generate man page (look for script mentioned on kde-devel). - - * 2004-01-27: BUG: if save fails (b/c of permission failure) KArm does not - give any feecback and proceeds as if there was no error. - - * 2003-09-17: BUG: entering a negative time increments total session time - (maybe only if session time is zero?) - -Mark - Later ... -------------------------- - - * 2004-06-14: In file exports, check if QT has a function to give you a - platform-specific end of line character. Right now, it is hard coded to a - "\n" - - * 2003-08-15: Implement comments: VTODO COMMENT or DESCRIPTION? - - Make sure wrapping works according to iCalendar spec. - - Handle multiple comments against same VEVENT. - - Show in history report. - - * 2004-01-27: Write dcop interface so time cards can be exported to other - systems. - - * 2003-09-24: Change menu entry from KArm to Time Clock. - - * 2003-08-15: Go over code and delete all cruft. In particular, take a look - at taskview.cpp. - - * 2003-09-26: Add totals table across entire date range. - - * 2003-09-19: If task active, editing task stops timer. Necessary? - - * 2003-08-15: When loading an empty ics file, ask user if they want to - import a task list from another file. If they say no, then pop up the new - task dialog. (TaskView::load). - - * 2003-09-03: Use file menu and delete storage page in preferences. - - * 2003-08-15: Add ability to import tasks from an iCalendar file. - - TaskView::load() - - * 2003-09-26: On timecard report, don't print rows for tasks with zero hours - unless a child task has hours logged (that is, show full tree for every - task with time logged). - - * 2003-10-13: New event: publish time card. Mark events that are published - as read-only. Create plug-in framework so that when this event occurs, we - export to a different backend. Write plugins for GnuCash and SQL-Ledger. - Hmmm ... or just write a sql calendar resource? - - -Wishlist: -------------------------- -* activeTasks should be cleaned up if two timers are active, associate a -* percentage with them, optimaly the - percentage should be configurable -* completed % per task don't display competed tasks context menu in headers -* for choosing if one wants to see some column or not - - -Design Notes -------------------------- - -- Taskview mediates access to KarmStorage. That is one overzealous ListView - subclass! - -- The original code was written with the expectation that the user would be - starting and stopping timers. This perspective loses relevance when you - want book time with an arbitrary start and stop time. This impacts method - names and the arguments passed. For example, see KarmStorage bookTime - versus changeTime. Duplicate code, different method signatures. - -- How do deal with keeping gui responsive while saving data. Really should be - asynchronous. Then we have to be careful with race conditions; for example, - if an external fires a DCOP event while the user is stopping a time and we - have a really slow remote resource. - -- Add the dcop method bookTime, I originally forgot to increment the total time - counter on the task. This is a bad design--a proper task class would provide - an interface to log a history event and would increment the total time for - me. diff --git a/ktimetracker/adddlg.cpp b/ktimetracker/adddlg.cpp deleted file mode 100644 index ef20efe7f1..0000000000 --- a/ktimetracker/adddlg.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * karm - * This file only: Copyright (C) 1999 Espen Sand, espensa@online.no - * Modifications (see CVS log) Copyright (C) 2000 Klarlvdalens - * Datakonsult AB , Jesper Pedersen - * - * - * 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., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * $Id$ - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "adddlg.h" -#include "karm.h" -#include "ktimewidget.h" - - -AddTaskDialog::AddTaskDialog(QString caption, bool editDlg) - :KDialogBase(0, "AddTaskDialog", true, caption, Ok|Cancel, Ok, true ) -{ - QWidget *page = new QWidget( this ); - setMainWidget(page); - - QVBoxLayout *lay1 = new QVBoxLayout(page); - - QHBoxLayout *lay2 = new QHBoxLayout(); - lay1->addLayout(lay2); - - // The name of the widget - QLabel *label = new QLabel( i18n("Task name"), page, "name" ); - lay2->addWidget( label ); - lay2->addSpacing(5); - - - _name = new QLineEdit( page, "lineedit" ); - - _name->setMinimumWidth(fontMetrics().maxWidth()*15); - lay2->addWidget( _name ); - - - // The "Edit Absolut" radio button - lay1->addSpacing(10);lay1->addStretch(1); - _absoluteRB = new QRadioButton( i18n( "Edit Absolute" ), page, "_absoluteRB" ); - lay1->addWidget( _absoluteRB ); - connect( _absoluteRB, SIGNAL( clicked() ), this, SLOT(slotAbsolutePressed()) ); - - - // Absolute times - QHBoxLayout *lay5 = new QHBoxLayout(); - lay1->addLayout(lay5); - lay5->addSpacing(20); - QGridLayout *lay3 = new QGridLayout( 2, 2, -1, "lay3" ); - lay5->addLayout(lay3); - - // Total Time - _totalLA = new QLabel( i18n("Total:"), page, "time" ); - lay3->addWidget( _totalLA, 0, 0 ); - - _totalTW = new KTimeWidget( page, "_totalTW" ); - lay3->addWidget( _totalTW, 0, 1 ); - - - // Session - _sessionLA = new QLabel( i18n("Session time:"), page, "session time" ); - lay3->addWidget( _sessionLA, 1, 0 ); - - _sessionTW = new KTimeWidget( page, "_sessionTW" ); - lay3->addWidget( _sessionTW, 1, 1 ); - - - // The "Edit relative" radio button - lay1->addSpacing(10);lay1->addStretch(1); - _relativeRB = new QRadioButton( i18n( "Edit Relative (Apply to both session and total)" ), page, "_relativeRB" ); - lay1->addWidget( _relativeRB ); - connect( _relativeRB, SIGNAL( clicked() ), this, SLOT(slotRelativePressed()) ); - - // The relative times - QHBoxLayout *lay4 = new QHBoxLayout(); - lay1->addLayout( lay4 ); - lay4->addSpacing(20); - - _operator = new QComboBox(page); - _operator->insertItem( QString::fromLatin1( "+" ) ); - _operator->insertItem( QString::fromLatin1( "-" ) ); - lay4->addWidget( _operator ); - - lay4->addSpacing(5); - - _diffTW = new KTimeWidget( page, "_sessionAddTW" ); - lay4->addWidget( _diffTW ); - - KIconLoader loader; - - QPixmap whatsThisIM = loader.loadIcon(QString::fromLatin1("contexthelp"), KIcon::Toolbar); - QPushButton* whatsThisBU = new QPushButton(page, "whatsThisLA"); - whatsThisBU->setFocusPolicy(NoFocus); - - connect(whatsThisBU, SIGNAL(clicked()), this, SLOT(enterWhatsThis())); - whatsThisBU->setPixmap( whatsThisIM ); - lay4->addWidget(whatsThisBU); - - lay1->addStretch(1); - - - if ( editDlg ) { - // This is an edit dialog. - _operator->setFocus(); - } - else { - // This is an initial dialog - _name->setFocus(); - } - origTotal = 0; - origSession = 0; - - slotRelativePressed(); - - // Whats this help. - QWhatsThis::add(_name, i18n("Enter the name of the task here. This name is for your eyes only.")); - QWhatsThis::add(_absoluteRB, i18n("If you select this radio button, you specify that you want " - "to enter the time as absolute values. For example: " - "total for this task is 20 hours and 15 minutes.\n\n" - "The time is specified for the session time and for the total time " - "separately.")); - QWhatsThis::add(_relativeRB, i18n("If you select this radio button, you specify that you want " - "to add or subtract time for the task. For example: I've worked 2 hours " - "and 20 minutes more on this task (without having the timer " - "running.)\n\n" - "This time will be added or subtracted for both the " - "session time and the total time.")); - QWhatsThis::add(_totalTW, i18n("This is the overall time this task has been running.")); - QWhatsThis::add(_sessionTW, i18n("This is the time the task has been running this session.")); - QWhatsThis::add(_diffTW, i18n("Specify how much time to add or subtract to the overall and " - "session time")); - -} - -void AddTaskDialog::enterWhatsThis() -{ - QWhatsThis::enterWhatsThisMode (); -} - - -void AddTaskDialog::slotAbsolutePressed() -{ - _relativeRB->setChecked( false ); - _absoluteRB->setChecked( true ); - - _operator->setEnabled( false ); - _diffTW->setEnabled( false ); - - _totalLA->setEnabled( true ); - _sessionLA->setEnabled( true ); - _totalTW->setEnabled( true ); - _sessionTW->setEnabled( true ); -} - -void AddTaskDialog::slotRelativePressed() -{ - _relativeRB->setChecked( true ); - _absoluteRB->setChecked( false ); - - _operator->setEnabled( true ); - _diffTW->setEnabled( true ); - - _totalLA->setEnabled( false ); - _sessionLA->setEnabled( false ); - _totalTW->setEnabled( false ); - _sessionTW->setEnabled( false ); -} - - - -void AddTaskDialog::setTask( const QString &name, long total, long session ) -{ - _name->setText( name ); - - _totalTW->setTime( total / 60, total % 60 ); - _sessionTW->setTime( session / 60, session % 60 ); - origTotal = total; - origSession = session; -} - - -QString AddTaskDialog::taskName( void ) const -{ - return( _name->text() ); -} - - -void AddTaskDialog::status( long *total, long *totalDiff, long *session, long *sessionDiff ) const -{ - if ( _absoluteRB->isChecked() ) { - *total = _totalTW->time(); - *session = _sessionTW->time(); - } - else { - int diff = _diffTW->time(); - if ( _operator->currentItem() == 1) { - diff = -diff; - } - *total = origTotal + diff; - *session = origSession + diff; - } - - *totalDiff = *total - origTotal; - *sessionDiff = *session - origSession; -} - -#include "adddlg.moc" diff --git a/ktimetracker/adddlg.h b/ktimetracker/adddlg.h deleted file mode 100644 index 263cda6355..0000000000 --- a/ktimetracker/adddlg.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * karm - * This file only: Copyright (C) 1999 Espen Sand, espensa@online.no - * - * 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., 675 Mass Ave, Cambridge, MA 02139, USA. - * - */ - -#ifndef KarmAddDlg_included -#define KarmAddDlg_included - -#include -#include -#include -#include "adddlg.h" -class QLineEdit; -class KTimeWidget; -class QRadioButton; - -class AddTaskDialog : public KDialogBase -{ - Q_OBJECT - - public: - AddTaskDialog(QString caption, bool editDlg); - void setTask(const QString &name, long time, long sessionTime ); - QString taskName( void ) const; - void status( long *total, long *totalDiff, long *session, long *sessionDiff ) const; - - private slots: - void slotAbsolutePressed(); - void slotRelativePressed(); - void enterWhatsThis(); - - private: - QLineEdit* _name; - KTimeWidget* _totalTW; - KTimeWidget* _sessionTW; - KTimeWidget* _diffTW; - QComboBox* _operator; - - long origTotal; - long origSession; - - QRadioButton *_absoluteRB; - QRadioButton *_relativeRB; - - QLabel* _totalLA; - QLabel* _sessionLA; -}; - - - - - -#endif // KarmAddDlg_included - diff --git a/ktimetracker/configure.in.in b/ktimetracker/configure.in.in deleted file mode 100644 index f17fa84ef9..0000000000 --- a/ktimetracker/configure.in.in +++ /dev/null @@ -1,13 +0,0 @@ -ac_ldflags_safe="$LDFLAGS" -ac_libs_safe="$LIBS" -LIBS="-lXext -lX11 $X_LDFLAGS" - -LIBXSS="" -AC_CHECK_LIB(Xss, XScreenSaverAllocInfo, [LIBXSS="-lXext -lXss"]) -if test "x$LIBXSS" != "x"; then - AC_DEFINE(HAVE_LIBXSS,1,[Define if you have libXss installed]) -fi - -LIBS="$ac_libs_safe" -LDFLAGS="$ac_ldflags_safe" -AC_SUBST(LIBXSS) diff --git a/ktimetracker/csvexportdialog.cpp b/ktimetracker/csvexportdialog.cpp deleted file mode 100644 index 4a5536d400..0000000000 --- a/ktimetracker/csvexportdialog.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2004 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "csvexportdialog.h" -#include "reportcriteria.h" - -CSVExportDialog::CSVExportDialog( ReportCriteria::REPORTTYPE rt, - QWidget *parent, - const char *name - ) - : CSVExportDialogBase( parent, name ) -{ - switch ( rt ) { - case ReportCriteria::CSVTotalsExport: - grpDateRange->setEnabled( false ); - grpDateRange->hide(); - rc.reportType = rt; - break; - case ReportCriteria::CSVHistoryExport: - grpDateRange->setEnabled( true ); - rc.reportType = rt; - break; - default: - break; - - } - - // If decimal symbol is a comma, then default field seperator to semi-colon. - // In France and Germany, one-and-a-half is written as 1,5 not 1.5 - QString d = KGlobal::locale()->decimalSymbol(); - if ( "," == d ) CSVExportDialogBase::radioSemicolon->setChecked(true); - else CSVExportDialogBase::radioComma->setChecked(true); - -} - -void CSVExportDialog::enableExportButton() -{ - btnExport->setEnabled( !urlExportTo->lineEdit()->text().isEmpty() ); -} - -void CSVExportDialog::enableTasksToExportQuestion() -{ - return; - //grpTasksToExport->setEnabled( true ); -} - -ReportCriteria CSVExportDialog::reportCriteria() -{ - rc.url = urlExportTo->url(); - rc.from = dtFrom->date(); - rc.to = dtTo->date(); - - // Hard code to true for now as the CSV export of totals does not support - // this choice currenly and I'm trying to minimize pre-3.3 hacking at the - // moment. - rc.allTasks = true; - - QString t = grpTimeFormat->selected()->name(); - rc.decimalMinutes = ( t == i18n( "radioDecimal" ) ); - - QString d = grpDelimiter->selected()->name(); - if ( d == "radioComma" ) rc.delimiter = ","; - else if ( d == "radioTab" ) rc.delimiter = "\t"; - else if ( d == "radioSemicolon" ) rc.delimiter = ";"; - else if ( d == "radioSpace" ) rc.delimiter = " "; - else if ( d == "radioOther" ) rc.delimiter = txtOther->text(); - else { - kdDebug(5970) - << "*** CSVExportDialog::reportCriteria: Unexpected delimiter choice '" - << d << "'--defaulting to a tab" << endl; - rc.delimiter = "\t"; - } - - rc.quote = cboQuote->currentText(); - - return rc; -} - -#include "csvexportdialog.moc" diff --git a/ktimetracker/csvexportdialog.h b/ktimetracker/csvexportdialog.h deleted file mode 100644 index eae6bd4abb..0000000000 --- a/ktimetracker/csvexportdialog.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2004 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ -#ifndef CSVEXPORTDIALOG_H -#define CSVEXPORTDIALOG_H - -#include "csvexportdialog_base.h" -#include "reportcriteria.h" - -class CSVExportDialog : public CSVExportDialogBase -{ - Q_OBJECT - - public: - CSVExportDialog( ReportCriteria::REPORTTYPE rt, - QWidget *parent = 0, - const char *name = 0 - ); - - /** - Enable the "Tasks to export" question in the dialog. - - Since Karm does not have the concept of a single root task, when the user - requests a report on a top-level task, it is impossible to know if they - want all tasks or just the currently selected top-level task. - - Stubbed for 3.3 release as CSV export of totals doesn't suppor this option. - */ - void enableTasksToExportQuestion(); - - /** - Return an object that encapsulates the choices the user has made. - */ - ReportCriteria reportCriteria(); - - private slots: - - /** - Enable export button if export url entered. - */ - void enableExportButton(); - - private: - ReportCriteria rc; -}; - -#endif diff --git a/ktimetracker/desktoptracker.cpp b/ktimetracker/desktoptracker.cpp deleted file mode 100644 index a84a8fdde5..0000000000 --- a/ktimetracker/desktoptracker.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include // std::find - -#include -#include - -#include "desktoptracker.h" - -// TODO: Put in config dialog -const int minimumInterval = 5; // seconds - -DesktopTracker::DesktopTracker () -{ - // Setup desktop change handling - connect( &kWinModule, SIGNAL( currentDesktopChanged(int) ), - this, SLOT( handleDesktopChange(int) )); - - _desktopCount = kWinModule.numberOfDesktops(); - _previousDesktop = kWinModule.currentDesktop()-1; - // TODO: removed? fixed by Lubos? - // currentDesktop will return 0 if no window manager is started - if( _previousDesktop < 0 ) _previousDesktop = 0; - - _timer = new QTimer(this); - connect( _timer, SIGNAL( timeout() ), this, SLOT( changeTimers() ) ); -} - -void DesktopTracker::handleDesktopChange( int desktop ) -{ - _desktop = desktop; - - // If user changes back and forth between desktops rapidly and frequently, - // the data file can get huge fast if logging is turned on. Then saving - // get's slower, etc. There's no benefit in saving a lot of start/stop - // events that are very small. Wait a bit to make sure the user is settled. - if ( !_timer->start( minimumInterval * 1000, true ) ) changeTimers(); -} - -void DesktopTracker::changeTimers() -{ - _desktop--; // desktopTracker starts with 0 for desktop 1 - // notify start all tasks setup for running on desktop - TaskVector::iterator it; - - // stop trackers for _previousDesktop - TaskVector tv = desktopTracker[_previousDesktop]; - for (it = tv.begin(); it != tv.end(); ++it) { - emit leftActiveDesktop(*it); - } - - // start trackers for desktop - tv = desktopTracker[_desktop]; - for (it = tv.begin(); it != tv.end(); ++it) { - emit reachedtActiveDesktop(*it); - } - _previousDesktop = _desktop; - - // emit updateButtons(); -} - -void DesktopTracker::startTracking() -{ - int currentDesktop = kWinModule.currentDesktop() -1; - // TODO: removed? fixed by Lubos? - // currentDesktop will return 0 if no window manager is started - if ( currentDesktop < 0 ) currentDesktop = 0; - - TaskVector &tv = desktopTracker[ currentDesktop ]; - TaskVector::iterator tit = tv.begin(); - while(tit!=tv.end()) { - emit reachedtActiveDesktop(*tit); - tit++; - } -} - -void DesktopTracker::registerForDesktops( Task* task, DesktopList desktopList) -{ - // if no desktop is marked, disable auto tracking for this task - if (desktopList.size()==0) { - for (int i=0; ibegin(), v->end(), task); - if (tit != v->end()) - desktopTracker[i].erase(tit); - // if the task was priviously tracking this desktop then - // emit a signal that is not tracking it any more - if( i == kWinModule.currentDesktop() -1) - emit leftActiveDesktop(task); - } - - return; - } - - // If desktop contains entries then configure desktopTracker - // If a desktop was disabled, it will not be stopped automatically. - // If enabled: Start it now. - if (desktopList.size()>0) { - for (int i=0; i -#include - -#include "docking.h" -#include -#include -#include -#include - -DockWidget::DockWidget( KarmWindow* parent, const char *name) - : KDockWindow( parent, name ) -{ - setPixmap( SmallIcon(QString::fromLatin1("karm"))); -} - -DockWidget::~DockWidget() { -} - -#include "docking.moc" diff --git a/ktimetracker/docking.h b/ktimetracker/docking.h deleted file mode 100644 index 894cc07f63..0000000000 --- a/ktimetracker/docking.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef _DOCKING_H_ -#define _DOCKING_H_ - -#include - -class KarmWindow; - -class DockWidget : public KDockWindow { - - Q_OBJECT - -public: - DockWidget( KarmWindow* parent, const char *name=0); - ~DockWidget(); - -}; - -#endif - - - diff --git a/ktimetracker/edittaskdialog.cpp b/ktimetracker/edittaskdialog.cpp deleted file mode 100644 index c1ef03f3e0..0000000000 --- a/ktimetracker/edittaskdialog.cpp +++ /dev/null @@ -1,339 +0,0 @@ -/* - * karm - * This file only: Copyright (C) 1999 Espen Sand, espensa@online.no - * Modifications (see CVS log) Copyright (C) 2000 Klarlvdalens - * Datakonsult AB , Jesper Pedersen - * - * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include // i18n -#include - -#include "edittaskdialog.h" -#include "ktimewidget.h" -#include "kdebug.h" - -EditTaskDialog::EditTaskDialog( QString caption, bool editDlg, - DesktopList* desktopList) - : KDialogBase(0, "EditTaskDialog", true, caption, Ok|Cancel, Ok, true ), - origTime( 0 ), origSession( 0 ) -{ - QWidget *page = new QWidget( this ); - setMainWidget(page); - KWinModule kwinmodule(0, KWinModule::INFO_DESKTOP); - - QVBoxLayout *lay1 = new QVBoxLayout(page); - - QHBoxLayout *lay2 = new QHBoxLayout(); - lay1->addLayout(lay2); - - // The name of the widget - QLabel *label = new QLabel( i18n("Task &name:"), page, "name" ); - lay2->addWidget( label ); - lay2->addSpacing(5); - - - _name = new QLineEdit( page, "lineedit" ); - - _name->setMinimumWidth(fontMetrics().maxWidth()*15); - lay2->addWidget( _name ); - label->setBuddy( _name ); - - - // The "Edit Absolut" radio button - lay1->addSpacing(10);lay1->addStretch(1); - _absoluteRB = new QRadioButton( i18n( "Edit &absolute" ), page, - "_absoluteRB" ); - lay1->addWidget( _absoluteRB ); - connect( _absoluteRB, SIGNAL( clicked() ), this, SLOT( slotAbsolutePressed() ) ); - - - // Absolute times - QHBoxLayout *lay5 = new QHBoxLayout(); - lay1->addLayout(lay5); - lay5->addSpacing(20); - QGridLayout *lay3 = new QGridLayout( 2, 2, -1, "lay3" ); - lay5->addLayout(lay3); - - _sessionLA = new QLabel( i18n("&Session time: "), page, "session time" ); - - // Time - _timeLA = new QLabel( i18n("&Time:"), page, "time" ); - lay3->addWidget( _timeLA, 0, 0 ); - _timeLA->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, - (QSizePolicy::SizeType)0, - 0, - 0, - _timeLA->sizePolicy().hasHeightForWidth()) ); - - // Based on measuring pixels in a screenshot, it looks like the fontmetrics - // call includes the ampersand when calculating the width. To be sure - // things will line up (no matter what language or widget style), set all - // three date entry label controls to the same width. - _timeLA->setMinimumWidth( fontMetrics().width( _sessionLA->text() ) ); - - _timeTW = new KArmTimeWidget( page, "_timeTW" ); - lay3->addWidget( _timeTW, 0, 1 ); - _timeLA->setBuddy( _timeTW ); - - - // Session - lay3->addWidget( _sessionLA, 1, 0 ); - - _sessionTW = new KArmTimeWidget( page, "_sessionTW" ); - lay3->addWidget( _sessionTW, 1, 1 ); - _sessionLA->setBuddy( _sessionTW ); - _sessionLA->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, - (QSizePolicy::SizeType)0, - 0, - 0, - _sessionLA->sizePolicy().hasHeightForWidth()) ); - _sessionLA->setMinimumWidth( fontMetrics().width( _sessionLA->text() ) ); - - - // The "Edit relative" radio button - lay1->addSpacing(10); - lay1->addStretch(1); - _relativeRB = new QRadioButton( i18n( "Edit &relative (apply to both time and" - " session time)" ), page, "_relativeRB" ); - lay1->addWidget( _relativeRB ); - connect( _relativeRB, SIGNAL( clicked() ), this, SLOT(slotRelativePressed()) ); - - // The relative times - QHBoxLayout *lay4 = new QHBoxLayout(); - lay1->addLayout( lay4 ); - lay4->addSpacing(20); - - _operator = new QComboBox(page); - _operator->insertItem( QString::fromLatin1( "+" ) ); - _operator->insertItem( QString::fromLatin1( "-" ) ); - _operator->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, - (QSizePolicy::SizeType)0, - 0, - 0, - _operator->sizePolicy().hasHeightForWidth()) ); - //kdDebug() << "text width=" << fontMetrics().width( _sessionLA->text() ) << endl; - _operator->setMinimumWidth( fontMetrics().width( _sessionLA->text() ) ); - lay4->addWidget( _operator ); - - _diffTW = new KArmTimeWidget( page, "_sessionAddTW" ); - lay4->addWidget( _diffTW ); - - desktopCount = kwinmodule.numberOfDesktops(); - - // If desktopList contains higher numbered desktops than desktopCount then - // delete those from desktopList. This may be the case if the user has - // configured virtual desktops. The values in desktopList are sorted. - if ( (desktopList != 0) && (desktopList->size() > 0) ) - { - DesktopList::iterator rit = desktopList->begin(); - while (*rit < desktopCount && rit!=desktopList->end()) - { - ++rit; - } - desktopList->erase(rit, desktopList->end()); - } - - // The "Choose Desktop" checkbox - lay1->addSpacing(10); - lay1->addStretch(1); - - _desktopCB = new QCheckBox(i18n("A&uto tracking"), page); - _desktopCB->setEnabled(true); - lay1->addWidget(_desktopCB); - - QGroupBox* groupBox; - { - int lines = (int)(desktopCount/2); - if (lines*2 != desktopCount) lines++; - groupBox = new QButtonGroup( lines, QGroupBox::Horizontal, - i18n("In Desktop"), page, "_desktopsGB"); - } - lay1->addWidget(groupBox); - - QHBoxLayout *lay6 = new QHBoxLayout(); - - lay1->addLayout(lay6); - for (int i=0; isetText(kwinmodule.desktopName(i+1)); - _deskBox[i]->setChecked(false); - - lay6->addWidget(_deskBox[i]); - } - // check specified Desktop Check Boxes - bool enableDesktops = false; - - if ( (desktopList != 0) && (desktopList->size() > 0) ) - { - DesktopList::iterator it = desktopList->begin(); - while (it != desktopList->end()) - { - _deskBox[*it]->setChecked(true); - it++; - } - enableDesktops = true; - } - // if some desktops were specified, then enable the parent box - _desktopCB->setChecked(enableDesktops); - - for (int i=0; isetEnabled(enableDesktops); - - connect(_desktopCB, SIGNAL(clicked()), this, SLOT(slotAutoTrackingPressed())); - - lay1->addStretch(1); - - - if ( editDlg ) { - // This is an edit dialog. - _operator->setFocus(); - } - else { - // This is an initial dialog - _name->setFocus(); - } - - slotRelativePressed(); - - // Whats this help. - QWhatsThis::add( _name, - i18n( "Enter the name of the task here. " - "This name is for your eyes only.")); - QWhatsThis::add( _absoluteRB, - i18n( "Use this option to set the time spent on this task " - "to an absolute value.\n\nFor example, if you have " - "worked exactly four hours on this task during the current " - "session, you would set the Session time to 4 hr." ) ); - QWhatsThis::add( _relativeRB, - i18n( "Use this option to change the time spent on this task " - "relative to its current value.\n\nFor example, if you worked " - "on this task for one hour without the timer running, you " - "would add 1 hr." ) ); - QWhatsThis::add( _timeTW, - i18n( "This is the time the task has been " - "running since all times were reset.")); - QWhatsThis::add( _sessionTW, - i18n( "This is the time the task has been running this " - "session.")); - QWhatsThis::add( _diffTW, i18n( "Specify how much time to add or subtract " - "to the overall and session time")); - - QWhatsThis::add( _desktopCB, - i18n( "Use this option to automatically start the timer " - "on this task when you switch to the specified desktop(s)." ) ); - QWhatsThis::add( groupBox, - i18n( "Select the desktop(s) that will automatically start the " - "timer on this task." ) ); -} - - -void EditTaskDialog::slotAbsolutePressed() -{ - _relativeRB->setChecked( false ); - _absoluteRB->setChecked( true ); - - _operator->setEnabled( false ); - _diffTW->setEnabled( false ); - - _timeLA->setEnabled( true ); - _sessionLA->setEnabled( true ); - _timeTW->setEnabled( true ); - _sessionTW->setEnabled( true ); -} - -void EditTaskDialog::slotRelativePressed() -{ - _relativeRB->setChecked( true ); - _absoluteRB->setChecked( false ); - - _operator->setEnabled( true ); - _diffTW->setEnabled( true ); - - _timeLA->setEnabled( false ); - _sessionLA->setEnabled( false ); - _timeTW->setEnabled( false ); - _sessionTW->setEnabled( false ); -} - -void EditTaskDialog::slotAutoTrackingPressed() -{ - bool checked = _desktopCB->isChecked(); - for (unsigned int i=0; i<_deskBox.size(); i++) - _deskBox[i]->setEnabled(checked); - - if (!checked) // uncheck all desktop boxes - for (int i=0; isetChecked(false); -} - -void EditTaskDialog::setTask( const QString &name, long time, long session ) -{ - _name->setText( name ); - - _timeTW->setTime( time / 60, time % 60 ); - _sessionTW->setTime( session / 60, session % 60 ); - origTime = time; - origSession = session; -} - - -QString EditTaskDialog::taskName() const -{ - return( _name->text() ); -} - - -void EditTaskDialog::status(long *time, long *timeDiff, long *session, - long *sessionDiff, DesktopList *desktopList) const -{ - if ( _absoluteRB->isChecked() ) { - *time = _timeTW->time(); - *session = _sessionTW->time(); - } - else { - int diff = _diffTW->time(); - if ( _operator->currentItem() == 1) { - diff = -diff; - } - *time = origTime + diff; - *session = origSession + diff; - } - - *timeDiff = *time - origTime; - *sessionDiff = *session - origSession; - - for (unsigned int i=0; i<_deskBox.size(); i++) { - if (_deskBox[i]->isChecked()) - desktopList->push_back(i); - } -} - -#include "edittaskdialog.moc" diff --git a/ktimetracker/edittaskdialog.h b/ktimetracker/edittaskdialog.h deleted file mode 100644 index 0954d8b5df..0000000000 --- a/ktimetracker/edittaskdialog.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * karm - * This file only: Copyright (C) 1999 Espen Sand, espensa@online.no - * - * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ - -#ifndef KARM_EDIT_TASK_DIALOG_H -#define KARM_EDIT_TASK_DIALOG_H - -#include - -#include -#include - -#include "desktoplist.h" - -class QComboBox; -class QLabel; -class QLineEdit; -class QRadioButton; -class QString; - -class KArmTimeWidget; - -/** - * Dialog to add a new task or edit an existing task. - */ - -class EditTaskDialog : public KDialogBase -{ - Q_OBJECT - - public: - EditTaskDialog(QString caption, bool editDlg, DesktopList* desktopList=0); - void setTask(const QString &name, long time, long sessionTime); - QString taskName() const; - - // return user choices - void status( long *time, long *timeDiff, - long *session, long *sessionDiff, - DesktopList *desktopList) const; - - private slots: - void slotAbsolutePressed(); - void slotRelativePressed(); - void slotAutoTrackingPressed(); - - private: - QLineEdit* _name; - KArmTimeWidget* _timeTW; - KArmTimeWidget* _sessionTW; - KArmTimeWidget* _diffTW; - QComboBox* _operator; - std::vector _deskBox; // we only need an array, but ISO forbids - // passing an array as a function argument - - long origTime; - long origSession; - - QRadioButton *_absoluteRB; - QRadioButton *_relativeRB; - - QCheckBox *_desktopCB; - int desktopCount; - - QLabel* _timeLA; - QLabel* _sessionLA; -}; - - - - - -#endif // KARM_EDIT_TASK_DIALOG - diff --git a/ktimetracker/idle.cpp b/ktimetracker/idle.cpp deleted file mode 100644 index 06b7aefd44..0000000000 --- a/ktimetracker/idle.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include "idle.h" -#include -#include -#include -#include - -IdleTimer::IdleTimer(int maxIdle) -{ - _maxIdle = maxIdle; - -#ifdef HAVE_LIBXSS - int event_base, error_base; - if(XScreenSaverQueryExtension(qt_xdisplay(), &event_base, &error_base)) { - _idleDetectionPossible = true; - } - else { - _idleDetectionPossible = false; - } - - _timer = new QTimer(this); - connect(_timer, SIGNAL(timeout()), this, SLOT(check())); -#else - _idleDetectionPossible = false; -#endif // HAVE_LIBXSS - -} - -bool IdleTimer::isIdleDetectionPossible() -{ - return _idleDetectionPossible; -} - -void IdleTimer::check() -{ -#ifdef HAVE_LIBXSS - if (_idleDetectionPossible) { - _mit_info = XScreenSaverAllocInfo (); - XScreenSaverQueryInfo(qt_xdisplay(), qt_xrootwin(), _mit_info); - int idleMinutes = (_mit_info->idle/1000)/secsPerMinutes;; - if (idleMinutes >= _maxIdle) { - informOverrun(idleMinutes); - } - } -#endif // HAVE_LIBXSS -} - -void IdleTimer::setMaxIdle(int maxIdle) -{ - _maxIdle = maxIdle; -} - -#ifdef HAVE_LIBXSS -void IdleTimer::informOverrun(int idleMinutes) -{ - if (!_overAllIdleDetect) { - return; // In the preferences the user has indicated that he do not - // want idle detection. - } - - _timer->stop(); - - QDateTime start = QDateTime::currentDateTime(); - QDateTime idleStart = start.addSecs(-60 * _maxIdle); - QString backThen; - backThen.sprintf("%d:%02d", idleStart.time().hour(), idleStart.time().minute()); - - int id = QMessageBox::warning(0,i18n("Idle detection"), - i18n("Desktop has been idle since %1." - " What should we do?").arg(backThen), - i18n("Revert and Stop"), i18n("Revert and Continue"), - i18n("Continue Timing"),0,2); - QDateTime end = QDateTime::currentDateTime(); - int diff = start.secsTo(end)/secsPerMinutes; - - if (id == 0) { - // Revert And Stop - emit(extractTime(idleMinutes+diff)); - emit(stopTimer()); - } - else if (id == 1) { - // Revert and Continue - emit(extractTime(idleMinutes+diff)); - _timer->start(testInterval); - } - else { - // Continue - _timer->start(testInterval); - } -} -#endif // HAVE_LIBXSS - -void IdleTimer::startIdleDetection() -{ -#ifdef HAVE_LIBXSS - if (!_timer->isActive()) - _timer->start(testInterval); -#endif //HAVE_LIBXSS -} - -void IdleTimer::stopIdleDetection() -{ -#ifdef HAVE_LIBXSS - if (_timer->isActive()) - _timer->stop(); -#endif // HAVE_LIBXSS -} -void IdleTimer::toggleOverAllIdleDetection(bool on) -{ - _overAllIdleDetect = on; -} - -#include "idle.moc" diff --git a/ktimetracker/idle.h b/ktimetracker/idle.h deleted file mode 100644 index f907f43438..0000000000 --- a/ktimetracker/idle.h +++ /dev/null @@ -1,93 +0,0 @@ -#ifndef __IDLETIMER -#define __IDLETIMER -#include -#include "config.h" -#ifdef HAVE_LIBXSS - #include - #include - #include -#endif // HAVE_LIBXSS -class QTimer; - -// Seconds per minutes - usefull for speeding debugging up! -const int secsPerMinutes = 60; - -// Minutes between each idle overrun test. -const int testInterval= secsPerMinutes * 1000; - -class IdleTimer :public QObject -{ -Q_OBJECT - -public: - /** - Initializes and idle test timer - @param maxIdle minutes before the idle timer will go off. - **/ - IdleTimer(int maxIdle); - - /** - Returns true if it is possible to do idle detection. - Idle detection relys on a feature in the X server, which might not - allways be present. - **/ - bool isIdleDetectionPossible(); - -signals: - /** - Tells the listener to extract time from current timing. - The time to extract is due to the idle time since the dialog wass - shown, and until the user answers the dialog. - @param minutes Minutes to extract. - **/ - void extractTime(int minutes); - - /** - Tells the listener to stop timing - **/ - void stopTimer(); - -public slots: - /** - Sets the maximum allowed idle. - @param maxIdle Maximum allowed idle time in minutes - **/ - void setMaxIdle(int maxIdle); - - /** - Starts detecting idle time - **/ - void startIdleDetection(); - - /** - Stops detecting idle time. - **/ - void stopIdleDetection(); - - /** - Sets whether idle detection should be done at all - @param on If true idle detection is done based on @ref - startIdleDetection and @ref stopIdleDetection - **/ - void toggleOverAllIdleDetection(bool); - - -protected: -#ifdef HAVE_LIBXSS - void informOverrun(int idle); -#endif // HAVE_LIBXSS - -protected slots: - void check(); - -private: -#ifdef HAVE_LIBXSS - XScreenSaverInfo *_mit_info; -#endif - bool _idleDetectionPossible; - bool _overAllIdleDetect; // Based on preferences. - int _maxIdle; - QTimer *_timer; -}; - -#endif // __IDLETIMER diff --git a/ktimetracker/idletimedetector.h b/ktimetracker/idletimedetector.h deleted file mode 100644 index e2d0e56c2e..0000000000 --- a/ktimetracker/idletimedetector.h +++ /dev/null @@ -1,101 +0,0 @@ -#ifndef KARM_IDLE_TIME_DETECTOR_H -#define KARM_IDLE_TIME_DETECTOR_H - -#include -#include "config.h" // HAVE_LIBXSS - -class QTimer; - -#ifdef HAVE_LIBXSS - #include - #include - #include - #include -#endif // HAVE_LIBXSS - -// Seconds per minutes - useful for speeding debugging up! -const int secsPerMinute = 60; - -// Minutes between each idle overrun test. -const int testInterval= secsPerMinute * 1000; - -/** - * Keep track of how long the computer has been idle. - */ - -class IdleTimeDetector :public QObject -{ -Q_OBJECT - -public: - /** - Initializes and idle test timer - @param maxIdle minutes before the idle timer will go off. - **/ - IdleTimeDetector(int maxIdle); - - /** - Returns true if it is possible to do idle detection. - Idle detection relys on a feature in the X server, which might not - always be present. - **/ - bool isIdleDetectionPossible(); - -signals: - /** - Tells the listener to extract time from current timing. - The time to extract is due to the idle time since the dialog wass - shown, and until the user answers the dialog. - @param minutes Minutes to extract. - **/ - void extractTime(int minutes); - - /** - Tells the listener to stop timing - **/ - void stopAllTimers(); - -public slots: - /** - Sets the maximum allowed idle. - @param maxIdle Maximum allowed idle time in minutes - **/ - void setMaxIdle(int maxIdle); - - /** - Starts detecting idle time - **/ - void startIdleDetection(); - - /** - Stops detecting idle time. - **/ - void stopIdleDetection(); - - /** - Sets whether idle detection should be done at all - @param on If true idle detection is done based on - startIdleDetection and @ref stopIdleDetection - **/ - void toggleOverAllIdleDetection(bool on); - - -protected: -#ifdef HAVE_LIBXSS - void informOverrun(int idle); -#endif // HAVE_LIBXSS - -protected slots: - void check(); - -private: -#ifdef HAVE_LIBXSS - XScreenSaverInfo *_mit_info; -#endif - bool _idleDetectionPossible; - bool _overAllIdleDetect; // Based on preferences. - int _maxIdle; - QTimer *_timer; -}; - -#endif // KARM_IDLE_TIME_DETECTOR_H diff --git a/ktimetracker/kaccelmenuwatch.cpp b/ktimetracker/kaccelmenuwatch.cpp deleted file mode 100644 index d3b536cf53..0000000000 --- a/ktimetracker/kaccelmenuwatch.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* -* kaccelmenuwatch.cpp -- Implementation of class KAccelMenuWatch. -* Author: Sirtaj Singh Kang -* Version: $Id$ -* Generated: Thu Jan 7 15:05:26 EST 1999 -*/ - -#include -#include"kaccelmenuwatch.h" - -KAccelMenuWatch::KAccelMenuWatch( KAccel *accel, QObject *parent ) - : QObject( parent ), - _accel( accel ), - _menu ( 0 ) -{ - _accList.setAutoDelete( true ); - _menuList.setAutoDelete( false ); -} - -void KAccelMenuWatch::setMenu( QPopupMenu *menu ) -{ - assert( menu ); - - // we use _menuList to ensure that the signal is - // connected only once per menu. - - if ( !_menuList.findRef( menu ) ) { - _menuList.append( menu ); - connect( menu, SIGNAL(destroyed()), - this, SLOT(removeDeadMenu()) ); - } - - _menu = menu; -} - -void KAccelMenuWatch::connectAccel( int itemId, const char *action ) -{ - AccelItem *item = newAccelItem( _menu, itemId, StringAccel ) ; - item->action = action; -} - -void KAccelMenuWatch::connectAccel( int itemId, KStdAccel::StdAccel accel ) -{ - AccelItem *item = newAccelItem( _menu, itemId, StdAccel ) ; - item->stdAction = accel; -} - -void KAccelMenuWatch::updateMenus() -{ - assert( _accel != 0 ); - - QListIterator iter( _accList ); - AccelItem *item; - - for( ; (item = iter.current()) ; ++iter ) { - switch( item->type ) { - case StringAccel: - _accel->changeMenuAccel( item->menu, - item->itemId, - item->action ); - break; - case StdAccel: - _accel->changeMenuAccel( item->menu, - item->itemId, - item->stdAction ); - break; - default: - break; - } - } - -} - -void KAccelMenuWatch::removeDeadMenu() -{ - QPopupMenu *sdr = (QPopupMenu *) sender(); - assert( sdr ); - - if ( !_menuList.findRef( sdr ) ) { - return; - } - - // remove all accels - - AccelItem *accel; - for ( accel = _accList.first(); accel; accel = _accList.next() ) { - -loop: - if( accel && accel->menu == sdr ) { - _accList.remove(); - accel = _accList.current(); - goto loop; - } - } - - - // remove from menu list - _menuList.remove( sdr ); - - return; -} - -KAccelMenuWatch::AccelItem *KAccelMenuWatch::newAccelItem( QPopupMenu *, - int itemId, AccelType type ) -{ - AccelItem *item = new AccelItem; - - item->menu = _menu; - item->itemId = itemId; - item->type = type; - - _accList.append( item ); - - return item; -} - -#include "kaccelmenuwatch.h" -#include "kaccelmenuwatch.moc" diff --git a/ktimetracker/kaccelmenuwatch.h b/ktimetracker/kaccelmenuwatch.h deleted file mode 100644 index 8e838f556f..0000000000 --- a/ktimetracker/kaccelmenuwatch.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -* kaccelmenuwatch.h -- Declaration of class KAccelMenuWatch. -* Generated by newclass on Thu Jan 7 15:05:26 EST 1999. -*/ -#ifndef SSK_KACCELMENUWATCH_H -#define SSK_KACCELMENUWATCH_H - -#include -#include -#include - -#include - -/** -* Easy updating of menu accels when changing a @ref KAccel object. -* -* Since a KAccel object does not keep track of menu items to which it -* is connected, we normally have to manually call -* @ref KAccel::changeMenuAccel again for each update of the KAccel object. -* -* With KAccelMenuWatch you provide the kaccel object and the menu -* items to which it connects, and if you update the kaccel you just have -* to call @ref ::updateMenus and the menu items will be updated. -* -* It is safe to delete menus that have connections handled by this class. -* On deletion of a menu, all associated accelerators will be deleted. -* -* Note that you _have_ to call updateMenus after you connect the -* accelerators, as they are not activated till then. -* - @author Sirtaj Singh Kang (taj@kde.org) -* @version $Id$ -*/ -class KAccelMenuWatch : public QObject -{ - Q_OBJECT - -private: - enum AccelType { StdAccel, StringAccel }; - - typedef struct AccelItem { - QPopupMenu *menu; - int itemId; - - AccelType type; - - // only one of these is used at a time - QString action; - KStdAccel::StdAccel stdAction; - - } AccelItem; - - KAccel *_accel; - QList _accList; - QList _menuList; - - QPopupMenu *_menu; - - KAccelMenuWatch::AccelItem *newAccelItem( QPopupMenu *menu, - int itemId, AccelType type ); - -public: - /** - * KAccelMenuWatch Constructor - */ - KAccelMenuWatch( KAccel *accel, QObject *parent = 0 ); - - /** - * KAccelMenuWatch Destructor - */ - virtual ~KAccelMenuWatch() {} - - /** - * Set the menu on which connectAccel calls will operate. - * All subsequent calls to connectAccel will be associated - * with this menu. You can call this function any number of - * times, so multiple menus can be handled. - */ - void setMenu( QPopupMenu *menu ); - - /** - * Return the last menu set with @ref ::setMenu, or 0 if none - * has been set. - */ - QPopupMenu *currentMenu() const { return _menu; } - - /** - * Connect the menu item identified to currentMenu()/id to - * the accelerator action. - */ - void connectAccel( int itemId, const char *action ); - - /** - * Same as above, but connects to standard accelerators. - */ - void connectAccel( int itemId, KStdAccel::StdAccel ); - -public slots: - /** - * Updates all menu accelerators. Call this after all accelerators - * have been connected or the kaccel object has been updated. - */ - void updateMenus(); - -private slots: - void removeDeadMenu(); - -private: - KAccelMenuWatch& operator=( const KAccelMenuWatch& ); - KAccelMenuWatch( const KAccelMenuWatch& ); -}; - -#endif // SSK_KACCELMENUWATCH_H diff --git a/ktimetracker/karm.cpp b/ktimetracker/karm.cpp deleted file mode 100644 index 1e187b9983..0000000000 --- a/ktimetracker/karm.cpp +++ /dev/null @@ -1,443 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "task.h" -#include "karm.h" -#include "adddlg.h" -#include "idle.h" -#include "preferences.h" - -#define T_LINESIZE 1023 - -Karm::Karm( QWidget *parent, const char *name ) - : QListView( parent, name ) -{ - _preferences = Preferences::instance(); - - connect(this, SIGNAL(doubleClicked(QListViewItem *)), - this, SLOT(changeTimer(QListViewItem *))); - - addColumn(i18n("Task Name")); - addColumn(i18n("Session Time")); - addColumn(i18n("Total Time")); - setAllColumnsShowFocus(true); - - // set up the minuteTimer - _minuteTimer = new QTimer(this); - connect(_minuteTimer, SIGNAL(timeout()), this, SLOT(minuteUpdate())); - _minuteTimer->start(1000 * secsPerMinutes); - - // Set up the idle detection. - _idleTimer = new IdleTimer(_preferences->idlenessTimeout()); - connect(_idleTimer, SIGNAL(extractTime(int)), this, SLOT(extractTime(int))); - connect(_idleTimer, SIGNAL(stopTimer()), this, SLOT(stopAllTimers())); - connect(_preferences, SIGNAL(idlenessTimeout(int)), _idleTimer, SLOT(setMaxIdle(int))); - connect(_preferences, SIGNAL(detectIdleness(bool)), _idleTimer, SLOT(toggleOverAllIdleDetection(bool))); - if (!_idleTimer->isIdleDetectionPossible()) - _preferences->disableIdleDetection(); - - // Setup auto save timer - _autoSaveTimer = new QTimer(this); - connect(_preferences, SIGNAL(autoSave(bool)), this, SLOT(autoSaveChanged(bool))); - connect(_preferences, SIGNAL(autoSavePeriod(int)), - this, SLOT(autoSavePeriodChanged(int))); - connect(_autoSaveTimer, SIGNAL(timeout()), this, SLOT(save())); -} - -Karm::~Karm() -{ - save(); -} - -void Karm::load() -{ - QFile f(_preferences->saveFile()); - - if( !f.exists() ) - return; - - if( !f.open( IO_ReadOnly ) ) - return; - - QString line; - - QStack stack; - Task *task; - - QTextStream stream(&f); - - while( !stream.atEnd() ) { - //lukas: this breaks for non-latin1 chars!!! - //if ( file.readLine( line, T_LINESIZE ) == 0 ) - // break; - - line = stream.readLine(); - - if (line.isNull()) - break; - - long minutes; - int level; - QString name; - - if (!parseLine(line, &minutes, &name, &level)) - continue; - - unsigned int stackLevel = stack.count(); - for (unsigned int i = level; i<=stackLevel ; i++) { - stack.pop(); - } - - if (level == 1) { - task = new Task(name, minutes, 0, this); - } - else { - Task *parent = stack.top(); - task = new Task(name, minutes, 0, parent); - setRootIsDecorated(true); - parent->setOpen(true); - } - stack.push(task); - } - f.close(); - - setSelected(firstChild(), true); - setCurrentItem(firstChild()); -} - -bool Karm::parseLine(QString line, long *time, QString *name, int *level) -{ - if (line.find('#') == 0) { - // A comment line - return false; - } - - int index = line.find('\t'); - if (index == -1) { - // This doesn't seem like a valid record - return false; - } - - QString levelStr = line.left(index); - QString rest = line.remove(0,index+1); - - index = rest.find('\t'); - if (index == -1) { - // This doesn't seem like a valid record - return false; - } - - QString timeStr = rest.left(index); - *name = rest.remove(0,index+1); - - bool ok; - *time = timeStr.toLong(&ok); - - if (!ok) { - // the time field was not a number - return false; - } - *level = levelStr.toInt(&ok); - if (!ok) { - // the time field was not a number - return false; - } - return true; -} - -void Karm::save() -{ - QFile f(_preferences->saveFile()); - - if ( !f.open( IO_WriteOnly | IO_Truncate ) ) { - QString msg = i18n - ("There was an error trying to save your data file.\n" - "Time accumulated this session will NOT be saved!\n"); - KMessageBox::error(0, msg ); - return; - } - const char * comment = "# Karm save data\n"; - - f.writeBlock(comment, strlen(comment)); //comment - f.flush(); - - QTextStream stream(&f); - - for (QListViewItem *child =firstChild(); child; child = child->nextSibling()) { - writeTaskToFile(&stream, child, 1); - } - f.close(); -} - -void Karm::writeTaskToFile(QTextStream *strm, QListViewItem *item, int level) -{ - Task * task = (Task *) item; - //lukas: correct version for non-latin1 users - QString _line = QString::fromLatin1("%1\t%2\t%3\n").arg(level). - arg(task->totalTime()).arg(task->name()); - - *strm << _line; - - QListViewItem * child; - for (child=item->firstChild(); child; child=child->nextSibling()) { - writeTaskToFile(strm, child, level+1); - } -} - -void Karm::startTimer() -{ - Task *item = ((Task *) currentItem()); - if (item != 0 && activeTasks.findRef(item) == -1) { - _idleTimer->startIdleDetection(); - item->setRunning(true); - activeTasks.append(item); - } -} - -void Karm::stopAllTimers() -{ - for(unsigned int i=0; isetRunning(false); - } - _idleTimer->stopIdleDetection(); - activeTasks.clear(); -} - -void Karm::resetSessionTimeForAllTasks() -{ - for(QListViewItem *child=firstChild(); child; child=child->itemBelow()) { - dynamic_cast(child)->setSessionTime(0); - } -} - -void Karm::stopCurrentTimer() -{ - Task *item = ((Task *) currentItem()); - if (item != 0 && activeTasks.findRef(item) != -1) { - activeTasks.removeRef(item); - item->setRunning(false); - if (activeTasks.count()== 0) - _idleTimer->stopIdleDetection(); - } -} - -void Karm::changeTimer(QListViewItem *) -{ - Task *item = ((Task *) currentItem()); - if (item != 0 && activeTasks.findRef(item) == -1) { - // Stop all the other timers. - for (unsigned int i=0; isetRunning(false); - } - activeTasks.clear(); - - // Start the new timer. - startTimer(); - } - else { - stopCurrentTimer(); - } -} - -void Karm::minuteUpdate() -{ - addTimeToActiveTasks(1); - if (activeTasks.count() != 0) - emit(timerTick()); -} - -void Karm::addTimeToActiveTasks(int minutes) -{ - for(unsigned int i=0; iincrementTime(minutes); - item = item->parent(); - } - } -} - -void Karm::newTask() -{ - newTask(i18n("New Task"), 0); -} - -void Karm::newTask(QString caption, QListViewItem *parent) -{ - AddTaskDialog *dialog = new AddTaskDialog(caption, false); - int result = dialog->exec(); - - if (result == QDialog::Accepted) { - QString taskName = i18n("Unnamed Task"); - if (!dialog->taskName().isEmpty()) { - taskName = dialog->taskName(); - } - - long total, totalDiff, session, sessionDiff; - dialog->status( &total, &totalDiff, &session, &sessionDiff ); - Task *task; - if (parent == 0) - task = new Task(taskName, total, session, this); - else - task = new Task(taskName, total, session, parent); - - updateParents( (QListViewItem *) task, totalDiff, sessionDiff ); - setCurrentItem(task); - setSelected(task, true); - } - delete dialog; -} - -void Karm::newSubTask() -{ - QListViewItem *item = currentItem(); - newTask(i18n("New Sub Task"), item); - item->setOpen(true); - setRootIsDecorated(true); -} - -void Karm::editTask() -{ - Task *task = (Task *) currentItem(); - if (!task) - return; - - AddTaskDialog *dialog = new AddTaskDialog(i18n("Edit Task"), true); - dialog->setTask(task->name(), - task->totalTime(), - task->sessionTime()); - int result = dialog->exec(); - if (result == QDialog::Accepted) { - QString taskName = i18n("Unnamed Task"); - if (!dialog->taskName().isEmpty()) { - taskName = dialog->taskName(); - } - task->setName(taskName); - - // update session time as well if the time was changed - long total, session, totalDiff, sessionDiff; - dialog->status( &total, &totalDiff, &session, &sessionDiff ); - - if( sessionDiff != 0 ) { - emit sessionTimeChanged( sessionDiff ); - } - task->setTotalTime( total); - task->setSessionTime( session ); - - // Update the parents for this task. - updateParents( (QListViewItem *) task, totalDiff, sessionDiff ); - } - delete dialog; -} - -void Karm::updateParents( QListViewItem* task, long totalDiff, long sessionDiff ) -{ - QListViewItem *item = task->parent(); - while (item) { - Task *parrentTask = (Task *) item; - parrentTask->setTotalTime(parrentTask->totalTime()+totalDiff); - parrentTask->setSessionTime(parrentTask->sessionTime()+sessionDiff); - item = item->parent(); - } -} - -void Karm::deleteTask() -{ - Task *item = ((Task *) currentItem()); - if (item == 0) { - KMessageBox::information(0,i18n("No task selected")); - return; - } - - int response; - if (item->childCount() == 0) { - response = KMessageBox::questionYesNo(0, - i18n( "Are you sure you want to delete the task named\n\"%1\"") - .arg(item->name()), - i18n( "Deleting Task")); - } - else { - response = KMessageBox::questionYesNo(0, - i18n( "Are you sure you want to delete the task named\n\"%1\"\n" - "NOTE: all its subtasks will also be deleted!") - .arg(item->name()), - i18n( "Deleting Task")); - } - - if (response == KMessageBox::Yes) { - - // Remove chilren from the active set of tasks. - stopChildCounters(item); - - // Stop idle detection if no more counters is running - if (activeTasks.count() == 0) { - _idleTimer->stopIdleDetection(); - } - - delete item; - - // remove root decoration if there is no more children. - bool anyChilds = false; - for(QListViewItem *child=firstChild(); child; child=child->nextSibling()) { - if (child->childCount() != 0) { - anyChilds = true; - break; - } - } - if (!anyChilds) { - setRootIsDecorated(false); - } - } -} - -void Karm::stopChildCounters(Task *item) -{ - for (QListViewItem *child=item->firstChild(); child; child=child->nextSibling()) { - stopChildCounters((Task *)child); - } - activeTasks.removeRef(item); -} - - -void Karm::extractTime(int minutes) -{ - addTimeToActiveTasks(-minutes); - emit(sessionTimeChanged(-minutes)); -} - -void Karm::autoSaveChanged(bool on) -{ - if (on) { - if (!_autoSaveTimer->isActive()) { - _autoSaveTimer->start(_preferences->autoSavePeriod()*1000*secsPerMinutes); - } - } - else { - if (_autoSaveTimer->isActive()) { - _autoSaveTimer->stop(); - } - } -} - -void Karm::autoSavePeriodChanged(int /*minutes*/) -{ - autoSaveChanged(_preferences->autoSave()); -} - -#include "karm.moc" diff --git a/ktimetracker/karm.h b/ktimetracker/karm.h deleted file mode 100644 index 81b991809a..0000000000 --- a/ktimetracker/karm.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef SSK_KARM_H -#define SSK_KARM_H - -#include -#include -#include -#include -#include - -class KMenuBar; -class KToolBar; -class QListBox; -class AddTaskDialog; -class IdleTimer; -class QTimer; -class Preferences; -class Task; - -class Karm : public QListView -{ - Q_OBJECT - -private: // member variables - IdleTimer *_idleTimer; - QTimer *_minuteTimer; - QTimer *_autoSaveTimer; - - Preferences *_preferences; - - QList activeTasks; - -public: - Karm( QWidget *parent = 0, const char *name = 0 ); - virtual ~Karm(); - static QString formatTime(long minutes); - -private: - void updateParents( QListViewItem* task, long totalDiff, long sesssionDiff ); - -public slots: - /* - File format: - zero or more lines of - 1 number - time in minutes - string task name - */ - void load(); - void save(); - void writeTaskToFile(QTextStream *, QListViewItem *, int); - bool parseLine(QString line, long *time, QString *name, int *level); - void stopCurrentTimer(); - void stopAllTimers(); - void startTimer(); - void changeTimer(QListViewItem *); - void newTask(); - void newTask(QString caption, QListViewItem *parent); - void newSubTask(); - void editTask(); - void deleteTask(); - void extractTime(int minutes); - void resetSessionTimeForAllTasks(); - -protected slots: - void autoSaveChanged(bool); - void autoSavePeriodChanged(int period); - void minuteUpdate(); - -signals: - void sessionTimeChanged( long difference ); - void timerTick(); - - -protected slots: - void stopChildCounters(Task *item); - void addTimeToActiveTasks(int minutes); -}; - -inline QString Karm::formatTime( long minutes ) -{ - QString time; - time.sprintf("%ld:%02ld", minutes / 60, minutes % 60); - return time; -} - -#endif diff --git a/ktimetracker/karmdcopiface.h b/ktimetracker/karmdcopiface.h deleted file mode 100644 index 1135c81e6a..0000000000 --- a/ktimetracker/karmdcopiface.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * This file only: - * Copyright (C) 2004 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - */ -#ifndef KARM_DCOP_IFAC_H -#define KARM_DCOP_IFAC_H - -#include - -/** Define DCOP interface to karm. Methods implemented in MainWindow */ -class KarmDCOPIface : virtual public DCOPObject -{ - K_DCOP - k_dcop: - - /** Return karm version. */ - virtual QString version() const = 0; - - /** Return id of task found, empty string if no match. */ - virtual QString taskIdFromName( const QString& taskName ) const = 0; - - /** - * Add a new top-level task. - * - * A top-level task is one that has no parent tasks. - * - * @param taskName Name of new task. - * - * @return 0 on success, error number on failure. - */ - virtual int addTask( const QString& taskName ) = 0; - - /** - * Set percent complete to a task - * - * @param taskName Name of new task. - * @param perCent percent, e.g. 99 - * - * @return "" on success, error msg on failure. - */ - virtual QString setPerCentComplete( const QString& taskName, int perCent ) = 0; - - /** - * Add time to a task. - * - * The GUI will be non-responsive until this method returns. - * - * @return 0 on success, error number on failure. - * - * @param taskId Unique ID of task to add time to - * - * @param iso8601StartDateTime Date and time the booking starts, in extended - * ISO-8601 format; for example, YYYY-MM-DDTHH:MI:SS format (see - * Qt::ISODate). No timezone support--time is interpreted as the local time. - * If just the date is passed in (i.e., YYYY-MM-DD) , then the time is set to - * noon. - * - * @param durationInMinutes The amount of time to book against the taskId. - * - */ - virtual int bookTime( const QString& taskId, const QString& iso8601StartDateTime, - long durationInMinutes ) = 0; - - /** - * Return error string associated with karm error number. - * - * @param karmErrorNumber An integer error number. - * - * @return String associated with error number. These strings are - * internationalized. An unknown error number produces an empty string as - * the return value. - * - */ - virtual QString getError( int karmErrorNumber ) const = 0; - - /** - * Total time currently associated with a task. - * - * A task has two counters: the total session time and the total time. Note - * that th euser can reset both counters. - * - * @param taskId Unique ID of task to lookup bookings for. - */ - virtual int totalMinutesForTaskId( const QString& taskId ) = 0; - - /** Start timer for all tasks with the summary taskname. */ - // may conflict with unitaskmode - virtual QString starttimerfor( const QString& taskname ) = 0; - - /** Stop timer for all tasks with the summary taskname. */ - // may conflict with unitaskmode - virtual QString stoptimerfor( const QString& taskname ) = 0; - - /** delete the current item */ - virtual QString deletetodo() = 0; - - /** set if prompted on deleting a task */ - virtual QString setpromptdelete( bool prompt ) = 0; - - /** get if prompted on deleting a task */ - virtual bool getpromptdelete() = 0; - - /** export csv history or totals file */ - virtual QString exportcsvfile( QString filename, QString from, QString to, int type = 0, bool decimalMinutes=true, bool allTasks=true, QString delimiter=";", QString quote="'" ) = 0; - - /** import planner project file */ - virtual QString importplannerfile( QString filename ) = 0; - - /** save your tasks */ - virtual bool save() = 0; - - /** Graceful shutdown. */ - virtual void quit() = 0; -}; - -#endif // KARM_DCOP_IFAC_H diff --git a/ktimetracker/karmstorage.cpp b/ktimetracker/karmstorage.cpp deleted file mode 100644 index a49994cb5f..0000000000 --- a/ktimetracker/karmstorage.cpp +++ /dev/null @@ -1,1196 +0,0 @@ -/* - * This file only: - * Copyright (C) 2003, 2004 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ - -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -#include "incidence.h" -#include "kapplication.h" // kapp -#include -#include -#include // i18n -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//#include -//#include -//#include -//#include - -#include "karmstorage.h" -#include "preferences.h" -#include "task.h" -#include "reportcriteria.h" - -using namespace std; - -KarmStorage *KarmStorage::_instance = 0; -static long linenr; // how many lines written by printTaskHistory so far - - -KarmStorage *KarmStorage::instance() -{ - if (_instance == 0) _instance = new KarmStorage(); - return _instance; -} - -KarmStorage::KarmStorage() -{ - _calendar = 0; -} - -QString KarmStorage::load (TaskView* view, const Preferences* preferences, QString fileName ) -// loads data from filename into view. If no filename is given, filename from preferences is used. -// filename might be of use if this program is run as embedded konqueror plugin. -{ - // When I tried raising an exception from this method, the compiler - // complained that exceptions are not allowed. Not sure how apps - // typically handle error conditions in KDE, but I'll return the error - // as a string (empty is no error). -- Mark, Aug 8, 2003 - - // Use KDE_CXXFLAGS=$(USE_EXCEPTIONS) in Makefile.am if you want to use - // exceptions (David Faure) - - QString err; - KEMailSettings settings; - if ( fileName.isEmpty() ) fileName = preferences->iCalFile(); - - // If same file, don't reload - if ( fileName == _icalfile ) return err; - - - // If file doesn't exist, create a blank one to avoid ResourceLocal load - // error. We make it user and group read/write, others read. This is - // masked by the users umask. (See man creat) - if ( ! remoteResource( _icalfile ) ) - { - int handle; - handle = open ( - QFile::encodeName( fileName ), - O_CREAT|O_EXCL|O_WRONLY, - S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH - ); - if (handle != -1) close(handle); - } - - if ( _calendar) - closeStorage(view); - - // Create local file resource and add to resources - _icalfile = fileName; - - KCal::ResourceCached *resource; - if ( remoteResource( _icalfile ) ) - { - KURL url( _icalfile ); - resource = new KCal::ResourceRemote( url, url ); // same url for upload and download - } - else - { - resource = new KCal::ResourceLocal( _icalfile ); - } - _calendar = resource; - - QObject::connect (_calendar, SIGNAL(resourceChanged(ResourceCalendar *)), - view, SLOT(iCalFileModified(ResourceCalendar *))); - _calendar->setTimeZoneId( KPimPrefs::timezone() ); - _calendar->setResourceName( QString::fromLatin1("KArm") ); - _calendar->open(); - _calendar->load(); - - // Claim ownership of iCalendar file if no one else has. - KCal::Person owner = resource->getOwner(); - if ( owner.isEmpty() ) - { - resource->setOwner( KCal::Person( - settings.getSetting( KEMailSettings::RealName ), - settings.getSetting( KEMailSettings::EmailAddress ) ) ); - } - - // Build task view from iCal data - if (!err) - { - KCal::Todo::List todoList; - KCal::Todo::List::ConstIterator todo; - QDict< Task > map; - - // Build dictionary to look up Task object from Todo uid. Each task is a - // QListViewItem, and is initially added with the view as the parent. - todoList = _calendar->rawTodos(); - kdDebug(5970) << "KarmStorage::load " - << "rawTodo count (includes completed todos) =" - << todoList.count() << endl; - for( todo = todoList.begin(); todo != todoList.end(); ++todo ) - { - // Initially, if a task was complete, it was removed from the view. - // However, this increased the complexity of reporting on task history. - // - // For example, if a task is complete yet has time logged to it during - // the date range specified on the history report, we have to figure out - // how that task fits into the task hierarchy. Currently, this - // structure is held in memory by the structure in the list view. - // - // I considered creating a second tree that held the full structure of - // all complete and incomplete tasks. But this seemed to much of a - // change with an impending beta release and a full todo list. - // - // Hence this "solution". Include completed tasks, but mark them as - // inactive in the view. - // - //if ((*todo)->isCompleted()) continue; - - Task* task = new Task(*todo, view); - map.insert( (*todo)->uid(), task ); - view->setRootIsDecorated(true); - task->setPixmapProgress(); - } - - // Load each task under it's parent task. - for( todo = todoList.begin(); todo != todoList.end(); ++todo ) - { - Task* task = map.find( (*todo)->uid() ); - - // No relatedTo incident just means this is a top-level task. - if ( (*todo)->relatedTo() ) - { - Task* newParent = map.find( (*todo)->relatedToUid() ); - - // Complete the loading but return a message - if ( !newParent ) - err = i18n("Error loading \"%1\": could not find parent (uid=%2)") - .arg(task->name()) - .arg((*todo)->relatedToUid()); - - if (!err) task->move( newParent); - } - } - - kdDebug(5970) << "KarmStorage::load - loaded " << view->count() - << " tasks from " << _icalfile << endl; - } - - return err; -} - -QString KarmStorage::buildTaskView(KCal::ResourceCalendar *rc, TaskView *view) -// makes *view contain the tasks out of *rc. -{ - QString err; - KCal::Todo::List todoList; - KCal::Todo::List::ConstIterator todo; - QDict< Task > map; - - // 1. delete old tasks - while (view->item_at_index(0)) view->item_at_index(0)->cut(); - - // 1. insert tasks form rc into taskview - // 1.1. Build dictionary to look up Task object from Todo uid. Each task is a - // QListViewItem, and is initially added with the view as the parent. - todoList = rc->rawTodos(); - for( todo = todoList.begin(); todo != todoList.end(); ++todo ) - { - Task* task = new Task(*todo, view); - map.insert( (*todo)->uid(), task ); - view->setRootIsDecorated(true); - task->setPixmapProgress(); - } - - // 1.1. Load each task under it's parent task. - for( todo = todoList.begin(); todo != todoList.end(); ++todo ) - { - Task* task = map.find( (*todo)->uid() ); - - // No relatedTo incident just means this is a top-level task. - if ( (*todo)->relatedTo() ) - { - Task* newParent = map.find( (*todo)->relatedToUid() ); - - // Complete the loading but return a message - if ( !newParent ) - err = i18n("Error loading \"%1\": could not find parent (uid=%2)") - .arg(task->name()) - .arg((*todo)->relatedToUid()); - - if (!err) task->move( newParent); - } - } - return err; -} - -void KarmStorage::closeStorage(TaskView* view) -{ - if ( _calendar ) - { - _calendar->close(); - delete _calendar; - _calendar = 0; - - view->clear(); - } -} - -QString KarmStorage::save(TaskView* taskview) -{ - kdDebug(5970) << "entering KarmStorage::save" << endl; - QString err; - - QPtrStack< KCal::Todo > parents; - - for (Task* task=taskview->first_child(); task; task = task->nextSibling()) - { - err=writeTaskAsTodo(task, 1, parents ); - } - - if ( !saveCalendar() ) - { - err="Could not save"; - } - - if ( err.isEmpty() ) - { - kdDebug(5970) - << "KarmStorage::save : wrote " - << taskview->count() << " tasks to " << _icalfile << endl; - } - else - { - kdWarning(5970) << "KarmStorage::save : " << err << endl; - } - - return err; -} - -QString KarmStorage::writeTaskAsTodo(Task* task, const int level, - QPtrStack< KCal::Todo >& parents ) -{ - QString err; - KCal::Todo* todo; - - todo = _calendar->todo(task->uid()); - if ( !todo ) - { - kdDebug(5970) << "Could not get todo from calendar" << endl; - return "Could not get todo from calendar"; - } - task->asTodo(todo); - if ( !parents.isEmpty() ) todo->setRelatedTo( parents.top() ); - parents.push( todo ); - - for ( Task* nextTask = task->firstChild(); nextTask; - nextTask = nextTask->nextSibling() ) - { - err = writeTaskAsTodo(nextTask, level+1, parents ); - } - - parents.pop(); - return err; -} - -bool KarmStorage::isEmpty() -{ - KCal::Todo::List todoList; - - todoList = _calendar->rawTodos(); - return todoList.empty(); -} - -bool KarmStorage::isNewStorage(const Preferences* preferences) const -{ - if ( !_icalfile.isNull() ) return preferences->iCalFile() != _icalfile; - else return false; -} - -//---------------------------------------------------------------------------- -// Routines that handle legacy flat file format. -// These only stored total and session times. -// - -QString KarmStorage::loadFromFlatFile(TaskView* taskview, - const QString& filename) -{ - QString err; - - kdDebug(5970) - << "KarmStorage::loadFromFlatFile: " << filename << endl; - - QFile f(filename); - if( !f.exists() ) - err = i18n("File \"%1\" not found.").arg(filename); - - if (!err) - { - if( !f.open( IO_ReadOnly ) ) - err = i18n("Could not open \"%1\".").arg(filename); - } - - if (!err) - { - - QString line; - - QPtrStack stack; - Task *task; - - QTextStream stream(&f); - - while( !stream.atEnd() ) { - // lukas: this breaks for non-latin1 chars!!! - // if ( file.readLine( line, T_LINESIZE ) == 0 ) - // break; - - line = stream.readLine(); - kdDebug(5970) << "DEBUG: line: " << line << "\n"; - - if (line.isNull()) - break; - - long minutes; - int level; - QString name; - DesktopList desktopList; - if (!parseLine(line, &minutes, &name, &level, &desktopList)) - continue; - - unsigned int stackLevel = stack.count(); - for (unsigned int i = level; i<=stackLevel ; i++) { - stack.pop(); - } - - if (level == 1) { - kdDebug(5970) << "KarmStorage::loadFromFlatFile - toplevel task: " - << name << " min: " << minutes << "\n"; - task = new Task(name, minutes, 0, desktopList, taskview); - task->setUid(addTask(task, 0)); - } - else { - Task *parent = stack.top(); - kdDebug(5970) << "KarmStorage::loadFromFlatFile - task: " << name - << " min: " << minutes << " parent" << parent->name() << "\n"; - task = new Task(name, minutes, 0, desktopList, parent); - - task->setUid(addTask(task, parent)); - - // Legacy File Format (!): - parent->changeTimes(0, -minutes); - taskview->setRootIsDecorated(true); - parent->setOpen(true); - } - if (!task->uid().isNull()) - stack.push(task); - else - delete task; - } - - f.close(); - - } - - return err; -} - -QString KarmStorage::loadFromFlatFileCumulative(TaskView* taskview, - const QString& filename) -{ - QString err = loadFromFlatFile(taskview, filename); - if (!err) - { - for (Task* task = taskview->first_child(); task; - task = task->nextSibling()) - { - adjustFromLegacyFileFormat(task); - } - } - return err; -} - -bool KarmStorage::parseLine(QString line, long *time, QString *name, - int *level, DesktopList* desktopList) -{ - if (line.find('#') == 0) { - // A comment line - return false; - } - - int index = line.find('\t'); - if (index == -1) { - // This doesn't seem like a valid record - return false; - } - - QString levelStr = line.left(index); - QString rest = line.remove(0,index+1); - - index = rest.find('\t'); - if (index == -1) { - // This doesn't seem like a valid record - return false; - } - - QString timeStr = rest.left(index); - rest = rest.remove(0,index+1); - - bool ok; - - index = rest.find('\t'); // check for optional desktops string - if (index >= 0) { - *name = rest.left(index); - QString deskLine = rest.remove(0,index+1); - - // now transform the ds string (e.g. "3", or "1,4,5") into - // an DesktopList - QString ds; - int d; - int commaIdx = deskLine.find(','); - while (commaIdx >= 0) { - ds = deskLine.left(commaIdx); - d = ds.toInt(&ok); - if (!ok) - return false; - - desktopList->push_back(d); - deskLine.remove(0,commaIdx+1); - commaIdx = deskLine.find(','); - } - - d = deskLine.toInt(&ok); - - if (!ok) - return false; - - desktopList->push_back(d); - } - else { - *name = rest.remove(0,index+1); - } - - *time = timeStr.toLong(&ok); - - if (!ok) { - // the time field was not a number - return false; - } - *level = levelStr.toInt(&ok); - if (!ok) { - // the time field was not a number - return false; - } - - return true; -} - -void KarmStorage::adjustFromLegacyFileFormat(Task* task) -{ - // unless the parent is the listView - if ( task->parent() ) - task->parent()->changeTimes(-task->sessionTime(), -task->time()); - - // traverse depth first - - // as soon as we're in a leaf, we'll substract it's time from the parent - // then, while descending back we'll do the same for each node untill - // we reach the root - for ( Task* subtask = task->firstChild(); subtask; - subtask = subtask->nextSibling() ) - adjustFromLegacyFileFormat(subtask); -} - -//---------------------------------------------------------------------------- -// Routines that handle Comma-Separated Values export file format. -// -QString KarmStorage::exportcsvFile( TaskView *taskview, - const ReportCriteria &rc ) -{ - QString delim = rc.delimiter; - QString dquote = rc.quote; - QString double_dquote = dquote + dquote; - bool to_quote = true; - - QString err; - Task* task; - int maxdepth=0; - - kdDebug(5970) - << "KarmStorage::exportcsvFile: " << rc.url << endl; - - QString title = i18n("Export Progress"); - KProgressDialog dialog( taskview, 0, title ); - dialog.setAutoClose( true ); - dialog.setAllowCancel( true ); - dialog.progressBar()->setTotalSteps( 2 * taskview->count() ); - - // The default dialog was not displaying all the text in the title bar. - int width = taskview->fontMetrics().width(title) * 3; - QSize dialogsize; - dialogsize.setWidth(width); - dialog.setInitialSize( dialogsize, true ); - - if ( taskview->count() > 1 ) dialog.show(); - - QString retval; - - // Find max task depth - int tasknr = 0; - while ( tasknr < taskview->count() && !dialog.wasCancelled() ) - { - dialog.progressBar()->advance( 1 ); - if ( tasknr % 15 == 0 ) kapp->processEvents(); // repainting is slow - if ( taskview->item_at_index(tasknr)->depth() > maxdepth ) - maxdepth = taskview->item_at_index(tasknr)->depth(); - tasknr++; - } - - // Export to file - tasknr = 0; - while ( tasknr < taskview->count() && !dialog.wasCancelled() ) - { - task = taskview->item_at_index( tasknr ); - dialog.progressBar()->advance( 1 ); - if ( tasknr % 15 == 0 ) kapp->processEvents(); - - // indent the task in the csv-file: - for ( int i=0; i < task->depth(); ++i ) retval += delim; - - /* - // CSV compliance - // Surround the field with quotes if the field contains - // a comma (delim) or a double quote - if (task->name().contains(delim) || task->name().contains(dquote)) - to_quote = true; - else - to_quote = false; - */ - to_quote = true; - - if (to_quote) - retval += dquote; - - // Double quotes replaced by a pair of consecutive double quotes - retval += task->name().replace( dquote, double_dquote ); - - if (to_quote) - retval += dquote; - - // maybe other tasks are more indented, so to align the columns: - for ( int i = 0; i < maxdepth - task->depth(); ++i ) retval += delim; - - retval += delim + formatTime( task->sessionTime(), - rc.decimalMinutes ) - + delim + formatTime( task->time(), - rc.decimalMinutes ) - + delim + formatTime( task->totalSessionTime(), - rc.decimalMinutes ) - + delim + formatTime( task->totalTime(), - rc.decimalMinutes ) - + "\n"; - tasknr++; - } - - // save, either locally or remote - if ((rc.url.isLocalFile()) || (!rc.url.url().contains("/"))) - { - QString filename=rc.url.path(); - if (filename.isEmpty()) filename=rc.url.url(); - QFile f( filename ); - if( !f.open( IO_WriteOnly ) ) { - err = i18n( "Could not open \"%1\"." ).arg( filename ); - } - if (!err) - { - QTextStream stream(&f); - // Export to file - stream << retval; - f.close(); - } - } - else // use remote file - { - KTempFile tmpFile; - if ( tmpFile.status() != 0 ) err = QString::fromLatin1( "Unable to get temporary file" ); - else - { - QTextStream *stream=tmpFile.textStream(); - *stream << retval; - tmpFile.close(); - if (!KIO::NetAccess::upload( tmpFile.name(), rc.url, 0 )) err=QString::fromLatin1("Could not upload"); - } - } - - return err; -} - -//---------------------------------------------------------------------------- -// Routines that handle logging KArm history -// - -// -// public routines: -// - -QString KarmStorage::addTask(const Task* task, const Task* parent) -{ - KCal::Todo* todo; - QString uid; - - todo = new KCal::Todo(); - if ( _calendar->addTodo( todo ) ) - { - task->asTodo( todo ); - if (parent) - todo->setRelatedTo(_calendar->todo(parent->uid())); - uid = todo->uid(); - } - else - { - // Most likely a lock could not be pulled, although there are other - // possiblities (like a really confused resource manager). - uid = ""; - } - - return uid; -} - -bool KarmStorage::removeTask(Task* task) -{ - - // delete history - KCal::Event::List eventList = _calendar->rawEvents(); - for(KCal::Event::List::iterator i = eventList.begin(); - i != eventList.end(); - ++i) - { - //kdDebug(5970) << "KarmStorage::removeTask: " - // << (*i)->uid() << " - relatedToUid() " - // << (*i)->relatedToUid() - // << ", relatedTo() = " << (*i)->relatedTo() <relatedToUid() == task->uid() - || ( (*i)->relatedTo() - && (*i)->relatedTo()->uid() == task->uid())) - { - _calendar->deleteEvent(*i); - } - } - - // delete todo - KCal::Todo *todo = _calendar->todo(task->uid()); - _calendar->deleteTodo(todo); - - // Save entire file - saveCalendar(); - - return true; -} - -void KarmStorage::addComment(const Task* task, const QString& comment) -{ - - KCal::Todo* todo; - - todo = _calendar->todo(task->uid()); - - // Do this to avoid compiler warnings about comment not being used. once we - // transition to using the addComment method, we need this second param. - QString s = comment; - - // TODO: Use libkcal comments - // todo->addComment(comment); - // temporary - todo->setDescription(task->comment()); - - saveCalendar(); -} - -long KarmStorage::printTaskHistory ( - const Task *task, - const QMap &taskdaytotals, - QMap &daytotals, - const QDate &from, - const QDate &to, - const int level, - vector &matrix, - const ReportCriteria &rc) -// to>=from is precondition -{ - long ownline=linenr++; // the how many-th instance of this function is this - long colrectot=0; // colum where to write the task's total recursive time - vector cell; // each line of the matrix is stored in an array of cells, one containing the recursive total - long add; // total recursive time of all subtasks - QString delim = rc.delimiter; - QString dquote = rc.quote; - QString double_dquote = dquote + dquote; - bool to_quote = true; - - const QString cr = QString::fromLatin1("\n"); - QString buf; - QString daytaskkey, daykey; - QDate day; - long sum; - - if ( !task ) return 0; - - day = from; - sum = 0; - while (day <= to) - { - // write the time in seconds for the given task for the given day to s - daykey = day.toString(QString::fromLatin1("yyyyMMdd")); - daytaskkey = QString::fromLatin1("%1_%2") - .arg(daykey) - .arg(task->uid()); - - if (taskdaytotals.contains(daytaskkey)) - { - cell.push_back(QString::fromLatin1("%1") - .arg(formatTime(taskdaytotals[daytaskkey]/60, rc.decimalMinutes))); - sum += taskdaytotals[daytaskkey]; // in seconds - - if (daytotals.contains(daykey)) - daytotals.replace(daykey, daytotals[daykey]+taskdaytotals[daytaskkey]); - else - daytotals.insert(daykey, taskdaytotals[daytaskkey]); - } - cell.push_back(delim); - - day = day.addDays(1); - } - - // Total for task - cell.push_back(QString::fromLatin1("%1").arg(formatTime(sum/60, rc.decimalMinutes))); - - // room for the recursive total time (that cannot be calculated now) - cell.push_back(delim); - colrectot = cell.size(); - cell.push_back("???"); - cell.push_back(delim); - - // Task name - for ( int i = level + 1; i > 0; i-- ) cell.push_back(delim); - - /* - // CSV compliance - // Surround the field with quotes if the field contains - // a comma (delim) or a double quote - to_quote = task->name().contains(delim) || task->name().contains(dquote); - */ - to_quote = true; - if ( to_quote) cell.push_back(dquote); - - - // Double quotes replaced by a pair of consecutive double quotes - cell.push_back(task->name().replace( dquote, double_dquote )); - - if ( to_quote) cell.push_back(dquote); - - cell.push_back(cr); - - add=0; - for (Task* subTask = task->firstChild(); - subTask; - subTask = subTask->nextSibling()) - { - add += printTaskHistory( subTask, taskdaytotals, daytotals, from, to , level+1, matrix, - rc ); - } - cell[colrectot]=(QString::fromLatin1("%1").arg(formatTime((add+sum)/60, rc.decimalMinutes ))); - for (unsigned int i=0; i < cell.size(); i++) matrix[ownline]+=cell[i]; - return add+sum; -} - -QString KarmStorage::report( TaskView *taskview, const ReportCriteria &rc ) -{ - QString err; - if ( rc.reportType == ReportCriteria::CSVHistoryExport ) - err = exportcsvHistory( taskview, rc.from, rc.to, rc ); - else if ( rc.reportType == ReportCriteria::CSVTotalsExport ) - err = exportcsvFile( taskview, rc ); - else - // hmmmm ... assert(0)? - ; - return err; -} - -// export history report as csv, all tasks X all dates in one block -QString KarmStorage::exportcsvHistory ( TaskView *taskview, - const QDate &from, - const QDate &to, - const ReportCriteria &rc) -{ - QString delim = rc.delimiter; - const QString cr = QString::fromLatin1("\n"); - QString err; - - // below taken from timekard.cpp - QString retval; - QString taskhdr, totalhdr; - QString line, buf; - long sum; - - QValueList events; - QValueList::iterator event; - QMap taskdaytotals; - QMap daytotals; - QString daytaskkey, daykey; - QDate day; - QDate dayheading; - - // parameter-plausi - if ( from > to ) - { - err = QString::fromLatin1 ( - "'to' has to be a date later than or equal to 'from'."); - } - - // header - retval += i18n("Task History\n"); - retval += i18n("From %1 to %2") - .arg(KGlobal::locale()->formatDate(from)) - .arg(KGlobal::locale()->formatDate(to)); - retval += cr; - retval += i18n("Printed on: %1") - .arg(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime())); - retval += cr; - - day=from; - events = taskview->getHistory(from, to); - taskdaytotals.clear(); - daytotals.clear(); - - // Build lookup dictionary used to output data in table cells. keys are - // in this format: YYYYMMDD_NNNNNN, where Y = year, M = month, d = day and - // NNNNN = the VTODO uid. The value is the total seconds logged against - // that task on that day. Note the UID is the todo id, not the event id, - // so times are accumulated for each task. - for (event = events.begin(); event != events.end(); ++event) - { - daykey = (*event).start().date().toString(QString::fromLatin1("yyyyMMdd")); - daytaskkey = QString(QString::fromLatin1("%1_%2")) - .arg(daykey) - .arg((*event).todoUid()); - - if (taskdaytotals.contains(daytaskkey)) - taskdaytotals.replace(daytaskkey, - taskdaytotals[daytaskkey] + (*event).duration()); - else - taskdaytotals.insert(daytaskkey, (*event).duration()); - } - - // day headings - dayheading = from; - while ( dayheading <= to ) - { - // Use ISO 8601 format for date. - retval += dayheading.toString(QString::fromLatin1("yyyy-MM-dd")); - retval += delim; - dayheading=dayheading.addDays(1); - } - retval += i18n("Sum") + delim + i18n("Total Sum") + delim + i18n("Task Hierarchy"); - retval += cr; - retval += line; - - // the tasks - vector matrix; - linenr=0; - for (int i=0; i<=taskview->count()+1; i++) matrix.push_back(""); - if (events.empty()) - { - retval += i18n(" No hours logged."); - } - else - { - if ( rc.allTasks ) - { - for ( Task* task= taskview->item_at_index(0); - task; task= task->nextSibling() ) - { - printTaskHistory( task, taskdaytotals, daytotals, from, to, 0, - matrix, rc ); - } - } - else - { - printTaskHistory( taskview->current_item(), taskdaytotals, daytotals, - from, to, 0, matrix, rc ); - } - for (unsigned int i=0; istartTime().secsTo(QDateTime::currentDateTime()); - changeTime(task, delta); -} - -bool KarmStorage::bookTime(const Task* task, - const QDateTime& startDateTime, - const long durationInSeconds) -{ - // Ignores preferences setting re: logging history. - KCal::Event* e; - QDateTime end; - - e = baseEvent( task ); - e->setDtStart( startDateTime ); - e->setDtEnd( startDateTime.addSecs( durationInSeconds ) ); - - // Use a custom property to keep a record of negative durations - e->setCustomProperty( kapp->instanceName(), - QCString("duration"), - QString::number(durationInSeconds)); - - return _calendar->addEvent(e); -} - -void KarmStorage::changeTime(const Task* task, const long deltaSeconds) -{ - KCal::Event* e; - QDateTime end; - - // Don't write events (with timer start/stop duration) if user has turned - // this off in the settings dialog. - if ( ! task->taskView()->preferences()->logging() ) return; - - e = baseEvent(task); - - // Don't use duration, as ICalFormatImpl::writeIncidence never writes a - // duration, even though it looks like it's used in event.cpp. - end = task->startTime(); - if ( deltaSeconds > 0 ) end = task->startTime().addSecs(deltaSeconds); - e->setDtEnd(end); - - // Use a custom property to keep a record of negative durations - e->setCustomProperty( kapp->instanceName(), - QCString("duration"), - QString::number(deltaSeconds)); - - _calendar->addEvent(e); - - // This saves the entire iCal file each time, which isn't efficient but - // ensures no data loss. A faster implementation would be to append events - // to a file, and then when KArm closes, append the data in this file to the - // iCal file. - // - // Meanwhile, we simply use a timer to delay the full-saving until the GUI - // has updated, for better user feedback. Feel free to get rid of this - // if/when implementing the faster saving (DF). - task->taskView()->scheduleSave(); -} - - -KCal::Event* KarmStorage::baseEvent(const Task * task) -{ - KCal::Event* e; - QStringList categories; - - e = new KCal::Event; - e->setSummary(task->name()); - - // Can't use setRelatedToUid()--no error, but no RelatedTo written to disk - e->setRelatedTo(_calendar->todo(task->uid())); - - // Debugging: some events where not getting a related-to field written. - assert(e->relatedTo()->uid() == task->uid()); - - // Have to turn this off to get datetimes in date fields. - e->setFloats(false); - e->setDtStart(task->startTime()); - - // So someone can filter this mess out of their calendar display - categories.append(i18n("KArm")); - e->setCategories(categories); - - return e; -} - -HistoryEvent::HistoryEvent(QString uid, QString name, long duration, - QDateTime start, QDateTime stop, QString todoUid) -{ - _uid = uid; - _name = name; - _duration = duration; - _start = start; - _stop = stop; - _todoUid = todoUid; -} - - -QValueList KarmStorage::getHistory(const QDate& from, - const QDate& to) -{ - QValueList retval; - QStringList processed; - KCal::Event::List events; - KCal::Event::List::iterator event; - QString duration; - - for(QDate d = from; d <= to; d = d.addDays(1)) - { - events = _calendar->rawEventsForDate( d ); - for (event = events.begin(); event != events.end(); ++event) - { - - // KArm events have the custom property X-KDE-Karm-duration - if (! processed.contains( (*event)->uid())) - { - // If an event spans multiple days, CalendarLocal::rawEventsForDate - // will return the same event on both days. To avoid double-counting - // such events, we (arbitrarily) attribute the hours from both days on - // the first day. This mis-reports the actual time spent, but it is - // an easy fix for a (hopefully) rare situation. - processed.append( (*event)->uid()); - - duration = (*event)->customProperty(kapp->instanceName(), - QCString("duration")); - if ( ! duration.isNull() ) - { - if ( (*event)->relatedTo() - && ! (*event)->relatedTo()->uid().isEmpty() ) - { - retval.append(HistoryEvent( - (*event)->uid(), - (*event)->summary(), - duration.toLong(), - (*event)->dtStart(), - (*event)->dtEnd(), - (*event)->relatedTo()->uid() - )); - } - else - // Something is screwy with the ics file, as this KArm history event - // does not have a todo related to it. Could have been deleted - // manually? We'll continue with report on with report ... - kdDebug(5970) << "KarmStorage::getHistory(): " - << "The event " << (*event)->uid() - << " is not related to a todo. Dropped." << endl; - } - } - } - } - - return retval; -} - -bool KarmStorage::remoteResource( const QString& file ) const -{ - QString f = file.lower(); - bool rval = f.startsWith( "http://" ) || f.startsWith( "ftp://" ); - - kdDebug(5970) << "KarmStorage::remoteResource( " << file << " ) returns " << rval << endl; - return rval; -} - -bool KarmStorage::saveCalendar() -{ - kdDebug(5970) << "KarmStorage::saveCalendar" << endl; - - KABC::Lock *lock = _calendar->lock(); - if ( !lock || !lock->lock() ) - return false; - - if ( _calendar && _calendar->save() ) { - lock->unlock(); - return true; - } - - lock->unlock(); - return false; -} diff --git a/ktimetracker/karmstorage.h b/ktimetracker/karmstorage.h deleted file mode 100644 index 8e92d1a478..0000000000 --- a/ktimetracker/karmstorage.h +++ /dev/null @@ -1,371 +0,0 @@ -/* - * This file only: - * Copyright (C) 2003 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ - -#ifndef KARM_STORAGE_H -#define KARM_STORAGE_H - -#include -#include - -#include "journal.h" -#include "reportcriteria.h" - -#include "desktoplist.h" - -#include -#include -#include "resourcecalendar.h" -#include - -class QDateTime; -class Preferences; -class Task; -class TaskView; -class HistoryEvent; -class KCal::Todo; - -/** - * Singleton to store/retrieve KArm data to/from persistent storage. - * - * The storage is an iCalendar file. Also included are methods to - * import KArm data from the two legacy file formats. - * - * All logic that deals with getting and saving data should go here. The - * storage logic has changed at least twice already in KArm's history, and - * chances are good it will change again (for example, allowing KOrganizer and - * KArm to access the same iCalendar file simultaneously). - * - * Prior to KDE 3.2, KArm just stored totals for each task--a session total - * and a task total. The session total was reset to zero each time KArm - * started up or after the user reset the session times to zero. With the - * release of KDE 3.2, KArm now stores these task totals as well as logging - * the history of each start/stop event; that is, every time you start a timer - * and then stop a timer on a task, KArm records this as an iCalendar event. - * - * @short Logic that gets and stores KArm data to disk. - * @author Mark Bucciarelli - */ - -class KarmStorage -{ - public: - /* - * Return reference to storage singleton. - * - * The constructors are private, so this must be used to create a - * KarmStorage instance. - */ - static KarmStorage *instance(); - - /* - * Load the list view with tasks read from iCalendar file. - * - * Parses iCalendar file, builds list view items in the proper - * hierarchy, and loads them into the list view widget. - * - * If the file name passed in is the same as the last file name that was - * loaded, this method does nothing. - * - * This method considers any of the following conditions errors: - * - * @li the iCalendar file does not exist - * @li the iCalendar file is not readable - * @li the list group currently has list items - * @li an iCalendar todo has no related to attribute - * @li a todo is related to another todo which does not exist - * - * @param taskview The list group used in the TaskView - * @param preferences The current KArm preferences. - * @param fileName Override preferences' filename - * - * @return empty string if success, error message if error. - * - */ - QString load(TaskView* taskview, const Preferences* preferences, QString fileName="" ); - - QString buildTaskView(KCal::ResourceCalendar *rc, TaskView *view); - - /* Close calendar and clear view. Release lock if holding one. */ - void closeStorage(TaskView* view); - - /* - * Save all tasks and their totals to an iCalendar file. - * - * All tasks must have an associated VTODO object already created in the - * calendar file; that is, the task->uid() must refer to a valid VTODO in - * the calender. - * Delivers empty string if successful, else error msg. - * - * @param taskview The list group used in the TaskView - */ - QString save(TaskView* taskview); - - /** - * Read tasks and their total times from a text file (legacy storage). - * - * This reads from one of the two legacy file formats. In this version, - * the parent task times do not include the sum of all their children's - * times. - * - * The format of the file is zero or more lines of: - * 1 task id (a number) - * time in minutes - * string task name - * [string] desktops, in which to count. e.g. "1,2,5" (optional) - */ - QString loadFromFlatFile(TaskView* taskview, const QString& filename); - - /** - * Reads tasks and their total times from text file (legacy). - * - * This is the older legacy format, where the task totals included the - * children totals. - * - * @see loadFromFlatFile - */ - QString loadFromFlatFileCumulative(TaskView* taskview, - const QString& filename); - - /** - Output a report based on contents of ReportCriteria. - */ - QString report( TaskView *taskview, const ReportCriteria &rc ); - - /* - * Log the change in a task's time. - * - * We create an iCalendar event to store each change. The event start - * date is set to the current datetime. If time is added to the task, the - * task end date is set to start time + delta. If the time is negative, - * the end date is set to the start time. - * - * In both cases (postive or negative delta), we create a custom iCalendar - * property that stores the delta (in seconds). This property is called - * X-KDE-karm-duration. - * - * Note that the KArm UI allows the user to change both the session and - * the total task time, and this routine does not account for all posibile - * cases. For example, it is possible for the user to do something crazy - * like add 10 minutes to the session time and subtract 50 minutes from - * the total time. Although this change violates a basic law of physics, - * it is allowed. - * - * For now, you should pass in the change to the total task time. - * Eventually, the UI should be changed. - * - * @param task The task the change is for. - * @param delta Change in task time, in seconds. Can be negative. - */ - void changeTime(const Task* task, const long deltaSeconds); - - /** - * Book time to a task. - * - * Creates an iCalendar event and adds it to the calendar. Does not write - * calender to disk, just adds event to calendar in memory. However, the - * resource framework does try to get a lock on the file. After a - * succesful lock, the calendar marks this incidence as modified and then - * releases the lock. - * - * @param task Task - * @param startDateTime Date and time the booking starts. - * @param durationInSeconds Duration of time to book, in seconds. - * - * @return true if event was added, false if not (if, for example, the - * attempted file lock failed). - */ - bool bookTime(const Task* task, const QDateTime& startDateTime, - long durationInSeconds); - - /** - * Log a change to a task name. - * - * For iCalendar storage, there is no need to log an Event for this event, - * since unique id's are used to link Events to Todos. No matter how many - * times you change a task's name, the uid stays the same. - * - * @param task The task - * @param oldname The old name of the task. The new name is in the task - * object already. - */ - void setName(const Task* task, const QString& oldname) { Q_UNUSED(task); Q_UNUSED(oldname); } - - - /** - * Log the event that a timer has started for a task. - * - * For the iCalendar storage, there is no need to log anything for this - * event. We log an event when the timer is stopped. - * - * @param task The task the timer was started for. - */ - void startTimer(const Task* task) { Q_UNUSED(task); } - - /** - * Log the event that the timer has stopped for this task. - * - * The task stores the last time a timer was started, so we log a new iCal - * Event with the start and end times for this task. - * @see KarmStorage::changeTime - * - * @param task The task the timer was stopped for. - */ - void stopTimer(const Task* task); - - /** - * Log a new comment for this task. - * - * iCal allows multiple comment tags. So we just add a new comment to the - * todo for this task and write the calendar. - * - * @param task The task that gets the comment - * @param comment The comment - */ - void addComment(const Task* task, const QString& comment); - - - /** - * Remove this task from iCalendar file. - * - * Removes task as well as all event history for this task. - * - * @param task The task to be removed. - * @return true if change was saved, false otherwise - */ - bool removeTask(Task* task); - - /** - * Add this task from iCalendar file. - * - * Create a new KCal::Todo object and load with task information. If - * parent is not zero, then set the RELATED-TO attribute for this Todo. - * - * @param task The task to be removed. - * @param parent The parent of this task. Must have a uid() that is in - * the existing calendar. If zero, this task is considered a root task. - * @return The unique ID for the new VTODO. Return an null QString if - * there was an error creating the new calendar object. - */ - QString addTask(const Task* task, const Task* parent); - - /** - * Check if the iCalendar file currently loaded has any Todos in it. - * - * @return true if iCalendar file has any todos - */ - bool isEmpty(); - - /** - * Check if iCalendar file name in the preferences has changed since the - * last call to load. If there is no calendar file currently loaded, - * return false. - * - * @param preferences Set of KArm preferences. - * - * @return true if a previous file has been loaded and the iCalendar file - * specified in the preferences is different. - */ - bool isNewStorage(const Preferences* preferences) const; - - /** Return a list of start/stop events for the given date range. */ - QValueList getHistory(const QDate& from, const QDate& to); - - private: - static KarmStorage *_instance; - KCal::ResourceCalendar *_calendar; - QString _icalfile; - - KarmStorage(); - void adjustFromLegacyFileFormat(Task* task); - bool parseLine(QString line, long *time, QString *name, int *level, - DesktopList* desktopList); - QString writeTaskAsTodo - (Task* task, const int level, QPtrStack< KCal::Todo >& parents); - bool saveCalendar(); - - KCal::Event* baseEvent(const Task*); - bool remoteResource( const QString& file ) const; - - /** - * Writes all tasks and their totals to a Comma-Separated Values file. - * - * The format of this file is zero or more lines of: - * taskName,subtaskName,..,sessionTime,time,totalSessionTime,totalTime - * the number of subtasks is determined at runtime. - */ - QString exportcsvFile( TaskView *taskview, const ReportCriteria &rc ); - - /** - * Write task history to file as comma-delimited data. - */ - QString exportcsvHistory ( - TaskView* taskview, - const QDate& from, - const QDate& to, - const ReportCriteria &rc - ); - - long printTaskHistory ( - const Task *task, - const QMap& taskdaytotals, - QMap& daytotals, - const QDate& from, - const QDate& to, - const int level, - std::vector &matrix, - const ReportCriteria &rc - ); -}; - -/** - * One start/stop event that has been logged. - * - * When a task is running and the user stops it, KArm logs this event and - * saves it in the history. This class represents such an event read from - * storage, and abstracts it from the specific storage used. - */ -class HistoryEvent -{ - public: - /** Needed to be used in a value list. */ - HistoryEvent() {} - HistoryEvent(QString uid, QString name, long duration, - QDateTime start, QDateTime stop, QString todoUid); - QString uid() {return _uid; } - QString name() {return _name; } - /** In seconds. */ - long duration() {return _duration; } - QDateTime start() {return _start; } - QDateTime stop() { return _stop; } - QString todoUid() {return _todoUid; } - - private: - QString _uid; - QString _todoUid; - QString _name; - long _duration; - QDateTime _start; - QDateTime _stop; - -}; - -#endif // KARM_STORAGE_H diff --git a/ktimetracker/karmui.rc b/ktimetracker/karmui.rc deleted file mode 100644 index d47608edb6..0000000000 --- a/ktimetracker/karmui.rc +++ /dev/null @@ -1,81 +0,0 @@ - - - - &File - - - - - &Import/Export - - - - - - - - - - &Clock - - - - - - &Task - - - - - - - - - - - &Settings - - - - - Main Toolbar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ktimetracker/ktimewidget.cpp b/ktimetracker/ktimewidget.cpp deleted file mode 100644 index 65f41c2ee6..0000000000 --- a/ktimetracker/ktimewidget.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include -#include -#include -#include "ktimewidget.h" -#include -#include - -enum ValidatorType { HOUR, MINUTE }; - -class TimeValidator :public QValidator -{ -public: - TimeValidator(ValidatorType tp, QWidget *parent=0, const char *name=0) :QValidator(parent, name) - { - _tp = tp; - } - State validate(QString &str, int &) const - { - if (str.isEmpty()) - return Acceptable; - - bool ok; - int val = str.toInt( &ok ); - if ( ! ok ) - return Invalid; - - if ( str.contains('-') != 0 ) - return Invalid; - - if ( _tp==MINUTE && val >= 60 ) - return Invalid; - else - return Acceptable; - } - -public: - ValidatorType _tp; -}; - - -class KarmLineEdit :public QLineEdit -{ - -public: - KarmLineEdit( QWidget* parent, const char* name = 0 ) :QLineEdit( parent, name ) - { - } - -protected: - - virtual void keyPressEvent( QKeyEvent *event ) { - QLineEdit::keyPressEvent( event ); - if ( text().length() == 2 && !event->text().isNull() ) - focusNextPrevChild(true); - } -}; - - - - -KTimeWidget::KTimeWidget( QWidget* parent, const char* name ) : QWidget(parent, name) -{ - QHBoxLayout *layout = new QHBoxLayout(this); - - _hourLE = new QLineEdit( this); - - _hourLE->setFixedWidth(fontMetrics().maxWidth()*5); - layout->addWidget(_hourLE); - TimeValidator *validator = new TimeValidator( HOUR, _hourLE, "Validator for _hourLE"); - _hourLE->setValidator( validator ); - _hourLE->setAlignment( Qt::AlignRight ); - - - QLabel *dot = new QLabel(QString::fromLatin1( " : " ), this); - layout->addWidget(dot); - - _minuteLE = new KarmLineEdit(this); - - _minuteLE->setFixedWidth(fontMetrics().maxWidth()*2); - layout->addWidget(_minuteLE); - validator = new TimeValidator( MINUTE, _minuteLE, "Validator for _minuteLE"); - _minuteLE->setValidator( validator ); - _minuteLE->setMaxLength(2); - _minuteLE->setAlignment( Qt::AlignRight ); - - layout->addStretch(1); - setFocusProxy( _hourLE ); -} - -void KTimeWidget::setTime( int hour, int minute ) -{ - QString dummy; - - dummy.setNum( hour ); - _hourLE->setText( dummy ); - - dummy.setNum( minute ); - if (minute < 10 ) { - dummy = QString::fromLatin1( "0" ) + dummy; - } - _minuteLE->setText( dummy ); -} - -long KTimeWidget::time() const -{ - bool ok; - return _hourLE->text().toInt( &ok ) * 60 + _minuteLE->text().toInt( &ok ); -} diff --git a/ktimetracker/ktimewidget.h b/ktimetracker/ktimewidget.h deleted file mode 100644 index d778f5588a..0000000000 --- a/ktimetracker/ktimewidget.h +++ /dev/null @@ -1,20 +0,0 @@ - -#ifndef KTIMEWIDGET_H_ -#define KTIMEWIDGET_H_ - -class QLineEdit; -class KarmLineEdit; - -class KTimeWidget :public QWidget -{ -public: - KTimeWidget( QWidget* parent = 0, const char* name = 0 ); - void setTime( int hour, int minute ); - long time() const; - -private: - QLineEdit *_hourLE; - KarmLineEdit *_minuteLE; -}; - -#endif diff --git a/ktimetracker/main.cpp b/ktimetracker/main.cpp deleted file mode 100644 index eef6184d29..0000000000 --- a/ktimetracker/main.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include -#include -#include -#include "version.h" -#include "top.h" - - -static const char *description = - I18N_NOOP("KDE Time tracker tool."); - - -int main( int argc, char *argv[] ) -{ - KAboutData aboutData( "karm", I18N_NOOP("KArm"), - KARM_VERSION, description, KAboutData::License_GPL, - "(c) 1997-2000, Sirtaj Singh Kang, Espen Sand, Jesper Pedersen,\nKalle Dalheimer, Klarlvdalens Datakonsult AB"); - aboutData.addAuthor( "Jesper Pedersen", I18N_NOOP("Current Maintainer"), "blackie@kde.org" ); - aboutData.addAuthor( "Sirtaj Singh Kang", I18N_NOOP("Original Author"), "taj@kde.org" ); - aboutData.addAuthor("Espen Sand",0, "espen@kde.org"); - aboutData.addAuthor( "Kalle Dalheimer", 0, "kalle@kde.org" ); - - KCmdLineArgs::init( argc, argv, &aboutData ); - KApplication myApp; - - KarmWindow *karm = new KarmWindow; - - myApp.setMainWidget( karm ); - karm->show(); - - int ret = myApp.exec(); - - return ret; -} diff --git a/ktimetracker/mainwindow.cpp b/ktimetracker/mainwindow.cpp deleted file mode 100644 index 79427f2a48..0000000000 --- a/ktimetracker/mainwindow.cpp +++ /dev/null @@ -1,721 +0,0 @@ -/* -* Top Level window for KArm. -* Distributed under the GPL. -*/ - -#include - -#include "kaccelmenuwatch.h" -#include -#include -#include -#include // kapp -#include -#include -#include -#include -#include // i18n -#include -#include // statusBar() -#include -#include -#include -#include -#include - -#include "karmerrors.h" -#include "karmutility.h" -#include "mainwindow.h" -#include "preferences.h" -#include "print.h" -#include "task.h" -#include "taskview.h" -#include "timekard.h" -#include "tray.h" -#include "version.h" - -MainWindow::MainWindow( const QString &icsfile ) - : DCOPObject ( "KarmDCOPIface" ), - KParts::MainWindow(), - _accel ( new KAccel( this ) ), - _watcher ( new KAccelMenuWatch( _accel, this ) ), - _totalSum ( 0 ), - _sessionSum( 0 ) -{ - - _taskView = new TaskView( this, 0, icsfile ); - - setCentralWidget( _taskView ); - // status bar - startStatusBar(); - - // setup PreferenceDialog. - _preferences = Preferences::instance(); - - // popup menus - makeMenus(); - _watcher->updateMenus(); - - // connections - connect( _taskView, SIGNAL( totalTimesChanged( long, long ) ), - this, SLOT( updateTime( long, long ) ) ); - connect( _taskView, SIGNAL( selectionChanged ( QListViewItem * )), - this, SLOT(slotSelectionChanged())); - connect( _taskView, SIGNAL( updateButtons() ), - this, SLOT(slotSelectionChanged())); - - loadGeometry(); - - // Setup context menu request handling - connect( _taskView, - SIGNAL( contextMenuRequested( QListViewItem*, const QPoint&, int )), - this, - SLOT( contextMenuRequest( QListViewItem*, const QPoint&, int ))); - - _tray = new KarmTray( this ); - - connect( _tray, SIGNAL( quitSelected() ), SLOT( quit() ) ); - - connect( _taskView, SIGNAL( timersActive() ), _tray, SLOT( startClock() ) ); - connect( _taskView, SIGNAL( timersActive() ), this, SLOT( enableStopAll() )); - connect( _taskView, SIGNAL( timersInactive() ), _tray, SLOT( stopClock() ) ); - connect( _taskView, SIGNAL( timersInactive() ), this, SLOT( disableStopAll())); - connect( _taskView, SIGNAL( tasksChanged( QPtrList ) ), - _tray, SLOT( updateToolTip( QPtrList ) )); - - _taskView->load(); - - // Everything that uses Preferences has been created now, we can let it - // emit its signals - _preferences->emitSignals(); - slotSelectionChanged(); - - // Register with DCOP - if ( !kapp->dcopClient()->isRegistered() ) - { - kapp->dcopClient()->registerAs( "karm" ); - kapp->dcopClient()->setDefaultObject( objId() ); - } - - // Set up DCOP error messages - m_error[ KARM_ERR_GENERIC_SAVE_FAILED ] = - i18n( "Save failed, most likely because the file could not be locked." ); - m_error[ KARM_ERR_COULD_NOT_MODIFY_RESOURCE ] = - i18n( "Could not modify calendar resource." ); - m_error[ KARM_ERR_MEMORY_EXHAUSTED ] = - i18n( "Out of memory--could not create object." ); - m_error[ KARM_ERR_UID_NOT_FOUND ] = - i18n( "UID not found." ); - m_error[ KARM_ERR_INVALID_DATE ] = - i18n( "Invalidate date--format is YYYY-MM-DD." ); - m_error[ KARM_ERR_INVALID_TIME ] = - i18n( "Invalid time--format is YYYY-MM-DDTHH:MM:SS." ); - m_error[ KARM_ERR_INVALID_DURATION ] = - i18n( "Invalid task duration--must be greater than zero." ); -} - -void MainWindow::slotSelectionChanged() -{ - Task* item= _taskView->current_item(); - actionDelete->setEnabled(item); - actionEdit->setEnabled(item); - actionStart->setEnabled(item && !item->isRunning() && !item->isComplete()); - actionStop->setEnabled(item && item->isRunning()); - actionMarkAsComplete->setEnabled(item && !item->isComplete()); - actionMarkAsIncomplete->setEnabled(item && item->isComplete()); -} - -// This is _old_ code, but shows how to enable/disable add comment menu item. -// We'll need this kind of logic when comments are implemented. -//void MainWindow::timeLoggingChanged(bool on) -//{ -// actionAddComment->setEnabled( on ); -//} - -bool MainWindow::save() -{ - kdDebug(5970) << "Saving time data to disk." << endl; - QString err=_taskView->save(); // untranslated error msg. - if (err.isEmpty()) statusBar()->message(i18n("Successfully saved tasks and history"),1807); - else statusBar()->message(i18n(err.ascii()),7707); // no msgbox since save is called when exiting - saveGeometry(); - return true; -} - -void MainWindow::exportcsvHistory() -{ - kdDebug(5970) << "Exporting History to disk." << endl; - QString err=_taskView->exportcsvHistory(); - if (err.isEmpty()) statusBar()->message(i18n("Successfully exported History to CSV-file"),1807); - else KMessageBox::error(this, err.ascii()); - saveGeometry(); - -} - -void MainWindow::quit() -{ - kapp->quit(); -} - - -MainWindow::~MainWindow() -{ - kdDebug(5970) << "MainWindow::~MainWindows: Quitting karm." << endl; - _taskView->stopAllTimers(); - save(); - _taskView->closeStorage(); -} - -void MainWindow::enableStopAll() -{ - actionStopAll->setEnabled(true); -} - -void MainWindow::disableStopAll() -{ - actionStopAll->setEnabled(false); -} - - -/** - * Calculate the sum of the session time and the total time for all - * toplevel tasks and put it in the statusbar. - */ - -void MainWindow::updateTime( long sessionDiff, long totalDiff ) -{ - _sessionSum += sessionDiff; - _totalSum += totalDiff; - - updateStatusBar(); -} - -void MainWindow::updateStatusBar( ) -{ - QString time; - - time = formatTime( _sessionSum ); - statusBar()->changeItem( i18n("Session: %1").arg(time), 0 ); - - time = formatTime( _totalSum ); - statusBar()->changeItem( i18n("Total: %1" ).arg(time), 1); -} - -void MainWindow::startStatusBar() -{ - statusBar()->insertItem( i18n("Session"), 0, 0, true ); - statusBar()->insertItem( i18n("Total" ), 1, 0, true ); -} - -void MainWindow::saveProperties( KConfig* cfg ) -{ - _taskView->stopAllTimers(); - _taskView->save(); - cfg->writeEntry( "WindowShown", isVisible()); -} - -void MainWindow::readProperties( KConfig* cfg ) -{ - if( cfg->readBoolEntry( "WindowShown", true )) - show(); -} - -void MainWindow::keyBindings() -{ - KKeyDialog::configure( actionCollection(), this ); -} - -void MainWindow::startNewSession() -{ - _taskView->startNewSession(); -} - -void MainWindow::resetAllTimes() -{ - if ( KMessageBox::warningContinueCancel( this, i18n( "Do you really want to reset the time to zero for all tasks?" ), - i18n( "Confirmation Required" ), KGuiItem( i18n( "Reset All Times" ) ) ) == KMessageBox::Continue ) - _taskView->resetTimeForAllTasks(); -} - -void MainWindow::makeMenus() -{ - KAction - *actionKeyBindings, - *actionNew, - *actionNewSub; - - (void) KStdAction::quit( this, SLOT( quit() ), actionCollection()); - (void) KStdAction::print( this, SLOT( print() ), actionCollection()); - actionKeyBindings = KStdAction::keyBindings( this, SLOT( keyBindings() ), - actionCollection() ); - actionPreferences = KStdAction::preferences(_preferences, - SLOT(showDialog()), - actionCollection() ); - (void) KStdAction::save( this, SLOT( save() ), actionCollection() ); - KAction* actionStartNewSession = new KAction( i18n("Start &New Session"), - 0, - this, - SLOT( startNewSession() ), - actionCollection(), - "start_new_session"); - KAction* actionResetAll = new KAction( i18n("&Reset All Times"), - 0, - this, - SLOT( resetAllTimes() ), - actionCollection(), - "reset_all_times"); - actionStart = new KAction( i18n("&Start"), - QString::fromLatin1("1rightarrow"), Key_S, - _taskView, - SLOT( startCurrentTimer() ), actionCollection(), - "start"); - actionStop = new KAction( i18n("S&top"), - QString::fromLatin1("stop"), 0, - _taskView, - SLOT( stopCurrentTimer() ), actionCollection(), - "stop"); - actionStopAll = new KAction( i18n("Stop &All Timers"), - Key_Escape, - _taskView, - SLOT( stopAllTimers() ), actionCollection(), - "stopAll"); - actionStopAll->setEnabled(false); - - actionNew = new KAction( i18n("&New..."), - QString::fromLatin1("filenew"), CTRL+Key_N, - _taskView, - SLOT( newTask() ), actionCollection(), - "new_task"); - actionNewSub = new KAction( i18n("New &Subtask..."), - QString::fromLatin1("kmultiple"), CTRL+ALT+Key_N, - _taskView, - SLOT( newSubTask() ), actionCollection(), - "new_sub_task"); - actionDelete = new KAction( i18n("&Delete"), - QString::fromLatin1("editdelete"), Key_Delete, - _taskView, - SLOT( deleteTask() ), actionCollection(), - "delete_task"); - actionEdit = new KAction( i18n("&Edit..."), - QString::fromLatin1("edit"), CTRL + Key_E, - _taskView, - SLOT( editTask() ), actionCollection(), - "edit_task"); -// actionAddComment = new KAction( i18n("&Add Comment..."), -// QString::fromLatin1("document"), -// CTRL+ALT+Key_E, -// _taskView, -// SLOT( addCommentToTask() ), -// actionCollection(), -// "add_comment_to_task"); - actionMarkAsComplete = new KAction( i18n("&Mark as Complete"), - QString::fromLatin1("document"), - CTRL+Key_M, - _taskView, - SLOT( markTaskAsComplete() ), - actionCollection(), - "mark_as_complete"); - actionMarkAsIncomplete = new KAction( i18n("&Mark as Incomplete"), - QString::fromLatin1("document"), - CTRL+Key_M, - _taskView, - SLOT( markTaskAsIncomplete() ), - actionCollection(), - "mark_as_incomplete"); - actionClipTotals = new KAction( i18n("&Copy Totals to Clipboard"), - QString::fromLatin1("klipper"), - CTRL+Key_C, - _taskView, - SLOT( clipTotals() ), - actionCollection(), - "clip_totals"); - actionClipHistory = new KAction( i18n("Copy &History to Clipboard"), - QString::fromLatin1("klipper"), - CTRL+ALT+Key_C, - _taskView, - SLOT( clipHistory() ), - actionCollection(), - "clip_history"); - - new KAction( i18n("Import &Legacy Flat File..."), 0, - _taskView, SLOT(loadFromFlatFile()), actionCollection(), - "import_flatfile"); - new KAction( i18n("&Export to CSV File..."), 0, - _taskView, SLOT(exportcsvFile()), actionCollection(), - "export_csvfile"); - new KAction( i18n("Export &History to CSV File..."), 0, - this, SLOT(exportcsvHistory()), actionCollection(), - "export_csvhistory"); - new KAction( i18n("Import Tasks From &Planner..."), 0, - _taskView, SLOT(importPlanner()), actionCollection(), - "import_planner"); - -/* - new KAction( i18n("Import E&vents"), 0, - _taskView, - SLOT( loadFromKOrgEvents() ), actionCollection(), - "import_korg_events"); - */ - - setXMLFile( QString::fromLatin1("karmui.rc") ); - createGUI( 0 ); - - // Tool tips must be set after the createGUI. - actionKeyBindings->setToolTip( i18n("Configure key bindings") ); - actionKeyBindings->setWhatsThis( i18n("This will let you configure key" - "bindings which is specific to karm") ); - - actionStartNewSession->setToolTip( i18n("Start a new session") ); - actionStartNewSession->setWhatsThis( i18n("This will reset the session time " - "to 0 for all tasks, to start a " - "new session, without affecting " - "the totals.") ); - actionResetAll->setToolTip( i18n("Reset all times") ); - actionResetAll->setWhatsThis( i18n("This will reset the session and total " - "time to 0 for all tasks, to restart from " - "scratch.") ); - - actionStart->setToolTip( i18n("Start timing for selected task") ); - actionStart->setWhatsThis( i18n("This will start timing for the selected " - "task.\n" - "It is even possible to time several tasks " - "simultaneously.\n\n" - "You may also start timing of a tasks by " - "double clicking the left mouse " - "button on a given task. This will, however, " - "stop timing of other tasks.")); - - actionStop->setToolTip( i18n("Stop timing of the selected task") ); - actionStop->setWhatsThis( i18n("Stop timing of the selected task") ); - - actionStopAll->setToolTip( i18n("Stop all of the active timers") ); - actionStopAll->setWhatsThis( i18n("Stop all of the active timers") ); - - actionNew->setToolTip( i18n("Create new top level task") ); - actionNew->setWhatsThis( i18n("This will create a new top level task.") ); - - actionDelete->setToolTip( i18n("Delete selected task") ); - actionDelete->setWhatsThis( i18n("This will delete the selected task and " - "all its subtasks.") ); - - actionEdit->setToolTip( i18n("Edit name or times for selected task") ); - actionEdit->setWhatsThis( i18n("This will bring up a dialog box where you " - "may edit the parameters for the selected " - "task.")); - //actionAddComment->setToolTip( i18n("Add a comment to a task") ); - //actionAddComment->setWhatsThis( i18n("This will bring up a dialog box where " - // "you can add a comment to a task. The " - // "comment can for instance add information on what you " - // "are currently doing. The comment will " - // "be logged in the log file.")); - actionClipTotals->setToolTip(i18n("Copy task totals to clipboard")); - actionClipHistory->setToolTip(i18n("Copy time card history to clipboard.")); - - slotSelectionChanged(); -} - -void MainWindow::print() -{ - MyPrinter printer(_taskView); - printer.print(); -} - -void MainWindow::loadGeometry() -{ - if (initialGeometrySet()) setAutoSaveSettings(); - else - { - KConfig &config = *kapp->config(); - - config.setGroup( QString::fromLatin1("Main Window Geometry") ); - int w = config.readNumEntry( QString::fromLatin1("Width"), 100 ); - int h = config.readNumEntry( QString::fromLatin1("Height"), 100 ); - w = QMAX( w, sizeHint().width() ); - h = QMAX( h, sizeHint().height() ); - resize(w, h); - } -} - - -void MainWindow::saveGeometry() -{ - KConfig &config = *KGlobal::config(); - config.setGroup( QString::fromLatin1("Main Window Geometry")); - config.writeEntry( QString::fromLatin1("Width"), width()); - config.writeEntry( QString::fromLatin1("Height"), height()); - config.sync(); -} - -bool MainWindow::queryClose() -{ - if ( !kapp->sessionSaving() ) { - hide(); - return false; - } - return KMainWindow::queryClose(); -} - -void MainWindow::contextMenuRequest( QListViewItem*, const QPoint& point, int ) -{ - QPopupMenu* pop = dynamic_cast( - factory()->container( i18n( "task_popup" ), this ) ); - if ( pop ) - pop->popup( point ); -} - -//---------------------------------------------------------------------------- -// -// D C O P I N T E R F A C E -// -//---------------------------------------------------------------------------- - -QString MainWindow::version() const -{ - return KARM_VERSION; -} - -QString MainWindow::deletetodo() -{ - _taskView->deleteTask(); - return ""; -} - -bool MainWindow::getpromptdelete() -{ - return _preferences->promptDelete(); -} - -QString MainWindow::setpromptdelete( bool prompt ) -{ - _preferences->setPromptDelete( prompt ); - return ""; -} - -QString MainWindow::taskIdFromName( const QString &taskname ) const -{ - QString rval = ""; - - Task* task = _taskView->first_child(); - while ( rval.isEmpty() && task ) - { - rval = _hasTask( task, taskname ); - task = task->nextSibling(); - } - - return rval; -} - -int MainWindow::addTask( const QString& taskname ) -{ - DesktopList desktopList; - QString uid = _taskView->addTask( taskname, 0, 0, desktopList ); - kdDebug(5970) << "MainWindow::addTask( " << taskname << " ) returns " << uid << endl; - if ( uid.length() > 0 ) return 0; - else - { - // We can't really tell what happened, b/c the resource framework only - // returns a boolean. - return KARM_ERR_GENERIC_SAVE_FAILED; - } -} - -QString MainWindow::setPerCentComplete( const QString& taskName, int perCent ) -{ - int index; - QString err="no such task"; - for (int i=0; i<_taskView->count(); i++) - { - if ((_taskView->item_at_index(i)->name()==taskName)) - { - index=i; - if (err==QString::null) err="task name is abigious"; - if (err=="no such task") err=QString::null; - } - } - if (err==QString::null) - { - _taskView->item_at_index(index)->setPercentComplete( perCent, _taskView->storage() ); - } - return err; -} - -int MainWindow::bookTime -( const QString& taskId, const QString& datetime, long minutes ) -{ - int rval = 0; - QDate startDate; - QTime startTime; - QDateTime startDateTime; - Task *task, *t; - - if ( minutes <= 0 ) rval = KARM_ERR_INVALID_DURATION; - - // Find task - task = _taskView->first_child(); - t = NULL; - while ( !t && task ) - { - t = _hasUid( task, taskId ); - task = task->nextSibling(); - } - if ( t == NULL ) rval = KARM_ERR_UID_NOT_FOUND; - - // Parse datetime - if ( !rval ) - { - startDate = QDate::fromString( datetime, Qt::ISODate ); - if ( datetime.length() > 10 ) // "YYYY-MM-DD".length() = 10 - { - startTime = QTime::fromString( datetime, Qt::ISODate ); - } - else startTime = QTime( 12, 0 ); - if ( startDate.isValid() && startTime.isValid() ) - { - startDateTime = QDateTime( startDate, startTime ); - } - else rval = KARM_ERR_INVALID_DATE; - - } - - // Update task totals (session and total) and save to disk - if ( !rval ) - { - t->changeTotalTimes( t->sessionTime() + minutes, t->totalTime() + minutes ); - if ( ! _taskView->storage()->bookTime( t, startDateTime, minutes * 60 ) ) - { - rval = KARM_ERR_GENERIC_SAVE_FAILED; - } - } - - return rval; -} - -// There was something really bad going on with DCOP when I used a particular -// argument name; if I recall correctly, the argument name was errno. -QString MainWindow::getError( int mkb ) const -{ - if ( mkb <= KARM_MAX_ERROR_NO ) return m_error[ mkb ]; - else return i18n( "Invalid error number: %1" ).arg( mkb ); -} - -int MainWindow::totalMinutesForTaskId( const QString& taskId ) -{ - int rval = 0; - Task *task, *t; - - kdDebug(5970) << "MainWindow::totalTimeForTask( " << taskId << " )" << endl; - - // Find task - task = _taskView->first_child(); - t = NULL; - while ( !t && task ) - { - t = _hasUid( task, taskId ); - task = task->nextSibling(); - } - if ( t != NULL ) - { - rval = t->totalTime(); - kdDebug(5970) << "MainWindow::totalTimeForTask - task found: rval = " << rval << endl; - } - else - { - kdDebug(5970) << "MainWindow::totalTimeForTask - task not found" << endl; - rval = KARM_ERR_UID_NOT_FOUND; - } - - return rval; -} - -QString MainWindow::_hasTask( Task* task, const QString &taskname ) const -{ - QString rval = ""; - if ( task->name() == taskname ) - { - rval = task->uid(); - } - else - { - Task* nexttask = task->firstChild(); - while ( rval.isEmpty() && nexttask ) - { - rval = _hasTask( nexttask, taskname ); - nexttask = nexttask->nextSibling(); - } - } - return rval; -} - -Task* MainWindow::_hasUid( Task* task, const QString &uid ) const -{ - Task *rval = NULL; - - //kdDebug(5970) << "MainWindow::_hasUid( " << task << ", " << uid << " )" << endl; - - if ( task->uid() == uid ) rval = task; - else - { - Task* nexttask = task->firstChild(); - while ( !rval && nexttask ) - { - rval = _hasUid( nexttask, uid ); - nexttask = nexttask->nextSibling(); - } - } - return rval; -} -QString MainWindow::starttimerfor( const QString& taskname ) -{ - int index; - QString err="no such task"; - for (int i=0; i<_taskView->count(); i++) - { - if ((_taskView->item_at_index(i)->name()==taskname)) - { - index=i; - if (err==QString::null) err="task name is abigious"; - if (err=="no such task") err=QString::null; - } - } - if (err==QString::null) _taskView->startTimerFor( _taskView->item_at_index(index) ); - return err; -} - -QString MainWindow::stoptimerfor( const QString& taskname ) -{ - int index; - QString err="no such task"; - for (int i=0; i<_taskView->count(); i++) - { - if ((_taskView->item_at_index(i)->name()==taskname)) - { - index=i; - if (err==QString::null) err="task name is abigious"; - if (err=="no such task") err=QString::null; - } - } - if (err==QString::null) _taskView->stopTimerFor( _taskView->item_at_index(index) ); - return err; -} - -QString MainWindow::exportcsvfile( QString filename, QString from, QString to, int type, bool decimalMinutes, bool allTasks, QString delimiter, QString quote ) -{ - ReportCriteria rc; - rc.allTasks=allTasks; - rc.decimalMinutes=decimalMinutes; - rc.delimiter=delimiter; - rc.from=QDate::fromString( from ); - rc.quote=quote; - rc.reportType=(ReportCriteria::REPORTTYPE) type; - rc.to=QDate::fromString( to ); - rc.url=filename; - return _taskView->report( rc ); -} - -QString MainWindow::importplannerfile( QString fileName ) -{ - return _taskView->importPlanner(fileName); -} - - -#include "mainwindow.moc" diff --git a/ktimetracker/mainwindow.h b/ktimetracker/mainwindow.h deleted file mode 100644 index 1899e11da4..0000000000 --- a/ktimetracker/mainwindow.h +++ /dev/null @@ -1,114 +0,0 @@ -#ifndef KARM_MAIN_WINDOW_H -#define KARM_MAIN_WINDOW_H - -#include - -#include "karmerrors.h" -#include -#include "reportcriteria.h" - -class KAccel; -class KAccelMenuWatch; -class KarmTray; -class QListViewItem; -class QPoint; -class QString; - -class Preferences; -class PrintDialog; -class Task; -class TaskView; - -/** - * Main window to tie the application together. - */ - -class MainWindow : public KParts::MainWindow, virtual public KarmDCOPIface -{ - Q_OBJECT - - private: - void makeMenus(); - QString _hasTask( Task* task, const QString &taskname ) const; - Task* _hasUid( Task* task, const QString &uid ) const; - - KAccel* _accel; - KAccelMenuWatch* _watcher; - TaskView* _taskView; - long _totalSum; - long _sessionSum; - Preferences* _preferences; - KarmTray* _tray; - KAction* actionStart; - KAction* actionStop; - KAction* actionStopAll; - KAction* actionDelete; - KAction* actionEdit; - KAction* actionMarkAsComplete; - KAction* actionMarkAsIncomplete; - KAction* actionPreferences; - KAction* actionClipTotals; - KAction* actionClipHistory; - QString m_error[ KARM_MAX_ERROR_NO + 1 ]; - - friend class KarmTray; - - //private: - - //KDialogBase *dialog; - - - - public: - MainWindow( const QString &icsfile = "" ); - virtual ~MainWindow(); - - // DCOP - QString version() const; - QString taskIdFromName( const QString &taskName ) const; - /** @reimp from KarmDCOPIface::addTask */ - int addTask( const QString &storage ); - /** @reimp from KarmDCOPIface::setPerCentComplete */ - QString setPerCentComplete( const QString& taskName, int PerCent ); - /** @reimp from KarmDCOPIface::bookTime */ - int bookTime( const QString& taskId, const QString& iso8601StartDateTime, long durationInMinutes ); - /** @reimp from KarmDCOPIface::getError */ - QString getError( int karmErrorNumber ) const; - int totalMinutesForTaskId( const QString& taskId ); - QString starttimerfor( const QString &taskname ); - QString stoptimerfor( const QString &taskname ); - QString deletetodo(); - bool getpromptdelete(); - QString setpromptdelete( bool prompt ); - QString exportcsvfile( QString filename, QString from, QString to, int type, bool decimalMinutes, bool allTasks, QString delimiter, QString quote ); - QString importplannerfile( QString filename ); - - public slots: - void quit(); - - protected slots: - void keyBindings(); - void startNewSession(); - void resetAllTimes(); - void updateTime( long, long ); - void updateStatusBar(); - bool save(); - void exportcsvHistory(); - void print(); - void slotSelectionChanged(); - void contextMenuRequest( QListViewItem*, const QPoint&, int ); - void enableStopAll(); - void disableStopAll(); -// void timeLoggingChanged( bool on ); - - protected: - void startStatusBar(); - virtual void saveProperties( KConfig* ); - virtual void readProperties( KConfig* ); - void saveGeometry(); - void loadGeometry(); - bool queryClose(); - -}; - -#endif // KARM_MAIN_WINDOW_H diff --git a/ktimetracker/pics/Makefile.am b/ktimetracker/pics/Makefile.am deleted file mode 100644 index c57c57a184..0000000000 --- a/ktimetracker/pics/Makefile.am +++ /dev/null @@ -1,10 +0,0 @@ -pics_DATA = filedel.xpm clock.xpm clockedit.xpm empty-watch.xpm\ - watch-0.xpm watch-1.xpm watch-2.xpm watch-3.xpm \ - watch-4.xpm watch-5.xpm watch-6.xpm watch-7.xpm \ - active-icon-0.xpm active-icon-1.xpm active-icon-2.xpm \ - active-icon-3.xpm active-icon-4.xpm active-icon-5.xpm \ - active-icon-6.xpm active-icon-7.xpm \ - task-complete.xpm task-incomplete.xpm - -picsdir = $(kde_datadir)/karm/pics - diff --git a/ktimetracker/pics/clock.xpm b/ktimetracker/pics/clock.xpm deleted file mode 100644 index 28b9885647..0000000000 --- a/ktimetracker/pics/clock.xpm +++ /dev/null @@ -1,34 +0,0 @@ -/* XPM */ -static char *magick[] = { -/* columns rows colors chars-per-pixel */ -"22 22 6 1", -" c #000000", -". c #008080", -"X c #808080", -"o c #c0c0c0", -"O c #ffffff", -"+ c None", -/* pixels */ -"++++++++++++++++++++++", -"+++++++++oooo+++++++++", -"++++++oooX..Xooo++++++", -"+++++oXXXO..OXXXo+++++", -"++++oXOOOO..OOOOXo++++", -"+++oXOOOOOOOOOOOOXo+++", -"++oXOOOOOOOOOOOOOOXo++", -"++oXOOOOOOOOOOOOOOXo++", -"++oXOOOOOOOOO.OOOOXo++", -"+oXOOOOOOOOO.OOOOOOXo+", -"+oXOOOOOOO..OOOOOOOXo+", -"+oXOOOOOOO..OOOOOOOXo+", -"+oXOOOOOOOOO.OOOOOOXo+", -"++oXOOOOOOOOO.OOOOXo++", -"++oXOOOOOOOOOO.OOOXo++", -"++oXOOOOOOOOOOO.OOXo++", -"+++oXOOOOOOOOOOOOXo+++", -"++++oXOOOOOOOOOOXo++++", -"+++++oXXXOOOOXXXo+++++", -"++++++oooXXXXooo++++++", -"+++++++++oooo+++++++++", -"++++++++++++++++++++++" -}; diff --git a/ktimetracker/pics/clockedit.xpm b/ktimetracker/pics/clockedit.xpm deleted file mode 100644 index f24ee221d7..0000000000 --- a/ktimetracker/pics/clockedit.xpm +++ /dev/null @@ -1,37 +0,0 @@ -/* XPM */ -static char *magick[] = { -/* columns rows colors chars-per-pixel */ -"22 22 9 1", -" c #000000", -". c #008080", -"X c #ff00ff", -"o c #808000", -"O c #ffff00", -"+ c #808080", -"@ c #c0c0c0", -"# c #ffffff", -"$ c None", -/* pixels */ -"$$$$$$$$$$$$$$$$$$$$$$", -"$$$$$$$$$@@@@$$$$$$$$$", -"$$$$$$@@@+..+@@@@@@$$$", -"$$$$$@++@@@@@@++@XXX$$", -"$$$$@+#@##..##@ooXXX@$", -"$$$@+@@######@ooooXX@$", -"$$@+#@######@ooOooo@$$", -"$$@+@######@oooOOoo@$$", -"$$@@######@ooOOOoo@@$$", -"$@+@#####@oooOOoo#@+@$", -"$@+@####@ooOOOoo##@+@$", -"$@+@###@oooOOoo###@+@$", -"$@+@##@ooOOOoo####@+@$", -"$$@@#@oooOOoo.####@@$$", -"$$@+@ooOOOoo##.##@+@$$", -"$$@+oooOOoo####.@#+@$$", -"$$$ooOOOoo#####@@+@$$$", -"$$ooOOOoo#####@#+@$$$$", -"$$ oOOoo@@@@@@++@$$$$$", -"$ ooooo@@++++@@@$$$$$$", -"$ oo o$$$@@@@$$$$$$$$$", -"$ $$$$$$$$$$$$$$$$$$" -}; diff --git a/ktimetracker/pics/empty-watch.xpm b/ktimetracker/pics/empty-watch.xpm deleted file mode 100644 index 8932686b19..0000000000 --- a/ktimetracker/pics/empty-watch.xpm +++ /dev/null @@ -1,19 +0,0 @@ -/* XPM */ -static char * x_xpm[] = { -"15 15 1 1", -" c None", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" "}; diff --git a/ktimetracker/pics/filedel.xpm b/ktimetracker/pics/filedel.xpm deleted file mode 100644 index 9c2b101389..0000000000 --- a/ktimetracker/pics/filedel.xpm +++ /dev/null @@ -1,31 +0,0 @@ -/* XPM */ -static char * delete_xpm[] = { -/* width height num_colors chars_per_pixel */ -"22 22 3 1", -/* colors */ -" c white", -". c none", -"X c black", -/* pixels */ -"......................", -"......................", -"......................", -"......................", -"......................", -"....XX ........XX ....", -"....XXXX .....XX .....", -".....XXXX ...XX ......", -".......XXX .X ........", -"........XXXXX ........", -".........XXX .........", -"........XXXXX ........", -".......XXX .XX .......", -"......XXX ...XX ......", -".....XXX .....X ......", -".....XXX ......X .....", -"......X ..............", -"................X ....", -"......................", -"......................", -"......................", -"......................"}; diff --git a/ktimetracker/pics/watch-0.xpm b/ktimetracker/pics/watch-0.xpm deleted file mode 100644 index 60f5d7e54d..0000000000 --- a/ktimetracker/pics/watch-0.xpm +++ /dev/null @@ -1,25 +0,0 @@ -/* XPM */ -static char * watch_0_xpm[] = { -"15 15 7 1", -" c None", -". c #000000", -"+ c #4A4A4A", -"@ c #ACACAC", -"# c #E9E9E9", -"$ c #989898", -"% c #FFFFFF", -" . ", -" +@#.#@+ ", -" $%%%.%%%$ ", -" $%%%%.%%%%$ ", -" +%%%%%.%%%%%+ ", -" @%%%%%.%%%%%@ ", -" #%%%%%.%%%%%# ", -".%%%%%%.%%%%%%.", -" #%%%%%%%%%%%# ", -" @%%%%%%%%%%%@ ", -" +%%%%%%%%%%%+ ", -" $%%%%%%%%%$ ", -" $%%%%%%%$ ", -" +@#%#@+ ", -" . "}; diff --git a/ktimetracker/pics/watch-1.xpm b/ktimetracker/pics/watch-1.xpm deleted file mode 100644 index 80450d54d8..0000000000 --- a/ktimetracker/pics/watch-1.xpm +++ /dev/null @@ -1,25 +0,0 @@ -/* XPM */ -static char * watch_1_xpm[] = { -"15 15 7 1", -" c None", -". c #000000", -"+ c #4A4A4A", -"@ c #ACACAC", -"# c #E9E9E9", -"$ c #FFFFFF", -"% c #989898", -" . ", -" +@#$#@+ ", -" %$$$$$$$% ", -" %$$$$$$$$.% ", -" +$$$$$$$$.$$+ ", -" @$$$$$$$.$$$@ ", -" #$$$$$$.$$$$# ", -".$$$$$$.$$$$$$.", -" #$$$$$$$$$$$# ", -" @$$$$$$$$$$$@ ", -" +$$$$$$$$$$$+ ", -" %$$$$$$$$$% ", -" %$$$$$$$% ", -" +@#$#@+ ", -" . "}; diff --git a/ktimetracker/pics/watch-2.xpm b/ktimetracker/pics/watch-2.xpm deleted file mode 100644 index 5314d936bd..0000000000 --- a/ktimetracker/pics/watch-2.xpm +++ /dev/null @@ -1,25 +0,0 @@ -/* XPM */ -static char * watch_2_xpm[] = { -"15 15 7 1", -" c None", -". c #000000", -"+ c #4A4A4A", -"@ c #ACACAC", -"# c #E9E9E9", -"$ c #FFFFFF", -"% c #989898", -" . ", -" +@#$#@+ ", -" %$$$$$$$% ", -" %$$$$$$$$$% ", -" +$$$$$$$$$$$+ ", -" @$$$$$$$$$$$@ ", -" #$$$$$$$$$$$# ", -".$$$$$$........", -" #$$$$$$$$$$$# ", -" @$$$$$$$$$$$@ ", -" +$$$$$$$$$$$+ ", -" %$$$$$$$$$% ", -" %$$$$$$$% ", -" +@#$#@+ ", -" . "}; diff --git a/ktimetracker/pics/watch-3.xpm b/ktimetracker/pics/watch-3.xpm deleted file mode 100644 index 0a61556479..0000000000 --- a/ktimetracker/pics/watch-3.xpm +++ /dev/null @@ -1,25 +0,0 @@ -/* XPM */ -static char * watch_3_xpm[] = { -"15 15 7 1", -" c None", -". c #000000", -"+ c #4A4A4A", -"@ c #ACACAC", -"# c #E9E9E9", -"$ c #FFFFFF", -"% c #989898", -" . ", -" +@#$#@+ ", -" %$$$$$$$% ", -" %$$$$$$$$$% ", -" +$$$$$$$$$$$+ ", -" @$$$$$$$$$$$@ ", -" #$$$$$$$$$$$# ", -".$$$$$$.$$$$$$.", -" #$$$$$$.$$$$# ", -" @$$$$$$$.$$$@ ", -" +$$$$$$$$.$$+ ", -" %$$$$$$$$.% ", -" %$$$$$$$% ", -" +@#$#@+ ", -" . "}; diff --git a/ktimetracker/pics/watch-4.xpm b/ktimetracker/pics/watch-4.xpm deleted file mode 100644 index 6129b5f7a4..0000000000 --- a/ktimetracker/pics/watch-4.xpm +++ /dev/null @@ -1,25 +0,0 @@ -/* XPM */ -static char * watch_4_xpm[] = { -"15 15 7 1", -" c None", -". c #000000", -"+ c #4A4A4A", -"@ c #ACACAC", -"# c #E9E9E9", -"$ c #FFFFFF", -"% c #989898", -" . ", -" +@#$#@+ ", -" %$$$$$$$% ", -" %$$$$$$$$$% ", -" +$$$$$$$$$$$+ ", -" @$$$$$$$$$$$@ ", -" #$$$$$$$$$$$# ", -".$$$$$$.$$$$$$.", -" #$$$$$.$$$$$# ", -" @$$$$$.$$$$$@ ", -" +$$$$$.$$$$$+ ", -" %$$$$.$$$$% ", -" %$$$.$$$% ", -" +@#.#@+ ", -" . "}; diff --git a/ktimetracker/pics/watch-5.xpm b/ktimetracker/pics/watch-5.xpm deleted file mode 100644 index ce57979052..0000000000 --- a/ktimetracker/pics/watch-5.xpm +++ /dev/null @@ -1,25 +0,0 @@ -/* XPM */ -static char * watch_5_xpm[] = { -"15 15 7 1", -" c None", -". c #000000", -"+ c #4A4A4A", -"@ c #ACACAC", -"# c #E9E9E9", -"$ c #FFFFFF", -"% c #989898", -" . ", -" +@#$#@+ ", -" %$$$$$$$% ", -" %$$$$$$$$$% ", -" +$$$$$$$$$$$+ ", -" @$$$$$$$$$$$@ ", -" #$$$$$$$$$$$# ", -".$$$$$$.$$$$$$.", -" #$$$$.$$$$$$# ", -" @$$$.$$$$$$$@ ", -" +$$.$$$$$$$$+ ", -" %.$$$$$$$$% ", -" %$$$$$$$% ", -" +@#$#@+ ", -" . "}; diff --git a/ktimetracker/pics/watch-6.xpm b/ktimetracker/pics/watch-6.xpm deleted file mode 100644 index 25323ec628..0000000000 --- a/ktimetracker/pics/watch-6.xpm +++ /dev/null @@ -1,25 +0,0 @@ -/* XPM */ -static char * watch_6_xpm[] = { -"15 15 7 1", -" c None", -". c #000000", -"+ c #4A4A4A", -"@ c #ACACAC", -"# c #E9E9E9", -"$ c #FFFFFF", -"% c #989898", -" . ", -" +@#$#@+ ", -" %$$$$$$$% ", -" %$$$$$$$$$% ", -" +$$$$$$$$$$$+ ", -" @$$$$$$$$$$$@ ", -" #$$$$$$$$$$$# ", -"........$$$$$$.", -" #$$$$$$$$$$$# ", -" @$$$$$$$$$$$@ ", -" +$$$$$$$$$$$+ ", -" %$$$$$$$$$% ", -" %$$$$$$$% ", -" +@#$#@+ ", -" . "}; diff --git a/ktimetracker/pics/watch-7.xpm b/ktimetracker/pics/watch-7.xpm deleted file mode 100644 index 35d962dc74..0000000000 --- a/ktimetracker/pics/watch-7.xpm +++ /dev/null @@ -1,25 +0,0 @@ -/* XPM */ -static char * watch_7_xpm[] = { -"15 15 7 1", -" c None", -". c #000000", -"+ c #4A4A4A", -"@ c #ACACAC", -"# c #E9E9E9", -"$ c #FFFFFF", -"% c #989898", -" . ", -" +@#$#@+ ", -" %$$$$$$$% ", -" %.$$$$$$$$% ", -" +$$.$$$$$$$$+ ", -" @$$$.$$$$$$$@ ", -" #$$$$.$$$$$$# ", -".$$$$$$.$$$$$$.", -" #$$$$$$$$$$$# ", -" @$$$$$$$$$$$@ ", -" +$$$$$$$$$$$+ ", -" %$$$$$$$$$% ", -" %$$$$$$$% ", -" +@#$#@+ ", -" . "}; diff --git a/ktimetracker/plannerparser.cpp b/ktimetracker/plannerparser.cpp deleted file mode 100644 index 21e0c4f768..0000000000 --- a/ktimetracker/plannerparser.cpp +++ /dev/null @@ -1,100 +0,0 @@ -// -// C++ Implementation: plannerparser -// -// Description: -/* - -this class is here to import tasks from a planner project file to karm. -the import shall not be limited to karm (kPlaTo sends greetings) -it imports planner's top-level-tasks on the same level-depth as current_item. -if there is no current_item, planner's top-level-tasks will become top-level-tasks in karm. -it imports as well the level-depth of each task, as its name, as its percent-complete. -test cases: - - deleting all tasks away, then import! - - having started with an empty ics, import! - - with current_item being a top-level-task, import! - - with current_item being a subtask, import! - - - Author: Thorsten Staerk , (C) 2004 - - Copyright: See COPYING file that comes with this distribution - - -*/ - -#include "plannerparser.h" - - - PlannerParser::PlannerParser(TaskView * tv) - // if there is a task one level above current_item, make it the father of all imported tasks. Set level accordingly. - // import as well if there a no task in the taskview as if there are. - // if there are, put the top-level tasks of planner on the same level as current_item. - // So you have the chance as well to have the planner tasks at top-level as at a whatever-so-deep sublevel. - { - kdDebug() << "entering constructor to import planner tasks" << endl; - _taskView=tv; - level=0; - if (_taskView->current_item()) if (_taskView->current_item()->parent()) - { - task = _taskView->current_item()->parent(); - level=1; - } - } - - bool PlannerParser::startDocument() - { - withInTasks=false; // becomes true as soon as parsing occurres - return true; - } - - bool PlannerParser::startElement( const QString&, const QString&, const QString& qName, const QXmlAttributes& att ) - { - kdDebug() << "entering startElement" << endl; - QString taskName; - int taskComplete=0; - - // only s within are processed - if (qName == QString::fromLatin1("tasks")) withInTasks=true; - if ((qName == QString::fromLatin1("task")) && (withInTasks)) - { - - // find out name and percent-complete - for (int i=0; i0) - { - parentTask=task; - task = new Task(taskName, 0, 0, dl, parentTask); - task->setUid(_taskView->storage()->addTask(task, parentTask)); - } - else - { - task = new Task(taskName, 0, 0, dl, _taskView); - kdDebug() << "added" << taskName << endl; - task->setUid(_taskView->storage()->addTask(task, 0)); - } - - task->setPercentComplete(taskComplete, _taskView->storage()); - } - return true; - } - - bool PlannerParser::endElement( const QString&, const QString&, const QString& qName) - { - // only s within increased level, so only decrease for s within - if (withInTasks) - { - if (qName=="task") if (level-->=0) task=task->parent(); - if (qName=="tasks") withInTasks=false; - } - return true; - } - diff --git a/ktimetracker/preferences.cpp b/ktimetracker/preferences.cpp deleted file mode 100644 index d02db1cdc6..0000000000 --- a/ktimetracker/preferences.cpp +++ /dev/null @@ -1,333 +0,0 @@ -#undef Unsorted // for --enable-final -#include -#include -#include -#include -#include - -#include // kapp -#include -#include -#include -#include -#include // lineEdit() -#include // i18n -#include -#include - -#include "preferences.h" - -Preferences *Preferences::_instance = 0; - -Preferences::Preferences( const QString& icsFile ) - : KDialogBase( IconList, i18n("Preferences"), Ok|Cancel, Ok ) -{ - - setIconListAllVisible( true ); - - makeBehaviorPage(); - makeDisplayPage(); - makeStoragePage(); - - load(); - - // command-line option overrides what is stored in - if ( ! icsFile.isEmpty() ) _iCalFileV = icsFile; - -} - -Preferences *Preferences::instance( const QString &icsfile ) -{ - if (_instance == 0) { - _instance = new Preferences( icsfile ); - } - return _instance; -} - -void Preferences::makeBehaviorPage() -{ - QPixmap icon = SmallIcon( "kcmsystem", KIcon::SizeMedium); - QFrame* behaviorPage = addPage( i18n("Behavior"), i18n("Behavior Settings"), - icon ); - - QVBoxLayout* topLevel = new QVBoxLayout( behaviorPage, 0, spacingHint() ); - QGridLayout* layout = new QGridLayout( topLevel, 2, 2 ); - layout->setColStretch( 1, 1 ); - - _doIdleDetectionW = new QCheckBox - ( i18n("Detect desktop as idle after"), behaviorPage, "_doIdleDetectionW"); - _idleDetectValueW = new QSpinBox - (1,60*24, 1, behaviorPage, "_idleDetectValueW"); - _idleDetectValueW->setSuffix(i18n(" min")); - _promptDeleteW = new QCheckBox - ( i18n( "Prompt before deleting tasks" ), behaviorPage, "_promptDeleteW" ); - - layout->addWidget(_doIdleDetectionW, 0, 0 ); - layout->addWidget(_idleDetectValueW, 0, 1 ); - layout->addWidget(_promptDeleteW, 1, 0 ); - - topLevel->addStretch(); - - connect( _doIdleDetectionW, SIGNAL( clicked() ), this, - SLOT( idleDetectCheckBoxChanged() )); -} - -void Preferences::makeDisplayPage() -{ - QPixmap icon = SmallIcon( "viewmag", KIcon::SizeMedium ); - QFrame* displayPage = addPage( i18n("Display"), i18n("Display Settings"), - icon ); - - QVBoxLayout* topLevel = new QVBoxLayout( displayPage, 0, spacingHint() ); - QGridLayout* layout = new QGridLayout( topLevel, 5, 2 ); - layout->setColStretch( 1, 1 ); - - QLabel* _displayColumnsLabelW = new QLabel( i18n("Columns displayed:"), - displayPage ); - _displaySessionW = new QCheckBox ( i18n("Session time"), - displayPage, "_displaySessionW"); - _displayTimeW = new QCheckBox ( i18n("Cumulative task time"), - displayPage, "_displayTimeW"); - _displayTotalSessionW = new QCheckBox( i18n("Total session time"), - displayPage, "_displayTotalSessionW"); - _displayTotalTimeW = new QCheckBox ( i18n("Total task time"), - displayPage, "_displayTotalTimeW"); - - layout->addMultiCellWidget( _displayColumnsLabelW, 0, 0, 0, 1 ); - layout->addWidget(_displaySessionW, 1, 1 ); - layout->addWidget(_displayTimeW, 2, 1 ); - layout->addWidget(_displayTotalSessionW, 3, 1 ); - layout->addWidget(_displayTotalTimeW, 4, 1 ); - - topLevel->addStretch(); -} - -void Preferences::makeStoragePage() -{ - QPixmap icon = SmallIcon( "kfm", KIcon::SizeMedium ); - QFrame* storagePage = addPage( i18n("Storage"), i18n("Storage Settings"), - icon ); - - QVBoxLayout* topLevel = new QVBoxLayout( storagePage, 0, spacingHint() ); - QGridLayout* layout = new QGridLayout( topLevel, 4, 2 ); - layout->setColStretch( 1, 1 ); - - // autosave - _doAutoSaveW = new QCheckBox - ( i18n("Save tasks every"), storagePage, "_doAutoSaveW" ); - _autoSaveValueW = new QSpinBox(1, 60*24, 1, storagePage, "_autoSaveValueW"); - _autoSaveValueW->setSuffix(i18n(" min")); - - // iCalendar - QLabel* _iCalFileLabel = new QLabel( i18n("iCalendar file:"), storagePage); - _iCalFileW = new KURLRequester(storagePage, "_iCalFileW"); - _iCalFileW->setFilter(QString::fromLatin1("*.ics")); - _iCalFileW->setMode(KFile::File); - - // Log time? - _loggingW = new QCheckBox - ( i18n("Log history"), storagePage, "_loggingW" ); - - // add widgets to layout - layout->addWidget(_doAutoSaveW, 0, 0); - layout->addWidget(_autoSaveValueW, 0, 1); - layout->addWidget(_iCalFileLabel, 1, 0 ); - layout->addWidget(_iCalFileW, 1, 1 ); - layout->addWidget(_loggingW, 2, 0 ); - - topLevel->addStretch(); - - // checkboxes disable file selection controls - connect( _doAutoSaveW, SIGNAL( clicked() ), - this, SLOT( autoSaveCheckBoxChanged() )); -} - -void Preferences::disableIdleDetection() -{ - _doIdleDetectionW->setEnabled(false); -} - - -//--------------------------------------------------------------------------- -// SLOTS -//--------------------------------------------------------------------------- - -void Preferences::showDialog() -{ - - // set all widgets - _iCalFileW->lineEdit()->setText(_iCalFileV); - - _doIdleDetectionW->setChecked(_doIdleDetectionV); - _idleDetectValueW->setValue(_idleDetectValueV); - - _doAutoSaveW->setChecked(_doAutoSaveV); - _autoSaveValueW->setValue(_autoSaveValueV); - _loggingW->setChecked(_loggingV); - - _promptDeleteW->setChecked(_promptDeleteV); - - _displaySessionW->setChecked(_displayColumnV[0]); - _displayTimeW->setChecked(_displayColumnV[1]); - _displayTotalSessionW->setChecked(_displayColumnV[2]); - _displayTotalTimeW->setChecked(_displayColumnV[3]); - - // adapt visibility of preference items according - // to settings - idleDetectCheckBoxChanged(); - autoSaveCheckBoxChanged(); - - show(); -} - -void Preferences::slotOk() -{ - - // storage - _iCalFileV = _iCalFileW->lineEdit()->text(); - - _doIdleDetectionV = _doIdleDetectionW->isChecked(); - _idleDetectValueV = _idleDetectValueW->value(); - - _doAutoSaveV = _doAutoSaveW->isChecked(); - _autoSaveValueV = _autoSaveValueW->value(); - _loggingV = _loggingW->isChecked(); - - // behavior - _promptDeleteV = _promptDeleteW->isChecked(); - - // display - _displayColumnV[0] = _displaySessionW->isChecked(); - _displayColumnV[1] = _displayTimeW->isChecked(); - _displayColumnV[2] = _displayTotalSessionW->isChecked(); - _displayColumnV[3] = _displayTotalTimeW->isChecked(); - - emitSignals(); - save(); - KDialogBase::slotOk(); -} - -void Preferences::slotCancel() -{ - KDialogBase::slotCancel(); -} - -void Preferences::idleDetectCheckBoxChanged() -{ - _idleDetectValueW->setEnabled(_doIdleDetectionW->isChecked()); -} - -void Preferences::autoSaveCheckBoxChanged() -{ - _autoSaveValueW->setEnabled(_doAutoSaveW->isChecked()); -} - -void Preferences::emitSignals() -{ - emit iCalFile( _iCalFileV ); - emit detectIdleness( _doIdleDetectionV ); - emit idlenessTimeout( _idleDetectValueV ); - emit autoSave( _doAutoSaveV ); - emit autoSavePeriod( _autoSaveValueV ); - emit setupChanged(); -} - -QString Preferences::iCalFile() const { return _iCalFileV; } -QString Preferences::activeCalendarFile() const { return _iCalFileV; } -bool Preferences::detectIdleness() const { return _doIdleDetectionV; } -int Preferences::idlenessTimeout() const { return _idleDetectValueV; } -bool Preferences::autoSave() const { return _doAutoSaveV; } -int Preferences::autoSavePeriod() const { return _autoSaveValueV; } -bool Preferences::logging() const { return _loggingV; } -bool Preferences::promptDelete() const { return _promptDeleteV; } -QString Preferences::setPromptDelete(bool prompt) { _promptDeleteV=prompt; return ""; } -bool Preferences::displayColumn(int n) const { return _displayColumnV[n]; } -QString Preferences::userRealName() const { return _userRealName; } - -//--------------------------------------------------------------------------- -// Load and Save -//--------------------------------------------------------------------------- -void Preferences::load() -{ - KConfig &config = *kapp->config(); - - config.setGroup( QString::fromLatin1("Idle detection") ); - _doIdleDetectionV = config.readBoolEntry( QString::fromLatin1("enabled"), - true ); - _idleDetectValueV = config.readNumEntry(QString::fromLatin1("period"), 15); - - config.setGroup( QString::fromLatin1("Saving") ); - _iCalFileV = config.readPathEntry - ( QString::fromLatin1("ical file"), - locateLocal( "appdata", QString::fromLatin1( "karm.ics"))); - _doAutoSaveV = config.readBoolEntry - ( QString::fromLatin1("auto save"), true); - _autoSaveValueV = config.readNumEntry - ( QString::fromLatin1("auto save period"), 5); - _promptDeleteV = config.readBoolEntry - ( QString::fromLatin1("prompt delete"), true); - _loggingV = config.readBoolEntry - ( QString::fromLatin1("logging"), true); - - _displayColumnV[0] = config.readBoolEntry - ( QString::fromLatin1("display session time"), true); - _displayColumnV[1] = config.readBoolEntry - ( QString::fromLatin1("display time"), true); - _displayColumnV[2] = config.readBoolEntry - ( QString::fromLatin1("display total session time"), true); - _displayColumnV[3] = config.readBoolEntry - ( QString::fromLatin1("display total time"), true); - - KEMailSettings settings; - _userRealName = settings.getSetting( KEMailSettings::RealName ); -} - -void Preferences::save() -{ - KConfig &config = *KGlobal::config(); - - config.setGroup( QString::fromLatin1("Idle detection")); - config.writeEntry( QString::fromLatin1("enabled"), _doIdleDetectionV); - config.writeEntry( QString::fromLatin1("period"), _idleDetectValueV); - - config.setGroup( QString::fromLatin1("Saving")); - config.writePathEntry( QString::fromLatin1("ical file"), _iCalFileV); - config.writeEntry( QString::fromLatin1("auto save"), _doAutoSaveV); - config.writeEntry( QString::fromLatin1("logging"), _loggingV); - config.writeEntry( QString::fromLatin1("auto save period"), _autoSaveValueV); - config.writeEntry( QString::fromLatin1("prompt delete"), _promptDeleteV); - - config.writeEntry( QString::fromLatin1("display session time"), - _displayColumnV[0]); - config.writeEntry( QString::fromLatin1("display time"), - _displayColumnV[1]); - config.writeEntry( QString::fromLatin1("display total session time"), - _displayColumnV[2]); - config.writeEntry( QString::fromLatin1("display total time"), - _displayColumnV[3]); - - config.sync(); -} - -// HACK: this entire config dialog should be upgraded to KConfigXT -bool Preferences::readBoolEntry( const QString& key ) -{ - KConfig &config = *KGlobal::config(); - return config.readBoolEntry ( key, true ); -} - -void Preferences::writeEntry( const QString &key, bool value) -{ - KConfig &config = *KGlobal::config(); - config.writeEntry( key, value ); - config.sync(); -} - -void Preferences::deleteEntry( const QString &key ) -{ - KConfig &config = *KGlobal::config(); - config.deleteEntry( key ); - config.sync(); -} - -#include "preferences.moc" diff --git a/ktimetracker/preferences.h b/ktimetracker/preferences.h deleted file mode 100644 index e917d70bbf..0000000000 --- a/ktimetracker/preferences.h +++ /dev/null @@ -1,90 +0,0 @@ -#ifndef KARM_PREFERENCES_H -#define KARM_PREFERENCES_H - -#include - -class QCheckBox; -class QLabel; -class QSpinBox; -class QString; -class KURLRequester; - -/** - * Provide an interface to the configuration options for the program. - */ - -class Preferences :public KDialogBase -{ - Q_OBJECT - - public: - static Preferences *instance( const QString& icsfile = "" ); - void disableIdleDetection(); - - // Retrive information about settings - bool detectIdleness() const; - int idlenessTimeout() const; - QString iCalFile() const; - QString activeCalendarFile() const; - bool autoSave() const; - bool logging() const; - int autoSavePeriod() const; - bool promptDelete() const; - QString setPromptDelete( bool prompt ); - bool displayColumn(int n) const; - QString userRealName() const; - - void emitSignals(); - bool readBoolEntry( const QString& uid ); - void writeEntry( const QString &key, bool value ); - void deleteEntry( const QString &key ); - - public slots: - void showDialog(); - void load(); - void save(); - - signals: - void detectIdleness(bool on); - void idlenessTimeout(int minutes); - void iCalFile(QString); - void autoSave(bool on); - void autoSavePeriod(int minutes); - void setupChanged(); - - protected slots: - virtual void slotOk(); - virtual void slotCancel(); - void idleDetectCheckBoxChanged(); - void autoSaveCheckBoxChanged(); - - private: - void makeDisplayPage(); - void makeBehaviorPage(); - void makeStoragePage(); - - Preferences( const QString& icsfile = "" ); - static Preferences *_instance; - bool _unsavedChanges; - - // Widgets - QCheckBox *_doIdleDetectionW, *_doAutoSaveW, *_promptDeleteW; - QCheckBox *_displayTimeW, *_displaySessionW, - *_displayTotalTimeW, *_displayTotalSessionW; - QCheckBox *_loggingW; - QLabel *_idleDetectLabelW, *_displayColumnsLabelW; - QSpinBox *_idleDetectValueW, *_autoSaveValueW; - KURLRequester *_iCalFileW ; - - // Values - bool _doIdleDetectionV, _doAutoSaveV, _promptDeleteV, _loggingV; - bool _displayColumnV[4]; - int _idleDetectValueV, _autoSaveValueV; - QString _iCalFileV; - - /** real name of the user, used during ICAL saving */ - QString _userRealName; -}; - -#endif // KARM_PREFERENCES_H - diff --git a/ktimetracker/print.cpp b/ktimetracker/print.cpp deleted file mode 100644 index ff00a3bc3a..0000000000 --- a/ktimetracker/print.cpp +++ /dev/null @@ -1,166 +0,0 @@ -// #include - -#include -#include -#include - -#include -#include // i18n - -#include "karmutility.h" // formatTime() -#include "print.h" -#include "task.h" -#include "taskview.h" - -const int levelIndent = 10; - -MyPrinter::MyPrinter(const TaskView *taskView) -{ - _taskView = taskView; -} - -void MyPrinter::print() -{ - // FIXME: make a better caption for the printingdialog - if (setup(0L, i18n("Print Times"))) { - // setup - QPainter painter(this); - QPaintDeviceMetrics deviceMetrics(this); - QFontMetrics metrics = painter.fontMetrics(); - pageHeight = deviceMetrics.height(); - int pageWidth = deviceMetrics.width(); - xMargin = margins().width(); - yMargin = margins().height(); - yoff = yMargin; - lineHeight = metrics.height(); - - // Calculate the totals - // Note the totals are only calculated at the top most levels, as the - // totals are increased together with its children. - int totalTotal = 0; - int sessionTotal = 0; - for (Task* task = _taskView->first_child(); - task; - task = static_cast(task->nextSibling())) { - totalTotal += task->totalTime(); - sessionTotal += task->totalSessionTime(); - } - - // Calculate the needed width for each of the fields - timeWidth = QMAX(metrics.width(i18n("Total")), - metrics.width(formatTime(totalTotal))); - sessionTimeWidth = QMAX(metrics.width(i18n("Session")), - metrics.width(formatTime(sessionTotal))); - - nameFieldWidth = pageWidth - xMargin - timeWidth - sessionTimeWidth - 2*5; - - int maxReqNameFieldWidth= metrics.width(i18n("Task Name ")); - - for ( Task* task = _taskView->first_child(); - task; - task = static_cast(task->nextSibling())) - { - int width = calculateReqNameWidth(task, metrics, 0); - maxReqNameFieldWidth = QMAX(maxReqNameFieldWidth, width); - } - nameFieldWidth = QMIN(nameFieldWidth, maxReqNameFieldWidth); - - int realPageWidth = nameFieldWidth + timeWidth + sessionTimeWidth + 2*5; - - // Print the header - QFont origFont, newFont; - origFont = painter.font(); - newFont = origFont; - newFont.setPixelSize( static_cast(origFont.pixelSize() * 1.5) ); - painter.setFont(newFont); - - int height = metrics.height(); - QString now = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime()); - - painter.drawText(xMargin, yoff, pageWidth, height, - QPainter::AlignCenter, - i18n("KArm - %1").arg(now)); - - painter.setFont(origFont); - yoff += height + 10; - - // Print the second header. - printLine(i18n("Total"), i18n("Session"), i18n("Task Name"), painter, 0); - - yoff += 4; - painter.drawLine(xMargin, yoff, xMargin + realPageWidth, yoff); - yoff += 2; - - // Now print the actual content - for ( Task* task = _taskView->first_child(); - task; - task = static_cast(task->nextSibling()) ) - { - printTask(task, painter, 0); - } - - yoff += 4; - painter.drawLine(xMargin, yoff, xMargin + realPageWidth, yoff); - yoff += 2; - - // Print the Totals - printLine( formatTime( totalTotal ), - formatTime( sessionTotal ), - QString(), painter, 0); - } -} - -int MyPrinter::calculateReqNameWidth( Task* task, - QFontMetrics &metrics, - int level) -{ - int width = metrics.width(task->name()) + level * levelIndent; - - for ( Task* subTask = task->firstChild(); - subTask; - subTask = subTask->nextSibling() ) { - int subTaskWidth = calculateReqNameWidth(subTask, metrics, level+1); - width = QMAX(width, subTaskWidth); - } - return width; -} - -void MyPrinter::printTask(Task *task, QPainter &painter, int level) -{ - QString time = formatTime(task->totalTime()); - QString sessionTime = formatTime(task->totalSessionTime()); - QString name = task->name(); - printLine(time, sessionTime, name, painter, level); - - for ( Task* subTask = task->firstChild(); - subTask; - subTask = subTask->nextSibling()) - { - printTask(subTask, painter, level+1); - } -} - -void MyPrinter::printLine( QString total, QString session, QString name, - QPainter &painter, int level ) -{ - int xoff = xMargin + 10 * level; - - painter.drawText( xoff, yoff, nameFieldWidth, lineHeight, - QPainter::AlignLeft, name); - xoff = xMargin + nameFieldWidth; - - painter.drawText( xoff, yoff, sessionTimeWidth, lineHeight, - QPainter::AlignRight, session); - xoff += sessionTimeWidth+ 5; - - painter.drawText( xoff, yoff, timeWidth, lineHeight, - QPainter::AlignRight, total); - xoff += timeWidth+5; - - yoff += lineHeight; - - if (yoff + 2* lineHeight > pageHeight) { - newPage(); - yoff = yMargin; - } -} diff --git a/ktimetracker/print.h b/ktimetracker/print.h deleted file mode 100644 index 14b15fbe2e..0000000000 --- a/ktimetracker/print.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef ___print_h -#define ___print_h - -#undef Color // X11 headers -#undef GrayScale // X11 headers -#include -#include -#include "karm.h" - -class MyPrinter :public KPrinter -{ -public: - MyPrinter(const Karm *karm); - void print(); - void printLine(QString total, QString session, QString name, QPainter &, int); - void printTask(QListViewItem *item, QPainter &,int level); - int calculateReqNameWidth(QListViewItem *item, QFontMetrics &metrics, int level); - -private: - const Karm *_karm; - - int xMargin, yMargin; - int yoff; - int totalTimeWidth; - int sessionTimeWidth; - int nameFieldWidth; - int lineHeight; - int pageHeight; -}; - -#endif - diff --git a/ktimetracker/printdialog.cpp b/ktimetracker/printdialog.cpp deleted file mode 100644 index 51603a8c55..0000000000 --- a/ktimetracker/printdialog.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * This file only: - * Copyright (C) 2003 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include // i18n -#include - -#include "printdialog.h" -#include - - -PrintDialog::PrintDialog() - : KDialogBase(0, "PrintDialog", true, i18n("Print Dialog"), Ok|Cancel, - Ok, true ) -{ - QWidget *page = new QWidget( this ); - setMainWidget(page); - int year, month; - - QVBoxLayout *layout = new QVBoxLayout(page, KDialog::spacingHint()); - layout->addSpacing(10); - layout->addStretch(1); - - // Date Range - QGroupBox *rangeGroup = new QGroupBox(1, Horizontal, i18n("Date Range"), - page); - layout->addWidget(rangeGroup); - - QWidget *rangeWidget = new QWidget(rangeGroup); - QHBoxLayout *rangeLayout = new QHBoxLayout(rangeWidget, 0, spacingHint()); - - rangeLayout->addWidget(new QLabel(i18n("From:"), rangeWidget)); - _from = new KDateEdit(rangeWidget); - - // Default from date to beginning of the month - year = QDate::currentDate().year(); - month = QDate::currentDate().month(); - _from->setDate(QDate(year, month, 1)); - rangeLayout->addWidget(_from); - rangeLayout->addWidget(new QLabel(i18n("To:"), rangeWidget)); - _to = new KDateEdit(rangeWidget); - rangeLayout->addWidget(_to); - - layout->addSpacing(10); - layout->addStretch(1); - - _allTasks = new QComboBox( page ); - _allTasks->insertItem( i18n( "Selected Task" ) ); - _allTasks->insertItem( i18n( "All Tasks" ) ); - layout->addWidget( _allTasks ); - - _perWeek = new QCheckBox( i18n( "Summarize per week" ), page ); - layout->addWidget( _perWeek ); - _totalsOnly = new QCheckBox( i18n( "Totals Only" ), page ); - layout->addWidget( _totalsOnly ); - - layout->addSpacing(10); - layout->addStretch(1); -} - -QDate PrintDialog::from() const -{ - return _from->date(); -} - -QDate PrintDialog::to() const -{ - return _to->date(); -} - -bool PrintDialog::perWeek() const -{ - return _perWeek->isChecked(); -} - -bool PrintDialog::allTasks() const -{ - return _allTasks->currentItem() == 1; -} - -bool PrintDialog::totalsOnly() const -{ - return _totalsOnly->isChecked(); -} - -#include "printdialog.moc" diff --git a/ktimetracker/printdialog.h b/ktimetracker/printdialog.h deleted file mode 100644 index 6c2c4c581f..0000000000 --- a/ktimetracker/printdialog.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file only: - * Copyright (C) 2003 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ -#ifndef KARM_PRINT_DIALOG_H -#define KARM_PRINT_DIALOG_H - -#include -#include - -class QCheckBox; -class KDateEdit; - -class PrintDialog : public KDialogBase -{ - Q_OBJECT - - public: - PrintDialog(); - - /* Return the from date entered. */ - QDate from() const; - - /* Return the to date entered. */ - QDate to() const; - - /* Whether to summarize per week */ - bool perWeek() const; - - /* Whether to print all tasks */ - bool allTasks() const; - - /* Whether to print totals only, instead of per-day columns */ - bool totalsOnly() const; - -private: - KDateEdit *_from, *_to; - QCheckBox *_perWeek; - QComboBox *_allTasks; - QCheckBox *_totalsOnly; -}; - -#endif // KARM_PRINT_DIALOG_H - diff --git a/ktimetracker/reportcriteria.h b/ktimetracker/reportcriteria.h deleted file mode 100644 index 66b5b8a02b..0000000000 --- a/ktimetracker/reportcriteria.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2004 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ -#ifndef REPORTCRITERIA_H -#define REPORTCRITERIA_H - -#include -#include -class QString; - -/** - Stores entries from export dialog. - - Keeps details (like CSV export dialog control names) out of the TaskView - class, which contains the slot triggered by the export action. - - The dialog and the report logic can change all they want and the TaskView - logic can stay the same. - */ - -class ReportCriteria -{ - public: - - /** - The different report types. - */ - enum REPORTTYPE { CSVTotalsExport = 0, CSVHistoryExport = 1 }; - - /** - The type of report we are running. - */ - REPORTTYPE reportType; - - /** - For reports that write to a file, the filename to write to. - */ - KURL url; - - /** - For history reports, the lower bound of the date range to report on. - */ - QDate from; - - /** - For history reports, the upper bound of the date range to report on. - */ - QDate to; - - /** - True if the report should contain all tasks in Karm. - - Defaults to true. - */ - bool allTasks; - - /** - True if the durations should be output in decimal hours. Otherwise, - output durations as HH24:MI - */ - bool decimalMinutes; - - /** - The delimiter to use when outputting comma-seperated value reports. - */ - QString delimiter; - - /** - The quote to use for text fields when outputting comma-seperated reports. - */ - QString quote; -}; - -#endif diff --git a/ktimetracker/support/Makefile.am b/ktimetracker/support/Makefile.am deleted file mode 100644 index a52fb8a4c3..0000000000 --- a/ktimetracker/support/Makefile.am +++ /dev/null @@ -1,4 +0,0 @@ -EXTRA_DIST = karm.desktop newtask.dlg - -datadir = $(kde_datadir)/karm - diff --git a/ktimetracker/support/karm.desktop b/ktimetracker/support/karm.desktop deleted file mode 100644 index 84b23edfa1..0000000000 --- a/ktimetracker/support/karm.desktop +++ /dev/null @@ -1,78 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Name=KArm -Name[af]=Karm -Name[ar]=كارم -Name[eo]=Tempomezurilo -Name[hi]=के-आर्म -Name[mk]=КРака -Name[sv]=Karm -Name[ta]=Kஅம் -Name[xh]=KAlrm -Name[xx]=xxKArmxx -GenericName=Personal Time Tracker -GenericName[af]=Persoonlike Tyd Volger -GenericName[ar]=جدول المواعيد -GenericName[az]=Şəxsi Saat İzləyici -GenericName[bg]=Отчитане на времето -GenericName[br]=Roudenner amzer personel -GenericName[bs]=Osobni mjerač vremena -GenericName[ca]=Cronòmetre personal -GenericName[cs]=Osobní měřič času -GenericName[cy]=Dilynnydd Amser Personol -GenericName[da]=Personlig tidsoversigt -GenericName[de]=Persönliche Zeiterfassung -GenericName[el]=Προσωπικός καταγραφέας χρόνου -GenericName[eo]=Tempomezurilo por viaj aktivecoj -GenericName[es]=Cronómetro personal -GenericName[et]=Personaalne ajaarvestus -GenericName[eu]=Denbora Kudeatzaile Pertsonala -GenericName[fi]=Henkilökohtainen ajanhallintaohjelma -GenericName[fr]=Chronomètre individuel de tâches -GenericName[gl]=Xestor Persoal de Proxectos -GenericName[he]=מנהל זמן אישי -GenericName[hr]=Osobni mjerač vremena -GenericName[hu]=Időfelhasználás-figyelő -GenericName[id]=Tracker Waktu Pribadi -GenericName[is]=Fylgjast með í hvað tíminn fer -GenericName[it]=Segnatempo personale -GenericName[ko]=일하는 시간을 잴 수 있습니다 -GenericName[lt]=Asmeninis laiko sekėjas -GenericName[lv]=Personālais Laika Atsekotājs -GenericName[mk]=Водење сметка за вашето слободно време -GenericName[ms]=Penjejak Waktu Peribadi -GenericName[mt]=Żomm il-ħin personali -GenericName[nb]=Personlig tidsoversikt -GenericName[nl]=Tijdsregistratie -GenericName[nn]=Personleg tidsmålar -GenericName[nso]=Seswaranako sa Nako ya Botho -GenericName[pl]=Osobisty Czasomierz -GenericName[pt]=Gestor Pessoal de Tempo -GenericName[pt_BR]=Gerenciador pessoal de tempo -GenericName[ro]=Organizator timp personal -GenericName[ru]=Учёт рабочего времени -GenericName[sk]=Osobný merač času -GenericName[sl]=Osebni merilec časa -GenericName[sr]=Лични пратилац времена -GenericName[sr@Latn]=Lični pratilac vremena -GenericName[sv]=Personlig tidmätare -GenericName[ta]=தனிப்பயன் நேரம் பின்பற்றி -GenericName[tg]=Баҳисобгирии вақти корӣ -GenericName[tr]=Kişisel Saat İzleyici -GenericName[uk]=Персональний лічильник часу -GenericName[ven]=Tshisedzulusi tsha tshifhinga tsha vhune -GenericName[vi]=Trình đo thời gian -GenericName[xh]=Umfumani Wexesha Lobuqu -GenericName[xx]=xxPersonal Time Trackerxx -GenericName[zh_CN]=个人时间记录 -GenericName[zh_TW]=個人時程記錄 -GenericName[zu]=Umgcini Wesikhathi Esemfihlo -Exec=karm -caption "%c" %i %m -Icon=karm -Path= -DocPath=karm/index.html -Type=Application -Terminal=false -X-KDE-StartupNotify=true -X-DCOP-ServiceType=Multi -Categories=Qt;KDE;Utility;X-KDE-More; diff --git a/ktimetracker/support/newtask.dlg b/ktimetracker/support/newtask.dlg deleted file mode 100644 index 3f4b1ad6c7..0000000000 --- a/ktimetracker/support/newtask.dlg +++ /dev/null @@ -1,79 +0,0 @@ -DlgEdit:v1.2:Dialog: -Dialog { - ClassHeader {adddlg.h} - ClassSource {adddlg.cpp} - ClassName {KarmAddDlg} - DataHeader {adddata.h} - DataSource {adddata.cpp} - DataName {KAddDlgData} - WindowBaseClass {QDialog} - IsModal {FALSE} - WindowCaption {Karm: New Task} -} -WidgetLayout { - Rect {5 102 300 150} - Grid {10} - -Frame { - Style {34} - Rect {10 10 280 90} - Name {Frame_1} -} -Label { - Text {Task Name} - Alignment {265} - AutoResize {FALSE} - Margin {-1} - Rect {20 20 100 30} - Name {Label_1} -} -Label { - Text {Accumutated time (in minutes)} - Alignment {1289} - AutoResize {FALSE} - Margin {-1} - Rect {20 60 100 30} - Name {Label_2} -} -LineEdit { - Text {} - EchoMode {Normal} - MaxLength {32767} - FrameShown {TRUE} - Rect {130 20 150 30} - Name {LineEdit_1} - Variable {_taskName} -} -LineEdit { - Text {} - EchoMode {Normal} - MaxLength {32767} - FrameShown {TRUE} - Rect {130 60 150 30} - Name {LineEdit_2} - Variable {_taskTime} -} -PushButton { - ToggleButton {FALSE} - Default {FALSE} - AutoDefault {FALSE} - Text {&Ok} - AutoRepeat {FALSE} - AutoResize {FALSE} - Rect {40 110 100 30} - Name {PushButton_1} - Variable {_okButton} - Signal {[Public] clicked --> okClicked ()} -} -PushButton { - ToggleButton {FALSE} - Default {FALSE} - AutoDefault {FALSE} - Text {&Cancel} - AutoRepeat {FALSE} - AutoResize {FALSE} - Rect {160 110 100 30} - Name {PushButton_2} - Variable {_cancelButton} - Signal {[Public] clicked --> cancelClicked ()} -}} diff --git a/ktimetracker/task.cpp b/ktimetracker/task.cpp deleted file mode 100644 index 3312f0bc1a..0000000000 --- a/ktimetracker/task.cpp +++ /dev/null @@ -1,457 +0,0 @@ -#include -#include -#include -#include - -#include - -#include "kapplication.h" // kapp -#include "kdebug.h" - -#include "event.h" - -#include "karmutility.h" -#include "task.h" -#include "taskview.h" -#include "preferences.h" - - -const int gSecondsPerMinute = 60; - - -QPtrVector *Task::icons = 0; - -Task::Task( const QString& taskName, long minutes, long sessionTime, - DesktopList desktops, TaskView *parent) - : QObject(), QListViewItem(parent) -{ - init(taskName, minutes, sessionTime, desktops, 0); -} - -Task::Task( const QString& taskName, long minutes, long sessionTime, - DesktopList desktops, Task *parent) - : QObject(), QListViewItem(parent) -{ - init(taskName, minutes, sessionTime, desktops, 0); -} - -Task::Task( KCal::Todo* todo, TaskView* parent ) - : QObject(), QListViewItem( parent ) -{ - long minutes = 0; - QString name; - long sessionTime = 0; - int percent_complete = 0; - DesktopList desktops; - - parseIncidence(todo, minutes, sessionTime, name, desktops, percent_complete); - init(name, minutes, sessionTime, desktops, percent_complete); -} - -void Task::init( const QString& taskName, long minutes, long sessionTime, - DesktopList desktops, int percent_complete) -{ - // If our parent is the taskview then connect our totalTimesChanged - // signal to its receiver - if ( ! parent() ) - connect( this, SIGNAL( totalTimesChanged ( long, long ) ), - listView(), SLOT( taskTotalTimesChanged( long, long) )); - - connect( this, SIGNAL( deletingTask( Task* ) ), - listView(), SLOT( deletingTask( Task* ) )); - - if (icons == 0) { - icons = new QPtrVector(8); - KIconLoader* kil = new KIconLoader("karm"); // always load icons from the KArm application - for (int i=0; i<8; i++) - { - QPixmap *icon = new QPixmap(); - QString name; - name.sprintf("watch-%d.xpm",i); - *icon = kil->loadIcon( name, KIcon::User ); - icons->insert(i,icon); - } - } - - _removing = false; - _name = taskName.stripWhiteSpace(); - _lastStart = QDateTime::currentDateTime(); - _totalTime = _time = minutes; - _totalSessionTime = _sessionTime = sessionTime; - _timer = new QTimer(this); - _desktops = desktops; - connect(_timer, SIGNAL(timeout()), this, SLOT(updateActiveIcon())); - setPixmap(1, UserIcon(QString::fromLatin1("empty-watch.xpm"))); - _currentPic = 0; - _percentcomplete = percent_complete; - - update(); - changeParentTotalTimes( _sessionTime, _time); -} - -Task::~Task() { - emit deletingTask(this); - delete _timer; -} - -void Task::setRunning( bool on, KarmStorage* storage ) -{ - if ( on ) { - if (isComplete()) return; // don't start if its marked complete - if (!_timer->isActive()) { - _timer->start(1000); - storage->startTimer(this); - _currentPic=7; - _lastStart = QDateTime::currentDateTime(); - updateActiveIcon(); - } - } - else { - if (_timer->isActive()) { - _timer->stop(); - if ( ! _removing ) { - storage->stopTimer(this); - setPixmap(1, UserIcon(QString::fromLatin1("empty-watch.xpm"))); - } - } - } -} - -void Task::setUid(QString uid) { - _uid = uid; -} - -bool Task::isRunning() const -{ - return _timer->isActive(); -} - -void Task::setName( const QString& name, KarmStorage* storage ) -{ - kdDebug(5970) << "Task:setName: " << name << endl; - - QString oldname = _name; - if ( oldname != name ) { - _name = name; - storage->setName(this, oldname); - update(); - } -} - -void Task::setPercentComplete(const int percent, KarmStorage *storage) -{ - kdDebug(5970) << "Task::setPercentComplete(" << percent << ", storage): " - << _uid << endl; - - if (!percent) - _percentcomplete = 0; - else if (percent > 100) - _percentcomplete = 100; - else if (percent < 0) - _percentcomplete = 0; - else - _percentcomplete = percent; - - if (isRunning() && _percentcomplete==100) setRunning(false, storage); - - setPixmapProgress(); - - // When parent marked as complete, mark all children as complete as well. - // Complete tasks are not displayed in the task view, so if a parent is - // marked as complete and some of the children are not, then we get an error - // message. KArm actually keep chugging along in this case and displays the - // child tasks just fine, so an alternative solution is to remove that error - // message (from KarmStorage::load). But I think it makes more sense that - // if you mark a parent task as complete, then all children should be - // complete as well. - // - // This behavior is consistent with KOrganizer (as of 2003-09-24). - if (_percentcomplete == 100) - { - for (Task* child= this->firstChild(); child; child = child->nextSibling()) - child->setPercentComplete(_percentcomplete, storage); - } -} - -void Task::setPixmapProgress() -{ - QPixmap* icon = new QPixmap(); - if (_percentcomplete >= 100) - *icon = UserIcon("task-complete.xpm"); - else - *icon = UserIcon("task-incomplete.xpm"); - setPixmap(0, *icon); -} - -bool Task::isComplete() { return _percentcomplete == 100; } - -void Task::removeFromView() -{ - for (Task* child= this->firstChild(); child; child= child->nextSibling()) - child->removeFromView(); - delete this; -} - -void Task::setDesktopList ( DesktopList desktopList ) -{ - _desktops = desktopList; -} - -void Task::changeTime( long minutes, KarmStorage* storage ) -{ - changeTimes( minutes, minutes, storage); -} - -void Task::changeTimes( long minutesSession, long minutes, KarmStorage* storage) -{ - if( minutesSession != 0 || minutes != 0) - { - _sessionTime += minutesSession; - _time += minutes; - if ( storage ) storage->changeTime(this, minutes * gSecondsPerMinute); - changeTotalTimes( minutesSession, minutes ); - } -} - -void Task::changeTotalTimes( long minutesSession, long minutes ) -{ - kdDebug(5970) - << "Task::changeTotalTimes(" << minutesSession << ", " - << minutes << ") for " << name() << endl; - - _totalSessionTime += minutesSession; - _totalTime += minutes; - update(); - changeParentTotalTimes( minutesSession, minutes ); -} - -void Task::resetTimes() -{ - _totalSessionTime -= _sessionTime; - _totalTime -= _time; - changeParentTotalTimes( -_sessionTime, -_time); - _sessionTime = 0; - _time = 0; - update(); -} - -void Task::changeParentTotalTimes( long minutesSession, long minutes ) -{ - //kdDebug(5970) - // << "Task::changeParentTotalTimes(" << minutesSession << ", " - // << minutes << ") for " << name() << endl; - - if ( isRoot() ) - emit totalTimesChanged( minutesSession, minutes ); - else - parent()->changeTotalTimes( minutesSession, minutes ); -} - -bool Task::remove( QPtrList& activeTasks, KarmStorage* storage) -{ - kdDebug(5970) << "Task::remove: " << _name << endl; - - bool ok = true; - - _removing = true; - storage->removeTask(this); - if( isRunning() ) setRunning( false, storage ); - - for (Task* child = this->firstChild(); child; child = child->nextSibling()) - { - if (child->isRunning()) - child->setRunning(false, storage); - child->remove(activeTasks, storage); - } - - changeParentTotalTimes( -_sessionTime, -_time); - - _removing = false; - - return ok; -} - -void Task::updateActiveIcon() -{ - _currentPic = (_currentPic+1) % 8; - setPixmap(1, *(*icons)[_currentPic]); -} - -QString Task::fullName() const -{ - if (isRoot()) - return name(); - else - return parent()->fullName() + QString::fromLatin1("/") + name(); -} - -KCal::Todo* Task::asTodo(KCal::Todo* todo) const -{ - - Q_ASSERT( todo != NULL ); - - kdDebug(5970) << "Task::asTodo: name() = '" << name() << "'" << endl; - todo->setSummary( name() ); - - // Note: if the date start is empty, the KOrganizer GUI will have the - // checkbox blank, but will prefill the todo's starting datetime to the - // time the file is opened. - // todo->setDtStart( current ); - - todo->setCustomProperty( kapp->instanceName(), - QCString( "totalTaskTime" ), QString::number( _time ) ); - todo->setCustomProperty( kapp->instanceName(), - QCString( "totalSessionTime" ), QString::number( _sessionTime) ); - - if (getDesktopStr().isEmpty()) - todo->removeCustomProperty(kapp->instanceName(), QCString("desktopList")); - else - todo->setCustomProperty( kapp->instanceName(), - QCString( "desktopList" ), getDesktopStr() ); - - todo->setOrganizer( Preferences::instance()->userRealName() ); - - todo->setPercentComplete(_percentcomplete); - - return todo; -} - -bool Task::parseIncidence( KCal::Incidence* incident, long& minutes, - long& sessionMinutes, QString& name, DesktopList& desktops, - int& percent_complete ) -{ - bool ok; - - name = incident->summary(); - _uid = incident->uid(); - - _comment = incident->description(); - - ok = false; - minutes = incident->customProperty( kapp->instanceName(), - QCString( "totalTaskTime" )).toInt( &ok ); - if ( !ok ) - minutes = 0; - - ok = false; - sessionMinutes = incident->customProperty( kapp->instanceName(), - QCString( "totalSessionTime" )).toInt( &ok ); - if ( !ok ) - sessionMinutes = 0; - - QString desktopList = incident->customProperty( kapp->instanceName(), - QCString( "desktopList" ) ); - QStringList desktopStrList = QStringList::split( QString::fromLatin1(","), - desktopList ); - desktops.clear(); - - for ( QStringList::iterator iter = desktopStrList.begin(); - iter != desktopStrList.end(); - ++iter ) { - int desktopInt = (*iter).toInt( &ok ); - if ( ok ) { - desktops.push_back( desktopInt ); - } - } - - percent_complete = static_cast(incident)->percentComplete(); - - //kdDebug(5970) << "Task::parseIncidence: " - // << name << ", Minutes: " << minutes - // << ", desktop: " << desktopList << endl; - - return true; -} - -QString Task::getDesktopStr() const -{ - if ( _desktops.empty() ) - return QString(); - - QString desktopstr; - for ( DesktopList::const_iterator iter = _desktops.begin(); - iter != _desktops.end(); - ++iter ) { - desktopstr += QString::number( *iter ) + QString::fromLatin1( "," ); - } - desktopstr.remove( desktopstr.length() - 1, 1 ); - return desktopstr; -} - -void Task::cut() -{ - //kdDebug(5970) << "Task::cut - " << name() << endl; - changeParentTotalTimes( -_totalSessionTime, -_totalTime); - if ( ! parent()) - listView()->takeItem(this); - else - parent()->takeItem(this); -} - -void Task::move(Task* destination) -{ - cut(); - paste(destination); -} - -void Task::paste(Task* destination) -{ - destination->insertItem(this); - changeParentTotalTimes( _totalSessionTime, _totalTime); -} - -void Task::update() -{ - setText(0, _name); - setText(1, formatTime(_sessionTime)); - setText(2, formatTime(_time)); - setText(3, formatTime(_totalSessionTime)); - setText(4, formatTime(_totalTime)); -} - -void Task::addComment( QString comment, KarmStorage* storage ) -{ - _comment = _comment + QString::fromLatin1("\n") + comment; - storage->addComment(this, comment); -} - -QString Task::comment() const -{ - return _comment; -} - -int Task::compare ( QListViewItem * i, int col, bool ascending ) const -{ - long thistime = 0; - long thattime = 0; - Task *task = static_cast(i); - - switch ( col ) - { - case 1: - thistime = _sessionTime; - thattime = task->sessionTime(); - break; - case 2: - thistime = _time; - thattime = task->time(); - break; - case 3: - thistime = _totalSessionTime; - thattime = task->totalSessionTime(); - break; - case 4: - thistime = _totalTime; - thattime = task->totalTime(); - break; - default: - return key(col, ascending).localeAwareCompare( i->key(col, ascending) ); - } - - if ( thistime < thattime ) return -1; - if ( thistime > thattime ) return 1; - return 0; - -} - -#include "task.moc" diff --git a/ktimetracker/task.h b/ktimetracker/task.h deleted file mode 100644 index 4bcb74efdc..0000000000 --- a/ktimetracker/task.h +++ /dev/null @@ -1,289 +0,0 @@ -#ifndef KARM_TASK_H -#define KARM_TASK_H - -// Required b/c QPtrList is a struct, not a class. -#include - -// Requred b/c/ QPtrVector is a template (?) -#include - -// Required b/c DesktopList is a typedef not a class. -#include "desktoplist.h" - -// Required b/c of static cast below? (How else can compiler know that a -// TaskView is a subclass or QListView?) -#include "taskview.h" - -class QFile; -class QString; -class KarmStorage; - -class QTimer; -class KCal::Incidence; -class KCal::Todo; -class QObject; -class QPixmap; - -/// \class Task -/** \brief A class representing a task - * - * A "Task" object stores information about a task such as it's name, - * total and session times. - * - * It can log when the task is started, stoped or deleted. - * - * If a task is associated with some desktop's activity it can remember that - * too. - * - * It can also contain subtasks - these are managed using the - * QListViewItem class. - */ -class Task : public QObject, public QListViewItem -{ - Q_OBJECT - - public: - //@{ constructors - Task( const QString& taskame, long minutes, long sessionTime, - DesktopList desktops, TaskView* parent = 0); - Task( const QString& taskame, long minutes, long sessionTime, - DesktopList desktops, Task* parent = 0); - Task( KCal::Todo* incident, TaskView* parent ); - //@} - /* destructor */ - ~Task(); - - /** return parent Task or null in case of TaskView. - * same as QListViewItem::parent() - */ - Task* firstChild() const { return (Task*)QListViewItem::firstChild(); } - Task* nextSibling() const { return (Task*)QListViewItem::nextSibling(); } - Task* parent() const { return (Task*)QListViewItem::parent(); } - - /** Return task view for this task */ - TaskView* taskView() const { - return static_cast( listView() ); - } - - /** Return unique iCalendar Todo ID for this task. */ - QString uid() const { return _uid; } - - /** - * Set unique id for the task. - * - * The uid is the key used to update the storage. - * - * @param uid The new unique id. - */ - void setUid(const QString uid); - - /** cut Task out of parent Task or the TaskView */ - void cut(); - /** cut Task out of parent Task or the TaskView and into the - * destination Task */ - void move(Task* destination); - /** insert Task into the destination Task */ - void paste(Task* destination); - - /** Sort times numerically, not alphabetically. */ - int compare ( QListViewItem * i, int col, bool ascending ) const; - - //@{ timing related functions - - /** - * Change task time. Adds minutes to both total time and session time. - * - * @param minutes minutes to add to - may be negative - * @param storage Pointer to KarmStorage instance. - * If zero, don't save changes. - */ - void changeTime( long minutes, KarmStorage* storage ); - - /** - * Add minutes to time and session time, and write to storage. - * - * @param minutesSession minutes to add to task session time - * @param minutes minutes to add to task time - * @param storage Pointer to KarmStorage instance. - * If zero, don't save changes. - */ - void changeTimes - ( long minutesSession, long minutes, KarmStorage* storage=0); - - /** adds minutes to total and session time - * - * @param minutesSession minutes to add to task total session time - * @param minutes minutes to add to task total time - */ - void changeTotalTimes( long minutesSession, long minutes ); - - /** - * Reset all times to 0 - */ - void resetTimes(); - - /*@{ returns the times accumulated by the task - * @return total time in minutes - */ - long time() const { return _time; }; - long totalTime() const { return _totalTime; }; - long sessionTime() const { return _sessionTime; }; - long totalSessionTime() const { return _totalSessionTime; }; - - /** - * Return time the task was started. - */ - QDateTime startTime() const { return _lastStart; }; - - /** sets session time to zero. */ - void startNewSession() { changeTimes( -_sessionTime, 0 ); }; - //@} - - //@{ desktop related functions - - void setDesktopList ( DesktopList dl ); - DesktopList getDesktops() const { return _desktops;} - - QString getDesktopStr() const; - //@} - - //@{ name related functions - - /** sets the name of the task - * @param name a pointer to the name. A deep copy will be made. - * @param storage a pointer to a KarmStorage object. - */ - void setName( const QString& name, KarmStorage* storage ); - - /** returns the name of this task. - * @return a pointer to the name. - */ - QString name() const { return _name; }; - - /** - * Returns that task name, prefixed by parent tree up to root. - * - * Task names are seperated by a forward slash: / - */ - QString fullName() const; - //@} - - /** Update the display of the task (all columns) in the UI. */ - void update(); - - //@{ the state of a Task - stopped, running - - /** starts or stops a task - * @param on true or false for starting or stopping a task - * @param storage a pointer to a KarmStorage object. - */ - void setRunning(bool on, KarmStorage* storage); - - /** return the state of a task - if it's running or not - * @return true or false depending on whether the task is running - */ - bool isRunning() const; - //@} - - bool parseIncidence(KCal::Incidence*, long& minutes, - long& sessionMinutes, QString& name, DesktopList& desktops, - int& percent_complete); - - /** - * Load the todo passed in with this tasks info. - */ - KCal::Todo* asTodo(KCal::Todo* calendar) const; - - /** Add a comment to this task. */ - void addComment( QString comment, KarmStorage* storage ); - - /** Retrieve the entire comment for the task. */ - QString comment() const; - - /** tells you whether this task is the root of the task tree */ - bool isRoot() const { return parent() == 0; } - - /** remove Task with all it's children - * @param activeTasks - list of aktive tasks - * @param storage a pointer to a KarmStorage object. - */ - bool remove( QPtrList& activeTasks, KarmStorage* storage ); - - /** - * Update percent complete for this task. - * - * Tasks that are complete (i.e., percent = 100) do not show up in - * taskview. If percent NULL, set to zero. If greater than 100, set to - * 100. If less than zero, set to zero. - */ - void setPercentComplete(const int percent, KarmStorage *storage); - - - /** Sets an appropriate icon for this task based on its level of - * completion */ - void setPixmapProgress(); - - /** Return true if task is complete (percent complete equals 100). */ - bool isComplete(); - - /** Remove current task and all it's children from the view. */ - void removeFromView(); - - protected: - void changeParentTotalTimes( long minutesSession, long minutes ); - - signals: - void totalTimesChanged( long minutesSession, long minutes); - /** signal that we're about to delete a task */ - void deletingTask(Task* thisTask); - - protected slots: - /** animate the active icon */ - void updateActiveIcon(); - - private: - - /** The iCal unique ID of the Todo for this task. */ - QString _uid; - - /** The comment associated with this Task. */ - QString _comment; - - int _percentcomplete; - - long totalTimeInSeconds() const { return _totalTime * 60; } - - /** if the time or session time is negative set them to zero */ - void noNegativeTimes(); - - /** initialize a task */ - void init( const QString& taskame, long minutes, long sessionTime, - DesktopList desktops, int percent_complete); - - - /** task name */ - QString _name; - - /** Last time this task was started. */ - QDateTime _lastStart; - - //@{ totals of the whole subtree including self - long _totalTime; - long _totalSessionTime; - //@} - - //@{ times spend on the task itself - long _time; - long _sessionTime; - //@} - DesktopList _desktops; - QTimer *_timer; - int _currentPic; - static QPtrVector *icons; - - /** Don't need to update storage when deleting task from list. */ - bool _removing; - -}; - -#endif // KARM_TASK_H diff --git a/ktimetracker/taskview.cpp b/ktimetracker/taskview.cpp deleted file mode 100644 index de768fc12b..0000000000 --- a/ktimetracker/taskview.cpp +++ /dev/null @@ -1,828 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "kapplication.h" // kapp -#include -#include -#include -#include // i18n -#include -#include - -#include "csvexportdialog.h" -#include "desktoptracker.h" -#include "edittaskdialog.h" -#include "idletimedetector.h" -#include "karmstorage.h" -#include "plannerparser.h" -#include "preferences.h" -#include "printdialog.h" -#include "reportcriteria.h" -#include "task.h" -#include "taskview.h" -#include "timekard.h" - -#define T_LINESIZE 1023 -#define HIDDEN_COLUMN -10 - -class DesktopTracker; - -TaskView::TaskView(QWidget *parent, const char *name, const QString &icsfile ):KListView(parent,name) -{ - _preferences = Preferences::instance( icsfile ); - _storage = KarmStorage::instance(); - - connect( this, SIGNAL( expanded( QListViewItem * ) ), - this, SLOT( itemStateChanged( QListViewItem * ) ) ); - connect( this, SIGNAL( collapsed( QListViewItem * ) ), - this, SLOT( itemStateChanged( QListViewItem * ) ) ); - - // setup default values - previousColumnWidths[0] = previousColumnWidths[1] - = previousColumnWidths[2] = previousColumnWidths[3] = HIDDEN_COLUMN; - - addColumn( i18n("Task Name") ); - addColumn( i18n("Session Time") ); - addColumn( i18n("Time") ); - addColumn( i18n("Total Session Time") ); - addColumn( i18n("Total Time") ); - setColumnAlignment( 1, Qt::AlignRight ); - setColumnAlignment( 2, Qt::AlignRight ); - setColumnAlignment( 3, Qt::AlignRight ); - setColumnAlignment( 4, Qt::AlignRight ); - adaptColumns(); - setAllColumnsShowFocus( true ); - - // set up the minuteTimer - _minuteTimer = new QTimer(this); - connect( _minuteTimer, SIGNAL( timeout() ), this, SLOT( minuteUpdate() )); - _minuteTimer->start(1000 * secsPerMinute); - - // React when user changes iCalFile - connect(_preferences, SIGNAL(iCalFile(QString)), - this, SLOT(iCalFileChanged(QString))); - - // resize columns when config is changed - connect(_preferences, SIGNAL( setupChanged() ), this,SLOT( adaptColumns() )); - - _minuteTimer->start(1000 * secsPerMinute); - - // Set up the idle detection. - _idleTimeDetector = new IdleTimeDetector( _preferences->idlenessTimeout() ); - connect( _idleTimeDetector, SIGNAL( extractTime(int) ), - this, SLOT( extractTime(int) )); - connect( _idleTimeDetector, SIGNAL( stopAllTimers() ), - this, SLOT( stopAllTimers() )); - connect( _preferences, SIGNAL( idlenessTimeout(int) ), - _idleTimeDetector, SLOT( setMaxIdle(int) )); - connect( _preferences, SIGNAL( detectIdleness(bool) ), - _idleTimeDetector, SLOT( toggleOverAllIdleDetection(bool) )); - if (!_idleTimeDetector->isIdleDetectionPossible()) - _preferences->disableIdleDetection(); - - // Setup auto save timer - _autoSaveTimer = new QTimer(this); - connect( _preferences, SIGNAL( autoSave(bool) ), - this, SLOT( autoSaveChanged(bool) )); - connect( _preferences, SIGNAL( autoSavePeriod(int) ), - this, SLOT( autoSavePeriodChanged(int) )); - connect( _autoSaveTimer, SIGNAL( timeout() ), this, SLOT( save() )); - - // Setup manual save timer (to save changes a little while after they happen) - _manualSaveTimer = new QTimer(this); - connect( _manualSaveTimer, SIGNAL( timeout() ), this, SLOT( save() )); - - // Connect desktop tracker events to task starting/stopping - _desktopTracker = new DesktopTracker(); - connect( _desktopTracker, SIGNAL( reachedtActiveDesktop( Task* ) ), - this, SLOT( startTimerFor(Task*) )); - connect( _desktopTracker, SIGNAL( leftActiveDesktop( Task* ) ), - this, SLOT( stopTimerFor(Task*) )); -} - -KarmStorage* TaskView::storage() -{ - return _storage; -} - -void TaskView::contentsMousePressEvent ( QMouseEvent * e ) -{ - kdDebug(5970) << "entering contentsMousePressEvent" << endl; - KListView::contentsMousePressEvent(e); - Task *task = current_item(); - // if clicked onto the "completed" icon - if ( e->x()<=18 ) - { - if ( task->isComplete() ) task->setPercentComplete( 0, _storage ); - else task->setPercentComplete( 100, _storage ); - } -} - -void TaskView::contentsMouseDoubleClickEvent ( QMouseEvent * e ) -{ - kdDebug(5970) << "entering contentsMouseDoubleClickEvent" << endl; - KListView::contentsMouseDoubleClickEvent(e); - - // start/stop timer - Task *task = current_item(); - - if ( task != 0 && activeTasks.findRef(task) == -1 ) - { - // Stop all the other timers. - for (unsigned int i=0; isetRunning(false, _storage); - activeTasks.clear(); - - // Start the new timer. - startCurrentTimer(); - } - else stopCurrentTimer(); -} - -TaskView::~TaskView() -{ - _preferences->save(); -} - -Task* TaskView::first_child() const -{ - return static_cast(firstChild()); -} - -Task* TaskView::current_item() const -{ - return static_cast(currentItem()); -} - -Task* TaskView::item_at_index(int i) -{ - return static_cast(itemAtIndex(i)); -} - -void TaskView::load( QString fileName ) -{ - // if the program is used as an embedded plugin for konqueror, there may be a need - // to load from a file without touching the preferences. - _isloading = true; - QString err = _storage->load(this, _preferences, fileName); - - if (!err.isEmpty()) - { - KMessageBox::error(this, err); - _isloading = false; - return; - } - - // Register tasks with desktop tracker - int i = 0; - for ( Task* t = item_at_index(i); t; t = item_at_index(++i) ) - _desktopTracker->registerForDesktops( t, t->getDesktops() ); - - restoreItemState( first_child() ); - - setSelected(first_child(), true); - setCurrentItem(first_child()); - _desktopTracker->startTracking(); - _isloading = false; - refresh(); -} - -void TaskView::restoreItemState( QListViewItem *item ) -{ - while( item ) - { - Task *t = (Task *)item; - t->setOpen( _preferences->readBoolEntry( t->uid() ) ); - if( item->childCount() > 0 ) restoreItemState( item->firstChild() ); - item = item->nextSibling(); - } -} - -void TaskView::itemStateChanged( QListViewItem *item ) -{ - if ( !item || _isloading ) return; - Task *t = (Task *)item; - kdDebug(5970) << "TaskView::itemStateChanged()" - << " uid=" << t->uid() << " state=" << t->isOpen() - << endl; - if( _preferences ) _preferences->writeEntry( t->uid(), t->isOpen() ); -} - -void TaskView::deleteItemState( QListViewItem *item ) -{ - if ( !item ) return; - Task *t = (Task *)item; - kdDebug(5970) << "TaskView:deleteItemState()" - << " uid=" << t->uid() << endl; - if( _preferences ) _preferences->deleteEntry( t->uid() ); -} - -void TaskView::closeStorage() { _storage->closeStorage( this ); } - -void TaskView::iCalFileModified(ResourceCalendar *rc) -{ - kdDebug(5970) << "entering iCalFileModified" << endl; - stopAllTimers(); - kdDebug(5970) << rc->infoText() << endl; - rc->dump(); - _storage->buildTaskView(rc,this); - kdDebug(5970) << "exiting iCalFileModified" << endl; -} - -void TaskView::refresh() -{ - kdDebug(5970) << "entering TaskView::refresh()" << endl; - this->setRootIsDecorated(true); - int i = 0; - for ( Task* t = item_at_index(i); t; t = item_at_index(++i) ) - { - t->setPixmapProgress(); - } - - // remove root decoration if there is no more children. - bool anyChilds = false; - for(Task* child = first_child(); - child; - child = child->nextSibling()) { - if (child->childCount() != 0) { - anyChilds = true; - break; - } - } - if (!anyChilds) { - setRootIsDecorated(false); - } - kdDebug(5970) << "exiting TaskView::refresh()" << endl; -} - -void TaskView::loadFromFlatFile() -{ - kdDebug(5970) << "TaskView::loadFromFlatFile()" << endl; - - //KFileDialog::getSaveFileName("icalout.ics",i18n("*.ics|ICalendars"),this); - - QString fileName(KFileDialog::getOpenFileName(QString::null, QString::null, - 0)); - if (!fileName.isEmpty()) { - QString err = _storage->loadFromFlatFile(this, fileName); - if (!err.isEmpty()) - { - KMessageBox::error(this, err); - return; - } - // Register tasks with desktop tracker - int task_idx = 0; - Task* task = item_at_index(task_idx++); - while (task) - { - // item_at_index returns 0 where no more items. - _desktopTracker->registerForDesktops( task, task->getDesktops() ); - task = item_at_index(task_idx++); - } - - setSelected(first_child(), true); - setCurrentItem(first_child()); - - _desktopTracker->startTracking(); - } -} - -QString TaskView::importPlanner(QString fileName) -{ - kdDebug(5970) << "entering importPlanner" << endl; - PlannerParser* handler=new PlannerParser(this); - if (fileName.isEmpty()) fileName=KFileDialog::getOpenFileName(QString::null, QString::null, 0); - QFile xmlFile( fileName ); - QXmlInputSource source( xmlFile ); - QXmlSimpleReader reader; - reader.setContentHandler( handler ); - reader.parse( source ); - refresh(); - return ""; -} - -QString TaskView::report( const ReportCriteria& rc ) -{ - return _storage->report( this, rc ); -} - -void TaskView::exportcsvFile() -{ - kdDebug(5970) << "TaskView::exportcsvFile()" << endl; - - CSVExportDialog dialog( ReportCriteria::CSVTotalsExport, this ); - if ( current_item() && current_item()->isRoot() ) - dialog.enableTasksToExportQuestion(); - dialog.urlExportTo->KURLRequester::setMode(KFile::File); - if ( dialog.exec() ) { - QString err = _storage->report( this, dialog.reportCriteria() ); - if ( !err.isEmpty() ) KMessageBox::error( this, i18n(err.ascii()) ); - } -} - -QString TaskView::exportcsvHistory() -{ - kdDebug(5970) << "TaskView::exportcsvHistory()" << endl; - QString err; - - CSVExportDialog dialog( ReportCriteria::CSVHistoryExport, this ); - if ( current_item() && current_item()->isRoot() ) - dialog.enableTasksToExportQuestion(); - dialog.urlExportTo->KURLRequester::setMode(KFile::File); - if ( dialog.exec() ) { - err = _storage->report( this, dialog.reportCriteria() ); - } - return err; -} - -void TaskView::scheduleSave() -{ - _manualSaveTimer->start( 10, true /*single-shot*/ ); -} - -Preferences* TaskView::preferences() { return _preferences; } - -QString TaskView::save() -{ - // DF: this code created a new event for the running task(s), - // at every call (very frequent with autosave) !!! - // -> if one wants autosave to save the current event, then - // Task needs to store the "current event" and we need to update - // it before calling save. -#if 0 - // Stop then start all timers so history entries are written. This is - // inefficient if more than one task running, but it is correct. It is - // inefficient because the iCalendar file is saved every time a task's - // setRunning(false, ...) is called. For a big ics file, this could be a - // drag. However, it does ensure that the data will be consistent. And - // if the most common use case is that one task is running most of the time, - // it won't make any difference. - for (unsigned int i = 0; i < activeTasks.count(); i++) - { - activeTasks.at(i)->setRunning(false, _storage); - activeTasks.at(i)->setRunning(true, _storage); - } - - // If there was an active task, the iCal file has already been saved. - if (activeTasks.count() == 0) -#endif - { - return _storage->save(this); - } -} - -void TaskView::startCurrentTimer() -{ - startTimerFor( current_item() ); -} - -long TaskView::count() -{ - long n = 0; - for (Task* t = item_at_index(n); t; t=item_at_index(++n)); - return n; -} - -void TaskView::startTimerFor(Task* task) -{ - if (task != 0 && activeTasks.findRef(task) == -1) { - _idleTimeDetector->startIdleDetection(); - task->setRunning(true, _storage); - activeTasks.append(task); - emit updateButtons(); - if ( activeTasks.count() == 1 ) - emit timersActive(); - - emit tasksChanged( activeTasks); - } -} - -void TaskView::stopAllTimers() -{ - for ( unsigned int i = 0; i < activeTasks.count(); i++ ) - activeTasks.at(i)->setRunning(false, _storage); - - _idleTimeDetector->stopIdleDetection(); - activeTasks.clear(); - emit updateButtons(); - emit timersInactive(); - emit tasksChanged( activeTasks); -} - -void TaskView::startNewSession() -{ - QListViewItemIterator item( first_child()); - for ( ; item.current(); ++item ) { - Task * task = (Task *) item.current(); - task->startNewSession(); - } -} - -void TaskView::resetTimeForAllTasks() -{ - QListViewItemIterator item( first_child()); - for ( ; item.current(); ++item ) { - Task * task = (Task *) item.current(); - task->resetTimes(); - } -} - -void TaskView::stopTimerFor(Task* task) -{ - if ( task != 0 && activeTasks.findRef(task) != -1 ) { - activeTasks.removeRef(task); - task->setRunning(false, _storage); - if ( activeTasks.count() == 0 ) { - _idleTimeDetector->stopIdleDetection(); - emit timersInactive(); - } - emit updateButtons(); - } - emit tasksChanged( activeTasks); -} - -void TaskView::stopCurrentTimer() -{ - stopTimerFor( current_item()); -} - -void TaskView::minuteUpdate() -{ - addTimeToActiveTasks(1, false); -} - -void TaskView::addTimeToActiveTasks(int minutes, bool save_data) -{ - for( unsigned int i = 0; i < activeTasks.count(); i++ ) - activeTasks.at(i)->changeTime(minutes, ( save_data ? _storage : 0 ) ); -} - -void TaskView::newTask() -{ - newTask(i18n("New Task"), 0); -} - -void TaskView::newTask(QString caption, Task *parent) -{ - EditTaskDialog *dialog = new EditTaskDialog(caption, false); - long total, totalDiff, session, sessionDiff; - DesktopList desktopList; - - int result = dialog->exec(); - if ( result == QDialog::Accepted ) { - QString taskName = i18n( "Unnamed Task" ); - if ( !dialog->taskName().isEmpty()) taskName = dialog->taskName(); - - total = totalDiff = session = sessionDiff = 0; - dialog->status( &total, &totalDiff, &session, &sessionDiff, &desktopList ); - - // If all available desktops are checked, disable auto tracking, - // since it makes no sense to track for every desktop. - if ( desktopList.size() == ( unsigned int ) _desktopTracker->desktopCount() ) - desktopList.clear(); - - QString uid = addTask( taskName, total, session, desktopList, parent ); - if ( uid.isNull() ) - { - KMessageBox::error( 0, i18n( - "Error storing new task. Your changes were not saved. Make sure you can edit your iCalendar file. Also quit all applications using this file and remove any lock file related to its name from ~/.kde/share/apps/kabc/lock/ " ) ); - } - - delete dialog; - } -} - -QString TaskView::addTask -( const QString& taskname, long total, long session, - const DesktopList& desktops, Task* parent ) -{ - Task *task; - - kdDebug(5970) << "TaskView::addTask: taskname = " << taskname << endl; - - if ( parent ) task = new Task( taskname, total, session, desktops, parent ); - else task = new Task( taskname, total, session, desktops, this ); - - task->setUid( _storage->addTask( task, parent ) ); - - if ( ! task->uid().isNull() ) - { - _desktopTracker->registerForDesktops( task, desktops ); - - setCurrentItem( task ); - - setSelected( task, true ); - - task->setPixmapProgress(); - - save(); - } - else - { - delete task; - } - - return task->uid(); -} - -void TaskView::newSubTask() -{ - Task* task = current_item(); - if(!task) - return; - newTask(i18n("New Sub Task"), task); - task->setOpen(true); - refresh(); -} - -void TaskView::editTask() -{ - Task *task = current_item(); - if (!task) - return; - - DesktopList desktopList = task->getDesktops(); - EditTaskDialog *dialog = new EditTaskDialog(i18n("Edit Task"), true, &desktopList); - dialog->setTask( task->name(), - task->time(), - task->sessionTime() ); - int result = dialog->exec(); - if (result == QDialog::Accepted) { - QString taskName = i18n("Unnamed Task"); - if (!dialog->taskName().isEmpty()) { - taskName = dialog->taskName(); - } - // setName only does something if the new name is different - task->setName(taskName, _storage); - - // update session time as well if the time was changed - long total, session, totalDiff, sessionDiff; - total = totalDiff = session = sessionDiff = 0; - DesktopList desktopList; - dialog->status( &total, &totalDiff, &session, &sessionDiff, &desktopList); - - if( totalDiff != 0 || sessionDiff != 0) - task->changeTimes( sessionDiff, totalDiff, _storage ); - - // If all available desktops are checked, disable auto tracking, - // since it makes no sense to track for every desktop. - if (desktopList.size() == (unsigned int)_desktopTracker->desktopCount()) - desktopList.clear(); - - task->setDesktopList(desktopList); - - _desktopTracker->registerForDesktops( task, desktopList ); - - emit updateButtons(); - } - delete dialog; -} - -//void TaskView::addCommentToTask() -//{ -// Task *task = current_item(); -// if (!task) -// return; - -// bool ok; -// QString comment = KLineEditDlg::getText(i18n("Comment"), -// i18n("Log comment for task '%1':").arg(task->name()), -// QString(), &ok, this); -// if ( ok ) -// task->addComment( comment, _storage ); -//} - -void TaskView::reinstateTask(int completion) -{ - Task* task = current_item(); - if (task == 0) { - KMessageBox::information(0,i18n("No task selected.")); - return; - } - - if (completion<0) completion=0; - if (completion<100) - { - task->setPercentComplete(completion, _storage); - task->setPixmapProgress(); - save(); - emit updateButtons(); - } -} - -void TaskView::deleteTask(bool markingascomplete) -{ - Task *task = current_item(); - if (task == 0) { - KMessageBox::information(0,i18n("No task selected.")); - return; - } - - int response = KMessageBox::Yes; - if (!markingascomplete && _preferences->promptDelete()) { - if (task->childCount() == 0) { - response = KMessageBox::warningContinueCancel( 0, - i18n( "Are you sure you want to delete " - "the task named\n\"%1\" and its entire history?") - .arg(task->name()), - i18n( "Deleting Task"), KStdGuiItem::del()); - } - else { - response = KMessageBox::warningContinueCancel( 0, - i18n( "Are you sure you want to delete the task named" - "\n\"%1\" and its entire history?\n" - "NOTE: all its subtasks and their history will also " - "be deleted.").arg(task->name()), - i18n( "Deleting Task"), KStdGuiItem::del()); - } - } - - if (response == KMessageBox::Continue) - { - if (markingascomplete) - { - task->setPercentComplete(100, _storage); - task->setPixmapProgress(); - save(); - emit updateButtons(); - - // Have to remove after saving, as the save routine only affects tasks - // that are in the view. Otherwise, the new percent complete does not - // get saved. (No longer remove when marked as complete.) - //task->removeFromView(); - - } - else - { - task->remove(activeTasks, _storage); - task->removeFromView(); - deleteItemState( task ); - save(); - } - - // remove root decoration if there is no more children. - bool anyChilds = false; - for(Task* child = first_child(); - child; - child = child->nextSibling()) { - if (child->childCount() != 0) { - anyChilds = true; - break; - } - } - if (!anyChilds) { - setRootIsDecorated(false); - } - - // Stop idle detection if no more counters are running - if (activeTasks.count() == 0) { - _idleTimeDetector->stopIdleDetection(); - emit timersInactive(); - } - - emit tasksChanged( activeTasks ); - } -} - -void TaskView::extractTime(int minutes) -{ - addTimeToActiveTasks(-minutes); -} - -void TaskView::autoSaveChanged(bool on) -{ - if (on) _autoSaveTimer->start(_preferences->autoSavePeriod()*1000*secsPerMinute); - else if (_autoSaveTimer->isActive()) _autoSaveTimer->stop(); -} - -void TaskView::autoSavePeriodChanged(int /*minutes*/) -{ - autoSaveChanged(_preferences->autoSave()); -} - -void TaskView::adaptColumns() -{ - // to hide a column X we set it's width to 0 - // at that moment we'll remember the original column within - // previousColumnWidths[X] - // - // When unhiding a previously hidden column - // (previousColumnWidths[X] != HIDDEN_COLUMN !) - // we restore it's width from the saved value and set - // previousColumnWidths[X] to HIDDEN_COLUMN - - for( int x=1; x <= 4; x++) { - // the column was invisible before and were switching it on now - if( _preferences->displayColumn(x-1) - && previousColumnWidths[x-1] != HIDDEN_COLUMN ) - { - setColumnWidth( x, previousColumnWidths[x-1] ); - previousColumnWidths[x-1] = HIDDEN_COLUMN; - setColumnWidthMode( x, QListView::Maximum ); - } - // the column was visible before and were switching it off now - else - if( ! _preferences->displayColumn(x-1) - && previousColumnWidths[x-1] == HIDDEN_COLUMN ) - { - setColumnWidthMode( x, QListView::Manual ); // we don't want update() - // to resize/unhide the col - previousColumnWidths[x-1] = columnWidth( x ); - setColumnWidth( x, 0 ); - } - } -} - -void TaskView::deletingTask(Task* deletedTask) -{ - DesktopList desktopList; - - _desktopTracker->registerForDesktops( deletedTask, desktopList ); - activeTasks.removeRef( deletedTask ); - - emit tasksChanged( activeTasks); -} - -void TaskView::iCalFileChanged(QString file) -{ - kdDebug(5970) << "TaskView:iCalFileChanged: " << file << endl; - stopAllTimers(); - _storage->save(this); - load(); -} - -QValueList TaskView::getHistory(const QDate& from, - const QDate& to) const -{ - return _storage->getHistory(from, to); -} - -void TaskView::markTaskAsComplete() -{ - if (current_item()) - kdDebug(5970) << "TaskView::markTaskAsComplete: " - << current_item()->uid() << endl; - else - kdDebug(5970) << "TaskView::markTaskAsComplete: null current_item()" << endl; - - bool markingascomplete = true; - deleteTask(markingascomplete); -} - -void TaskView::markTaskAsIncomplete() -{ - if (current_item()) - kdDebug(5970) << "TaskView::markTaskAsComplete: " - << current_item()->uid() << endl; - else - kdDebug(5970) << "TaskView::markTaskAsComplete: null current_item()" << endl; - - reinstateTask(50); // if it has been reopened, assume half-done -} - - -void TaskView::clipTotals() -{ - TimeKard t; - if (current_item() && current_item()->isRoot()) - { - int response = KMessageBox::questionYesNo( 0, - i18n("Copy totals for just this task and its subtasks, or copy totals for all tasks?"), - i18n("Copy Totals to Clipboard"), - i18n("Copy This Task"), i18n("Copy All Tasks") ); - if (response == KMessageBox::Yes) // this task only - { - KApplication::clipboard()->setText(t.totalsAsText(this)); - } - else // only task - { - KApplication::clipboard()->setText(t.totalsAsText(this, false)); - } - } - else - { - KApplication::clipboard()->setText(t.totalsAsText(this)); - } -} - -void TaskView::clipHistory() -{ - PrintDialog dialog; - if (dialog.exec()== QDialog::Accepted) - { - TimeKard t; - KApplication::clipboard()-> - setText( t.historyAsText(this, dialog.from(), dialog.to(), !dialog.allTasks(), dialog.perWeek(), dialog.totalsOnly() ) ); - } -} - -#include "taskview.moc" diff --git a/ktimetracker/taskview.h b/ktimetracker/taskview.h deleted file mode 100644 index f286d457a7..0000000000 --- a/ktimetracker/taskview.h +++ /dev/null @@ -1,216 +0,0 @@ -#ifndef KARM_TASK_VIEW_H -#define KARM_TASK_VIEW_H - -#include -#include -#include - -#include - -#include "desktoplist.h" -#include "resourcecalendar.h" -#include "karmstorage.h" -#include "reportcriteria.h" -#include -//#include "desktoptracker.h" - -//#include "karmutility.h" - -class QListBox; -class QString; -class QTextStream; -class QTimer; - -class KMenuBar; -class KToolBar; - -class DesktopTracker; -class EditTaskDialog; -class IdleTimeDetector; -class Preferences; -class Task; -class KarmStorage; -class HistoryEvent; - -using namespace KCal; - -/** - * Container and interface for the tasks. - */ - -class TaskView : public KListView -{ - Q_OBJECT - - public: - TaskView( QWidget *parent = 0, const char *name = 0, const QString &icsfile = "" ); - virtual ~TaskView(); - - /** Return the first item in the view, cast to a Task pointer. */ - Task* first_child() const; - - /** Return the current item in the view, cast to a Task pointer. */ - Task* current_item() const; - - /** Return the i'th item (zero-based), cast to a Task pointer. */ - Task* item_at_index(int i); - - /** Load the view from storage. */ - void load( QString filename="" ); - - /** Close the storage and release lock. */ - void closeStorage(); - - /** Reset session time to zero for all tasks. */ - void startNewSession(); - - /** Reset session and total time to zero for all tasks. */ - void resetTimeForAllTasks(); - - /** Return the total number if items in the view. */ - long count(); - - /** Return list of start/stop events for given date range. */ - QValueList getHistory(const QDate& from, const QDate& to) const; - - /** Schedule that we should save very soon */ - void scheduleSave(); - - /** Return preferences user selected on settings dialog. **/ - Preferences *preferences(); - - /** Add a task to view and storage. */ - QString addTask( const QString& taskame, long total, long session, const DesktopList& desktops, - Task* parent = 0 ); - - public slots: - /** Save to persistent storage. */ - QString save(); - - /** Start the timer on the current item (task) in view. */ - void startCurrentTimer(); - - /** Stop the timer for the current item in the view. */ - void stopCurrentTimer(); - - /** Stop all running timers. */ - void stopAllTimers(); - - /** Calls newTask dialog with caption "New Task". */ - void newTask(); - - /** Display edit task dialog and create a new task with results. */ - void newTask( QString caption, Task* parent ); - - /** Used to refresh (e.g. after import) */ - void refresh(); - - /** Used to import a legacy file format. */ - void loadFromFlatFile(); - - /** used to import tasks from imendio planner */ - QString importPlanner( QString fileName="" ); - - /** call export function for csv totals or history */ - QString report( const ReportCriteria &rc ); - - /** Export comma separated values format for task time totals. */ - void exportcsvFile(); - - /** Export comma-separated values format for task history. */ - QString exportcsvHistory(); - - /** Calls newTask dialog with caption "New Sub Task". */ - void newSubTask(); - - void editTask(); - - /** - * Returns a pointer to storage object. - * - * This is poor object oriented design--the task view should - * expose wrappers around the storage methods we want to access instead of - * giving clients full access to objects that we own. - * - * Hopefully, this will be redesigned as part of the Qt4 migration. - */ - KarmStorage* storage(); - - /** - * Delete task (and children) from view. - * - * @param markingascomplete If false (the default), deletes history for - * current task and all children. If markingascomplete is true, then sets - * percent complete to 100 and removes task and all it's children from the - * list view. - */ - void deleteTask(bool markingascomplete=false); - - /** Reinstates the current task as incomplete. - * @param completion The percentage complete to mark the task as. */ - void reinstateTask(int completion); -// void addCommentToTask(); - void markTaskAsComplete(); - void markTaskAsIncomplete(); - - /** Subtracts time from all active tasks, and does not log event. */ - void extractTime( int minutes ); - void taskTotalTimesChanged( long session, long total) - { emit totalTimesChanged( session, total); }; - void adaptColumns(); - /** receiving signal that a task is being deleted */ - void deletingTask(Task* deletedTask); - void startTimerFor( Task* task ); - void stopTimerFor( Task* task ); - - /** User has picked a new iCalendar file on preferences screen. */ - void iCalFileChanged(QString file); - - /** Copy totals for current and all sub tasks to clipboard. */ - void clipTotals(); - - /** Copy history for current and all sub tasks to clipboard. */ - void clipHistory(); - - signals: - void totalTimesChanged( long session, long total ); - void updateButtons(); - void timersActive(); - void timersInactive(); - void tasksChanged( QPtrList activeTasks ); - - private: // member variables - IdleTimeDetector *_idleTimeDetector; - QTimer *_minuteTimer; - QTimer *_autoSaveTimer; - QTimer *_manualSaveTimer; - Preferences *_preferences; - QPtrList activeTasks; - int previousColumnWidths[4]; - DesktopTracker* _desktopTracker; - bool _isloading; - - //KCal::CalendarLocal _calendar; - KarmStorage * _storage; - - private: - void contentsMousePressEvent ( QMouseEvent * e ); - void contentsMouseDoubleClickEvent ( QMouseEvent * e ); - void updateParents( Task* task, long totalDiff, long sesssionDiff); - void deleteChildTasks( Task *item ); - void addTimeToActiveTasks( int minutes, bool save_data = true ); - /** item state stores if a task is expanded so you can see the subtasks */ - void restoreItemState( QListViewItem *item ); - - protected slots: - void autoSaveChanged( bool ); - void autoSavePeriodChanged( int period ); - void minuteUpdate(); - /** item state stores if a task is expanded so you can see the subtasks */ - void itemStateChanged( QListViewItem *item ); - /** item state stores if a task is expanded so you can see the subtasks */ - void deleteItemState( QListViewItem *item ); - void iCalFileModified(ResourceCalendar *); -}; - -#endif // KARM_TASK_VIEW diff --git a/ktimetracker/test/Makefile.am b/ktimetracker/test/Makefile.am deleted file mode 100644 index d4f4c1aa07..0000000000 --- a/ktimetracker/test/Makefile.am +++ /dev/null @@ -1,17 +0,0 @@ -METASOURCES = AUTO - -check_PROGRAMS = runscripts locking - -runscripts_SOURCES = script.cpp runscripts.cpp -runscripts_LDFLAGS = $(all_libraries) $(KDE_RPATH) -runscripts_LDADD = $(LIB_QT) $(LIB_KDECORE) - -locking_SOURCES = locking.cpp lockerthread.cpp -locking_LDFLAGS = $(all_libraries) $(KDE_RPATH) -locking_LDADD = $(LIB_QT) $(top_builddir)/libkcal/libkcal.la - -KDE_CXXFLAGS = $(USE_EXCEPTIONS) - -INCLUDES = -I$(srcdir) -I$(top_srcdir) -I$(top_srcdir)/libkcal $(all_includes) - -TESTS = runscripts locking diff --git a/ktimetracker/test/README b/ktimetracker/test/README deleted file mode 100644 index e7c30d0b33..0000000000 --- a/ktimetracker/test/README +++ /dev/null @@ -1,76 +0,0 @@ -This directory holds automated tests for karm. - -It's in very rough shape. - - -How you start: - - (1) get and install kdepim including karm - - (2) get and install xautomation from http://hoopajoo.net/projects/xautomation.html - - (3) get and install Net::DAV::Server with CPAN - - (4) start the automated tests with the command make check - - -Here are some of the issues: - - (1) The tests require KDE to be running in English. - - The automated XTests use shortcut keys to drive the app. These key - combinations are language specific. - - (2) The tests require that you "make install" first. - - The XAutomation tests and tests that use DCOP run karm from the bash - prompt. - - (3) The tests are destructive. - - If you have an already running instance of karm, the tests will kill - that instance. So you cannot, for example, record time spent running - karm automated tests. - - The tests are smart enough to use test iCalendar files. But they will - alter the karm storage settings for the ics file name. - - (4) The runscripts program does not kill scripts that never return. - - You have to monitor the progress and press Control-C if you think a - script is hung. - - (5) No attempt is made to check for installed script interpreters. - - In addition to required interpreters (Python 2.2, for example), the bash - scripts use xte, which on Debian is in the xautomation package. - - If a required library is not found, runscripts will consider this a - script failure and stop. - - (6) I have only tested this with Bash on GNU/Linux. - - (7) When a test fails, it is really hard to figure out why. There is too - much stuff mixed together on the console output, and the tests - themselves do not give much info when they fail. - -That having been said, I find it so useful that I will keep working on this so -it should get better shortly. - - -Some notes on runscripts.cpp: - - Parses this directory for script files (Python, PHP, Perl and Bash). It - identifies a script file by the extension. - - It runs any script files it finds. Within each script type, it runs the - scripts in alphabetical order. Scripts that start with a double underscore - are skipped. - - When a script fails runscripts stops. - - Script files should return a non-zero exit code to indicate a failure. - --- -Mark Bucciarelli -December 6, 2004 diff --git a/ktimetracker/test/__lib.sh b/ktimetracker/test/__lib.sh deleted file mode 100644 index 06fd9df62b..0000000000 --- a/ktimetracker/test/__lib.sh +++ /dev/null @@ -1,79 +0,0 @@ - -# Expects karm test file in $TESTFILE -# Returns dcop id in $DCOP_ID -function set_up() -{ - DCOPID=`dcop 2>/dev/null | grep karm` - - if [ -n "$DCOPID" ]; then dcop $DCOPID KarmDCOPIface quit; fi; - - if [ "x$SKIP_TESTFILE_DELETE" != "xtrue" ]; then - if [ -e "$TESTFILE" ]; then rm $TESTFILE; fi - fi - - #echo "__lib.sh - starting karm with $TESTFILE" - karm "$TESTFILE" & - - # Make sure karm is up and running - limit=10 - idx=0 - DCOPID="" - while [ "$idx" -lt "$limit" ] - do - #echo "__lib.sh: dcop 2>/dev/null | grep karm" - DCOPID=`dcop 2>/dev/null | grep karm` - if [ -n "$DCOPID" ] - then - break - else - let "idx += 1" - fi - sleep 1 - done - - # It's not enough to get the dcop id, as this is available almost - # immediately. We need to make sure karm (and fam) is done loading data. - limit=20 - idx=0 - KARM_VERSION="" - while [ "$idx" -lt "$limit" ] - do - #echo "__lib.sh: dcop $DCOPID KarmDCOPIface version 2>/dev/null" - KARM_VERSION=`dcop $DCOPID KarmDCOPIface version 2>/dev/null` - if [ -n "$KARM_VERSION" ] - then - break - else - let "idx += 1" - fi - sleep 1 - done - - if [ "x$DCOPID" = x ] - then - echo "__lib.sh set_up error: could not start karm--no dcop id." - exit 1 - else - echo "__lib.sh: DCOPID = $DCOPID, KARM_VERSION = $KARM_VERSION" - fi - - if [ "x$KARM_VERSION" = x ] - then - echo "__lib.sh set_up error: karm did not return a version string." - exit 1 - fi -} - -function test_func() -{ - echo "Yep, that works." -} - -function tear_down() -{ - if [ -n "$DCOPID" ]; then dcop "$DCOPID" KarmDCOPIface quit; fi; - - if [ "x$SKIP_TESTFILE_DELETE" != "xtrue" ]; then - if [ -e "$TESTFILE" ]; then rm "$TESTFILE"; fi - fi -} diff --git a/ktimetracker/test/bug94447.sh b/ktimetracker/test/bug94447.sh deleted file mode 100755 index fa163735ba..0000000000 --- a/ktimetracker/test/bug94447.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh - -# Create files relative to current directory if no "/" prefix -# in file name given on command line - -exec >>check.log 2>&1 - -TESTFILE="testkarm.ics" -TESTTODO="testtodo" - -source __lib.sh - -set_up - -# make karm create the file. -dcop $DCOPID KarmDCOPIface addtodo "$TESTTODO" - -RVAL=1 -if [ -e $TESTFILE ]; then RVAL=0; fi - -tear_down - -if [ $RVAL -eq 0 ] -then - echo "PASS $0" - exit 0 -else - echo "FAIL $0" - exit 1 -fi diff --git a/ktimetracker/test/lifetest.php b/ktimetracker/test/lifetest.php deleted file mode 100644 index 7f4766545d..0000000000 --- a/ktimetracker/test/lifetest.php +++ /dev/null @@ -1,219 +0,0 @@ -#!/usr/bin/php - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'); -fclose($handle); -}; - -function simkey($s) -// This function simulates keypresses that form the string $s, e.g. for $s==hallo, it simulates the keypress of h, then a, then l and so on. -// find a useful list of keycodes under /usr/include/X11/keysymdef.h -{ - for ($i=0; $i/dev/null",$rc); - if ($rc==0) echo " You have.\n"; - if ($rc==127) echo " You do not have, please get it from http://hoopajoo.net/projects/xautomation.html .\n"; - echo "This program will test karm by issueing karm, so, make sure, this calls the version you want to test (make install).\n\n"; - - echo "This program will now stop unless you give the parameter --batch (confirming that you do not touch the keyboard)\n"; - - $err=""; - $exit=0; -} -else -{ - switch (funkeysim("Alt_L")) - { - case 1: - $err.="this must be run in an X environment\n"; - break; - case 127: - $err.="you do not have XAutomation installed, get it from http://hoopajoo.net/projects/xautomation.html\n"; - break; - } - // the following is the same as 'if file_exist(...) unlink(...)', but atomic - @unlink ("/tmp/karmtest.ics"); - @unlink ("/tmp/example.planner"); - if ($err=="") - { - // start and wait till mainwindow is up - // the mouse can be in the way, so, move it out. This here even works with "focus strictly under mouse". - system("xte 'mousemove 1 1'"); - echo "\nStarting karm"; - $process=popen("karm --geometry 200x100+0+0 /tmp/karmtest.ics >/dev/null 2>&1", 'w'); - $rc=1; - while ($rc==1) system("dcop `dcop 2>/dev/null | grep karm` KarmDCOPIface version",$rc); - echo "mainwindow is ready"; - sleep (1); - - funkeysim("Alt_L"); - - funkeysim("Right",3); - funkeysim("Down",2); - funkeysim("Return"); - sleep (1); - funkeysim("Down",2); - funkeysim("Tab",5); - simkey("/tmp/karmtest.ics"); - sleep (1); - funkeysim("Return"); - sleep (1); - funkeysim("Return"); - sleep (1); - - # add a new task - funkeysim("Alt_L"); - funkeysim("Right",2); - funkeysim("Down"); - sleep (1); - funkeysim("Return"); - sleep (1); - simkey("example 1"); - funkeysim("Return"); - sleep (1); - - echo "\nCreating a planner project file..."; - createplannerexample(); - - # import planner project file - funkeysim("Alt_L"); - funkeysim("Down",5); - funkeysim("Right"); - funkeysim("Down"); - funkeysim("Return"); - sleep (2); - keysim("/tmp/example.planner"); - sleep (1); - funkeysim("Return"); - sleep (1); - - # export to CSV file - funkeysim("Alt_L"); - funkeysim("Down",5); - funkeysim("Right"); - funkeysim("Down",2); - funkeysim("Return"); - sleep(1); - keysim("/tmp/exporttest.csv"); - sleep(1); - funkeysim("Tab",6); - system ("xte 'keydown Alt_L'"); - system ("xte 'key m'"); - system ("xte 'keyup Alt_L'"); - sleep(1); - funkeysim("Return"); - - # send CTRL_Q - sleep (2); - echo "\nsending CTRL_Q...\n"; - system ("xte 'keydown Control_L'"); - system ("xte 'key Q'"); - system ("xte 'keyup Control_L'"); - - $content=file_get_contents("/tmp/karmtest.ics"); - $lines=explode("\n",$content); - if (!preg_match("/DTSTAMP:[0-9]{1,8}T[0-9]{1,6}Z/", $lines[4])) $err.="iCal file: wrong dtstamp"; - if ($lines[12]<>"SUMMARY:example 1") $err.="iCal file: wrong task example 1"; - if ($lines[16]<>"END:VTODO") $err.="iCal file: wrong end of vtodo"; - if ($lines[27]<>"SUMMARY:task 1") $err.="iCal file: wrong task task 1"; - if (!preg_match("/^UID:libkcal-[0-9]{1,8}.[0-9]{1,3}/", $lines[39])) $err.="iCal file: wrong uid"; - $content=file_get_contents("/tmp/exporttest.csv"); - $lines=explode("\n",$content); - if (!preg_match("/\"example 1\",,0[,|.]00,0[,|.]00,0[,|.]00,0[,|.]00/", $lines[0])) $err.="csv export is wrong"; - pclose($process); - @unlink ("/tmp/karmtest.ics"); - @unlink ("/tmp/example.planner"); - @unlink ("/tmp/exporttest.csv"); - } -} - echo $err; - if ($err!="") exit(1); -?> \ No newline at end of file diff --git a/ktimetracker/test/refresh_on_change.sh b/ktimetracker/test/refresh_on_change.sh deleted file mode 100755 index 5a33f11d74..0000000000 --- a/ktimetracker/test/refresh_on_change.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/sh - -# I cannot get this test to work reliably! -# I suspect the culprit is FAM. -# -- Mark - -exec >>check.log 2>&1 - -source __lib.sh - -TESTFILE="/tmp/testkarm.ics" - -set_up - -TODO_NAME=$0 -TODO_UID=abc-123 -TODO_TIME=`date +%Y%m%dT%H%M%SZ` - -cat >> $TESTFILE << endl -BEGIN:VCALENDAR -PRODID:-//K Desktop Environment//NONSGML KArm Test Scripts//EN -VERSION:2.0 - -BEGIN:VTODO -DTSTAMP:$TODO_TIME -ORGANIZER;CN=Anonymous:MAILTO:nobody@nowhere -CREATED:$TODO_TIME -UID:$TODO_UID -SEQUENCE:0 -LAST-MODIFIED:$TODO_TIME -SUMMARY:$TODO_NAME -CLASS:PUBLIC -PRIORITY:5 -PERCENT-COMPLETE:0 -END:VTODO - -END:VCALENDAR -endl - -# wait so FAM and KDirWatcher tell karm and karm refreshes view -sleep 2 - -RVAL=`dcop $DCOPID KarmDCOPIface hastodo $TODO_NAME` -#echo "RVAL = $RVAL" - -tear_down - -# check that todo was found -if [ "$RVAL" == "$TODO_UID" ]; then - echo "PASS $0" - exit 0; -else - echo "FAIL $0: got /$RVAL/, expected /$TODO_UID/" - exit 1; -fi diff --git a/ktimetracker/test/remote_storage.sh b/ktimetracker/test/remote_storage.sh deleted file mode 100755 index a4335b6c10..0000000000 --- a/ktimetracker/test/remote_storage.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh - -# Karm can read and write to an FTP server for storage file. - -exec >>check.log 2>&1 - -PORT=8000 -TESTFILE="http://localhost:$PORT/testkarm.ics" -TESTFILE_LOCAL="testkarm.ics" -TESTTODO="testtodo" - -# Start with clean environment -# If runscripts sees output on stderr, it thinks script failed. -DCOPID=`dcop | grep karm 2>/dev/null` -if [ -n $DCOPID ]; then dcop $DCOPID KarmDCOPIface quit; fi; -if [ -e $TESTFILE_LOCAL ]; then rm $TESTFILE_LOCAL; fi - -# if the file does not exist, kresources pops up a modal dialog box -# telling us that a file does not exist. - -touch $TESTFILE_LOCAL - -python __httpd.py $PORT & - -sleep 2 - -HTTPD_PID=`ps -C "python __httpd.py" -o pid=` - -karm $TESTFILE & - -sleep 2 - -DCOPID=`dcop | grep karm` - -# karm does not write file until data is saved. - -echo "DEBUG: dcop $DCOPID KarmDCOPIface addtodo \"$TESTTODO\"" -dcop $DCOPID KarmDCOPIface addtodo "$TESTTODO" - -sleep 1 - -RVAL=1 -if [ -e $TESTFILE_LOCAL ]; then RVAL=0; fi - -# clean up -if [ -n $DCOPID ]; then dcop $DCOPID KarmDCOPIface quit; fi; -if [ -e $TESTFILE_LOCAL ]; then rm $TESTFILE_LOCAL; fi -if [ -n $HTTPD_PID ]; then kill $HTTPD_PID; fi - -# return 0 on success, 1 on failure -if [ $RVAL -eq 0 ] -then - echo "PASS $0" - exit 0 -else - echo "FAIL $0" - exit 1 -fi diff --git a/ktimetracker/test/runscripts.cpp b/ktimetracker/test/runscripts.cpp deleted file mode 100644 index deabd879aa..0000000000 --- a/ktimetracker/test/runscripts.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2004 Mark Bucciarelli - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include -#include -#include -#include -#include -#include - -#include "script.h" - -static QString srcdir(); -static int runscripts -( const QString &interpreter, const QString &extension, const QString &path ); - -const QString dots = ".................................................."; -const QString not_a_test_filename_prefix = "__"; - -// Read srcdir from Makefile (for builddir != srcdir). -QString srcdir() -{ - bool found = false; - QString dir; - - QFile file( "Makefile" ); - if ( !file.open( IO_ReadOnly | IO_Translate ) ) return ""; - - QTextStream in( &file ); - QString line; - while ( !found && !in.atEnd() ) - { - line = in.readLine(); - if ( line.startsWith( "srcdir = " ) ) - { - dir = line.mid( 9 ); - found = true; - } - } - - if ( !found ) dir = ""; - - return dir; -} - -int runscripts -( const QString &interpreter, const QString &extension, const QString &path ) -{ - int rval = 0; - QStringList files; - - QDir dir( path ); - - Script* s = new Script( dir ); - - dir.setNameFilter( extension ); - dir.setFilter( QDir::Files ); - dir.setSorting( QDir::Name | QDir::IgnoreCase ); - const QFileInfoList *list = dir.entryInfoList(); - QFileInfoListIterator it( *list ); - QFileInfo *fi; - while ( !rval && ( fi = it.current() ) != 0 ) - { - // Don't run scripts that are shared routines. - if ( ! fi->fileName().startsWith( not_a_test_filename_prefix ) ) - { - s->addArgument( interpreter ); - s->addArgument( path + QDir::separator() + fi->fileName().latin1() ); - - // Thorsten's xautomation tests run with user interaction by default. - if ( interpreter == "sh" ) s->addArgument( "--batch" ); - if ( interpreter == "php" ) s->addArgument( "--batch" ); - - rval = s->run(); - - kdDebug() << "runscripts: " << fi->fileName() - << " " << dots.left( dots.length() - fi->fileName().length() ) - << " " << ( ! rval ? "PASS" : "FAIL" ) << endl; - - // Don't abort if one test files--run them all - if ( rval ) rval = 0; - - delete s; - s = new Script( dir ); - } - ++it; - } - delete s; - s = 0; - - return rval; -} - -int main( int, char** ) -{ - int rval = 0; - - QString path = srcdir(); - - if ( !rval ) rval = runscripts( "python", "*.py *.Py *.PY *.pY", path ); - - if ( !rval ) rval = runscripts( "sh", "*.sh *.Sh *.SH *.sH", path ); - - if ( !rval ) rval = runscripts( "perl", "*.pl *.Pl *.PL *.pL", path ); - - if ( !rval ) rval = runscripts( "php", "*.php *.php3 *.php4 *.php5", path ); - - return rval; -} diff --git a/ktimetracker/test/script.cpp b/ktimetracker/test/script.cpp deleted file mode 100644 index 37fe058d3f..0000000000 --- a/ktimetracker/test/script.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2002 Anders Lund - Copyright (C) 2004 Mark Bucciarelli - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ -#include -#include -#include -#include -#include - -#include - -#include "script.h" - -/* - n.b. Do not use kdDebug statements in this file. - - With qt-copy 3_3_BRANCH, they cause a Valgrind error. - Ref: KDE bug #95237. -*/ - -// Wait for terminate() attempt to return before using kill() -// kill() doesn't let script interpreter try to clean up. -const int NICE_KILL_TIMEOUT_IN_SECS = 5; - -Script::Script( const QDir& workingDirectory ) -{ - m_status = 0; - m_stderr = false; - m_timeoutInSeconds = 5; - - m_proc = new QProcess( this ); - m_proc->setWorkingDirectory( workingDirectory ); - - connect ( m_proc, SIGNAL( readyReadStdout() ), - this , SLOT ( stdout() ) - ); - connect ( m_proc, SIGNAL( readyReadStderr() ), - this , SLOT ( stderr() ) - ); - connect ( m_proc, SIGNAL( processExited() ), - this , SLOT ( exit() ) - ); -} - -Script::~Script() -{ - delete m_proc; - m_proc = 0; -} - -void Script::addArgument( const QString &arg ) -{ - m_proc->addArgument( arg ); -} - -void Script::setTimeout( int seconds ) -{ - if ( seconds <= 0 ) return; - m_timeoutInSeconds = seconds; -} - -int Script::run() -{ - m_proc->start(); - // This didn't work. But Ctrl-C does. :P - //QTimer::singleShot( m_timeoutInSeconds * 1000, m_proc, SLOT( kill() ) ); - //while ( ! m_proc->normalExit() ); - while ( m_proc->isRunning() ); - return m_status; -} - -void Script::terminate() -{ - // These both trigger processExited, so exit() will run. - m_proc->tryTerminate(); - QTimer::singleShot( NICE_KILL_TIMEOUT_IN_SECS*1000, m_proc, SLOT( kill() ) ); -} - -void Script::exit() -{ - m_status = m_proc->exitStatus(); - delete m_proc; - m_proc = 0; -} - -void Script::stderr() -{ - // Treat any output to std err as a script failure - m_status = 1; - QString data = QString( m_proc->readStderr() ); - m_stderr= true; -} - -void Script::stdout() -{ - QString data = QString( m_proc->readStdout() ); -} - -#include "script.moc" diff --git a/ktimetracker/test/script.h b/ktimetracker/test/script.h deleted file mode 100644 index f5ae1e2272..0000000000 --- a/ktimetracker/test/script.h +++ /dev/null @@ -1,52 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2004 Mark Bucciarelli - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _script_h_ -#define _script_h_ - -//#include -#include - -class QDir; -class QProcess; -class QString; -class QStringList; - -class Script : public QObject -{ - Q_OBJECT -public: - Script( const QDir& workingDirectory ); - virtual ~Script(); - void addArgument( const QString &arg ); - void setTimeout( int seconds ); - int run(); -private slots: - void exit(); - void stderr(); - void stdout(); - void terminate(); -private: - QProcess *m_proc; - int m_status; - bool m_stderr; - int m_timeoutInSeconds; -}; - -#endif // _script_h_ diff --git a/ktimetracker/test/version.sh b/ktimetracker/test/version.sh deleted file mode 100755 index 64fbc8fb06..0000000000 --- a/ktimetracker/test/version.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh - -# First test, just check version. - -exec >>check.log 2>&1 - -TESTFILE="/tmp/testkarm1.ics" -VERSION="1.6.0" - -source __lib.sh - -set_up - -RVAL=`dcop $DCOPID KarmDCOPIface version 2>/dev/null` - -tear_down - -if [ "$RVAL" == "$VERSION" ]; then - echo "PASS $0" - exit 0; -else - echo "FAIL $0: got /$RVAL/, expected /$VERSION/" - exit 1; -fi diff --git a/ktimetracker/timekard.cpp b/ktimetracker/timekard.cpp deleted file mode 100644 index 95884219ad..0000000000 --- a/ktimetracker/timekard.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/* - * This file only: - * Copyright (C) 2003 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ - -// #include - -#include -#include -#include -#include - -#include -#include -#include // i18n -#include - -#include "karmutility.h" // formatTime() -#include "timekard.h" -#include "task.h" -#include "taskview.h" -#include - -const int taskWidth = 40; -const int timeWidth = 6; -const int totalTimeWidth = 7; -const int reportWidth = taskWidth + timeWidth; - -const QString cr = QString::fromLatin1("\n"); - -QString TimeKard::totalsAsText(TaskView* taskview, bool justThisTask) -{ - QString retval; - QString line; - QString buf; - long sum; - - line.fill('-', reportWidth); - line += cr; - - // header - retval += i18n("Task Totals") + cr; - retval += KGlobal::locale()->formatDateTime(QDateTime::currentDateTime()); - retval += cr + cr; - retval += QString(QString::fromLatin1("%1 %2")) - .arg(i18n("Time"), timeWidth) - .arg(i18n("Task")); - retval += cr; - retval += line; - - // tasks - if (taskview->current_item()) - { - if (justThisTask) - { - // a task's total time includes the sum of all subtask times - sum = taskview->current_item()->totalTime(); - printTask(taskview->current_item(), retval, 0); - } - else - { - sum = 0; - for (Task* task= taskview->current_item(); task; - task= task->nextSibling()) - { - sum += task->totalTime(); - if ( task->totalTime() ) - printTask(task, retval, 0); - } - } - - // total - buf.fill('-', reportWidth); - retval += QString(QString::fromLatin1("%1")).arg(buf, timeWidth) + cr; - retval += QString(QString::fromLatin1("%1 %2")) - .arg(formatTime(sum),timeWidth) - .arg(i18n("Total")); - } - else - retval += i18n("No tasks."); - - return retval; -} - -// Print out " ", for task and subtasks. Used by totalsAsText. -void TimeKard::printTask(Task *task, QString &s, int level) -{ - QString buf; - - s += buf.fill(' ', level); - s += QString(QString::fromLatin1("%1 %2")) - .arg(formatTime(task->totalTime()), timeWidth) - .arg(task->name()); - s += cr; - - for (Task* subTask = task->firstChild(); - subTask; - subTask = subTask->nextSibling()) - { - if ( subTask->totalTime() ) // to avoid 00:00 entries - printTask(subTask, s, level+1); - } -} - -void TimeKard::printTaskHistory(const Task *task, - const QMap& taskdaytotals, - QMap& daytotals, - const QDate& from, - const QDate& to, - const int level, QString& s, bool totalsOnly) -{ - long sectionsum = 0; - for ( QDate day = from; day <= to; day = day.addDays(1) ) - { - QString daykey = day.toString(QString::fromLatin1("yyyyMMdd")); - QString daytaskkey = QString::fromLatin1("%1_%2") - .arg(daykey) - .arg(task->uid()); - - if (taskdaytotals.contains(daytaskkey)) - { - if ( !totalsOnly ) - { - s += QString::fromLatin1("%1") - .arg(formatTime(taskdaytotals[daytaskkey]/60), timeWidth); - } - sectionsum += taskdaytotals[daytaskkey]; // in seconds - - if (daytotals.contains(daykey)) - daytotals.replace(daykey, daytotals[daykey] + taskdaytotals[daytaskkey]); - else - daytotals.insert(daykey, taskdaytotals[daytaskkey]); - } - else if ( !totalsOnly ) - { - QString buf; - buf.fill(' ', timeWidth); - s += buf; - } - } - - // Total for task this section (e.g. week) - s += QString::fromLatin1("%1").arg(formatTime(sectionsum/60), totalTimeWidth); - - // Task name - QString buf; - s += buf.fill(' ', level + 1); - s += QString::fromLatin1("%1").arg(task->name()); - s += cr; - - for (Task* subTask = task->firstChild(); - subTask; - subTask = subTask->nextSibling()) - { - // recursive - printTaskHistory(subTask, taskdaytotals, daytotals, from, to, level+1, s, totalsOnly); - } -} - -QString TimeKard::sectionHistoryAsText( - TaskView* taskview, - const QDate& sectionFrom, const QDate& sectionTo, - const QDate& from, const QDate& to, - const QString& name, - bool justThisTask, bool totalsOnly) -{ - - const int sectionReportWidth = taskWidth + ( totalsOnly ? 0 : sectionFrom.daysTo(sectionTo) * timeWidth ) + totalTimeWidth; - assert( sectionReportWidth > 0 ); - QString line; - line.fill('-', sectionReportWidth); - line += cr; - - QValueList events; - if ( sectionFrom < from && sectionTo > to) - { - events = taskview->getHistory(from, to); - } - else if ( sectionFrom < from ) - { - events = taskview->getHistory(from, sectionTo); - } - else if ( sectionTo > to) - { - events = taskview->getHistory(sectionFrom, to); - } - else - { - events = taskview->getHistory(sectionFrom, sectionTo); - } - - QMap taskdaytotals; - QMap daytotals; - - // Build lookup dictionary used to output data in table cells. keys are - // in this format: YYYYMMDD_NNNNNN, where Y = year, M = month, d = day and - // NNNNN = the VTODO uid. The value is the total seconds logged against - // that task on that day. Note the UID is the todo id, not the event id, - // so times are accumulated for each task. - for (QValueList::iterator event = events.begin(); event != events.end(); ++event) - { - QString daykey = (*event).start().date().toString(QString::fromLatin1("yyyyMMdd")); - QString daytaskkey = QString::fromLatin1("%1_%2") - .arg(daykey) - .arg((*event).todoUid()); - - if (taskdaytotals.contains(daytaskkey)) - taskdaytotals.replace(daytaskkey, - taskdaytotals[daytaskkey] + (*event).duration()); - else - taskdaytotals.insert(daytaskkey, (*event).duration()); - } - - QString retval; - // section name (e.g. week name) - retval += cr + cr; - QString buf; - if ( name.length() < (unsigned int)sectionReportWidth ) - buf.fill(' ', int((sectionReportWidth - name.length()) / 2)); - retval += buf + name + cr; - - if ( !totalsOnly ) - { - // day headings - for (QDate day = sectionFrom; day <= sectionTo; day = day.addDays(1)) - { - retval += QString::fromLatin1("%1").arg(day.day(), timeWidth); - } - retval += cr; - retval += line; - } - - // the tasks - if (events.empty()) - { - retval += " "; - retval += i18n("No hours logged."); - } - else - { - if (justThisTask) - { - printTaskHistory(taskview->current_item(), taskdaytotals, daytotals, - sectionFrom, sectionTo, 0, retval, totalsOnly); - } - else - { - for (Task* task= taskview->current_item(); task; - task= task->nextSibling()) - { - printTaskHistory(task, taskdaytotals, daytotals, - sectionFrom, sectionTo, 0, retval, totalsOnly); - } - } - retval += line; - - // per-day totals at the bottom of the section - long sum = 0; - for (QDate day = sectionFrom; day <= sectionTo; day = day.addDays(1)) - { - QString daykey = day.toString(QString::fromLatin1("yyyyMMdd")); - - if (daytotals.contains(daykey)) - { - if ( !totalsOnly ) - { - retval += QString::fromLatin1("%1") - .arg(formatTime(daytotals[daykey]/60), timeWidth); - } - sum += daytotals[daykey]; // in seconds - } - else if ( !totalsOnly ) - { - buf.fill(' ', timeWidth); - retval += buf; - } - } - - retval += QString::fromLatin1("%1 %2") - .arg(formatTime(sum/60), totalTimeWidth) - .arg(i18n("Total")); - } - return retval; -} - -QString TimeKard::historyAsText(TaskView* taskview, const QDate& from, - const QDate& to, bool justThisTask, bool perWeek, bool totalsOnly) -{ - // header - QString retval; - retval += totalsOnly ? i18n("Task Totals") : i18n("Task History"); - retval += cr; - retval += i18n("From %1 to %2") - .arg(KGlobal::locale()->formatDate(from)) - .arg(KGlobal::locale()->formatDate(to)); - retval += cr; - retval += i18n("Printed on: %1") - .arg(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime())); - - if ( perWeek ) - { - // output one time card table for each week in the date range - QValueList weeks = Week::weeksFromDateRange(from, to); - for (QValueList::iterator week = weeks.begin(); week != weeks.end(); ++week) - { - retval += sectionHistoryAsText( taskview, (*week).start(), (*week).end(), from, to, (*week).name(), justThisTask, totalsOnly ); - } - } else - { - retval += sectionHistoryAsText( taskview, from, to, from, to, "", justThisTask, totalsOnly ); - } - return retval; -} - -Week::Week() {} - -Week::Week(QDate from) -{ - _start = from; -} - -QDate Week::start() const -{ - return _start; -} - -QDate Week::end() const -{ - return _start.addDays(7); -} - -QString Week::name() const -{ - return i18n("Week of %1").arg(KGlobal::locale()->formatDate(start())); -} - -QValueList Week::weeksFromDateRange(const QDate& from, const QDate& to) -{ - QDate start; - QValueList weeks; - - // The QDate weekNumber() method always puts monday as the first day of the - // week. - // - // Not that it matters here, but week 1 always includes the first Thursday - // of the year. For example, January 1, 2000 was a Saturday, so - // QDate(2000,1,1).weekNumber() returns 52. - - // Since report always shows a full week, we generate a full week of dates, - // even if from and to are the same date. The week starts on the day - // that is set in the locale settings. - start = from.addDays( - -((7 - KGlobal::locale()->weekStartDay() + from.dayOfWeek()) % 7)); - - for (QDate d = start; d <= to; d = d.addDays(7)) - weeks.append(Week(d)); - - return weeks; -} - diff --git a/ktimetracker/timekard.h b/ktimetracker/timekard.h deleted file mode 100644 index 9d9de6765d..0000000000 --- a/ktimetracker/timekard.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * This file only: - * Copyright (C) 2003 Mark Bucciarelli - * - * 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. - * 51 Franklin Street, Fifth Floor - * Boston, MA 02110-1301 USA. - * - */ - -#ifndef KARM_TIMEKARD_H -#define KARM_TIMEKARD_H - -#undef Color // X11 headers -#undef GrayScale // X11 headers -#include -//#include - -#include "karmstorage.h" - -class QString; -class QDate; - -class TaskView; - - -/** - * Seven consecutive days. - * - * The timecard report prints out one table for each week of data. The first - * day of the week should be read from the KControlPanel. Currently, it is - * hardcoded to Sunday. - */ -class Week -{ - public: - /** Need an empty constructor to use in a QValueList. */ - Week(); - Week(QDate from); - QDate start() const; - QDate end() const; - QValueList days() const; - - /** - * Returns a list of weeks for the given date range. - * - * The first day of the week is picked up from the settings in the - * KontrolPanel. - * - * The list is inclusive; for example, if you pass in a date range of two - * days, one being a Sunday and the other being a Monday, you will get two - * weeks back in the list. - */ - static QValueList weeksFromDateRange(const QDate& from, - const QDate& to); - - /** - * Return the name of the week. - * - * Uses whatever the user has set up for the long date format in - * KControlPanel, prefixed by "Week of". - */ - QString name() const; - - - private: - QDate _start; -}; - -/** - * Routines to output timecard data. - */ -class TimeKard -{ - public: - TimeKard() {}; - - /** - * Generates ascii text of task totals, for current task on down. - * - * Formatted for pasting into clipboard. - * - * @param taskview The view whose tasks need to be formatted. - * - * @param justThisTask Only useful when user has picked a root task. We - * use this parameter to distinguish between when a user just wants to - * print the task subtree for a root task and when they want to print - * all tasks. - */ - QString totalsAsText(TaskView* taskview, bool justThisTask = true); - - /** - * Generates ascii text of weekly task history, for current task on down. - * - * Formatted for pasting into clipboard. - */ - QString historyAsText(TaskView* taskview, const QDate& from, - const QDate& to, bool justThisTask, bool perWeek, bool totalsOnly); - -private: - void printTask(Task *t, QString &s, int level); - - void printTaskHistory(const Task *t, const QMap& datamap, - QMap& daytotals, - const QDate& from, const QDate& to, - const int level, QString& retval, bool totalsOnly); - - QString sectionHistoryAsText(TaskView* taskview, - const QDate& sectionFrom, const QDate& sectionTo, - const QDate& from, const QDate& to, - const QString& name, - bool justThisTask, bool totalsOnly); - - }; -#endif // KARM_TIMEKARD_H diff --git a/ktimetracker/toolicons.h b/ktimetracker/toolicons.h deleted file mode 100644 index cf64a18ddf..0000000000 --- a/ktimetracker/toolicons.h +++ /dev/null @@ -1,164 +0,0 @@ -/* Generated by qembed */ -static const unsigned int clock_xpm_len = 765; -static const unsigned char clock_xpm_data[] = { - 0x2f,0x2a,0x20,0x58,0x50,0x4d,0x20,0x2a,0x2f,0x0a,0x73,0x74,0x61,0x74, - 0x69,0x63,0x20,0x63,0x68,0x61,0x72,0x20,0x2a,0x6d,0x61,0x67,0x69,0x63, - 0x6b,0x5b,0x5d,0x20,0x3d,0x20,0x7b,0x0a,0x2f,0x2a,0x20,0x63,0x6f,0x6c, - 0x75,0x6d,0x6e,0x73,0x20,0x72,0x6f,0x77,0x73,0x20,0x63,0x6f,0x6c,0x6f, - 0x72,0x73,0x20,0x63,0x68,0x61,0x72,0x73,0x2d,0x70,0x65,0x72,0x2d,0x70, - 0x69,0x78,0x65,0x6c,0x20,0x2a,0x2f,0x0a,0x22,0x32,0x32,0x20,0x32,0x32, - 0x20,0x36,0x20,0x31,0x22,0x2c,0x0a,0x22,0x20,0x20,0x63,0x20,0x23,0x30, - 0x30,0x38,0x30,0x38,0x30,0x22,0x2c,0x0a,0x22,0x2e,0x20,0x63,0x20,0x23, - 0x38,0x30,0x38,0x30,0x30,0x30,0x22,0x2c,0x0a,0x22,0x58,0x20,0x63,0x20, - 0x23,0x38,0x30,0x38,0x30,0x38,0x30,0x22,0x2c,0x0a,0x22,0x6f,0x20,0x63, - 0x20,0x23,0x63,0x30,0x63,0x30,0x63,0x30,0x22,0x2c,0x0a,0x22,0x4f,0x20, - 0x63,0x20,0x47,0x72,0x61,0x79,0x31,0x30,0x30,0x22,0x2c,0x0a,0x22,0x2b, - 0x20,0x63,0x20,0x4e,0x6f,0x6e,0x65,0x22,0x2c,0x0a,0x2f,0x2a,0x20,0x70, - 0x69,0x78,0x65,0x6c,0x73,0x20,0x2a,0x2f,0x0a,0x22,0x2b,0x2b,0x2b,0x2b, - 0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b, - 0x2b,0x2b,0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b, - 0x2b,0x2b,0x2b,0x6f,0x6f,0x6f,0x6f,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b, - 0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x6f,0x6f, - 0x6f,0x58,0x20,0x20,0x58,0x6f,0x6f,0x6f,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b, - 0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x2b,0x2b,0x2b,0x6f,0x58,0x58,0x58,0x4f, - 0x20,0x20,0x4f,0x58,0x58,0x58,0x6f,0x2b,0x2b,0x2b,0x2b,0x2b,0x22,0x2c, - 0x0a,0x22,0x2b,0x2b,0x2b,0x2b,0x6f,0x58,0x4f,0x4f,0x4f,0x4f,0x20,0x20, - 0x4f,0x4f,0x4f,0x4f,0x58,0x6f,0x2b,0x2b,0x2b,0x2b,0x22,0x2c,0x0a,0x22, - 0x2b,0x2b,0x2b,0x6f,0x58,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f, - 0x4f,0x4f,0x4f,0x58,0x6f,0x2b,0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b, - 0x6f,0x58,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f, - 0x4f,0x4f,0x58,0x6f,0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x6f,0x58, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f, - 0x58,0x6f,0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x6f,0x58,0x4f,0x4f, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x20,0x4f,0x4f,0x4f,0x4f,0x58,0x6f, - 0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x6f,0x58,0x4f,0x4f,0x4f,0x4f,0x4f, - 0x4f,0x4f,0x4f,0x4f,0x20,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x58,0x6f,0x2b, - 0x22,0x2c,0x0a,0x22,0x2b,0x6f,0x58,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f, - 0x20,0x20,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x58,0x6f,0x2b,0x22,0x2c, - 0x0a,0x22,0x2b,0x6f,0x58,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x20,0x20, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x58,0x6f,0x2b,0x22,0x2c,0x0a,0x22, - 0x2b,0x6f,0x58,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x20,0x4f, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x58,0x6f,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b, - 0x6f,0x58,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x20,0x4f,0x4f, - 0x4f,0x4f,0x58,0x6f,0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x6f,0x58, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x20,0x4f,0x4f,0x4f, - 0x58,0x6f,0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x6f,0x58,0x4f,0x4f, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x20,0x4f,0x4f,0x58,0x6f, - 0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x2b,0x6f,0x58,0x4f,0x4f,0x4f, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x58,0x6f,0x2b,0x2b,0x2b, - 0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x2b,0x2b,0x6f,0x58,0x4f,0x4f,0x4f,0x4f, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x4f,0x58,0x6f,0x2b,0x2b,0x2b,0x2b,0x22,0x2c, - 0x0a,0x22,0x2b,0x2b,0x2b,0x2b,0x2b,0x6f,0x58,0x58,0x58,0x4f,0x4f,0x4f, - 0x4f,0x58,0x58,0x58,0x6f,0x2b,0x2b,0x2b,0x2b,0x2b,0x22,0x2c,0x0a,0x22, - 0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x6f,0x6f,0x6f,0x58,0x58,0x58,0x58,0x6f, - 0x6f,0x6f,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b, - 0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x6f,0x6f,0x6f,0x6f,0x2b,0x2b,0x2b, - 0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x22,0x2c,0x0a,0x22,0x2b,0x2b,0x2b,0x2b, - 0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b, - 0x2b,0x2b,0x2b,0x2b,0x22,0x0a,0x7d,0x3b,0x0a -}; - - -static const unsigned int clockedit_xpm_len = 819; -static const unsigned char clockedit_xpm_data[] = { - 0x2f,0x2a,0x20,0x58,0x50,0x4d,0x20,0x2a,0x2f,0x0a,0x73,0x74,0x61,0x74, - 0x69,0x63,0x20,0x63,0x68,0x61,0x72,0x20,0x2a,0x6d,0x61,0x67,0x69,0x63, - 0x6b,0x5b,0x5d,0x20,0x3d,0x20,0x7b,0x0a,0x2f,0x2a,0x20,0x63,0x6f,0x6c, - 0x75,0x6d,0x6e,0x73,0x20,0x72,0x6f,0x77,0x73,0x20,0x63,0x6f,0x6c,0x6f, - 0x72,0x73,0x20,0x63,0x68,0x61,0x72,0x73,0x2d,0x70,0x65,0x72,0x2d,0x70, - 0x69,0x78,0x65,0x6c,0x20,0x2a,0x2f,0x0a,0x22,0x32,0x32,0x20,0x32,0x32, - 0x20,0x31,0x30,0x20,0x31,0x22,0x2c,0x0a,0x22,0x20,0x20,0x63,0x20,0x42, - 0x6c,0x61,0x63,0x6b,0x22,0x2c,0x0a,0x22,0x2e,0x20,0x63,0x20,0x23,0x30, - 0x30,0x38,0x30,0x38,0x30,0x22,0x2c,0x0a,0x22,0x58,0x20,0x63,0x20,0x52, - 0x65,0x64,0x22,0x2c,0x0a,0x22,0x6f,0x20,0x63,0x20,0x4d,0x61,0x67,0x65, - 0x6e,0x74,0x61,0x22,0x2c,0x0a,0x22,0x4f,0x20,0x63,0x20,0x23,0x38,0x30, - 0x38,0x30,0x30,0x30,0x22,0x2c,0x0a,0x22,0x2b,0x20,0x63,0x20,0x59,0x65, - 0x6c,0x6c,0x6f,0x77,0x22,0x2c,0x0a,0x22,0x40,0x20,0x63,0x20,0x23,0x38, - 0x30,0x38,0x30,0x38,0x30,0x22,0x2c,0x0a,0x22,0x23,0x20,0x63,0x20,0x23, - 0x63,0x30,0x63,0x30,0x63,0x30,0x22,0x2c,0x0a,0x22,0x24,0x20,0x63,0x20, - 0x47,0x72,0x61,0x79,0x31,0x30,0x30,0x22,0x2c,0x0a,0x22,0x25,0x20,0x63, - 0x20,0x4e,0x6f,0x6e,0x65,0x22,0x2c,0x0a,0x2f,0x2a,0x20,0x70,0x69,0x78, - 0x65,0x6c,0x73,0x20,0x2a,0x2f,0x0a,0x22,0x25,0x25,0x25,0x25,0x25,0x25, - 0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25, - 0x25,0x25,0x22,0x2c,0x0a,0x22,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25, - 0x25,0x23,0x23,0x23,0x23,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25, - 0x22,0x2c,0x0a,0x22,0x25,0x25,0x25,0x25,0x25,0x25,0x23,0x23,0x23,0x40, - 0x2e,0x2e,0x40,0x23,0x23,0x23,0x23,0x23,0x23,0x25,0x25,0x25,0x22,0x2c, - 0x0a,0x22,0x25,0x25,0x25,0x25,0x25,0x23,0x40,0x40,0x23,0x23,0x23,0x23, - 0x23,0x23,0x40,0x40,0x23,0x6f,0x6f,0x6f,0x25,0x25,0x22,0x2c,0x0a,0x22, - 0x25,0x25,0x25,0x25,0x23,0x40,0x24,0x23,0x24,0x24,0x2e,0x2e,0x24,0x24, - 0x23,0x4f,0x4f,0x6f,0x6f,0x6f,0x23,0x25,0x22,0x2c,0x0a,0x22,0x25,0x25, - 0x25,0x23,0x40,0x23,0x23,0x24,0x24,0x24,0x24,0x24,0x24,0x23,0x4f,0x4f, - 0x4f,0x4f,0x6f,0x6f,0x23,0x25,0x22,0x2c,0x0a,0x22,0x25,0x25,0x23,0x40, - 0x24,0x23,0x24,0x24,0x24,0x24,0x24,0x24,0x23,0x4f,0x4f,0x2b,0x4f,0x4f, - 0x4f,0x23,0x25,0x25,0x22,0x2c,0x0a,0x22,0x25,0x25,0x23,0x40,0x23,0x24, - 0x24,0x24,0x24,0x24,0x24,0x23,0x4f,0x4f,0x4f,0x2b,0x2b,0x4f,0x4f,0x23, - 0x25,0x25,0x22,0x2c,0x0a,0x22,0x25,0x25,0x23,0x23,0x24,0x24,0x24,0x24, - 0x24,0x24,0x23,0x4f,0x4f,0x2b,0x2b,0x2b,0x4f,0x4f,0x23,0x23,0x25,0x25, - 0x22,0x2c,0x0a,0x22,0x25,0x23,0x40,0x23,0x24,0x24,0x24,0x24,0x24,0x23, - 0x4f,0x4f,0x4f,0x2b,0x2b,0x4f,0x4f,0x24,0x23,0x40,0x23,0x25,0x22,0x2c, - 0x0a,0x22,0x25,0x23,0x40,0x23,0x24,0x24,0x24,0x24,0x23,0x4f,0x4f,0x2b, - 0x2b,0x2b,0x4f,0x4f,0x24,0x24,0x23,0x40,0x23,0x25,0x22,0x2c,0x0a,0x22, - 0x25,0x23,0x40,0x23,0x24,0x24,0x24,0x23,0x4f,0x4f,0x4f,0x2b,0x2b,0x4f, - 0x4f,0x24,0x24,0x24,0x23,0x40,0x23,0x25,0x22,0x2c,0x0a,0x22,0x25,0x23, - 0x40,0x23,0x24,0x24,0x23,0x4f,0x4f,0x2b,0x2b,0x2b,0x4f,0x4f,0x24,0x24, - 0x24,0x24,0x23,0x40,0x23,0x25,0x22,0x2c,0x0a,0x22,0x25,0x25,0x23,0x23, - 0x24,0x23,0x4f,0x4f,0x4f,0x2b,0x2b,0x4f,0x4f,0x2e,0x24,0x24,0x24,0x24, - 0x23,0x23,0x25,0x25,0x22,0x2c,0x0a,0x22,0x25,0x25,0x23,0x40,0x23,0x4f, - 0x4f,0x2b,0x2b,0x2b,0x4f,0x4f,0x24,0x24,0x2e,0x24,0x24,0x23,0x40,0x23, - 0x25,0x25,0x22,0x2c,0x0a,0x22,0x25,0x25,0x23,0x40,0x4f,0x4f,0x4f,0x2b, - 0x2b,0x4f,0x4f,0x24,0x24,0x24,0x24,0x2e,0x23,0x24,0x40,0x23,0x25,0x25, - 0x22,0x2c,0x0a,0x22,0x25,0x25,0x25,0x4f,0x4f,0x2b,0x2b,0x2b,0x4f,0x4f, - 0x24,0x24,0x24,0x24,0x24,0x23,0x23,0x40,0x23,0x25,0x25,0x25,0x22,0x2c, - 0x0a,0x22,0x25,0x25,0x4f,0x4f,0x2b,0x2b,0x2b,0x4f,0x4f,0x24,0x24,0x24, - 0x24,0x24,0x23,0x24,0x40,0x23,0x25,0x25,0x25,0x25,0x22,0x2c,0x0a,0x22, - 0x25,0x25,0x20,0x4f,0x2b,0x2b,0x4f,0x4f,0x23,0x23,0x23,0x23,0x23,0x23, - 0x40,0x40,0x23,0x25,0x25,0x25,0x25,0x25,0x22,0x2c,0x0a,0x22,0x25,0x20, - 0x4f,0x4f,0x4f,0x4f,0x4f,0x23,0x23,0x40,0x40,0x40,0x40,0x23,0x23,0x23, - 0x25,0x25,0x25,0x25,0x25,0x25,0x22,0x2c,0x0a,0x22,0x25,0x20,0x4f,0x4f, - 0x20,0x4f,0x25,0x25,0x25,0x23,0x23,0x23,0x23,0x25,0x25,0x25,0x25,0x25, - 0x25,0x25,0x25,0x25,0x22,0x2c,0x0a,0x22,0x25,0x20,0x20,0x20,0x25,0x25, - 0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25,0x25, - 0x25,0x25,0x22,0x0a,0x7d,0x3b,0x0a -}; - -const char * delete_xpm[] = { -/* width height num_colors chars_per_pixel */ -"22 22 3 1", -/* colors */ -" c white", -". c none", -"X c black", -/* pixels */ -"......................", -"......................", -"......................", -"......................", -"......................", -"....XX ........XX ....", -"....XXXX .....XX .....", -".....XXXX ...XX ......", -".......XXX .X ........", -"........XXXXX ........", -".........XXX .........", -"........XXXXX ........", -".......XXX .XX .......", -"......XXX ...XX ......", -".....XXX .....X ......", -".....XXX ......X .....", -"......X ..............", -"................X ....", -"......................", -"......................", -"......................", -"......................"}; - -struct { - unsigned int size; - const unsigned char *data; - const char *name; -} embed_vec[] = { - { 765, clock_xpm_data, "clock.xpm" }, - { 819, clockedit_xpm_data, "clockedit.xpm" }, - { 0, 0, "dummy" } -}; diff --git a/ktimetracker/top.cpp b/ktimetracker/top.cpp deleted file mode 100644 index eb57f51976..0000000000 --- a/ktimetracker/top.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/* -* Top Level window for KArm. -* Distributed under the GPL. -*/ - - -/* - * $Id$ - */ - -#include "top.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "kaccelmenuwatch.h" -#include "karm.h" -#include "print.h" -#include "docking.h" -#include "preferences.h" - -KarmWindow::KarmWindow() - : KMainWindow(0), - _accel( new KAccel( this ) ), - _watcher( new KAccelMenuWatch( _accel, this ) ), - _karm( new Karm( this ) ), - _totalTime( 0 ) -{ - setCentralWidget( _karm ); - connect( _karm, SIGNAL( sessionTimeChanged( long ) ), - this, SLOT( updateTime( long ) ) ); - - // status bar - - statusBar()->insertItem( i18n( "This session: %1" ) - .arg(QString::fromLatin1("0:00")), 0, 0, true ); - - // setup PreferenceDialog. - _preferences = Preferences::instance(); - - // popup menus - makeMenus(); - _watcher->updateMenus(); - - // connections - connect( _karm, SIGNAL(timerTick()), this, SLOT(updateTime())); - - _preferences->load(); - loadGeometry(); - - // FIXME: this shouldnt stay. We need to check whether the - // file exists and if not, create a blank one and ask whether - // we want to add a task. - _karm->load(); - - DockWidget *dockWidget = new DockWidget(this,"doc widget"); - dockWidget->show(); -} - -void KarmWindow::save() -{ - _karm->save(); - saveGeometry(); -} - -void KarmWindow::quit() -{ - save(); - kapp->quit(); -} - - -KarmWindow::~KarmWindow() -{ - quit(); -} - -/** - * Updates the total time tally by one minute. - */ -void KarmWindow::updateTime() -{ - _totalTime++; - updateStatusBar(); -} - -/** - * Updates the total time tally by the value specified in newval. - */ -void KarmWindow::updateTime( long difference ) -{ - _totalTime += difference; - updateStatusBar(); -} - -void KarmWindow::updateStatusBar() -{ - QString time = Karm::formatTime( _totalTime ); - statusBar()->changeItem( i18n("This session: %1" ).arg(time), 0); -} - -void KarmWindow::saveProperties( KConfig* ) -{ - _karm->save(); -} - -void KarmWindow::keyBindings() -{ - KKeyDialog::configureKeys( actionCollection(), xmlFile()); -} - -void KarmWindow::resetSessionTime() -{ - _totalTime = 0; - statusBar()->changeItem( i18n("This session: %1").arg(QString::fromLatin1("0:00")), 0 ); - _karm->resetSessionTimeForAllTasks(); -} - - -void KarmWindow::makeMenus() -{ - KAction - *actionKeyBindings, - *actionResetSession, - *actionStart, - *actionStop, - *actionNew, - *actionNewSub, - *actionDelete, - *actionEdit; - - (void) KStdAction::quit(this, SLOT(quit()), actionCollection()); - (void) KStdAction::print(this, SLOT(print()), actionCollection()); - actionKeyBindings = KStdAction::keyBindings(this, SLOT(keyBindings()),actionCollection()); - (void) KStdAction::preferences(_preferences, SLOT(showDialog()),actionCollection()); - (void) KStdAction::save(_preferences, SLOT(save()),actionCollection()); - actionResetSession = new KAction(i18n("&Reset Session Time"), CTRL + Key_R,this, - SLOT(resetSessionTime()),actionCollection(), - "reset_session_time"); - actionStart = new KAction(i18n("&Start"), QString::fromLatin1("1rightarrow"), - Key_S ,_karm, - SLOT(startTimer()),actionCollection(),"start"); - actionStop = new KAction(i18n("S&top"), QString::fromLatin1("stop"), - Key_Escape,_karm, - SLOT(stopCurrentTimer()),actionCollection(),"stop"); - actionNew = KStdAction::action( KStdAction::New, _karm, SLOT(newTask()), - actionCollection(),"new_task"); - actionNewSub = new KAction(i18n("New Subtask"), QString::fromLatin1("kmultiple"), - CTRL+ALT+Key_N, - _karm, SLOT(newSubTask()), - actionCollection(), "new_sub_task"); - actionDelete = new KAction(i18n("&Delete"), QString::fromLatin1("editdelete"), - Key_Delete,_karm, - SLOT(deleteTask()),actionCollection(),"delete_task"); - actionEdit = new KAction(i18n("&Edit"), QString::fromLatin1("edit"), - CTRL + Key_E,_karm, - SLOT(editTask()),actionCollection(),"edit_task"); - createGUI( QString::fromLatin1("karmui.rc") ); - - // Tool tops must be set after the createGUI. - actionKeyBindings->setToolTip(i18n("Configure key bindings")); - actionKeyBindings->setWhatsThis(i18n("This will let you configure keybindings which is specific to karm")); - - actionResetSession->setToolTip(i18n("Reset session time")); - actionResetSession->setWhatsThis(i18n("This will reset the session time for all tasks.")); - - actionStart->setToolTip(i18n("Start timing for selected task")); - actionStart->setWhatsThis(i18n("This will start timing for the selected task.\n" - "It is even possible to time several tasks simultaneously.\n\n" - "You may also start timing of a tasks by double clicking the left mouse " - "button on a given task. This will, however, stop timing of other tasks.")); - - actionStop->setToolTip(i18n("Stop timing of the selected task")); - actionStop->setWhatsThis(i18n("Stop timing of the selected task")); - - actionNew->setToolTip(i18n("Create new top level task")); - actionNew->setWhatsThis(i18n("This will create a new top level task.")); - - actionDelete->setToolTip(i18n("Delete selected task")); - actionDelete->setWhatsThis(i18n("This will delete the selected task and all its subtasks.")); - - actionEdit->setToolTip(i18n("Edit name or times for selected task")); - actionEdit->setWhatsThis(i18n("This will bring up a dialog box where you may edit the parameters for the selected task.")); -} - -void KarmWindow::print() -{ - MyPrinter printer(_karm); - printer.print(); -} - -void KarmWindow::loadGeometry() -{ - KConfig &config = *kapp->config(); - - config.setGroup( QString::fromLatin1("Main Window Geometry") ); - int w = config.readNumEntry( QString::fromLatin1("Width"), 100 ); - int h = config.readNumEntry( QString::fromLatin1("Height"), 100 ); - w = QMAX( w, sizeHint().width() ); - h = QMAX( h, sizeHint().height() ); - resize(w, h); -} - - -void KarmWindow::saveGeometry() -{ - KConfig &config = *KGlobal::config(); - config.setGroup( QString::fromLatin1("Main Window Geometry")); - config.writeEntry( QString::fromLatin1("Width"), width()); - config.writeEntry( QString::fromLatin1("Height"), height()); - config.sync(); -} - -#include "top.moc" diff --git a/ktimetracker/top.h b/ktimetracker/top.h deleted file mode 100644 index 3eb40623fa..0000000000 --- a/ktimetracker/top.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef KARM_TOP_H -#define KARM_TOP_H - -#include -#include - -class QPopupMenu; -class Karm; -class KAccel; -class KAccelMenuWatch; -class Preferences; -class QTimer; - -class KarmWindow : public KMainWindow -{ - Q_OBJECT - -private: - KAccel *_accel; - KAccelMenuWatch *_watcher; - Karm *_karm; - long _totalTime; - Preferences *_preferences; - - public: - KarmWindow(); - virtual ~KarmWindow(); - - public slots: - void updateTime( long difference ); - -protected slots: - void keyBindings(); - void resetSessionTime(); - void updateTime(); - void updateStatusBar(); - void save(); - void quit(); - void print(); - -protected: - virtual void saveProperties( KConfig* ); - void saveGeometry(); - void loadGeometry(); - - private: - void makeMenus(); - KDialogBase *dialog; -}; - -#endif - - diff --git a/ktimetracker/tray.cpp b/ktimetracker/tray.cpp deleted file mode 100644 index 228d807d81..0000000000 --- a/ktimetracker/tray.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* -* KTray. -* -* This implements the functionality of the little icon in the kpanel -* tray. Among which are tool tips and the running clock animated icon -* -* Distributed under the GPL. -*/ - - -// #include -// #include -#include -#include -#include -#include -#include - -#include // actionPreferences() -#include -#include -#include // UserIcon -#include // i18n -#include // plug() -#include - -#include "mainwindow.h" -#include "task.h" -#include "tray.h" - -QPtrVector *KarmTray::icons = 0; - -KarmTray::KarmTray(MainWindow* parent) - : KSystemTray(parent, "Karm Tray") -{ - // the timer that updates the "running" icon in the tray - _taskActiveTimer = new QTimer(this); - connect( _taskActiveTimer, SIGNAL( timeout() ), this, - SLOT( advanceClock()) ); - - if (icons == 0) { - icons = new QPtrVector(8); - for (int i=0; i<8; i++) { - QPixmap *icon = new QPixmap(); - QString name; - name.sprintf("active-icon-%d.xpm",i); - *icon = UserIcon(name); - icons->insert(i,icon); - } - } - - parent->actionPreferences->plug( contextMenu() ); - parent->actionStopAll->plug( contextMenu() ); - - resetClock(); - initToolTip(); - - // start of a kind of menu for the tray - // this are experiments/tests - /* - for (int i=0; i<30; i++) - _tray->insertTitle(i 18n("bla ").arg(i)); - for (int i=0; i<30; i++) - _tray->insertTitle2(i 18n("bli ").arg(i)); - */ - // experimenting with menus for the tray - /* - trayPopupMenu = contextMenu(); - trayPopupMenu2 = new QPopupMenu(); - trayPopupMenu->insertItem(i18n("Submenu"), *trayPopupMenu2); - */ -} - -KarmTray::KarmTray(karmPart * parent) - : KSystemTray( 0 , "Karm Tray") -{ -// it is not convenient if every kpart gets an icon in the systray. - _taskActiveTimer = 0; -} - -KarmTray::~KarmTray() -{ -} - - -// experiment -/* -void KarmTray::insertTitle(QString title) -{ - trayPopupMenu->insertTitle(title); -} -*/ - -void KarmTray::startClock() -{ - if ( _taskActiveTimer ) - { - _taskActiveTimer->start(1000); - setPixmap( *(*icons)[_activeIcon] ); - show(); - } -} - -void KarmTray::stopClock() -{ - if ( _taskActiveTimer ) - { - _taskActiveTimer->stop(); - show(); - } -} - -void KarmTray::advanceClock() -{ - _activeIcon = (_activeIcon+1) % 8; - setPixmap( *(*icons)[_activeIcon]); -} - -void KarmTray::resetClock() -{ - _activeIcon = 0; - setPixmap( *(*icons)[_activeIcon]); - show(); -} - -void KarmTray::initToolTip() -{ - updateToolTip(QPtrList ()); -} - -void KarmTray::updateToolTip(QPtrList activeTasks) -{ - if ( activeTasks.isEmpty() ) { - QToolTip::add( this, i18n("No active tasks") ); - return; - } - - QFontMetrics fm( QToolTip::font() ); - const QString continued = i18n( ", ..." ); - const int buffer = fm.boundingRect( continued ).width(); - const int desktopWidth = KGlobalSettings::desktopGeometry(this).width(); - const int maxWidth = desktopWidth - buffer; - - QString qTip; - QString s; - - // Build the tool tip with all of the names of the active tasks. - // If at any time the width of the tool tip is larger than the desktop, - // stop building it. - QPtrListIterator item( activeTasks ); - for ( int i = 0; item.current(); ++item, ++i ) { - Task* task = item.current(); - if ( i > 0 ) - s += i18n( ", " ) + task->name(); - else - s += task->name(); - int width = fm.boundingRect( s ).width(); - if ( width > maxWidth ) { - qTip += continued; - break; - } - qTip = s; - } - - QToolTip::add( this, qTip ); -} - -#include "tray.moc" diff --git a/ktimetracker/tray.h b/ktimetracker/tray.h deleted file mode 100644 index 34701cff4b..0000000000 --- a/ktimetracker/tray.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef KARM_TRAY_H -#define KARM_TRAY_H - -#include -#include -#include -// experiement -// #include -#include - -#include "task.h" -#include "karm_part.h" - -class KarmPart; - -class QPopupMenu; -class QTimer; - -class KSystemTray; -class MainWindow; -// experiment -// class KPopupMenu; - -class KarmTray : public KSystemTray -{ - Q_OBJECT - - public: - KarmTray(MainWindow * parent); - KarmTray(karmPart * parent); - ~KarmTray(); - - private: - int _activeIcon; - static QPtrVector *icons; - QTimer *_taskActiveTimer; - - public slots: - void startClock(); - void stopClock(); - void resetClock(); - void updateToolTip( QPtrList activeTasks); - void initToolTip(); - - protected slots: - void advanceClock(); - - // experiment - /* - void insertTitle(QString title); - - private: - KPopupMenu *trayPopupMenu; - QPopupMenu *trayPopupMenu2; - */ -}; - -#endif // KARM_TRAY_H diff --git a/ktimetracker/version.h b/ktimetracker/version.h deleted file mode 100644 index 1a1820cf03..0000000000 --- a/ktimetracker/version.h +++ /dev/null @@ -1,3 +0,0 @@ -#ifndef KARM_VERSION -#define KARM_VERSION "1.6.0" -#endif diff --git a/strigi-analyzer/Makefile.am b/strigi-analyzer/Makefile.am deleted file mode 100644 index 7ebdda7043..0000000000 --- a/strigi-analyzer/Makefile.am +++ /dev/null @@ -1,6 +0,0 @@ -if compile_kpilot -PILOTPLUGIN = palm-databases -endif - -SUBDIRS=vcf ics $(PILOTPLUGIN) - diff --git a/strigi-analyzer/ics/kfile_ics.cpp b/strigi-analyzer/ics/kfile_ics.cpp deleted file mode 100644 index a78ec04000..0000000000 --- a/strigi-analyzer/ics/kfile_ics.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* This file is part of the KDE project - * Copyright (C) 2004 Bram Schoenmakers - * - * 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 version 2. - * - * This program is distributed in the hope that -t 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#include -#include - -#include -#include - -#include "kfile_ics.h" - -#include - -using namespace KCal; - -typedef KGenericFactory ICSFactory; -K_EXPORT_COMPONENT_FACTORY(kfile_ics, ICSFactory( "kfile_ics" )) - -ICSPlugin::ICSPlugin( QObject *parent, const char *name, const QStringList& args ) - : KFilePlugin( parent, name, args ) -{ - KFileMimeTypeInfo* info = addMimeTypeInfo( "text/calendar" ); //TODO: vcs !! - - KFileMimeTypeInfo::GroupInfo* group = 0L; - group = addGroupInfo(info, "ICSInfo", i18n("Calendar Statistics")); - - addItemInfo( group, "ProductID", i18n("Product ID"), QVariant::String ); - addItemInfo( group, "Events", i18n("Events"), QVariant::Int ); - addItemInfo( group, "Todos", i18n("To-dos"), QVariant::Int ); - addItemInfo( group, "TodoCompleted", i18n("Completed To-dos"), QVariant::Int ); - addItemInfo( group, "TodoOverdue", i18n("Overdue To-dos"), QVariant::Int ); - addItemInfo( group, "Journals", i18n("Journals"), QVariant::Int ); -// addItemInfo( group, "Reminders", i18n("Reminders"), QVariant::Int ); - -} - -/* -I chose to use libkcal instead of reading the calendar manually. It's easier to -maintain this way. -*/ -bool ICSPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) -{ - KFileMetaInfoGroup group = appendGroup( info, "ICSInfo"); - - CalendarLocal cal ( QString::fromLatin1( "UTC" ) ); - if( !cal.load( info.path() ) ) { - kdDebug() << "Could not load calendar" << endl; - return false; - } - - appendItem( group, "ProductID", QVariant( cal.productId() ) ); - appendItem( group, "Events", QVariant( int( cal.events().count() ) ) ); - appendItem( group, "Journals", QVariant( int( cal.journals().count() ) ) ); - Todo::List todos = cal.todos(); - - // count completed and overdue - Todo::List::ConstIterator it = todos.begin(); - Todo::List::ConstIterator end = todos.end(); - - int completed = 0; - int overdue = 0; - for ( ; it != end ; ++it ) { - Todo *todo = *it; - if ( todo->isCompleted() ) - ++completed; - else if ( todo->hasDueDate() && todo->dtDue().date() < QDate::currentDate() ) - ++overdue; - } - - appendItem( group, "Todos", QVariant( int(todos.count() ) ) ); - appendItem( group, "TodoCompleted", QVariant( completed ) ); - appendItem( group, "TodoOverdue", QVariant( overdue ) ); - - cal.close(); - - return true; -} - -#include "kfile_ics.moc" diff --git a/strigi-analyzer/ics/kfile_ics.desktop b/strigi-analyzer/ics/kfile_ics.desktop deleted file mode 100644 index df8e87081b..0000000000 --- a/strigi-analyzer/ics/kfile_ics.desktop +++ /dev/null @@ -1,37 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Type=Service -Name=ICS information -Name[be]=Інфармацыя аб ICS -Name[bg]=Информация ICS -Name[br]=Titouroù ICS -Name[ca]=Informació ICS -Name[cs]=Informace o ICS -Name[da]=ICS-information -Name[de]=ICS-Information -Name[es]=Información ICS -Name[et]=ICS info -Name[fr]=Information sur ICS -Name[hu]=ICS-jellemzők -Name[it]=Informazioni ICS -Name[nl]=ICS-informatie -Name[nn]=ICS-informasjon -Name[pa]=ICS ਜਾਣਕਾਰੀ -Name[pl]=Informacja ICS -Name[pt]=Informação ICS -Name[pt_BR]=Informações ICS -Name[ru]=Информация ICS -Name[sl]=Podatki ICS -Name[sr]=ICS информације -Name[sr@Latn]=ICS informacije -Name[sv]=ICS-information -Name[ta]=ICS தகவல் -Name[tr]=ICS bilgisi -Name[uk]=Інформація про ICS -Name[xx]=xxICS informationxx -Name[zh_CN]=ICS 信息 -ServiceTypes=KFilePlugin -X-KDE-Library=kfile_ics -MimeType=text/calendar -PreferredGroups=ICSInfo -PreferredItems=Events,Todos,Journals diff --git a/strigi-analyzer/ics/kfile_ics.h b/strigi-analyzer/ics/kfile_ics.h deleted file mode 100644 index 27e7e43db8..0000000000 --- a/strigi-analyzer/ics/kfile_ics.h +++ /dev/null @@ -1,36 +0,0 @@ - /* This file is part of the KDE project - * Copyright (C) 2004 Bram Schoenmakers - * - * 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 version 2. - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#ifndef KFILE_ICS_H -#define KFILE_ICS_H - -#include - -class QStringList; - -class ICSPlugin : public KFilePlugin -{ - Q_OBJECT -public: - ICSPlugin( QObject *parent, const char *name, const QStringList& args ); - - virtual bool readInfo( KFileMetaInfo& info, uint what ); -}; - -#endif diff --git a/strigi-analyzer/palm-databases/Makefile.am b/strigi-analyzer/palm-databases/Makefile.am deleted file mode 100644 index 43dbc74960..0000000000 --- a/strigi-analyzer/palm-databases/Makefile.am +++ /dev/null @@ -1,22 +0,0 @@ -## Makefile.am for palm database meta info plugin - -# set the include path for X, qt and KDE -INCLUDES = $(PISOCK_INCLUDE) $(all_includes) - -# these are the headers for your project -noinst_HEADERS = kfile_palm.h - -kde_module_LTLIBRARIES = kfile_palm.la - -kfile_palm_la_SOURCES = kfile_palm.cpp -kfile_palm_la_LDFLAGS = $(PISOCK_LDFLAGS) $(all_libraries) -module $(KDE_PLUGIN) -kfile_palm_la_LIBADD = $(LIB_KSYCOCA) $(PISOCK_LIB) - -# let automoc handle all of the meta source files (moc) -METASOURCES = AUTO - -messages: rc.cpp - $(XGETTEXT) kfile_palm.cpp -o $(podir)/kfile_palm.pot - -services_DATA = kfile_palm.desktop -servicesdir = $(kde_servicesdir) diff --git a/strigi-analyzer/palm-databases/kfile_palm.cpp b/strigi-analyzer/palm-databases/kfile_palm.cpp deleted file mode 100644 index 3b6c13c3ef..0000000000 --- a/strigi-analyzer/palm-databases/kfile_palm.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* This file is part of the KDE project - * Copyright (C) 2004 Reinhold Kainhofer - * Based on the vcf plugin: - * Copyright (C) 2002 Shane Wright - * - * 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 version 2. - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#include "kfile_palm.h" - -#include -#include - -#include -#include -#include - - -typedef KGenericFactory PalmFactory; - -K_EXPORT_COMPONENT_FACTORY(kfile_palm, PalmFactory( "kfile_palm" )) - -KPalmPlugin::KPalmPlugin(QObject *parent, const char *name, - const QStringList &args) - - : KFilePlugin(parent, name, args) -{ - KFileMimeTypeInfo* info = addMimeTypeInfo( "application/vnd.palm" ); - - KFileMimeTypeInfo::GroupInfo* group; - KFileMimeTypeInfo::ItemInfo* item; - - group = addGroupInfo(info, "General", i18n("General Information")); - item = addItemInfo(group, "Name", i18n("Name"), QVariant::String); - item = addItemInfo(group, "DBType", i18n("DB Type"), QVariant::String); - item = addItemInfo(group, "TypeID", i18n("Type ID"), QVariant::String); - item = addItemInfo(group, "CreatorID", i18n("Creator ID"), QVariant::String); - item = addItemInfo(group, "NrRecords", i18n("# of Records"), QVariant::Int); - - group = addGroupInfo(info, "TimeStamps", i18n("Time Stamps")); - item = addItemInfo(group, "CreationDate", i18n("Creation Date"), QVariant::DateTime); - item = addItemInfo(group, "ModificationDate", i18n("Modification Date"), QVariant::DateTime); - item = addItemInfo(group, "BackupDate", i18n("Backup Date"), QVariant::DateTime); - - group = addGroupInfo(info, "Flags", i18n("Flags")); - item = addItemInfo(group, "ReadOnly", i18n("Read-Only"), QVariant::String); - item = addItemInfo(group, "MakeBackup", i18n("Make Backup"), QVariant::String); - item = addItemInfo(group, "CopyProtected", i18n("Copy Protected"), QVariant::String); - item = addItemInfo(group, "Reset", i18n("Reset Handheld After Installing"), QVariant::String); - item = addItemInfo(group, "ExcludeFromSync", i18n("Exclude From Sync"), QVariant::String); -} - - -bool KPalmPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) -{ - int nrRec; - QString tempName = info.path(); - QCString fileName = QFile::encodeName(tempName); - pi_file *dbFile = pi_file_open(const_cast < char *>((const char *) fileName)); - if (dbFile == 0L) return false; - - struct DBInfo dBInfo; - pi_file_get_info( dbFile, &dBInfo ); - pi_file_get_entries( dbFile, &nrRec ); - pi_file_close(dbFile); - - KFileMetaInfoGroup generalGroup = appendGroup(info, "General"); - appendItem(generalGroup, "Name", dBInfo.name ); - appendItem(generalGroup, "DBType", (dBInfo.flags & dlpDBFlagResource)?i18n("PalmOS Application"):i18n("PalmOS Record Database") ); - - char buff[5]; - set_long(buff, dBInfo.type); - buff[4]='\0'; - appendItem(generalGroup, "TypeID", buff ); - - set_long(buff, dBInfo.creator); - buff[4]='\0'; - appendItem(generalGroup, "CreatorID", buff ); - appendItem(generalGroup, "NrRecords", nrRec ); - - - KFileMetaInfoGroup timeGroup = appendGroup(info, "TimeStamps"); - QDateTime tm; - tm.setTime_t( dBInfo.createDate ); - appendItem(timeGroup, "CreationDate", tm); - tm.setTime_t( dBInfo.modifyDate ); - appendItem(timeGroup, "ModificationDate", tm); - tm.setTime_t( dBInfo.backupDate ); - appendItem(timeGroup, "BackupDate", tm); - - KFileMetaInfoGroup flagGroup = appendGroup(info, "Flags"); - appendItem(flagGroup, "ReadOnly", (dBInfo.flags & dlpDBFlagReadOnly)?i18n("Yes"):i18n("No") ); - appendItem(flagGroup, "MakeBackup", (dBInfo.flags & dlpDBFlagBackup)?i18n("Yes"):i18n("No") ); - appendItem(flagGroup, "CopyProtected", (dBInfo.flags & dlpDBFlagCopyPrevention)?i18n("Yes"):i18n("No") ); - appendItem(flagGroup, "Reset", (dBInfo.flags & dlpDBFlagReset)?i18n("Yes"):i18n("No") ); - appendItem(flagGroup, "ExcludeFromSync", (dBInfo.miscFlags & dlpDBMiscFlagExcludeFromSync)?i18n("Yes"):i18n("No") ); - - return true; -} - -/*bool KPalmPlugin::writeInfo( const KFileMetaInfo& info ) const -{ -// int pi_file_set_info((struct pi_file * pf, struct DBInfo * infop)); -//info["tuteTextTechnical"].value("An integer").toInt() -// Do the stuff with low-level functions. See lines 1119-1142 of pi-file.cc for writing, 244-273 for reading. -}*/ - -#include "kfile_palm.moc" diff --git a/strigi-analyzer/palm-databases/kfile_palm.desktop b/strigi-analyzer/palm-databases/kfile_palm.desktop deleted file mode 100644 index bc29c98829..0000000000 --- a/strigi-analyzer/palm-databases/kfile_palm.desktop +++ /dev/null @@ -1,44 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Type=Service -Name=PalmOS Database Info -Name[be]=Інфармацыя аб базе дадзеных PalmOS -Name[bg]=Информация за БД за PalmOS -Name[br]=Titouroù diwar-benn ar stlennvon PalmOS -Name[bs]=Informacije o PalmOS bazi podataka -Name[ca]=Informació de base de dades PalmOS -Name[cs]=Informace o databázi PalmOS -Name[da]=PalmOS database-info -Name[de]=PalmOS Datenbank Informationen -Name[es]=Info. de la base de datos de PalmOS -Name[et]=PalmOS andmebaasi info -Name[fr]=Informations sur les bases de données PalmOS -Name[he]=מידע אודות בסיס הנתונים של PalmOS -Name[hu]=PalmOS adatbázis-jellemzők -Name[is]=PalmOS gagnagrunnsupplýsingar -Name[it]=Informazioni database PalmOs -Name[ja]=PalmOS データベース 情報 -Name[nb]=PalmOS Database info -Name[nl]=PalmOS-database informatie -Name[nn]=PalmOS-databaseinfo -Name[pl]=Baza danych PalmOS -Name[pt]=Informações de Base de Dados PalmOS -Name[pt_BR]=Informações da Base de Dados do PalmOS -Name[ru]=Сведения о базе данных PalmOS -Name[se]=PalmOS-diehtovuođđodieđut -Name[sk]=Informácie o databázach PalmOS -Name[sl]=Informacije zbirke podatkov za PalmOS -Name[sr]=Информације о PalmOS базама података -Name[sr@Latn]=Informacije o PalmOS bazama podataka -Name[sv]=PalmOS-databasinformation -Name[ta]=பால்ம்OS தரவுத்தள தகவல் -Name[tg]=Иттилоот дар бораи бонки додаҳои PalmOS -Name[tr]=PalmOS Veritabanı Bilgisi -Name[uk]=Інформація про базу даних PalmOS -Name[xx]=xxPalmOS Database Infoxx -Name[zh_CN]=PalmOS 数据库信息 -ServiceTypes=KFilePlugin -X-KDE-Library=kfile_palm -MimeType=application/vnd.palm -PreferredGroups=General -PreferredItems=Name,DBType,TypeID,CreatorID,NrRecords,Size diff --git a/strigi-analyzer/palm-databases/kfile_palm.h b/strigi-analyzer/palm-databases/kfile_palm.h deleted file mode 100644 index fcd928a00f..0000000000 --- a/strigi-analyzer/palm-databases/kfile_palm.h +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the KDE project - * Copyright (C) 2004 Reinhold Kainhofer - * Based on the vcf plugin: - * Copyright (C) 2002 Shane Wright - * - * 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 version 2. - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#ifndef __KFILE_PALM_H__ -#define __KFILE_PALM_H__ - -#include - -class QStringList; - -class KPalmPlugin: public KFilePlugin -{ - Q_OBJECT - -public: - KPalmPlugin( QObject *parent, const char *name, const QStringList& args ); - - virtual bool readInfo( KFileMetaInfo& info, uint what); -// virtual bool writeInfo( const KFileMetaInfo& info ) const; -}; - -#endif diff --git a/strigi-analyzer/rfc822/kfile_rfc822.cpp b/strigi-analyzer/rfc822/kfile_rfc822.cpp deleted file mode 100644 index 794d335d64..0000000000 --- a/strigi-analyzer/rfc822/kfile_rfc822.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* This file is part of the KDE project - * Copyright (C) 2002 Shane Wright - * - * 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 version 2. - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#include -#include "kfile_rfc822.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#if !defined(__osf__) -#include -#else -typedef unsigned short uint32_t; -#endif - -typedef KGenericFactory Rfc822Factory; - -K_EXPORT_COMPONENT_FACTORY(kfile_rfc822, Rfc822Factory( "kfile_rfc822" )) - -KRfc822Plugin::KRfc822Plugin(QObject *parent, const char *name, - const QStringList &args) - - : KFilePlugin(parent, name, args) -{ - KFileMimeTypeInfo* info = addMimeTypeInfo( "message/rfc822" ); - - KFileMimeTypeInfo::GroupInfo* group = 0L; - - group = addGroupInfo(info, "Technical", i18n("Technical Details")); - - KFileMimeTypeInfo::ItemInfo* item; - - item = addItemInfo(group, "From", i18n("From"), QVariant::String); - item = addItemInfo(group, "To", i18n("To"), QVariant::String); - item = addItemInfo(group, "Subject", i18n("Subject"), QVariant::String); - item = addItemInfo(group, "Date", i18n("Date"), QVariant::String); - item = addItemInfo(group, "Content-Type", i18n("Content-Type"), QVariant::String); -} - - -bool KRfc822Plugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) -{ - - QFile file(info.path()); - - if (!file.open(IO_ReadOnly)) - { - kdDebug(7034) << "Couldn't open " << QFile::encodeName(info.path()) << endl; - return false; - } - - /* - Note to self: probably should use QCString for all this, but - what we're doing is simple and self-contained so never mind.. - */ - - char id_from[] = "From: "; - char id_to[] = "To: "; - char id_subject[] = "Subject: "; - char id_date[] = "Date: "; - char id_contenttype[] = "Content-Type: "; - - // we need a buffer for lines - char linebuf[4096]; - - // we need a buffer for other stuff - char buf_from[1000] = ""; - char buf_to[1000] = ""; - char buf_subject[1000] = ""; - char buf_date[1000] = ""; - char buf_contenttype[1000] = ""; - - memset(buf_from, 0, 999); - memset(buf_to, 0, 999); - memset(buf_subject, 0, 999); - memset(buf_date, 0, 999); - memset(buf_contenttype, 0, 999); - char * myptr; - - bool done=false; - while (!done) { - - // read a line - file.readLine(linebuf, sizeof( linebuf )); - - // have we got something useful? - if (memcmp(linebuf, id_from, 6) == 0) { - // we have a name - myptr = linebuf + 6; - strncpy(buf_from, myptr, sizeof( buf_from )); - buf_from[998]='\0'; - } else if (memcmp(linebuf, id_to, 4) == 0) { - // we have a name - myptr = linebuf + 4; - strncpy(buf_to, myptr, sizeof( buf_to )); - buf_to[998]='\0'; - } else if (memcmp(linebuf, id_subject, 9) == 0) { - // we have a name - myptr = linebuf + 9; - strncpy(buf_subject, myptr, sizeof( buf_subject )); - buf_subject[998]='\0'; - } else if (memcmp(linebuf, id_date, 6) == 0) { - // we have a name - myptr = linebuf + 6; - strncpy(buf_date, myptr, sizeof( buf_date )); - buf_date[998]='\0'; - } else if (memcmp(linebuf, id_contenttype, 14) == 0) { - // we have a name - myptr = linebuf + 14; - strncpy(buf_contenttype, myptr, sizeof( buf_contenttype )); - buf_contenttype[998]='\0'; - } - - // are we done yet? - if ( - ((strlen(buf_from) > 0) && (strlen(buf_to) > 0) && - (strlen(buf_subject) > 0) && (strlen(buf_date) > 0) && - (strlen(buf_contenttype) > 0)) || - (file.atEnd()) - ) - done = true; - - }; - - KFileMetaInfoGroup group = appendGroup(info, "Technical"); - - if (strlen(buf_from) > 0) appendItem(group, "From", buf_from); - if (strlen(buf_to) > 0) appendItem(group, "To", buf_to); - if (strlen(buf_subject) > 0) appendItem(group, "Subject", buf_subject); - if (strlen(buf_date) > 0) appendItem(group, "Date", buf_date); - if (strlen(buf_contenttype) > 0) appendItem(group, "Content-Type", buf_contenttype); - - return true; -} - -#include "kfile_rfc822.moc" diff --git a/strigi-analyzer/rfc822/kfile_rfc822.desktop b/strigi-analyzer/rfc822/kfile_rfc822.desktop deleted file mode 100644 index d41b431c9e..0000000000 --- a/strigi-analyzer/rfc822/kfile_rfc822.desktop +++ /dev/null @@ -1,51 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Type=Service -Name=Email Info -Name[be]=Інфармацыя аб паведамленьні электроннай пошты -Name[bg]=Информация за е-поща -Name[br]=Titouroù postel -Name[ca]=Informació de correu-e -Name[cs]=Informace o emailu -Name[cy]=Gwybodaeth Ebost -Name[da]=Email-info -Name[de]=E-Mail-Info -Name[el]=Πληροφορίες Email -Name[es]=Info de correo electrónico -Name[et]=Meili info -Name[fi]=Sähköpostitiedot -Name[fr]=Informations sur le courrier électronique -Name[he]=מידע על דוא"ל -Name[hi]=ई-मेल जानकारी -Name[hr]=Email Informacije -Name[hu]=E-mail-jellemzők -Name[is]=Email upplýsingar -Name[it]=Informazioni di posta elettronica -Name[ja]=Eメール 情報 -Name[ms]=Info Emel -Name[nb]=E-post-info -Name[nl]=E-mail-informatie -Name[nn]=Epost-info -Name[pa]=ਈ-ਪੱਤਰ ਜਾਣਕਾਰੀ -Name[pl]=Informacja o e-mailu -Name[pt]=Informação do E-Mail -Name[pt_BR]=Informações sobre E-mail -Name[ro]=Informaţii e-mail -Name[ru]=Сведения об электронной почте -Name[se]=E-boastadieđut -Name[sk]=Informácie o emaily -Name[sl]=Informacije o e-pošti -Name[sr]=Е-поштанске информације -Name[sr@Latn]=E-poštanske informacije -Name[sv]=E-postinformation -Name[ta]=மின்னஞ்சல் தகவல் -Name[tg]=Иттилоот дар бораи почтаи электронӣ -Name[tr]=E-Posta Bilgisi -Name[uk]=Інформація про повідомлення ел. пошти -Name[xx]=xxEmail Infoxx -Name[zh_CN]=电子邮件信息 -ServiceTypes=KFilePlugin -X-KDE-Library=kfile_rfc822 -MimeType=message/rfc822 -PreferredGroups=Technical -PreferredItems=From,To,Subject,Date,Content-Type diff --git a/strigi-analyzer/rfc822/kfile_rfc822.h b/strigi-analyzer/rfc822/kfile_rfc822.h deleted file mode 100644 index f2066754af..0000000000 --- a/strigi-analyzer/rfc822/kfile_rfc822.h +++ /dev/null @@ -1,37 +0,0 @@ -/* This file is part of the KDE project - * Copyright (C) 2002 Shane Wright - * - * 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 version 2. - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#ifndef __KFILE_RFC822_H__ -#define __KFILE_RFC822_H__ - -#include - -class QStringList; - -class KRfc822Plugin: public KFilePlugin -{ - Q_OBJECT - -public: - KRfc822Plugin( QObject *parent, const char *name, const QStringList& args ); - - virtual bool readInfo( KFileMetaInfo& info, uint what); -}; - -#endif diff --git a/strigi-analyzer/vcf/kfile_vcf.cpp b/strigi-analyzer/vcf/kfile_vcf.cpp deleted file mode 100644 index fcdf4984d7..0000000000 --- a/strigi-analyzer/vcf/kfile_vcf.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* This file is part of the KDE project - * Copyright (C) 2002 Shane Wright - * - * 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 version 2. - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#include -#include -#include "kfile_vcf.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#if !defined(__osf__) -#include -#else -typedef unsigned short uint32_t; -#endif - -typedef KGenericFactory VcfFactory; - -K_EXPORT_COMPONENT_FACTORY(kfile_vcf, VcfFactory( "kfile_vcf" )) - -KVcfPlugin::KVcfPlugin(QObject *parent, const char *name, - const QStringList &args) - - : KFilePlugin(parent, name, args) -{ - KFileMimeTypeInfo* info = addMimeTypeInfo( "text/x-vcard" ); - - KFileMimeTypeInfo::GroupInfo* group = 0L; - - group = addGroupInfo(info, "Technical", i18n("Technical Details")); - - KFileMimeTypeInfo::ItemInfo* item; - - item = addItemInfo(group, "Name", i18n("Name"), QVariant::String); - item = addItemInfo(group, "Email", i18n("Email"), QVariant::String); - item = addItemInfo(group, "Telephone", i18n("Telephone"), QVariant::String); -} - - -bool KVcfPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) -{ - - QFile file(info.path()); - - if (!file.open(IO_ReadOnly)) - { - kdDebug(7034) << "Couldn't open " << QFile::encodeName(info.path()) << endl; - return false; - } - - char id_name[] = "FN:"; - char id_email[] = "EMAIL;INTERNET:"; - - // we need a buffer for lines - char linebuf[1000]; - - // we need a buffer for other stuff - char buf_name[1000] = ""; - char buf_email[1000] = ""; - buf_name[999] = '\0'; - buf_email[999] = '\0'; - char * myptr; - - // FIXME: This is intensely inefficient!!! - - bool done=false; - while (!done) { - - // read a line - int r = file.readLine(linebuf, sizeof( linebuf )); - - if ( r < 0 ) { - done = true; - break; - } - - // have we got something useful? - if (memcmp(linebuf, id_name, 3) == 0) { - // we have a name - myptr = linebuf + 3; - strlcpy(buf_name, myptr, sizeof( buf_name )); - } else if (memcmp(linebuf, id_email, 15) == 0) { - // we have an email - myptr = linebuf + 15; - strlcpy(buf_email, myptr, sizeof( buf_email )); - } - - // are we done yet? - if ((strlen(buf_name) > 0 && strlen(buf_email) > 0) || file.atEnd()) - done = true; - - } - - - KFileMetaInfoGroup group = appendGroup(info, "Technical"); - - if (strlen(buf_name) > 0) - appendItem(group, "Name", QString::fromUtf8(buf_name)); - - if (strlen(buf_email) > 0) - appendItem(group, "Email", buf_email); - - return true; -} - -#include "kfile_vcf.moc" diff --git a/strigi-analyzer/vcf/kfile_vcf.desktop b/strigi-analyzer/vcf/kfile_vcf.desktop deleted file mode 100644 index c5bb12953f..0000000000 --- a/strigi-analyzer/vcf/kfile_vcf.desktop +++ /dev/null @@ -1,58 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Type=Service -Name=vCard Info -Name[af]=Vkaart Inligting -Name[be]=Інфармацыя аб vCard -Name[bg]=Информация за vCard -Name[br]=Titouroù diwar-benn vCard -Name[ca]=Informació de vCard -Name[cs]=VCard info -Name[cy]=Gwybodaeth vCard -Name[da]=VCard-info -Name[de]=vCard-Info -Name[el]=Πληροφορίες vCard -Name[eo]=vCard-informo -Name[es]=Info de vCard -Name[et]=vCardi info -Name[fi]=vCard tiedot -Name[fr]=Informations vCard -Name[he]=מידע vCard -Name[hi]=वी-कार्ड जानकारी -Name[hu]=VCard-jellemzők -Name[is]=vCard upplýsingar -Name[it]=Informazioni vCard -Name[ja]=vCard 情報 -Name[lt]=vCard informacija -Name[ms]=Info vCard -Name[mt]=Informazzjoni vCard -Name[nb]=vCard info -Name[nl]=vCard-informatie -Name[nn]=vCard-info -Name[nso]=Tshedimoso ya vKarata -Name[pa]=vCard ਜਾਣਕਾਰੀ -Name[pl]=Informacja vCard -Name[pt]=Informação do vCard -Name[pt_BR]=Informações sobre vCard -Name[ro]=Informaţii vCard -Name[ru]=Сведения о визитке vCard -Name[se]=vCard-dieđut -Name[sl]=Informacije o vCard -Name[sr]=vCard информације -Name[sr@Latn]=vCard informacije -Name[sv]=vCard-information -Name[ta]=விஅட்டை தகவல் -Name[tg]=Иттилоот дар бораи визиткаи vCard -Name[tr]=VCard Bilgisi -Name[uk]=Інформація про vCard -Name[ven]=Mafhungo a vCard -Name[xh]=Inkcukacha ye vCard -Name[xx]=xxvCard Infoxx -Name[zh_CN]=vCard 信息 -Name[zh_TW]=vCard 資訊 -Name[zu]=Ulwazi lwe-vCard -ServiceTypes=KFilePlugin -X-KDE-Library=kfile_vcf -MimeType=text/x-vcard -PreferredGroups=Technical -PreferredItems=Name,Email,Telephone diff --git a/strigi-analyzer/vcf/kfile_vcf.h b/strigi-analyzer/vcf/kfile_vcf.h deleted file mode 100644 index a0b147c637..0000000000 --- a/strigi-analyzer/vcf/kfile_vcf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* This file is part of the KDE project - * Copyright (C) 2002 Shane Wright - * - * 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 version 2. - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#ifndef __KFILE_VCF_H__ -#define __KFILE_VCF_H__ - -#include - -class QStringList; - -class KVcfPlugin: public KFilePlugin -{ - Q_OBJECT - -public: - KVcfPlugin( QObject *parent, const char *name, const QStringList& args ); - - virtual bool readInfo( KFileMetaInfo& info, uint what); -}; - -#endif