author | zautrix <zautrix> | 2004-10-07 09:56:31 (UTC) |
---|---|---|
committer | zautrix <zautrix> | 2004-10-07 09:56:31 (UTC) |
commit | edd36b813763c304b104f276437c2c60ee9bd1f1 (patch) (side-by-side diff) | |
tree | da3a9f6fbd905fe876131af5025690806ce60704 | |
parent | 9345818e9c291130691288e4b065190259eb4e01 (diff) | |
download | kdepimpi-edd36b813763c304b104f276437c2c60ee9bd1f1.zip kdepimpi-edd36b813763c304b104f276437c2c60ee9bd1f1.tar.gz kdepimpi-edd36b813763c304b104f276437c2c60ee9bd1f1.tar.bz2 |
sync fixes
-rw-r--r-- | kabc/addressbook.cpp | 70 | ||||
-rw-r--r-- | kabc/addressbook.h | 5 | ||||
-rw-r--r-- | kaddressbook/kabcore.cpp | 20 | ||||
-rw-r--r-- | kaddressbook/kabcore.h | 2 | ||||
-rw-r--r-- | kaddressbook/xxport/vcard_xxport.cpp | 1 | ||||
-rw-r--r-- | libkdepim/ksyncmanager.cpp | 5 | ||||
-rw-r--r-- | libkdepim/ksyncmanager.h | 5 |
7 files changed, 90 insertions, 18 deletions
diff --git a/kabc/addressbook.cpp b/kabc/addressbook.cpp index 5fb49eb..295cf03 100644 --- a/kabc/addressbook.cpp +++ b/kabc/addressbook.cpp @@ -1,676 +1,734 @@ /* This file is part of libkabc. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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. */ /* Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ /*US #include <qfile.h> #include <qregexp.h> #include <qtimer.h> #include <kapplication.h> #include <kinstance.h> #include <kstandarddirs.h> #include "errorhandler.h" */ #include <qptrlist.h> +#include <qtextstream.h> +#include <qfile.h> #include <kglobal.h> -#include <klocale.h> +#include <klocale.h>> +#include <kmessagebox.h> #include <kdebug.h> #include <libkcal/syncdefines.h> #include "addressbook.h" #include "resource.h" +#include "vcardconverter.h" +#include "vcardparser/vcardtool.h" //US #include "addressbook.moc" using namespace KABC; struct AddressBook::AddressBookData { Addressee::List mAddressees; Addressee::List mRemovedAddressees; Field::List mAllFields; KConfig *mConfig; KRES::Manager<Resource> *mManager; //US ErrorHandler *mErrorHandler; }; struct AddressBook::Iterator::IteratorData { Addressee::List::Iterator mIt; }; struct AddressBook::ConstIterator::ConstIteratorData { Addressee::List::ConstIterator mIt; }; AddressBook::Iterator::Iterator() { d = new IteratorData; } AddressBook::Iterator::Iterator( const AddressBook::Iterator &i ) { d = new IteratorData; d->mIt = i.d->mIt; } AddressBook::Iterator &AddressBook::Iterator::operator=( const AddressBook::Iterator &i ) { if( this == &i ) return *this; // guard against self assignment delete d; // delete the old data the Iterator was completely constructed before d = new IteratorData; d->mIt = i.d->mIt; return *this; } AddressBook::Iterator::~Iterator() { delete d; } const Addressee &AddressBook::Iterator::operator*() const { return *(d->mIt); } Addressee &AddressBook::Iterator::operator*() { return *(d->mIt); } Addressee *AddressBook::Iterator::operator->() { return &(*(d->mIt)); } AddressBook::Iterator &AddressBook::Iterator::operator++() { (d->mIt)++; return *this; } AddressBook::Iterator &AddressBook::Iterator::operator++(int) { (d->mIt)++; return *this; } AddressBook::Iterator &AddressBook::Iterator::operator--() { (d->mIt)--; return *this; } AddressBook::Iterator &AddressBook::Iterator::operator--(int) { (d->mIt)--; return *this; } bool AddressBook::Iterator::operator==( const Iterator &it ) { return ( d->mIt == it.d->mIt ); } bool AddressBook::Iterator::operator!=( const Iterator &it ) { return ( d->mIt != it.d->mIt ); } AddressBook::ConstIterator::ConstIterator() { d = new ConstIteratorData; } AddressBook::ConstIterator::ConstIterator( const AddressBook::ConstIterator &i ) { d = new ConstIteratorData; d->mIt = i.d->mIt; } AddressBook::ConstIterator &AddressBook::ConstIterator::operator=( const AddressBook::ConstIterator &i ) { if( this == &i ) return *this; // guard for self assignment delete d; // delete the old data because the Iterator was really constructed before d = new ConstIteratorData; d->mIt = i.d->mIt; return *this; } AddressBook::ConstIterator::~ConstIterator() { delete d; } const Addressee &AddressBook::ConstIterator::operator*() const { return *(d->mIt); } const Addressee* AddressBook::ConstIterator::operator->() const { return &(*(d->mIt)); } AddressBook::ConstIterator &AddressBook::ConstIterator::operator++() { (d->mIt)++; return *this; } AddressBook::ConstIterator &AddressBook::ConstIterator::operator++(int) { (d->mIt)++; return *this; } AddressBook::ConstIterator &AddressBook::ConstIterator::operator--() { (d->mIt)--; return *this; } AddressBook::ConstIterator &AddressBook::ConstIterator::operator--(int) { (d->mIt)--; return *this; } bool AddressBook::ConstIterator::operator==( const ConstIterator &it ) { return ( d->mIt == it.d->mIt ); } bool AddressBook::ConstIterator::operator!=( const ConstIterator &it ) { return ( d->mIt != it.d->mIt ); } AddressBook::AddressBook() { init(0, "contact"); } AddressBook::AddressBook( const QString &config ) { init(config, "contact"); } AddressBook::AddressBook( const QString &config, const QString &family ) { init(config, family); } // the default family is "contact" void AddressBook::init(const QString &config, const QString &family ) { blockLSEchange = false; d = new AddressBookData; QString fami = family; if (config != 0) { if ( family == "syncContact" ) { qDebug("creating sync config "); fami = "contact"; KConfig* con = new KConfig( locateLocal("config", "syncContactrc") ); con->setGroup( "General" ); con->writeEntry( "ResourceKeys", QString("sync") ); con->writeEntry( "Standard", QString("sync") ); con->setGroup( "Resource_sync" ); con->writeEntry( "FileName", config ); con->writeEntry( "FileFormat", QString("vcard") ); con->writeEntry( "ResourceIdentifier", QString("sync") ); con->writeEntry( "ResourceName", QString("sync_res") ); if ( config.right(4) == ".xml" ) con->writeEntry( "ResourceType", QString("qtopia") ); else if ( config == "sharp" ) { con->writeEntry( "ResourceType", QString("sharp") ); } else { con->writeEntry( "ResourceType", QString("file") ); } //con->sync(); d->mConfig = con; } else d->mConfig = new KConfig( locateLocal("config", config) ); // qDebug("AddressBook::init 1 config=%s",config.latin1() ); } else { d->mConfig = 0; // qDebug("AddressBook::init 1 config=0"); } //US d->mErrorHandler = 0; d->mManager = new KRES::Manager<Resource>( fami, false ); d->mManager->readConfig( d->mConfig ); if ( family == "syncContact" ) { KRES::Manager<Resource> *manager = d->mManager; KRES::Manager<Resource>::ActiveIterator it; for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) { (*it)->setAddressBook( this ); if ( !(*it)->open() ) error( QString( "Unable to open resource '%1'!" ).arg( (*it)->resourceName() ) ); } Resource *res = standardResource(); if ( !res ) { qDebug("ERROR: no standard resource"); res = manager->createResource( "file" ); if ( res ) { addResource( res ); } else qDebug(" No resource available!!!"); } setStandardResource( res ); manager->writeConfig(); } addCustomField( i18n( "Department" ), KABC::Field::Organization, "X-Department", "KADDRESSBOOK" ); addCustomField( i18n( "Profession" ), KABC::Field::Organization, "X-Profession", "KADDRESSBOOK" ); addCustomField( i18n( "Assistant's Name" ), KABC::Field::Organization, "X-AssistantsName", "KADDRESSBOOK" ); addCustomField( i18n( "Manager's Name" ), KABC::Field::Organization, "X-ManagersName", "KADDRESSBOOK" ); addCustomField( i18n( "Spouse's Name" ), KABC::Field::Personal, "X-SpousesName", "KADDRESSBOOK" ); addCustomField( i18n( "Office" ), KABC::Field::Personal, "X-Office", "KADDRESSBOOK" ); addCustomField( i18n( "IM Address" ), KABC::Field::Personal, "X-IMAddress", "KADDRESSBOOK" ); addCustomField( i18n( "Anniversary" ), KABC::Field::Personal, "X-Anniversary", "KADDRESSBOOK" ); //US added this field to become compatible with Opie/qtopia addressbook // values can be "female" or "male" or "". An empty field represents undefined. addCustomField( i18n( "Gender" ), KABC::Field::Personal, "X-Gender", "KADDRESSBOOK" ); addCustomField( i18n( "Children" ), KABC::Field::Personal, "X-Children", "KADDRESSBOOK" ); addCustomField( i18n( "FreeBusyUrl" ), KABC::Field::Personal, "X-FreeBusyUrl", "KADDRESSBOOK" ); addCustomField( i18n( "ExternalID" ), KABC::Field::Personal, "X-ExternalID", "KADDRESSBOOK" ); } AddressBook::~AddressBook() { delete d->mConfig; d->mConfig = 0; delete d->mManager; d->mManager = 0; //US delete d->mErrorHandler; d->mErrorHandler = 0; delete d; d = 0; } bool AddressBook::load() { clear(); KRES::Manager<Resource>::ActiveIterator it; bool ok = true; for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) if ( !(*it)->load() ) { error( i18n("Unable to load resource '%1'").arg( (*it)->resourceName() ) ); ok = false; } // mark all addressees as unchanged Addressee::List::Iterator addrIt; for ( addrIt = d->mAddressees.begin(); addrIt != d->mAddressees.end(); ++addrIt ) { (*addrIt).setChanged( false ); QString id = (*addrIt).custom( "KADDRESSBOOK", "X-ExternalID" ); if ( !id.isEmpty() ) { //qDebug("setId aa %s ", id.latin1()); (*addrIt).setIDStr(id ); } } blockLSEchange = true; return ok; } bool AddressBook::save( Ticket *ticket ) { kdDebug(5700) << "AddressBook::save()"<< endl; if ( ticket->resource() ) { deleteRemovedAddressees(); return ticket->resource()->save( ticket ); } return false; } +void AddressBook::export2File( QString fileName ) +{ + + QFile outFile( fileName ); + if ( !outFile.open( IO_WriteOnly ) ) { + QString text = i18n( "<qt>Unable to open file <b>%1</b> for export.</qt>" ); + KMessageBox::error( 0, text.arg( fileName ) ); + return ; + } + QTextStream t( &outFile ); + t.setEncoding( QTextStream::UnicodeUTF8 ); + Iterator it; + KABC::VCardConverter::Version version; + version = KABC::VCardConverter::v3_0; + for ( it = begin(); it != end(); ++it ) { + if ( !(*it).IDStr().isEmpty() ) { + (*it).insertCustom( "KADDRESSBOOK", "X-ExternalID", (*it).IDStr() ); + } + KABC::VCardConverter converter; + QString vcard; + //Resource *resource() const; + converter.addresseeToVCard( *it, vcard, version ); + t << vcard << "\r\n"; + } + outFile.close(); +} +void AddressBook::importFromFile( QString fileName ) +{ + + KABC::Addressee::List list; + QFile file( fileName ); + + file.open( IO_ReadOnly ); + QByteArray rawData = file.readAll(); + file.close(); + + QString data = QString::fromUtf8( rawData.data(), rawData.size() + 1 ); + KABC::VCardTool tool; + list = tool.parseVCards( data ); + + KABC::Addressee::List::Iterator it; + for ( it = list.begin(); it != list.end(); ++it ) { + (*it).setResource( 0 ); + insertAddressee( (*it), false, true ); + } + +} + bool AddressBook::saveAB() { bool ok = true; deleteRemovedAddressees(); Iterator ait; for ( ait = begin(); ait != end(); ++ait ) { if ( !(*ait).IDStr().isEmpty() ) { (*ait).insertCustom( "KADDRESSBOOK", "X-ExternalID", (*ait).IDStr() ); } } KRES::Manager<Resource>::ActiveIterator it; KRES::Manager<Resource> *manager = d->mManager; for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) { if ( !(*it)->readOnly() && (*it)->isOpen() ) { Ticket *ticket = requestSaveTicket( *it ); // qDebug("StdAddressBook::save '%s'", (*it)->resourceName().latin1() ); if ( !ticket ) { error( i18n( "Unable to save to resource '%1'. It is locked." ) .arg( (*it)->resourceName() ) ); return false; } //if ( !save( ticket ) ) if ( ticket->resource() ) { if ( ! ticket->resource()->save( ticket ) ) ok = false; } else ok = false; } } return ok; } AddressBook::Iterator AddressBook::begin() { Iterator it = Iterator(); it.d->mIt = d->mAddressees.begin(); return it; } AddressBook::ConstIterator AddressBook::begin() const { ConstIterator it = ConstIterator(); it.d->mIt = d->mAddressees.begin(); return it; } AddressBook::Iterator AddressBook::end() { Iterator it = Iterator(); it.d->mIt = d->mAddressees.end(); return it; } AddressBook::ConstIterator AddressBook::end() const { ConstIterator it = ConstIterator(); it.d->mIt = d->mAddressees.end(); return it; } void AddressBook::clear() { d->mAddressees.clear(); } Ticket *AddressBook::requestSaveTicket( Resource *resource ) { kdDebug(5700) << "AddressBook::requestSaveTicket()" << endl; if ( !resource ) { qDebug("AddressBook::requestSaveTicket no resource" ); resource = standardResource(); } KRES::Manager<Resource>::ActiveIterator it; for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) { if ( (*it) == resource ) { if ( (*it)->readOnly() || !(*it)->isOpen() ) return 0; else return (*it)->requestSaveTicket(); } } return 0; } -void AddressBook::insertAddressee( const Addressee &a, bool setRev ) +void AddressBook::insertAddressee( const Addressee &a, bool setRev, bool takeResource ) { if ( blockLSEchange && setRev && a.uid().left( 19 ) == QString("last-syncAddressee-") ) { //qDebug("block insert "); return; } //qDebug("inserting.... %s ",a.uid().latin1() ); bool found = false; Addressee::List::Iterator it; for ( it = d->mAddressees.begin(); it != d->mAddressees.end(); ++it ) { if ( a.uid() == (*it).uid() ) { bool changed = false; Addressee addr = a; if ( addr != (*it) ) changed = true; - (*it) = a; - if ( (*it).resource() == 0 ) - (*it).setResource( standardResource() ); - + if ( takeResource ) { + Resource * res = (*it).resource(); + (*it) = a; + (*it).setResource( res ); + } else { + (*it) = a; + if ( (*it).resource() == 0 ) + (*it).setResource( standardResource() ); + } if ( changed ) { if ( setRev ) { // get rid of micro seconds QDateTime dt = QDateTime::currentDateTime(); QTime t = dt.time(); dt.setTime( QTime (t.hour (), t.minute (), t.second () ) ); (*it).setRevision( dt ); } (*it).setChanged( true ); } found = true; } else { if ( (*it).uid().left( 19 ) == QString("last-syncAddressee-") ) { QString name = (*it).uid().mid( 19 ); Addressee b = a; QString id = b.getID( name ); if ( ! id.isEmpty() ) { QString des = (*it).note(); int startN; if( (startN = des.find( id ) ) >= 0 ) { int endN = des.find( ",", startN+1 ); des = des.left( startN ) + des.mid( endN+1 ); (*it).setNote( des ); } } } } } if ( found ) return; d->mAddressees.append( a ); Addressee& addr = d->mAddressees.last(); if ( addr.resource() == 0 ) addr.setResource( standardResource() ); addr.setChanged( true ); } void AddressBook::removeAddressee( const Addressee &a ) { Iterator it; Iterator it2; bool found = false; for ( it = begin(); it != end(); ++it ) { if ( a.uid() == (*it).uid() ) { found = true; it2 = it; } else { if ( (*it).uid().left( 19 ) == QString("last-syncAddressee-") ) { QString name = (*it).uid().mid( 19 ); Addressee b = a; QString id = b.getID( name ); if ( ! id.isEmpty() ) { QString des = (*it).note(); if( des.find( id ) < 0 ) { des += id + ","; (*it).setNote( des ); } } } } } if ( found ) removeAddressee( it2 ); } void AddressBook::removeSyncAddressees( bool removeDeleted ) { Iterator it = begin(); Iterator it2 ; QDateTime dt ( QDate( 2004,1,1) ); while ( it != end() ) { (*it).setRevision( dt ); (*it).removeCustom( "KADDRESSBOOK", "X-ExternalID" ); (*it).setIDStr(""); if ( ( (*it).tempSyncStat() == SYNC_TEMPSTATE_DELETE && removeDeleted )|| (*it).uid().left( 19 ) == QString("last-syncAddressee-")) { it2 = it; //qDebug("removing %s ",(*it).uid().latin1() ); ++it; removeAddressee( it2 ); } else { //qDebug("skipping %s ",(*it).uid().latin1() ); ++it; } } deleteRemovedAddressees(); } void AddressBook::removeAddressee( const Iterator &it ) { d->mRemovedAddressees.append( (*it) ); d->mAddressees.remove( it.d->mIt ); } AddressBook::Iterator AddressBook::find( const Addressee &a ) { Iterator it; for ( it = begin(); it != end(); ++it ) { if ( a.uid() == (*it).uid() ) { return it; } } return end(); } Addressee AddressBook::findByUid( const QString &uid ) { Iterator it; for ( it = begin(); it != end(); ++it ) { if ( uid == (*it).uid() ) { return *it; } } return Addressee(); } void AddressBook::preExternSync( AddressBook* aBook, const QString& csd ) { //qDebug("AddressBook::preExternSync "); AddressBook::Iterator it; for ( it = begin(); it != end(); ++it ) { (*it).setID( csd, (*it).externalUID() ); (*it).computeCsum( csd ); } mergeAB( aBook ,csd ); } void AddressBook::postExternSync( AddressBook* aBook , const QString& csd) { //qDebug("AddressBook::postExternSync "); AddressBook::Iterator it; for ( it = begin(); it != end(); ++it ) { // qDebug("check uid %s ", (*it).uid().latin1() ); if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_ID || (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_CSUM ) { Addressee ad = aBook->findByUid( ( (*it).uid() )); if ( ad.isEmpty() ) { qDebug("postExternSync:ERROR addressee is empty: %s ", (*it).uid().latin1()); } else { (*it).computeCsum( csd ); if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_ID ) ad.setID( csd, (*it).externalUID() ); ad.setCsum( csd, (*it).getCsum( csd ) ); aBook->insertAddressee( ad ); } } } } bool AddressBook::containsExternalUid( const QString& uid ) { Iterator it; for ( it = begin(); it != end(); ++it ) { if ( uid == (*it).externalUID( ) ) return true; } return false; } Addressee AddressBook::findByExternUid( const QString& uid , const QString& profile ) { Iterator it; for ( it = begin(); it != end(); ++it ) { if ( uid == (*it).getID( profile ) ) return (*it); } return Addressee(); } void AddressBook::mergeAB( AddressBook *aBook, const QString& profile ) { Iterator it; Addressee ad; for ( it = begin(); it != end(); ++it ) { ad = aBook->findByExternUid( (*it).externalUID(), profile ); if ( !ad.isEmpty() ) { (*it).mergeContact( ad ); } } #if 0 // test only for ( it = begin(); it != end(); ++it ) { qDebug("uid %s ", (*it).uid().latin1()); } #endif } #if 0 Addressee::List AddressBook::getExternLastSyncAddressees() { diff --git a/kabc/addressbook.h b/kabc/addressbook.h index 8f62f0d..3603ec1 100644 --- a/kabc/addressbook.h +++ b/kabc/addressbook.h @@ -1,340 +1,341 @@ /* This file is part of libkabc. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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. */ /* Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ #ifndef KABC_ADDRESSBOOK_H #define KABC_ADDRESSBOOK_H #include <qobject.h> #include <kresources/manager.h> #include <qptrlist.h> #include "addressee.h" #include "field.h" namespace KABC { class ErrorHandler; class Resource; class Ticket; /** @short Address Book This class provides access to a collection of address book entries. */ class AddressBook : public QObject { Q_OBJECT friend QDataStream &operator<<( QDataStream &, const AddressBook & ); friend QDataStream &operator>>( QDataStream &, AddressBook & ); friend class StdAddressBook; public: /** @short Address Book Iterator This class provides an iterator for address book entries. */ class Iterator { public: Iterator(); Iterator( const Iterator & ); ~Iterator(); Iterator &operator=( const Iterator & ); const Addressee &operator*() const; Addressee &operator*(); Addressee* operator->(); Iterator &operator++(); Iterator &operator++(int); Iterator &operator--(); Iterator &operator--(int); bool operator==( const Iterator &it ); bool operator!=( const Iterator &it ); struct IteratorData; IteratorData *d; }; /** @short Address Book Const Iterator This class provides a const iterator for address book entries. */ class ConstIterator { public: ConstIterator(); ConstIterator( const ConstIterator & ); ~ConstIterator(); ConstIterator &operator=( const ConstIterator & ); const Addressee &operator*() const; const Addressee* operator->() const; ConstIterator &operator++(); ConstIterator &operator++(int); ConstIterator &operator--(); ConstIterator &operator--(int); bool operator==( const ConstIterator &it ); bool operator!=( const ConstIterator &it ); struct ConstIteratorData; ConstIteratorData *d; }; /** Constructs a address book object. @param format File format class. */ AddressBook(); AddressBook( const QString &config ); AddressBook( const QString &config, const QString &family ); virtual ~AddressBook(); /** Requests a ticket for saving the addressbook. Calling this function locks the addressbook for all other processes. If the address book is already locked the function returns 0. You need the returned @ref Ticket object for calling the @ref save() function. @see save() */ Ticket *requestSaveTicket( Resource *resource=0 ); /** Load address book from file. */ bool load(); /** Save address book. The address book is saved to the file, the Ticket object has been requested for by @ref requestSaveTicket(). @param ticket a ticket object returned by @ref requestSaveTicket() */ bool save( Ticket *ticket ); bool saveAB( ); - + void export2File( QString fileName ); + void importFromFile( QString fileName ); /** Returns a iterator for first entry of address book. */ Iterator begin(); /** Returns a const iterator for first entry of address book. */ ConstIterator begin() const; /** Returns a iterator for first entry of address book. */ Iterator end(); /** Returns a const iterator for first entry of address book. */ ConstIterator end() const; /** Removes all entries from address book. */ void clear(); /** Insert an Addressee object into address book. If an object with the same unique id already exists in the address book it it replaced by the new one. If not the new object is appended to the address book. */ - void insertAddressee( const Addressee &, bool setRev = true ); + void insertAddressee( const Addressee &, bool setRev = true, bool takeResource = false); /** Removes entry from the address book. */ void removeAddressee( const Addressee & ); /** This is like @ref removeAddressee() just above, with the difference that the first element is a iterator, returned by @ref begin(). */ void removeAddressee( const Iterator & ); /** Find the specified entry in address book. Returns end(), if the entry couldn't be found. */ Iterator find( const Addressee & ); /** Find the entry specified by an unique id. Returns an empty Addressee object, if the address book does not contain an entry with this id. */ Addressee findByUid( const QString & ); /** Returns a list of all addressees in the address book. This list can be sorted with @ref KABC::AddresseeList for example. */ Addressee::List allAddressees(); /** Find all entries with the specified name in the address book. Returns an empty list, if no entries could be found. */ Addressee::List findByName( const QString & ); /** Find all entries with the specified email address in the address book. Returns an empty list, if no entries could be found. */ Addressee::List findByEmail( const QString & ); /** Find all entries wich have the specified category in the address book. Returns an empty list, if no entries could be found. */ Addressee::List findByCategory( const QString & ); /** Return a string identifying this addressbook. */ virtual QString identifier(); /** Used for debug output. */ void dump() const; void emitAddressBookLocked() { emit addressBookLocked( this ); } void emitAddressBookUnlocked() { emit addressBookUnlocked( this ); } void emitAddressBookChanged() { emit addressBookChanged( this ); } /** Return list of all Fields known to the address book which are associated with the given field category. */ Field::List fields( int category = Field::All ); /** Add custom field to address book. @param label User visible label of the field. @param category Ored list of field categories. @param key Identifier used as key for reading and writing the field. @param app String used as application key for reading and writing the field. */ bool addCustomField( const QString &label, int category = Field::All, const QString &key = QString::null, const QString &app = QString::null ); /** Add address book resource. */ bool addResource( Resource * ); /** Remove address book resource. */ bool removeResource( Resource * ); /** Return pointer list of all resources. */ QPtrList<Resource> resources(); /** Set the @p ErrorHandler, that is used by @ref error() to provide gui-independend error messages. */ void setErrorHandler( ErrorHandler * ); /** Shows gui independend error messages. */ void error( const QString& ); /** Query all resources to clean up their lock files */ void cleanUp(); // sync stuff //Addressee::List getExternLastSyncAddressees(); void resetTempSyncStat(); QStringList uidList(); void removeSyncAddressees( bool removeDeleted = false ); void mergeAB( AddressBook *aBook, const QString& profile ); Addressee findByExternUid( const QString& uid , const QString& profile ); bool containsExternalUid( const QString& uid ); void preExternSync( AddressBook* aBook, const QString& csd ); void postExternSync( AddressBook* aBook, const QString& csd ); signals: /** Emitted, when the address book has changed on disk. */ void addressBookChanged( AddressBook * ); /** Emitted, when the address book has been locked for writing. */ void addressBookLocked( AddressBook * ); /** Emitted, when the address book has been unlocked. */ void addressBookUnlocked( AddressBook * ); protected: void deleteRemovedAddressees(); void setStandardResource( Resource * ); Resource *standardResource(); KRES::Manager<Resource> *resourceManager(); void init(const QString &config, const QString &family); private: //US QPtrList<Resource> mDummy; // Remove in KDE 4 struct AddressBookData; AddressBookData *d; bool blockLSEchange; }; QDataStream &operator<<( QDataStream &, const AddressBook & ); QDataStream &operator>>( QDataStream &, AddressBook & ); } #endif diff --git a/kaddressbook/kabcore.cpp b/kaddressbook/kabcore.cpp index 83fede4..6404410 100644 --- a/kaddressbook/kabcore.cpp +++ b/kaddressbook/kabcore.cpp @@ -1494,387 +1494,387 @@ void KABCore::addGUIClient( KXMLGUIClient *client ) void KABCore::configurationChanged() { mExtensionManager->reconfigure(); } void KABCore::addressBookChanged() { /*US QDictIterator<AddresseeEditorDialog> it( mEditorDict ); while ( it.current() ) { if ( it.current()->dirty() ) { QString text = i18n( "Data has been changed externally. Unsaved " "changes will be lost." ); KMessageBox::information( this, text ); } it.current()->setAddressee( mAddressBook->findByUid( it.currentKey() ) ); ++it; } */ if (mEditorDialog) { if (mEditorDialog->dirty()) { QString text = i18n( "Data has been changed externally. Unsaved " "changes will be lost." ); KMessageBox::information( this, text ); } QString currentuid = mEditorDialog->addressee().uid(); mEditorDialog->setAddressee( mAddressBook->findByUid( currentuid ) ); } mViewManager->refreshView(); // mDetails->refreshView(); } AddresseeEditorDialog *KABCore::createAddresseeEditorDialog( QWidget *parent, const char *name ) { if ( mEditorDialog == 0 ) { mEditorDialog = new AddresseeEditorDialog( this, parent, name ? name : "editorDialog" ); connect( mEditorDialog, SIGNAL( contactModified( const KABC::Addressee& ) ), SLOT( contactModified( const KABC::Addressee& ) ) ); //connect( mEditorDialog, SIGNAL( editorDestroyed( const QString& ) ), // SLOT( slotEditorDestroyed( const QString& ) ) ; } return mEditorDialog; } void KABCore::slotEditorDestroyed( const QString &uid ) { //mEditorDict.remove( uid ); } void KABCore::initGUI() { #ifndef KAB_EMBEDDED QHBoxLayout *topLayout = new QHBoxLayout( this ); topLayout->setSpacing( KDialogBase::spacingHint() ); mExtensionBarSplitter = new QSplitter( this ); mExtensionBarSplitter->setOrientation( Qt::Vertical ); mDetailsSplitter = new QSplitter( mExtensionBarSplitter ); QVBox *viewSpace = new QVBox( mDetailsSplitter ); mIncSearchWidget = new IncSearchWidget( viewSpace ); connect( mIncSearchWidget, SIGNAL( doSearch( const QString& ) ), SLOT( incrementalSearch( const QString& ) ) ); mViewManager = new ViewManager( this, viewSpace ); viewSpace->setStretchFactor( mViewManager, 1 ); mDetails = new ViewContainer( mDetailsSplitter ); mJumpButtonBar = new JumpButtonBar( this, this ); mExtensionManager = new ExtensionManager( this, mExtensionBarSplitter ); topLayout->addWidget( mExtensionBarSplitter ); topLayout->setStretchFactor( mExtensionBarSplitter, 100 ); topLayout->addWidget( mJumpButtonBar ); topLayout->setStretchFactor( mJumpButtonBar, 1 ); mXXPortManager = new XXPortManager( this, this ); #else //KAB_EMBEDDED //US initialize viewMenu before settingup viewmanager. // Viewmanager needs this menu to plugin submenues. viewMenu = new QPopupMenu( this ); settingsMenu = new QPopupMenu( this ); //filterMenu = new QPopupMenu( this ); ImportMenu = new QPopupMenu( this ); ExportMenu = new QPopupMenu( this ); syncMenu = new QPopupMenu( this ); changeMenu= new QPopupMenu( this ); //US since we have no splitter for the embedded system, setup // a layout with two frames. One left and one right. QBoxLayout *topLayout; // = new QHBoxLayout( this ); // QBoxLayout *topLayout = (QBoxLayout*)layout(); // QWidget *mainBox = new QWidget( this ); // QBoxLayout * mainBoxLayout = new QHBoxLayout(mainBox); #ifdef DESKTOP_VERSION topLayout = new QHBoxLayout( this ); mMiniSplitter = new KDGanttMinimizeSplitter( Qt::Horizontal, this); mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Right ); topLayout->addWidget(mMiniSplitter ); mExtensionBarSplitter = new KDGanttMinimizeSplitter( Qt::Vertical,mMiniSplitter ); mExtensionBarSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Down ); mViewManager = new ViewManager( this, mExtensionBarSplitter ); mDetails = new ViewContainer( mMiniSplitter ); mExtensionManager = new ExtensionManager( this, mExtensionBarSplitter ); #else if ( QApplication::desktop()->width() > 480 ) { topLayout = new QHBoxLayout( this ); mMiniSplitter = new KDGanttMinimizeSplitter( Qt::Horizontal, this); mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Right ); } else { topLayout = new QHBoxLayout( this ); mMiniSplitter = new KDGanttMinimizeSplitter( Qt::Vertical, this); mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Down ); } topLayout->addWidget(mMiniSplitter ); mViewManager = new ViewManager( this, mMiniSplitter ); mDetails = new ViewContainer( mMiniSplitter ); mExtensionManager = new ExtensionManager( this, mMiniSplitter ); #endif //eh->hide(); // topLayout->addWidget(mExtensionManager ); /*US #ifndef KAB_NOSPLITTER QHBoxLayout *topLayout = new QHBoxLayout( this ); //US topLayout->setSpacing( KDialogBase::spacingHint() ); topLayout->setSpacing( 10 ); mDetailsSplitter = new QSplitter( this ); QVBox *viewSpace = new QVBox( mDetailsSplitter ); mViewManager = new ViewManager( this, viewSpace ); viewSpace->setStretchFactor( mViewManager, 1 ); mDetails = new ViewContainer( mDetailsSplitter ); topLayout->addWidget( mDetailsSplitter ); topLayout->setStretchFactor( mDetailsSplitter, 100 ); #else //KAB_NOSPLITTER QHBoxLayout *topLayout = new QHBoxLayout( this ); //US topLayout->setSpacing( KDialogBase::spacingHint() ); topLayout->setSpacing( 10 ); // mDetailsSplitter = new QSplitter( this ); QVBox *viewSpace = new QVBox( this ); mViewManager = new ViewManager( this, viewSpace ); viewSpace->setStretchFactor( mViewManager, 1 ); mDetails = new ViewContainer( this ); topLayout->addWidget( viewSpace ); // topLayout->setStretchFactor( mDetailsSplitter, 100 ); topLayout->addWidget( mDetails ); #endif //KAB_NOSPLITTER */ syncManager = new KSyncManager((QWidget*)this, (KSyncInterface*)this, KSyncManager::KAPI, KABPrefs::instance(), syncMenu); syncManager->setBlockSave(false); - connect(syncManager , SIGNAL( save() ), this, SLOT( save() ) ); + connect(syncManager , SIGNAL( request_file() ), this, SLOT( syncFileRequest() ) ); connect(syncManager , SIGNAL( getFile( bool )), this, SLOT(getFile( bool ) ) ); - syncManager->setDefaultFileName(locateLocal( "apps","kabc/std.vcf") ); + syncManager->setDefaultFileName( sentSyncFile()); //connect(syncManager , SIGNAL( ), this, SLOT( ) ); #endif //KAB_EMBEDDED initActions(); #ifdef KAB_EMBEDDED addActionsManually(); //US make sure the export and import menues are initialized before creating the xxPortManager. mXXPortManager = new XXPortManager( this, this ); // LR mIncSearchWidget = new IncSearchWidget( mMainWindow->getIconToolBar() ); //mMainWindow->toolBar()->insertWidget(-1, 4, mIncSearchWidget); // mActionQuit->plug ( mMainWindow->toolBar()); //mIncSearchWidget = new IncSearchWidget( mMainWindow->toolBar() ); //mMainWindow->toolBar()->insertWidget(-1, 0, mIncSearchWidget); // mIncSearchWidget->hide(); connect( mIncSearchWidget, SIGNAL( doSearch( const QString& ) ), SLOT( incrementalSearch( const QString& ) ) ); mJumpButtonBar = new JumpButtonBar( this, this ); topLayout->addWidget( mJumpButtonBar ); //US topLayout->setStretchFactor( mJumpButtonBar, 10 ); // mMainWindow->getIconToolBar()->raise(); #endif //KAB_EMBEDDED } void KABCore::initActions() { //US qDebug("KABCore::initActions(): mIsPart %i", mIsPart); #ifndef KAB_EMBEDDED connect( QApplication::clipboard(), SIGNAL( dataChanged() ), SLOT( clipboardDataChanged() ) ); #endif //KAB_EMBEDDED // file menu if ( mIsPart ) { mActionMail = new KAction( i18n( "&Mail" ), "mail_generic", 0, this, SLOT( sendMail() ), actionCollection(), "kaddressbook_mail" ); mActionPrint = new KAction( i18n( "&Print" ), "fileprint", CTRL + Key_P, this, SLOT( print() ), actionCollection(), "kaddressbook_print" ); } else { mActionMail = KStdAction::mail( this, SLOT( sendMail() ), actionCollection() ); mActionPrint = KStdAction::print( this, SLOT( print() ), actionCollection() ); } mActionSave = new KAction( i18n( "&Save" ), "filesave", CTRL+Key_S, this, SLOT( save() ), actionCollection(), "file_sync" ); mActionNewContact = new KAction( i18n( "&New Contact..." ), "filenew", CTRL+Key_N, this, SLOT( newContact() ), actionCollection(), "file_new_contact" ); mActionMailVCard = new KAction(i18n("Mail &vCard..."), "mail_post_to", 0, this, SLOT( mailVCard() ), actionCollection(), "file_mail_vcard"); mActionExport2phone = new KAction( i18n( "Selected to phone" ), "ex2phone", 0, this, SLOT( export2phone() ), actionCollection(), "kaddressbook_ex2phone" ); mActionBeamVCard = 0; mActionBeam = 0; #ifndef DESKTOP_VERSION if ( Ir::supported() ) { mActionBeamVCard = new KAction( i18n( "Beam selected v&Card(s)" ), "beam", 0, this, SLOT( beamVCard() ), actionCollection(), "kaddressbook_beam_vcard" ); mActionBeam = new KAction( i18n( "&Beam personal vCard" ), "beam", 0, this, SLOT( beamMySelf() ), actionCollection(), "kaddressbook_beam_myself" ); } #endif mActionEditAddressee = new KAction( i18n( "&Edit Contact..." ), "edit", 0, this, SLOT( editContact2() ), actionCollection(), "file_properties" ); #ifdef KAB_EMBEDDED // mActionQuit = KStdAction::quit( mMainWindow, SLOT( exit() ), actionCollection() ); mActionQuit = new KAction( i18n( "&Exit" ), "exit", 0, mMainWindow, SLOT( exit() ), actionCollection(), "quit" ); #endif //KAB_EMBEDDED // edit menu if ( mIsPart ) { mActionCopy = new KAction( i18n( "&Copy" ), "editcopy", CTRL + Key_C, this, SLOT( copyContacts() ), actionCollection(), "kaddressbook_copy" ); mActionCut = new KAction( i18n( "Cu&t" ), "editcut", CTRL + Key_X, this, SLOT( cutContacts() ), actionCollection(), "kaddressbook_cut" ); mActionPaste = new KAction( i18n( "&Paste" ), "editpaste", CTRL + Key_V, this, SLOT( pasteContacts() ), actionCollection(), "kaddressbook_paste" ); mActionSelectAll = new KAction( i18n( "Select &All" ), CTRL + Key_A, this, SLOT( selectAllContacts() ), actionCollection(), "kaddressbook_select_all" ); mActionUndo = new KAction( i18n( "&Undo" ), "undo", CTRL + Key_Z, this, SLOT( undo() ), actionCollection(), "kaddressbook_undo" ); mActionRedo = new KAction( i18n( "Re&do" ), "redo", CTRL + SHIFT + Key_Z, this, SLOT( redo() ), actionCollection(), "kaddressbook_redo" ); } else { mActionCopy = KStdAction::copy( this, SLOT( copyContacts() ), actionCollection() ); mActionCut = KStdAction::cut( this, SLOT( cutContacts() ), actionCollection() ); mActionPaste = KStdAction::paste( this, SLOT( pasteContacts() ), actionCollection() ); mActionSelectAll = KStdAction::selectAll( this, SLOT( selectAllContacts() ), actionCollection() ); mActionUndo = KStdAction::undo( this, SLOT( undo() ), actionCollection() ); mActionRedo = KStdAction::redo( this, SLOT( redo() ), actionCollection() ); } mActionDelete = new KAction( i18n( "&Delete Contact" ), "editdelete", Key_Delete, this, SLOT( deleteContacts() ), actionCollection(), "edit_delete" ); mActionUndo->setEnabled( false ); mActionRedo->setEnabled( false ); // settings menu #ifdef KAB_EMBEDDED //US special menuentry to configure the addressbook resources. On KDE // you do that through the control center !!! mActionConfigResources = new KAction( i18n( "Configure &Resources..." ), "configure_resources", 0, this, SLOT( configureResources() ), actionCollection(), "kaddressbook_configure_resources" ); #endif //KAB_EMBEDDED if ( mIsPart ) { mActionConfigKAddressbook = new KAction( i18n( "&Configure KAddressBook..." ), "configure", 0, this, SLOT( openConfigDialog() ), actionCollection(), "kaddressbook_configure" ); mActionConfigShortcuts = new KAction( i18n( "Configure S&hortcuts..." ), "configure_shortcuts", 0, this, SLOT( configureKeyBindings() ), actionCollection(), "kaddressbook_configure_shortcuts" ); #ifdef KAB_EMBEDDED mActionConfigureToolbars = KStdAction::configureToolbars( this, SLOT( mMainWindow->configureToolbars() ), actionCollection() ); mActionConfigureToolbars->setEnabled( false ); #endif //KAB_EMBEDDED } else { mActionConfigKAddressbook = KStdAction::preferences( this, SLOT( openConfigDialog() ), actionCollection() ); mActionKeyBindings = KStdAction::keyBindings( this, SLOT( configureKeyBindings() ), actionCollection() ); } mActionJumpBar = new KToggleAction( i18n( "Show Jump Bar" ), 0, 0, actionCollection(), "options_show_jump_bar" ); connect( mActionJumpBar, SIGNAL( toggled( bool ) ), SLOT( setJumpButtonBarVisible( bool ) ) ); mActionDetails = new KToggleAction( i18n( "Show Details" ), "listview", 0, actionCollection(), "options_show_details" ); connect( mActionDetails, SIGNAL( toggled( bool ) ), SLOT( setDetailsVisible( bool ) ) ); // misc // only enable LDAP lookup if we can handle the protocol #ifndef KAB_EMBEDDED if ( KProtocolInfo::isKnownProtocol( KURL( "ldap://localhost" ) ) ) { new KAction( i18n( "&Lookup Addresses in Directory" ), "find", 0, this, SLOT( openLDAPDialog() ), actionCollection(), "ldap_lookup" ); } #else //KAB_EMBEDDED //qDebug("KABCore::initActions() LDAP has to be implemented"); #endif //KAB_EMBEDDED mActionWhoAmI = new KAction( i18n( "Set Who Am I" ), "personal", 0, this, SLOT( setWhoAmI() ), actionCollection(), "set_personal" ); mActionCategories = new KAction( i18n( "Set Categories" ), 0, this, SLOT( setCategories() ), actionCollection(), "edit_set_categories" ); mActionRemoveVoice = new KAction( i18n( "Remove \"voice\"..." ), 0, this, SLOT( removeVoice() ), actionCollection(), "remove_voice" ); @@ -2673,199 +2673,209 @@ bool KABCore::synchronizeAddressbooks( KABC::AddressBook* local, KABC::AddressBo inR = remote->findByUid( uid ); if ( inR.isEmpty() ) { if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) { if ( !inL.getID(mCurrentSyncDevice).isEmpty() && mode != 4 ) { // pending checkExternSyncAddressee(addresseeLSyncSharp, inL); local->removeAddressee( inL ); ++deletedAddresseeL; } else { if ( ! syncManager->mWriteBackExistingOnly ) { inL.removeID(mCurrentSyncDevice ); ++addedAddresseeR; inL.setRevision( modifiedCalendar ); local->insertAddressee( inL, false ); inR = inL; inR.setTempSyncStat( SYNC_TEMPSTATE_ADDED_EXTERNAL ); inR.setResource( 0 ); remote->insertAddressee( inR, false ); } } } else { if ( inL.revision() < mLastAddressbookSync && mode != 4 ) { // pending checkExternSyncAddressee(addresseeLSyncSharp, inL); local->removeAddressee( inL ); ++deletedAddresseeL; } else { if ( ! syncManager->mWriteBackExistingOnly ) { ++addedAddresseeR; inL.setRevision( modifiedCalendar ); local->insertAddressee( inL, false ); inR = inL; inR.setResource( 0 ); remote->insertAddressee( inR, false ); } } } } } ++incCounter; } el.clear(); syncManager->hideProgressBar(); mLastAddressbookSync = QDateTime::currentDateTime().addSecs( 1 ); // get rid of micro seconds QTime t = mLastAddressbookSync.time(); mLastAddressbookSync.setTime( QTime (t.hour (), t.minute (), t.second () ) ); addresseeLSync.setRevision( mLastAddressbookSync ); addresseeRSync.setRevision( mLastAddressbookSync ); addresseeRSync.setRole( i18n("!Remote from: ")+mCurrentSyncName ) ; addresseeLSync.setRole(i18n("!Local from: ") + mCurrentSyncName ); addresseeRSync.setGivenName( i18n("!DO NOT EDIT!") ) ; addresseeLSync.setGivenName(i18n("!DO NOT EDIT!") ); addresseeRSync.setOrganization( "!"+mLastAddressbookSync.toString() ) ; addresseeLSync.setOrganization("!"+ mLastAddressbookSync.toString() ); addresseeRSync.setNote( "" ) ; addresseeLSync.setNote( "" ); if ( mGlobalSyncMode == SYNC_MODE_NORMAL) remote->insertAddressee( addresseeRSync, false ); local->insertAddressee( addresseeLSync, false ); QString mes; mes .sprintf( i18n("Synchronization summary:\n\n %d items added to local\n %d items added to remote\n %d items updated on local\n %d items updated on remote\n %d items deleted on local\n %d items deleted on remote\n"),addedAddressee, addedAddresseeR, changedLocal, changedRemote, deletedAddresseeL, deletedAddresseeR ); if ( syncManager->mShowSyncSummary ) { KMessageBox::information(this, mes, i18n("KA/Pi Synchronization") ); } qDebug( mes ); return syncOK; } //this is a overwritten callbackmethods from the syncinterface bool KABCore::sync(KSyncManager* manager, QString filename, int mode) { //pending prepare addresseeview for output //pending detect, if remote file has REV field. if not switch to external sync mGlobalSyncMode = SYNC_MODE_NORMAL; QString mCurrentSyncDevice = manager->getCurrentSyncDevice(); AddressBook abLocal(filename,"syncContact"); bool syncOK = false; if ( abLocal.load() ) { qDebug("AB loaded %s,sync mode %d",filename.latin1(), mode ); bool external = false; bool isXML = false; if ( filename.right(4) == ".xml") { mGlobalSyncMode = SYNC_MODE_EXTERNAL; isXML = true; abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice ); } else { Addressee lse = mAddressBook->findByUid( "last-syncAddressee-"+mCurrentSyncDevice ); if ( ! lse.isEmpty() ) { if ( lse.familyName().left(4) == "!E: " ) external = true; } else { bool found = false; AddressBook::Iterator it; for ( it = abLocal.begin(); it != abLocal.end(); ++it ) { if ( (*it).revision().date().year() > 2003 ) { found = true; break; } } external = ! found; } if ( external ) { qDebug("Setting vcf mode to external "); mGlobalSyncMode = SYNC_MODE_EXTERNAL; AddressBook::Iterator it; for ( it = abLocal.begin(); it != abLocal.end(); ++it ) { (*it).setID( mCurrentSyncDevice, (*it).uid() ); (*it).computeCsum( mCurrentSyncDevice ); } } } //AddressBook::Iterator it; //QStringList vcards; //for ( it = abLocal.begin(); it != abLocal.end(); ++it ) { // qDebug("Name %s ", (*it).familyName().latin1()); //} syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, mode ); if ( syncOK ) { if ( syncManager->mWriteBackFile ) { if ( external ) abLocal.removeSyncAddressees( !isXML); qDebug("Saving remote AB "); abLocal.saveAB(); if ( isXML ) { // afterwrite processing abLocal.postExternSync( mAddressBook,mCurrentSyncDevice ); } } } setModified(); } if ( syncOK ) mViewManager->refreshView(); return syncOK; #if 0 if ( storage->load(KOPrefs::instance()->mUseQuicksave) ) { getEventViewerDialog()->setSyncMode( true ); syncOK = synchronizeCalendar( mCalendar, calendar, mode ); getEventViewerDialog()->setSyncMode( false ); if ( syncOK ) { if ( KOPrefs::instance()->mWriteBackFile ) { storage->setSaveFormat( new ICalFormat( KOPrefs::instance()->mUseQuicksave) ); storage->save(); } } setModified(); } #endif } //this is a overwritten callbackmethods from the syncinterface bool KABCore::syncExternal(KSyncManager* manager, QString resource) { QString mCurrentSyncDevice = manager->getCurrentSyncDevice(); AddressBook abLocal( resource,"syncContact"); bool syncOK = false; if ( abLocal.load() ) { qDebug("AB sharp loaded ,sync device %s",mCurrentSyncDevice.latin1()); mGlobalSyncMode = SYNC_MODE_EXTERNAL; abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice ); syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, syncManager->mSyncAlgoPrefs ); if ( syncOK ) { if ( syncManager->mWriteBackFile ) { abLocal.saveAB(); abLocal.postExternSync( mAddressBook,mCurrentSyncDevice ); } } setModified(); } if ( syncOK ) mViewManager->refreshView(); return syncOK; } void KABCore::getFile( bool success ) { if ( ! success ) { setCaption( i18n("Error receiving file. Nothing changed!") ); return; } - //mView->watchSavedFile(); - //mView->openCalendar( defaultFileName() ); - // pending: reload received file! + mAddressBook->importFromFile( sentSyncFile() ); setCaption( i18n("Pi-Sync successful!") ); } +void KABCore::syncFileRequest() +{ + mAddressBook->export2File( sentSyncFile() ); +} +QString KABCore::sentSyncFile() +{ +#ifdef _WIN32_ + return locateLocal( "tmp", "syncab.ics" ); +#else + return QString( "/tmp/kapitempfile.vcf" ); +#endif +} diff --git a/kaddressbook/kabcore.h b/kaddressbook/kabcore.h index 355e828..987369d 100644 --- a/kaddressbook/kabcore.h +++ b/kaddressbook/kabcore.h @@ -154,326 +154,328 @@ class KABCore : public QWidget, public KSyncInterface /** Opens the preferred mail composer with all selected contacts as arguments. */ void sendMail(); /** Opens the preferred mail composer with the given contacts as arguments. */ void sendMail( const QString& email ); void mailVCard(); void mailVCard(const QStringList& uids); /** Beams the "WhoAmI contact. */ void beamMySelf(); void beamVCard(); void export2phone(); void beamVCard(const QStringList& uids); void beamDone( Ir *ir ); /** Starts the preferred web browser with the given URL as argument. */ void browse( const QString& url ); /** Select all contacts in the view. */ void selectAllContacts(); /** Deletes all selected contacts from the address book. */ void deleteContacts(); /** Deletes given contacts from the address book. @param uids The uids of the contacts, which shall be deleted. */ void deleteContacts( const QStringList &uids ); /** Copys the selected contacts into clipboard for later pasting. */ void copyContacts(); /** Cuts the selected contacts and stores them for later pasting. */ void cutContacts(); /** Paste contacts from clipboard into the address book. */ void pasteContacts(); /** Paste given contacts into the address book. @param list The list of addressee, which shall be pasted. */ void pasteContacts( KABC::Addressee::List &list ); /** Sets the whoAmI contact, that is used by many other programs to get personal information about the current user. */ void setWhoAmI(); /** Displays the category dialog and applies the result to all selected contacts. */ void setCategories(); /** Sets the field list of the Incremental Search Widget. */ void setSearchFields( const KABC::Field::List &fields ); /** Search with the current search field for a contact, that matches the given text, and selects it in the view. */ void incrementalSearch( const QString& text ); /** Marks the address book as modified. */ void setModified(); /** Marks the address book as modified without refreshing the view. */ void setModifiedWOrefresh(); /** Marks the address book as modified concerning the argument. */ void setModified( bool modified ); /** Returns whether the address book is modified. */ bool modified() const; /** Called whenever an contact is modified in the contact editor dialog or the quick edit. */ void contactModified( const KABC::Addressee &addr ); /** DCOP METHODS. */ void addEmail( QString addr ); void importVCard( const KURL& url, bool showPreview ); void importVCard( const QString& vCard, bool showPreview ); void newContact(); QString getNameByPhone( const QString& phone ); /** END DCOP METHODS */ /** Saves the contents of the AddressBook back to disk. */ void save(); /** Undos the last command using the undo stack. */ void undo(); /** Redos the last command that was undone, using the redo stack. */ void redo(); /** Shows the edit dialog for the given uid. If the uid is QString::null, the method will try to find a selected addressee in the view. */ void editContact( const QString &uid /*US = QString::null*/ ); //US added a second method without defaultparameter void editContact2(); /** Shows or edits the detail view for the given uid. If the uid is QString::null, the method will try to find a selected addressee in the view. */ void executeContact( const QString &uid /*US = QString::null*/ ); /** Launches the configuration dialog. */ void openConfigDialog(); /** Launches the ldap search dialog. */ void openLDAPDialog(); /** Creates a KAddressBookPrinter, which will display the print dialog and do the printing. */ void print(); /** Registers a new GUI client, so plugins can register its actions. */ void addGUIClient( KXMLGUIClient *client ); void requestForNameEmailUidList(const QString& sourceChannel, const QString& sessionuid); void requestForDetails(const QString& sourceChannel, const QString& sessionuid, const QString& name, const QString& email, const QString& uid); void requestForBirthdayList(const QString& sourceChannel, const QString& sessionuid); signals: void contactSelected( const QString &name ); void contactSelected( const QPixmap &pixmap ); public slots: void getFile( bool success ); + void syncFileRequest(); void setDetailsVisible( bool visible ); void setDetailsToState(); // void slotSyncMenu( int ); private slots: void setJumpButtonBarVisible( bool visible ); void importFromOL(); void extensionModified( const KABC::Addressee::List &list ); void extensionChanged( int id ); void clipboardDataChanged(); void updateActionMenu(); void configureKeyBindings(); void removeVoice(); #ifdef KAB_EMBEDDED void configureResources(); #endif //KAB_EMBEDDED void slotEditorDestroyed( const QString &uid ); void configurationChanged(); void addressBookChanged(); private: void initGUI(); void initActions(); AddresseeEditorDialog *createAddresseeEditorDialog( QWidget *parent, const char *name = 0 ); KXMLGUIClient *mGUIClient; KABC::AddressBook *mAddressBook; ViewManager *mViewManager; // QSplitter *mDetailsSplitter; KDGanttMinimizeSplitter *mExtensionBarSplitter; ViewContainer *mDetails; KDGanttMinimizeSplitter* mMiniSplitter; XXPortManager *mXXPortManager; JumpButtonBar *mJumpButtonBar; IncSearchWidget *mIncSearchWidget; ExtensionManager *mExtensionManager; KCMultiDialog *mConfigureDialog; #ifndef KAB_EMBEDDED LDAPSearchDialog *mLdapSearchDialog; #endif //KAB_EMBEDDED // QDict<AddresseeEditorDialog> mEditorDict; AddresseeEditorDialog *mEditorDialog; bool mReadWrite; bool mModified; bool mIsPart; bool mMultipleViewsAtOnce; //US file menu KAction *mActionMail; KAction *mActionBeam; KAction *mActionExport2phone; KAction* mActionPrint; KAction* mActionNewContact; KAction *mActionSave; KAction *mActionEditAddressee; KAction *mActionMailVCard; KAction *mActionBeamVCard; KAction *mActionQuit; //US edit menu KAction *mActionCopy; KAction *mActionCut; KAction *mActionPaste; KAction *mActionSelectAll; KAction *mActionUndo; KAction *mActionRedo; KAction *mActionDelete; //US settings menu KAction *mActionConfigResources; KAction *mActionConfigKAddressbook; KAction *mActionConfigShortcuts; KAction *mActionConfigureToolbars; KAction *mActionKeyBindings; KToggleAction *mActionJumpBar; KToggleAction *mActionDetails; KAction *mActionWhoAmI; KAction *mActionCategories; KAction *mActionAboutKAddressbook; KAction *mActionLicence; KAction *mActionFaq; KAction *mActionDeleteView; QPopupMenu *viewMenu; QPopupMenu *filterMenu; QPopupMenu *settingsMenu; QPopupMenu *changeMenu; //US QAction *mActionSave; QPopupMenu *ImportMenu; QPopupMenu *ExportMenu; //LR additional methods KAction *mActionRemoveVoice; KAction * mActionImportOL; #ifndef KAB_EMBEDDED KAddressBookService *mAddressBookService; #endif //KAB_EMBEDDED class KABCorePrivate; KABCorePrivate *d; //US bool mBlockSaveFlag; #ifdef KAB_EMBEDDED KAddressBookMain *mMainWindow; // should be the same like mGUIClient #endif //KAB_EMBEDDED //this are the overwritten callbackmethods from the syncinterface virtual bool sync(KSyncManager* manager, QString filename, int mode); virtual bool syncExternal(KSyncManager* manager, QString resource); // LR ******************************* // sync stuff! + QString sentSyncFile(); QPopupMenu *syncMenu; KSyncManager* syncManager; int mGlobalSyncMode; bool synchronizeAddressbooks( KABC::AddressBook* local, KABC::AddressBook* remote,int mode); KABC::Addressee getLastSyncAddressee(); QDateTime mLastAddressbookSync; int takeAddressee( KABC::Addressee* local, KABC::Addressee* remote, int mode , bool full ); // ********************* }; #endif diff --git a/kaddressbook/xxport/vcard_xxport.cpp b/kaddressbook/xxport/vcard_xxport.cpp index acf6419..3079d42 100644 --- a/kaddressbook/xxport/vcard_xxport.cpp +++ b/kaddressbook/xxport/vcard_xxport.cpp @@ -1,256 +1,257 @@ /* This file is part of KAddressbook. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ /* Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ #include <qfile.h> #include <qtextstream.h> #include <kabc/vcardconverter.h> #include <kabc/vcardparser/vcardtool.h> #include <kfiledialog.h> #ifndef KAB_EMBEDDED #include <kio/netaccess.h> #endif //KAB_EMBEDDED #include <klocale.h> #include <kmessagebox.h> #include <ktempfile.h> #include <kurl.h> #include "xxportmanager.h" #include "vcard_xxport.h" #ifndef KAB_EMBEDDED class VCardXXPortFactory : public XXPortFactory { public: XXPortObject *xxportObject( KABC::AddressBook *ab, QWidget *parent, const char *name ) { return new VCardXXPort( ab, parent, name ); } }; #endif //KAB_EMBEDDED extern "C" { #ifndef KAB_EMBEDDED void *init_libkaddrbk_vcard_xxport() #else //KAB_EMBEDDED void *init_microkaddrbk_vcard_xxport() #endif //KAB_EMBEDDED { return ( new VCardXXPortFactory() ); } } VCardXXPort::VCardXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name ) : XXPortObject( ab, parent, name ) { createImportAction( i18n( "Import vCard..." ) ); //US KABC::VCardConverter does not support the export of 2.1 addressbooks. //US createExportAction( i18n( "Export vCard 2.1..." ), "v21" ); createExportAction( i18n( "Export vCard 3.0..." ), "v30" ); } bool VCardXXPort::exportContacts( const KABC::AddresseeList &list, const QString &data ) { QString name; if ( list.count() == 1 ) name = list[ 0 ].givenName() + "_" + list[ 0 ].familyName() + ".vcf"; else name = "addressbook.vcf"; #ifndef KAB_EMBEDDED QString fileName = KFileDialog::getSaveFileName( name ); #else //KAB_EMBEDDED QString fileName = KFileDialog::getSaveFileName( name, i18n("Save file"), parentWidget() ); #endif //KAB_EMBEDDED if ( fileName.isEmpty() ) return false; QFile outFile( fileName ); if ( !outFile.open( IO_WriteOnly ) ) { QString text = i18n( "<qt>Unable to open file <b>%1</b> for export.</qt>" ); KMessageBox::error( parentWidget(), text.arg( fileName ) ); return false; } QTextStream t( &outFile ); t.setEncoding( QTextStream::UnicodeUTF8 ); KABC::Addressee::List::ConstIterator it; for ( it = list.begin(); it != list.end(); ++it ) { KABC::VCardConverter converter; QString vcard; KABC::VCardConverter::Version version; if ( data == "v21" ) version = KABC::VCardConverter::v2_1; else version = KABC::VCardConverter::v3_0; + version = KABC::VCardConverter::v2_1; converter.addresseeToVCard( *it, vcard, version ); t << vcard << "\r\n\r\n"; } outFile.close(); return true; } KABC::AddresseeList VCardXXPort::importContacts( const QString& ) const { QString fileName; KABC::AddresseeList addrList; KURL url; #ifndef KAB_EMBEDDED if ( !XXPortManager::importData.isEmpty() ) addrList = parseVCard( XXPortManager::importData ); else { if ( XXPortManager::importURL.isEmpty() ) { url = KFileDialog::getLoadFileName( QString::null, i18n("Select vCard to Import"), parentWidget() ); } else url = XXPortManager::importURL; if ( url.isEmpty() ) return addrList; QString caption( i18n( "vCard Import Failed" ) ); if ( KIO::NetAccess::download( url, fileName ) ) { QFile file( fileName ); file.open( IO_ReadOnly ); QByteArray rawData = file.readAll(); file.close(); QString data = QString::fromUtf8( rawData.data(), rawData.size() + 1 ); addrList = parseVCard( data ); if ( !url.isLocalFile() ) KIO::NetAccess::removeTempFile( fileName ); } else { QString text = i18n( "<qt>Unable to access <b>%1</b>.</qt>" ); KMessageBox::error( parentWidget(), text.arg( url.url() ), caption ); } } #else //KAB_EMBEDDED if ( !XXPortManager::importData.isEmpty() ) addrList = parseVCard( XXPortManager::importData ); else { if ( XXPortManager::importURL.isEmpty() ) { fileName = KFileDialog::getOpenFileName( QString::null, i18n("Select vCard to Import"), parentWidget() ); if ( fileName.isEmpty() ) return addrList; } else { //US url = XXPortManager::importURL; qDebug("VCardXXPort::importContacts Urls at the moment not supported"); if ( url.isEmpty() ) return addrList; } QFile file( fileName ); file.open( IO_ReadOnly ); QByteArray rawData = file.readAll(); file.close(); QString data = QString::fromUtf8( rawData.data(), rawData.size() + 1 ); addrList = parseVCard( data ); } #endif //KAB_EMBEDDED return addrList; } KABC::AddresseeList VCardXXPort::parseVCard( const QString &data ) const { KABC::VCardTool tool; KABC::AddresseeList addrList; addrList = tool.parseVCards( data ); // LR : I switched to the code, which is in current cvs HEAD /* uint numVCards = data.contains( "BEGIN:VCARD", false ); QStringList dataList = QStringList::split( "\r\n\r\n", data ); for ( uint i = 0; i < numVCards && i < dataList.count(); ++i ) { KABC::Addressee addr; bool ok = false; if ( dataList[ i ].contains( "VERSION:3.0" ) ) ok = converter.vCardToAddressee( dataList[ i ], addr, KABC::VCardConverter::v3_0 ); else if ( dataList[ i ].contains( "VERSION:2.1" ) ) ok = converter.vCardToAddressee( dataList[ i ], addr, KABC::VCardConverter::v2_1 ); else { KMessageBox::sorry( parentWidget(), i18n( "Not supported vCard version." ) ); continue; } if ( !addr.isEmpty() && ok ) addrList.append( addr ); else { QString text = i18n( "The selected file does not include a valid vCard. " "Please check the file and try again." ); KMessageBox::sorry( parentWidget(), text ); } } */ if ( addrList.isEmpty() ) { QString text = i18n( "The selected file does not\ninclude a valid vCard.\nPlease check the file and try again.\n" ); KMessageBox::sorry( parentWidget(), text ); } return addrList; } #ifndef KAB_EMBEDDED #include "vcard_xxport.moc" #endif //KAB_EMBEDDED diff --git a/libkdepim/ksyncmanager.cpp b/libkdepim/ksyncmanager.cpp index 5d48884..ea543dd 100644 --- a/libkdepim/ksyncmanager.cpp +++ b/libkdepim/ksyncmanager.cpp @@ -86,385 +86,386 @@ void KSyncManager::fillSyncMenu() mSyncMenu->insertSeparator(); if ( mServerSocket == 0 ) { mSyncMenu->insertItem( i18n("Enable Pi-Sync"), 2 ); } else { mSyncMenu->insertItem( i18n("Disable Pi-Sync"), 3 ); } mSyncMenu->insertSeparator(); mSyncMenu->insertItem( i18n("Multiple sync"), 1 ); mSyncMenu->insertSeparator(); KConfig config ( locateLocal( "config","ksyncprofilesrc" ) ); config.setGroup("General"); QStringList prof = config.readListEntry("SyncProfileNames"); mLocalMachineName = config.readEntry("LocalMachineName","undefined"); if ( prof.count() < 2 ) { prof.clear(); prof << i18n("Sharp_DTM"); prof << i18n("Local_file"); KSyncProfile* temp = new KSyncProfile (); temp->setName( prof[0] ); temp->writeConfig(&config); temp->setName( prof[1] ); temp->writeConfig(&config); config.setGroup("General"); config.writeEntry("SyncProfileNames",prof); config.writeEntry("ExternSyncProfiles","Sharp_DTM"); config.sync(); delete temp; } mExternSyncProfiles = config.readListEntry("ExternSyncProfiles"); mSyncProfileNames = prof; unsigned int i; for ( i = 0; i < prof.count(); ++i ) { mSyncMenu->insertItem( prof[i], 1000+i ); if ( i == 2 ) mSyncMenu->insertSeparator(); } QDir app_dir; //US do not display SharpDTM if app is pwmpi, or no sharpfiles available if ( mTargetApp == PWMPI) { mSyncMenu->removeItem( 1000 ); } else if (!app_dir.exists(QDir::homeDirPath()+"/Applications/dtm" ) ) { mSyncMenu->setItemEnabled( 1000, false ); } } void KSyncManager::slotSyncMenu( int action ) { //qDebug("syncaction %d ", action); if ( action == 0 ) { // seems to be a Qt2 event handling bug // syncmenu.clear causes a segfault at first time // when we call it after the main event loop, it is ok // same behaviour when calling OM/Pi via QCOP for the first time QTimer::singleShot ( 1, this, SLOT ( confSync() ) ); //confSync(); return; } if ( action == 1 ) { multiSync( true ); return; } if ( action == 2 ) { enableQuick(); QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) ); return; } if ( action == 3 ) { delete mServerSocket; mServerSocket = 0; QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) ); return; } if (blockSave()) return; setBlockSave(true); mCurrentSyncProfile = action - 1000 ; mCurrentSyncDevice = mSyncProfileNames[mCurrentSyncProfile] ; mCurrentSyncName = mLocalMachineName ; KConfig config ( locateLocal( "config","ksyncprofilesrc" ) ); KSyncProfile* temp = new KSyncProfile (); temp->setName(mSyncProfileNames[mCurrentSyncProfile]); temp->readConfig(&config); mAskForPreferences = temp->getAskForPreferences(); mSyncAlgoPrefs = temp->getSyncPrefs(); mWriteBackFile = temp->getWriteBackFile(); mWriteBackExistingOnly = temp->getWriteBackExisting(); mWriteBackInFuture = 0; if ( temp->getWriteBackFuture() ) mWriteBackInFuture = temp->getWriteBackFutureWeeks( ); mShowSyncSummary = temp->getShowSummaryAfterSync(); if ( action == 1000 ) { syncSharp(); } else if ( action == 1001 ) { syncLocalFile(); } else if ( action == 1002 ) { quickSyncLocalFile(); } else if ( action >= 1003 ) { if ( temp->getIsLocalFileSync() ) { switch(mTargetApp) { case (KAPI): if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) ) mLastSyncedLocalFile = temp->getRemoteFileNameAB(); break; case (KOPI): if ( syncWithFile( temp->getRemoteFileName( ), false ) ) mLastSyncedLocalFile = temp->getRemoteFileName(); break; case (PWMPI): if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) ) mLastSyncedLocalFile = temp->getRemoteFileNamePWM(); break; default: qDebug("KSyncManager::slotSyncMenu: invalid apptype selected"); break; } } else { if ( temp->getIsPhoneSync() ) { mPhoneDevice = temp->getPhoneDevice( ) ; mPhoneConnection = temp->getPhoneConnection( ); mPhoneModel = temp->getPhoneModel( ); syncPhone(); } else if ( temp->getIsPiSync() ) { mPassWordPiSync = temp->getRemotePw(); mActiveSyncPort = temp->getRemotePort(); mActiveSyncIP = temp->getRemoteIP(); syncPi(); } syncRemote( temp ); } } delete temp; setBlockSave(false); } void KSyncManager::enableQuick() { QDialog dia ( 0, "input-dialog", true ); QLineEdit lab ( &dia ); QVBoxLayout lay( &dia ); lab.setText( mPrefs->mPassiveSyncPort ); lay.setMargin(7); lay.setSpacing(7); int po = 9197+mTargetApp; QLabel label ( i18n("Port number (Default: %1)").arg(po), &dia ); lay.addWidget( &label); lay.addWidget( &lab); QLineEdit lepw ( &dia ); lepw.setText( mPrefs->mPassiveSyncPw ); QLabel label2 ( i18n("Password to enable\naccess from remote:"), &dia ); lay.addWidget( &label2); lay.addWidget( &lepw); dia.setFixedSize( 230,80 ); dia.setCaption( i18n("Enter port for Pi-Sync") ); QPushButton pb ( "OK", &dia); lay.addWidget( &pb ); connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) ); dia.show(); if ( ! dia.exec() ) return; dia.hide(); qApp->processEvents(); mPrefs->mPassiveSyncPw = lepw.text(); mPrefs->mPassiveSyncPort = lab.text(); bool ok; Q_UINT16 port = mPrefs->mPassiveSyncPort.toUInt(&ok); if ( ! ok ) { KMessageBox::information( 0, i18n("No valid port")); return; } //qDebug("port %d ", port); mServerSocket = new KServerSocket ( mPrefs->mPassiveSyncPw, port ,1 ); mServerSocket->setFileName( defaultFileName() ); //qDebug("connected "); if ( !mServerSocket->ok() ) { KMessageBox::information( 0, i18n("Failed to bind or\nlisten to the port!")); delete mServerSocket; mServerSocket = 0; return; } - connect( mServerSocket, SIGNAL ( saveFile() ),this, SIGNAL ( save() ) ); + //connect( mServerSocket, SIGNAL ( saveFile() ),this, SIGNAL ( save() ) ); + connect( mServerSocket, SIGNAL ( request_file() ),this, SIGNAL ( request_file() ) ); connect( mServerSocket, SIGNAL ( file_received( bool ) ), this, SIGNAL ( getFile( bool ) ) ); } void KSyncManager::syncLocalFile() { QString fn =mLastSyncedLocalFile; QString ext; switch(mTargetApp) { case (KAPI): ext = "(*.vcf)"; break; case (KOPI): ext = "(*.ics/*.vcs)"; break; case (PWMPI): ext = "(*.pwm)"; break; default: qDebug("KSyncManager::syncLocalFile: invalid apptype selected"); break; } fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename"+ext), mParent ); if ( fn == "" ) return; if ( syncWithFile( fn, false ) ) { qDebug("syncLocalFile() successful "); } } bool KSyncManager::syncWithFile( QString fn , bool quick ) { bool ret = false; QFileInfo info; info.setFile( fn ); QString mess; bool loadbup = true; if ( !info. exists() ) { mess = i18n( "Sync file \n...%1\ndoes not exist!\nNothing synced!\n").arg(fn.right( 30) ); int result = QMessageBox::warning( mParent, i18n("Warning!"), mess ); return ret; } int result = 0; if ( !quick ) { mess = i18n("Sync with file \n...%1\nfrom:\n%2\n").arg(fn.right( 25)).arg(KGlobal::locale()->formatDateTime(info.lastModified (), true, false )); result = QMessageBox::warning( mParent, i18n("Warning!"), mess, i18n("Sync"), i18n("Cancel"), 0, 0, 1 ); if ( result ) return false; } if ( mAskForPreferences ) edit_sync_options(); if ( result == 0 ) { //qDebug("Now sycing ... "); if ( ret = mImplementation->sync( this, fn, mSyncAlgoPrefs ) ) mParent->setCaption( i18n("Synchronization successful") ); else mParent->setCaption( i18n("Sync cancelled or failed. Nothing synced.") ); if ( ! quick ) mLastSyncedLocalFile = fn; } return ret; } void KSyncManager::quickSyncLocalFile() { if ( syncWithFile( mLastSyncedLocalFile, false ) ) { qDebug("quick syncLocalFile() successful "); } } void KSyncManager::multiSync( bool askforPrefs ) { if (blockSave()) return; setBlockSave(true); QString question = i18n("Do you really want\nto multiple sync\nwith all checked profiles?\nSyncing takes some\ntime - all profiles\nare synced twice!"); if ( QMessageBox::information( mParent, i18n("Sync"), question, i18n("Yes"), i18n("No"), 0, 0 ) != 0 ) { setBlockSave(false); mParent->setCaption(i18n("Aborted! Nothing synced!")); return; } mCurrentSyncDevice = i18n("Multiple profiles") ; mSyncAlgoPrefs = mRingSyncAlgoPrefs; if ( askforPrefs ) { edit_sync_options(); mRingSyncAlgoPrefs = mSyncAlgoPrefs; } mParent->setCaption(i18n("Multiple sync started.") ); qApp->processEvents(); int num = ringSync() ; if ( num > 1 ) ringSync(); setBlockSave(false); if ( num ) emit save(); if ( num ) mParent->setCaption(i18n("%1 profiles synced. Multiple sync completed!").arg(num) ); else mParent->setCaption(i18n("Nothing synced! No profiles defined for multisync!")); return; } int KSyncManager::ringSync() { int syncedProfiles = 0; unsigned int i; QTime timer; KConfig config ( locateLocal( "config","ksyncprofilesrc" ) ); QStringList syncProfileNames = mSyncProfileNames; KSyncProfile* temp = new KSyncProfile (); mAskForPreferences = false; for ( i = 0; i < syncProfileNames.count(); ++i ) { mCurrentSyncProfile = i; temp->setName(syncProfileNames[mCurrentSyncProfile]); temp->readConfig(&config); QString includeInRingSync; switch(mTargetApp) { case (KAPI): includeInRingSync = temp->getIncludeInRingSyncAB(); break; case (KOPI): includeInRingSync = temp->getIncludeInRingSync(); break; case (PWMPI): includeInRingSync = temp->getIncludeInRingSyncPWM(); break; default: qDebug("KSyncManager::ringSync: invalid apptype selected"); break; } if ( includeInRingSync && ( i < 1 || i > 2 )) { mParent->setCaption(i18n("Profile ")+syncProfileNames[mCurrentSyncProfile]+ i18n(" is synced ... ")); ++syncedProfiles; // mAskForPreferences = temp->getAskForPreferences(); mWriteBackFile = temp->getWriteBackFile(); mWriteBackExistingOnly = temp->getWriteBackExisting(); mWriteBackInFuture = 0; if ( temp->getWriteBackFuture() ) mWriteBackInFuture = temp->getWriteBackFutureWeeks( ); mShowSyncSummary = false; mCurrentSyncDevice = syncProfileNames[i] ; mCurrentSyncName = mLocalMachineName; if ( i == 0 ) { syncSharp(); } else { if ( temp->getIsLocalFileSync() ) { switch(mTargetApp) { case (KAPI): if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) ) mLastSyncedLocalFile = temp->getRemoteFileNameAB(); break; case (KOPI): if ( syncWithFile( temp->getRemoteFileName( ), false ) ) mLastSyncedLocalFile = temp->getRemoteFileName(); break; case (PWMPI): if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) ) mLastSyncedLocalFile = temp->getRemoteFileNamePWM(); break; default: qDebug("KSyncManager::slotSyncMenu: invalid apptype selected"); break; } } else { if ( temp->getIsPhoneSync() ) { mPhoneDevice = temp->getPhoneDevice( ) ; mPhoneConnection = temp->getPhoneConnection( ); mPhoneModel = temp->getPhoneModel( ); syncPhone(); } else syncRemote( temp, false ); } } timer.start(); mParent->setCaption(i18n("Multiple sync in progress ... please wait!") ); @@ -739,385 +740,385 @@ QString KSyncManager::syncFileName() { case (KAPI): fn = "addressbook.vcf"; break; case (KOPI): fn = "synccalendar.ics"; break; case (PWMPI): fn = "manager.pwm"; break; default: break; } #ifdef _WIN32_ return locateLocal( "tmp", fn ); #else return (QString( "/tmp/" )+ fn ); #endif } void KSyncManager::syncPi() { qApp->processEvents(); bool ok; Q_UINT16 port = mActiveSyncPort.toUInt(&ok); if ( ! ok ) { mParent->setCaption( i18n("Sorry, no valid port.Syncing cancelled.") ); return; } KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, port, mActiveSyncIP, this ); connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int )), this, SLOT(deleteCommandSocket(KCommandSocket*, int)) ); mParent->setCaption( i18n("Sending request for remote file ...") ); commandSocket->readFile( syncFileName() ); } void KSyncManager::deleteCommandSocket(KCommandSocket*s, int state) { qDebug("MainWindow::deleteCommandSocket %d", state); //enum { success, errorW, errorR, quiet }; if ( state == KCommandSocket::errorR ) { mParent->setCaption( i18n("ERROR: Receiving remote file failed.") ); delete s; KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this ); connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) ); commandSocket->sendStop(); return; } else if ( state == KCommandSocket::errorW ) { mParent->setCaption( i18n("ERROR:Writing back file failed.") ); } else if ( state == KCommandSocket::successR ) { QTimer::singleShot( 1, this , SLOT ( readFileFromSocket())); } else if ( state == KCommandSocket::successW ) { mParent->setCaption( i18n("Pi-Sync succesful!") ); } delete s; } void KSyncManager::readFileFromSocket() { QString fileName = syncFileName(); mParent->setCaption( i18n("Remote file saved to temp file.") ); if ( ! syncWithFile( fileName , true ) ) { mParent->setCaption( i18n("Syncing failed.") ); qDebug("Syncing failed "); return; } KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this ); connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) ); if ( mWriteBackFile ) commandSocket->writeFile( fileName ); else { commandSocket->sendStop(); mParent->setCaption( i18n("Pi-Sync succesful!") ); } } KServerSocket:: KServerSocket ( QString pw, Q_UINT16 port, int backlog, QObject * parent, const char * name ) : QServerSocket( port, backlog, parent, name ) { mPassWord = pw; mSocket = 0; mSyncActionDialog = 0; blockRC = false; }; void KServerSocket::newConnection ( int socket ) { // qDebug("KServerSocket:New connection %d ", socket); if ( mSocket ) { qDebug("KServerSocket::newConnection Socket deleted! "); delete mSocket; mSocket = 0; } mSocket = new QSocket( this ); connect( mSocket , SIGNAL(readyRead()), this, SLOT(readClient()) ); connect( mSocket , SIGNAL(delayedCloseFinished()), this, SLOT(discardClient()) ); mSocket->setSocket( socket ); } void KServerSocket::discardClient() { //qDebug(" KServerSocket::discardClient()"); if ( mSocket ) { delete mSocket; mSocket = 0; } //emit endConnect(); } void KServerSocket::readClient() { if ( blockRC ) return; if ( mSocket == 0 ) { qDebug("ERROR::KServerSocket::readClient(): mSocket == 0 "); return; } qDebug("KServerSocket readClient()"); if ( mSocket->canReadLine() ) { QString line = mSocket->readLine(); qDebug("KServerSocket readline: %s ", line.latin1()); QStringList tokens = QStringList::split( QRegExp("[ \r\n][ \r\n]*"), line ); if ( tokens[0] == "GET" ) { if ( tokens[1] == mPassWord ) //emit sendFile( mSocket ); send_file(); else { KMessageBox::information( 0, i18n("ERROR:\nGot send file request\nwith invalid password")); qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() ); } } if ( tokens[0] == "PUT" ) { if ( tokens[1] == mPassWord ) { //emit getFile( mSocket ); blockRC = true; get_file(); } else { KMessageBox::information( 0, i18n("ERROR:\nGot receive file request\nwith invalid password")); qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() ); } } if ( tokens[0] == "STOP" ) { //emit endConnect(); end_connect(); } } } void KServerSocket::end_connect() { delete mSyncActionDialog; mSyncActionDialog = 0; } void KServerSocket::send_file() { //qDebug("MainWindow::sendFile(QSocket* s) "); if ( mSyncActionDialog ) delete mSyncActionDialog; mSyncActionDialog = new QDialog ( 0, "input-dialog", true ); mSyncActionDialog->setCaption(i18n("Received sync request")); QLabel* label = new QLabel( i18n("Synchronizing from remote ...\n\nDo not use this application!\n\nIf syncing fails\nyou can close this dialog."), mSyncActionDialog ); QVBoxLayout* lay = new QVBoxLayout( mSyncActionDialog ); lay->addWidget( label); lay->setMargin(7); lay->setSpacing(7); mSyncActionDialog->setFixedSize( 230, 120); mSyncActionDialog->show(); qDebug("KSS::saving ... "); - emit saveFile(); + emit request_file(); qApp->processEvents(); QString fileName = mFileName; QFile file( fileName ); if (!file.open( IO_ReadOnly ) ) { delete mSyncActionDialog; mSyncActionDialog = 0; qDebug("KSS::error open file "); mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( discardClient())); return ; } mSyncActionDialog->setCaption( i18n("Sending file...") ); QTextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); QTextStream os( mSocket ); os.setCodec( QTextCodec::codecForName("utf8") ); //os.setEncoding( QTextStream::UnicodeUTF8 ); while ( ! ts.atEnd() ) { os << ts.readLine() << "\n"; } //os << ts.read(); file.close(); mSyncActionDialog->setCaption( i18n("Waiting for synced file...") ); mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( discardClient())); } void KServerSocket::get_file() { mSyncActionDialog->setCaption( i18n("Receiving synced file...") ); piTime.start(); piFileString = ""; QTimer::singleShot( 1, this , SLOT (readBackFileFromSocket( ) )); } void KServerSocket::readBackFileFromSocket() { //qDebug("readBackFileFromSocket() %d ", piTime.elapsed ()); while ( mSocket->canReadLine () ) { piTime.restart(); QString line = mSocket->readLine (); piFileString += line; //qDebug("readline: %s ", line.latin1()); mSyncActionDialog->setCaption( i18n("Received %1 bytes").arg( piFileString.length() ) ); } if ( piTime.elapsed () < 3000 ) { // wait for more //qDebug("waitformore "); QTimer::singleShot( 100, this , SLOT (readBackFileFromSocket( ) )); return; } QString fileName = mFileName; QFile file ( fileName ); if (!file.open( IO_WriteOnly ) ) { delete mSyncActionDialog; mSyncActionDialog = 0; qDebug("error open cal file "); piFileString = ""; emit file_received( false ); blockRC = false; return ; } // mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1)); QTextStream ts ( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); mSyncActionDialog->setCaption( i18n("Writing file to disk...") ); ts << piFileString; mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( discardClient())); file.close(); delete mSyncActionDialog; mSyncActionDialog = 0; piFileString = ""; blockRC = false; emit file_received( true ); } KCommandSocket::KCommandSocket ( QString password, Q_UINT16 port, QString host, QObject * parent, const char * name ): QObject( parent, name ) { mPassWord = password; mSocket = 0; mPort = port; mHost = host; mRetVal = quiet; mTimerSocket = new QTimer ( this ); connect( mTimerSocket, SIGNAL ( timeout () ), this, SLOT ( deleteSocket() ) ); } void KCommandSocket::readFile( QString fn ) { if ( !mSocket ) { mSocket = new QSocket( this ); connect( mSocket, SIGNAL(readyRead()), this, SLOT(startReadFileFromSocket()) ); connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) ); } mFileString = ""; mFileName = fn; mFirst = true; mSocket->connectToHost( mHost, mPort ); QTextStream os( mSocket ); os.setEncoding( QTextStream::UnicodeUTF8 ); os << "GET " << mPassWord << "\r\n"; mTimerSocket->start( 10000 ); } void KCommandSocket::writeFile( QString fileName ) { if ( !mSocket ) { mSocket = new QSocket( this ); connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) ); connect( mSocket, SIGNAL(connected ()), this, SLOT(writeFileToSocket()) ); } mFileName = fileName ; mSocket->connectToHost( mHost, mPort ); } void KCommandSocket::writeFileToSocket() { QFile file2( mFileName ); if (!file2.open( IO_ReadOnly ) ) { mRetVal= errorW; mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( deleteSocket())); return ; } QTextStream ts2( &file2 ); ts2.setCodec( QTextCodec::codecForName("utf8") ); QTextStream os2( mSocket ); os2.setCodec( QTextCodec::codecForName("utf8") ); os2 << "PUT " << mPassWord << "\r\n";; while ( ! ts2.atEnd() ) { os2 << ts2.readLine() << "\n"; } mRetVal= successW; file2.close(); mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( deleteSocket())); } void KCommandSocket::sendStop() { if ( !mSocket ) { mSocket = new QSocket( this ); connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) ); } mSocket->connectToHost( mHost, mPort ); QTextStream os2( mSocket ); os2.setCodec( QTextCodec::codecForName("utf8") ); os2 << "STOP\r\n"; mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( deleteSocket())); } void KCommandSocket::startReadFileFromSocket() { if ( ! mFirst ) return; mFirst = false; mTimerSocket->stop(); mFileString = ""; mTime.start(); QTimer::singleShot( 1, this , SLOT (readFileFromSocket( ) )); } void KCommandSocket::readFileFromSocket() { //qDebug("readBackFileFromSocket() %d ", mTime.elapsed ()); while ( mSocket->canReadLine () ) { mTime.restart(); QString line = mSocket->readLine (); mFileString += line; //qDebug("readline: %s ", line.latin1()); } if ( mTime.elapsed () < 3000 ) { // wait for more //qDebug("waitformore "); QTimer::singleShot( 100, this , SLOT (readFileFromSocket( ) )); return; } QString fileName = mFileName; QFile file ( fileName ); if (!file.open( IO_WriteOnly ) ) { diff --git a/libkdepim/ksyncmanager.h b/libkdepim/ksyncmanager.h index 52e2772..0eb3323 100644 --- a/libkdepim/ksyncmanager.h +++ b/libkdepim/ksyncmanager.h @@ -1,228 +1,227 @@ /* This file is part of KDE-Pim/Pi. Copyright (c) 2004 Ulf Schenk 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. $Id$ */ #ifndef _KSYNCMANAGER_H #define _KSYNCMANAGER_H #include <qobject.h> #include <qstring.h> #include <qsocket.h> #include <qdatetime.h> #include <qserversocket.h> #include <qtextstream.h> #include <qregexp.h> class QPopupMenu; class KSyncProfile; class KPimPrefs; class QWidget; class KSyncManager; class KSyncInterface; class QProgressBar; class KServerSocket : public QServerSocket { Q_OBJECT public: KServerSocket ( QString password, Q_UINT16 port, int backlog = 0, QObject * parent=0, const char * name=0 ); void newConnection ( int socket ) ; void setFileName( QString fn ) {mFileName = fn;}; signals: - //void sendFile(QSocket*); - //void getFile(QSocket*); void file_received( bool ); - //void file_sent(); + void request_file(); void saveFile(); void endConnect(); private slots: void discardClient(); void readClient(); void readBackFileFromSocket(); private : bool blockRC; void send_file(); void get_file(); void end_connect(); QDialog* mSyncActionDialog; QSocket* mSocket; QString mPassWord; QString mFileName; QTime piTime; QString piFileString; }; class KCommandSocket : public QObject { Q_OBJECT public: enum state { successR, errorR, successW, errorW, quiet }; KCommandSocket ( QString password, Q_UINT16 port, QString host, QObject * parent=0, const char * name=0 ); void readFile( QString ); void writeFile( QString ); void sendStop(); signals: void commandFinished( KCommandSocket*, int ); private slots: void startReadFileFromSocket(); void readFileFromSocket(); void deleteSocket(); void writeFileToSocket(); private : QSocket* mSocket; QString mPassWord; Q_UINT16 mPort; QString mHost; QString mFileName; QTimer* mTimerSocket; int mRetVal; QTime mTime; QString mFileString; bool mFirst; }; class KSyncManager : public QObject { Q_OBJECT public: enum TargetApp { KOPI = 0, KAPI = 1, PWMPI = 2 }; KSyncManager(QWidget* parent, KSyncInterface* implementation, TargetApp ta, KPimPrefs* prefs, QPopupMenu* syncmenu); ~KSyncManager() ; bool blockSave() { return mBlockSaveFlag; } void setBlockSave(bool sa) { mBlockSaveFlag = sa; } void setDefaultFileName( QString s) { mDefFileName = s ;} QString defaultFileName() { return mDefFileName ;} QString syncFileName(); void fillSyncMenu(); QString getCurrentSyncDevice() { return mCurrentSyncDevice; } QString getCurrentSyncName() { return mCurrentSyncName; } void showProgressBar(int percentage, QString caption = QString::null, int total=100); void hideProgressBar(); bool isProgressBarCanceled(); // sync stuff QString mLocalMachineName; QStringList mExternSyncProfiles; QStringList mSyncProfileNames; bool mAskForPreferences; bool mShowSyncSummary; bool mShowSyncEvents; bool mShowTodoInAgenda; bool mWriteBackExistingOnly; int mSyncAlgoPrefs; int mRingSyncAlgoPrefs; bool mWriteBackFile; int mWriteBackInFuture; QString mPhoneDevice; QString mPhoneConnection; QString mPhoneModel; QString mLastSyncedLocalFile; // save! QString mPassWordPiSync; QString mActiveSyncPort; QString mActiveSyncIP ; signals: void save(); + void request_file(); void getFile( bool ); public slots: void slotSyncMenu( int ); private: // LR ******************************* // sync stuff! void syncPi(); void deleteCommandSocket(KCommandSocket*s, int state); void readFileFromSocket(); KServerSocket * mServerSocket; void enableQuick(); KPimPrefs* mPrefs; QString mDefFileName; QString mCurrentSyncDevice; QString mCurrentSyncName; void quickSyncLocalFile(); bool syncWithFile( QString fn , bool quick ); void syncLocalFile(); void syncPhone(); void syncSharp(); bool syncExternalApplication(QString); void multiSync( bool askforPrefs ); int mCurrentSyncProfile ; void syncRemote( KSyncProfile* prof, bool ask = true); void edit_sync_options(); int ringSync(); QString getPassword( ); private slots: void confSync(); // ********************* private: bool mBlockSaveFlag; QWidget* mParent; KSyncInterface* mImplementation; TargetApp mTargetApp; QPopupMenu* mSyncMenu; QProgressBar* bar; }; class KSyncInterface { public : virtual bool sync(KSyncManager* manager, QString filename, int mode) = 0; virtual bool syncExternal(KSyncManager* manager, QString resource) { // empty implementation, because some syncable applications do not have an external(sharpdtm) syncmode, like pwmanager. return false; } }; #endif |