summaryrefslogtreecommitdiffabout
authorzautrix <zautrix>2006-02-24 18:49:56 (UTC)
committer zautrix <zautrix>2006-02-24 18:49:56 (UTC)
commitd7738fdfc685192eb2f8317db6ffad3c246001c8 (patch) (side-by-side diff)
treed9aae6ca97851fd1b53c4d9e74740a5ee2b69ea9
parent987757f168bbae56100f2aff763b865e81ceec18 (diff)
downloadkdepimpi-d7738fdfc685192eb2f8317db6ffad3c246001c8.zip
kdepimpi-d7738fdfc685192eb2f8317db6ffad3c246001c8.tar.gz
kdepimpi-d7738fdfc685192eb2f8317db6ffad3c246001c8.tar.bz2
kapi sync
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--kabc/addressbook.cpp22
-rw-r--r--kabc/addressbook.h1
-rw-r--r--kabc/addressee.cpp75
-rw-r--r--kabc/addressee.h4
-rw-r--r--kabc/phonenumber.cpp24
-rw-r--r--kaddressbook/kabcore.cpp130
-rw-r--r--kaddressbook/kabcore.h5
-rw-r--r--kaddressbook/kaimportoldialog.cpp712
-rw-r--r--kaddressbook/kaimportoldialog.h63
-rw-r--r--kaddressbook/phoneeditwidget.cpp11
-rw-r--r--korganizer/journalentry.h1
-rw-r--r--korganizer/kojournalview.cpp9
-rw-r--r--libkdepim/externalapphandler.cpp2
-rw-r--r--libkdepim/ksyncmanager.cpp71
-rw-r--r--libkdepim/ksyncmanager.h3
-rw-r--r--libkdepim/libkdepim.pro15
16 files changed, 337 insertions, 811 deletions
diff --git a/kabc/addressbook.cpp b/kabc/addressbook.cpp
index f9e4387..fe59fcb 100644
--- a/kabc/addressbook.cpp
+++ b/kabc/addressbook.cpp
@@ -1,1296 +1,1314 @@
/*
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 <qregexp.h>
#include <kglobal.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <libkcal/syncdefines.h>
#include <libkdepim/phoneaccess.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 );
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() ) {
qDebug( i18n("Unable to load resource '%1'").arg( (*it)->resourceName() ) );
ok = false;
} else {
qDebug( i18n("Resource loaded: '%1'").arg( (*it)->resourceName() ) );
}
// 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;
}
// exports all Addressees, which are syncable
void AddressBook::export2File( QString fileName, QString resourceName )
{
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).resource() ) {
bool include = (*it).resource()->includeInSync();
if ( !resourceName.isEmpty() )
include = (resourceName == (*it).resource()->resourceName() );
if ( include ) {
//qDebug(QString ("Exporting resource %1 to file %2").arg( (*it).resource()->resourceName() ).arg( fileName ) );
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";
}
}
}
t << "\r\n\r\n";
outFile.close();
}
// if QStringList uids is empty, all are exported
bool AddressBook::export2PhoneFormat( QStringList uids ,QString fileName )
{
KABC::VCardConverter converter;
QString datastream;
Iterator it;
bool all = uids.isEmpty();
for ( it = begin(); it != end(); ++it ) {
// for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) {
if ( ! all ) {
if ( ! ( uids.contains((*it).uid() ) ))
continue;
}
KABC::Addressee a = ( *it );
if ( a.isEmpty() )
continue;
if ( all && a.resource() && !a.resource()->includeInSync() )
continue;
a.simplifyEmails();
a.simplifyPhoneNumbers();
a.simplifyPhoneNumberTypes();
a.simplifyAddresses();
QString vcard;
QString vcardnew;
converter.addresseeToVCard( a, vcard );
int start = 0;
int next;
while ( (next = vcard.find("TYPE=", start) )>= 0 ) {
int semi = vcard.find(";", next);
int dopp = vcard.find(":", next);
int sep;
if ( semi < dopp && semi >= 0 )
sep = semi ;
else
sep = dopp;
vcardnew +=vcard.mid( start, next - start);
vcardnew +=vcard.mid( next+5,sep -next -5 ).upper();
start = sep;
}
vcardnew += vcard.mid( start,vcard.length() );
vcard = "";
start = 0;
while ( (next = vcardnew.find("ADR", start) )>= 0 ) {
int sep = vcardnew.find(":", next);
vcard +=vcardnew.mid( start, next - start+3);
start = sep;
}
vcard += vcardnew.mid( start,vcardnew.length() );
vcard.replace ( QRegExp(";;;") , "" );
vcard.replace ( QRegExp(";;") , "" );
datastream += vcard;
}
QFile outFile(fileName);
if ( outFile.open(IO_WriteOnly) ) {
datastream.replace ( QRegExp("VERSION:3.0") , "VERSION:2.1" );
QTextStream t( &outFile ); // use a text stream
t.setEncoding( QTextStream::UnicodeUTF8 );
t <<datastream;
t << "\r\n\r\n";
outFile.close();
} else {
qDebug("Error open temp file ");
return false;
}
return true;
}
int AddressBook::importFromFile( QString fileName, bool replaceLabel, bool removeOld, QString resource )
{
if ( removeOld )
setUntagged( true, resource );
KABC::Addressee::List list;
QFile file( fileName );
file.open( IO_ReadOnly );
QByteArray rawData = file.readAll();
file.close();
QString data;
if ( replaceLabel ) {
data = QString::fromLatin1( rawData.data(), rawData.size() + 1 );
data.replace ( QRegExp("LABEL") , "ADR" );
data.replace ( QRegExp("CHARSET=ISO-8859-1") , "" );
} else
data = QString::fromUtf8( rawData.data(), rawData.size() + 1 );
KABC::VCardTool tool;
list = tool.parseVCards( data );
KABC::Addressee::List::Iterator it;
Resource * setRes = 0;
if ( !resource.isEmpty() ) {
KRES::Manager<Resource>::ActiveIterator it;
KRES::Manager<Resource> *manager = d->mManager;
for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) {
//qDebug("SaveAB::checking resource..." );
if ( (*it)->resourceName() == resource ) {
setRes = (*it);
qDebug("KA: AB: Inserting imported contacs to resource %s", resource.latin1());
break;
}
}
}
for ( it = list.begin(); it != list.end(); ++it ) {
QString id = (*it).custom( "KADDRESSBOOK", "X-ExternalID" );
if ( !id.isEmpty() )
(*it).setIDStr(id );
(*it).setResource( setRes );
if ( replaceLabel )
(*it).removeVoice();
if ( removeOld )
(*it).setTagged( true );
insertAddressee( (*it), false, true );
}
if ( removeOld )
removeUntagged();
return list.count();
}
void AddressBook::setUntagged(bool setNonSyncTagged, QString resource) // = false , "")
{
Iterator ait;
if ( !resource.isEmpty() ) {
for ( ait = begin(); ait != end(); ++ait ) {
if ( (*ait).resource() && (*ait).resource()->resourceName() == resource ) {
(*ait).setTagged( false );
}
else
(*ait).setTagged( true );
}
} else {
for ( ait = begin(); ait != end(); ++ait ) {
if ( setNonSyncTagged ) {
if ( (*ait).resource() && ! (*ait).resource()->includeInSync() ) {
(*ait).setTagged( true );
} else
(*ait).setTagged( false );
} else
(*ait).setTagged( false );
}
}
}
void AddressBook::removeUntagged()
{
Iterator ait;
bool todelete = false;
Iterator todel;
for ( ait = begin(); ait != end(); ++ait ) {
if ( todelete )
removeAddressee( todel );
if (!(*ait).tagged()) {
todelete = true;
todel = ait;
} else
todelete = false;
}
if ( todelete )
removeAddressee( todel );
deleteRemovedAddressees();
}
void AddressBook::smplifyAddressees()
{
Iterator ait;
for ( ait = begin(); ait != end(); ++ait ) {
(*ait).simplifyEmails();
(*ait).simplifyPhoneNumbers();
(*ait).simplifyPhoneNumberTypes();
(*ait).simplifyAddresses();
}
}
void AddressBook::removeSyncInfo( QString syncProfile)
{
Iterator ait;
for ( ait = begin(); ait != end(); ++ait ) {
(*ait).removeID( syncProfile );
}
if ( syncProfile.isEmpty() ) {
Iterator it = begin();
Iterator it2 ;
while ( it != end() ) {
if ( (*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;
}
}
} else {
Addressee lse;
lse = findByUid( "last-syncAddressee-"+ syncProfile );
if ( ! lse.isEmpty() )
removeAddressee( lse );
}
}
void AddressBook::preparePhoneSync( QString currentSyncDevice, bool isPreSync )
{
Iterator ait;
for ( ait = begin(); ait != end(); ++ait ) {
QString id = (*ait).IDStr();
(*ait).setIDStr( ":");
(*ait).setExternalUID( id );
(*ait).setOriginalExternalUID( id );
if ( isPreSync )
(*ait).setTempSyncStat( SYNC_TEMPSTATE_NEW_EXTERNAL );
else {
(*ait).setTempSyncStat( SYNC_TEMPSTATE_NEW_ID );
(*ait).setID( currentSyncDevice,id );
}
}
}
void AddressBook::findNewExtIds( QString fileName, QString currentSyncDevice )
{
setUntagged();
KABC::Addressee::List list;
QFile file( fileName );
file.open( IO_ReadOnly );
QByteArray rawData = file.readAll();
file.close();
QString data;
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 ) {
Iterator ait;
for ( ait = begin(); ait != end(); ++ait ) {
if ( !(*ait).tagged() ) {
if ( (*ait).containsAdr(*it)) {
(*ait).setTagged(true);
QString id = (*it).custom( "KADDRESSBOOK", "X-ExternalID" );
(*it).setIDStr( ":");
(*it).setID( currentSyncDevice,id );
(*it).setExternalUID( id );
(*it).setTempSyncStat( SYNC_TEMPSTATE_NEW_ID );
(*it).setUid( ( (*ait).uid() ));
break;
}
}
}
if ( ait == end() )
qDebug("ERROR:: no ext ID found for uid: %s", (*it).uid().latin1());
}
clear();
for ( it = list.begin(); it != list.end(); ++it ) {
insertAddressee( (*it) );
}
}
bool AddressBook::saveABphone( QString fileName )
{
//smplifyAddressees();
qDebug("saveABphone:: saving AB... ");
if ( ! export2PhoneFormat( QStringList() ,fileName ) )
return false;
qDebug("saveABphone:: writing to phone... ");
if ( !PhoneAccess::writeToPhone( fileName) ) {
return false;
}
qDebug("saveABphone:: re-reading from phone... ");
if ( !PhoneAccess::readFromPhone( fileName) ) {
return false;
}
return 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;
qDebug("SaveAB::saving..." );
for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) {
qDebug("SaveAB::checking resource..." );
if ( (*it)->readOnly() )
qDebug("SaveAB::resource is readonly." );
if ( (*it)->isOpen() )
qDebug("SaveAB::resource is open" );
if ( !(*it)->readOnly() && (*it)->isOpen() ) {
Ticket *ticket = requestSaveTicket( *it );
qDebug("SaveAB::StdAddressBook::save '%s'", (*it)->resourceName().latin1() );
if ( !ticket ) {
qDebug( i18n( "SaveAB::Unable to save to resource '%1'. It is locked." )
.arg( (*it)->resourceName() ) );
return false;
}
//if ( !save( ticket ) )
if ( ticket->resource() ) {
QString name = ticket->resource()->resourceName();
if ( ! ticket->resource()->save( ticket ) )
ok = false;
else
qDebug("SaveAB::resource saved '%s'", name.latin1() );
} 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 insertAddressee( const Addressee &, bool setRev = true, bool takeResource = false);
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;
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 ) {
(*it).setRevision( QDateTime::currentDateTime() );
}
(*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( 2003,1,1) );
while ( it != end() ) {
(*it).setRevision( dt );
if (( *it).IDStr() != "changed" ) {
// "changed" is used for tagging changed addressees when syncing with KDE or OL
(*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() );
if ( removeDeleted ) {
// we have no postprocessing in the resource, we have to do it here
// we have to compute csum for all, because it could be the first sync
(*it).setTempSyncStat( SYNC_TEMPSTATE_NEW_ID );
}
++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 , bool isSubset )
{
//qDebug("AddressBook::preExternSync ");
AddressBook::Iterator it;
for ( it = begin(); it != end(); ++it ) {
(*it).setID( csd, (*it).externalUID() );
(*it).computeCsum( csd );
}
mergeAB( aBook ,csd, isSubset );
}
+void AddressBook::preOLSync( 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 );
+ }
+
+ Addressee ad;
+ for ( it = begin(); it != end(); ++it ) {
+ ad = aBook->findByExternUid( (*it).externalUID(), csd );
+ if ( !ad.isEmpty() ) {
+ (*it).mergeOLContact( ad );
+ }
+ }
+}
void AddressBook::postExternSync( AddressBook* aBook , const QString& csd, bool setID)
{
//qDebug("AddressBook::postExternSync ");
AddressBook::Iterator it;
int foundEmpty = 0;
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 ||
(*it).tempSyncStat() == SYNC_TEMPSTATE_ADDED_EXTERNAL) {
Addressee ad = aBook->findByUid( ( (*it).uid() ));
if ( ad.isEmpty() ) {
++foundEmpty;
//qDebug("postExternSync:addressee is empty: %s ", (*it).uid().latin1());
//qDebug("-- formatted name %s ",(*it).formattedName().latin1() );
} else {
(*it).setIDStr(":");
if ( setID ) {
- if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_ID )
- ad.setID( csd, (*it).externalUID() );
+ if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_ID )
+ ad.setID( csd, (*it).externalUID() );{
+ }
} else
ad.setID( csd, (*it).uid() );
(*it).computeCsum( csd );
ad.setCsum( csd, (*it).getCsum( csd ) );
//qDebug("CSUM %s ",(*it).getCsum( csd ).latin1() );
aBook->insertAddressee( ad , false);
}
}
}
if ( foundEmpty ) {
qDebug("postExternSync:%d empty addressees found:\n probably filtered out by incoming sync filter.",foundEmpty );
}
}
bool AddressBook::containsExternalUid( const QString& uid )
{
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( uid == (*it).externalUID( ) )
return true;
}
return false;
}
const Addressee AddressBook::findByExternUid( const QString& uid , const QString& profile ) const
{
ConstIterator it;
for ( it = begin(); it != end(); ++it ) {
if ( uid == (*it).getID( profile ) )
return (*it);
}
return Addressee();
}
void AddressBook::mergeAB( AddressBook *aBook, const QString& profile , bool isSubset )
{
Iterator it;
Addressee ad;
for ( it = begin(); it != end(); ++it ) {
ad = aBook->findByExternUid( (*it).externalUID(), profile );
if ( !ad.isEmpty() ) {
(*it).mergeContact( ad ,isSubset);
}
}
#if 0
// test only
for ( it = begin(); it != end(); ++it ) {
qDebug("uid %s ", (*it).uid().latin1());
}
#endif
}
#if 0
Addressee::List AddressBook::getExternLastSyncAddressees()
{
Addressee::List results;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( (*it).uid().left( 19 ) == "last-syncAddressee-" ) {
if ( (*it).familyName().left(4) == "!E: " )
results.append( *it );
}
}
return results;
}
#endif
void AddressBook::resetTempSyncStat()
{
Iterator it;
for ( it = begin(); it != end(); ++it ) {
(*it).setTempSyncStat ( SYNC_TEMPSTATE_INITIAL );
}
}
QStringList AddressBook:: uidList()
{
QStringList results;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
results.append( (*it).uid() );
}
return results;
}
Addressee::List AddressBook::allAddressees()
{
return d->mAddressees;
}
Addressee::List AddressBook::findByName( const QString &name )
{
Addressee::List results;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( name == (*it).realName() ) {
results.append( *it );
}
}
return results;
}
Addressee::List AddressBook::findByEmail( const QString &email )
{
Addressee::List results;
QStringList mailList;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
mailList = (*it).emails();
for ( QStringList::Iterator ite = mailList.begin(); ite != mailList.end(); ++ite ) {
if ( email == (*ite) ) {
results.append( *it );
}
}
}
return results;
}
Addressee::List AddressBook::findByCategory( const QString &category )
{
Addressee::List results;
Iterator it;
for ( it = begin(); it != end(); ++it ) {
if ( (*it).hasCategory( category) ) {
results.append( *it );
}
}
return results;
}
void AddressBook::dump() const
{
kdDebug(5700) << "AddressBook::dump() --- begin ---" << endl;
ConstIterator it;
for( it = begin(); it != end(); ++it ) {
(*it).dump();
}
kdDebug(5700) << "AddressBook::dump() --- end ---" << endl;
}
QString AddressBook::identifier()
{
QStringList identifier;
KRES::Manager<Resource>::ActiveIterator it;
for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) {
if ( !(*it)->identifier().isEmpty() )
identifier.append( (*it)->identifier() );
}
return identifier.join( ":" );
}
Field::List AddressBook::fields( int category )
{
if ( d->mAllFields.isEmpty() ) {
d->mAllFields = Field::allFields();
}
if ( category == Field::All ) return d->mAllFields;
Field::List result;
Field::List::ConstIterator it;
for( it = d->mAllFields.begin(); it != d->mAllFields.end(); ++it ) {
if ( (*it)->category() & category ) result.append( *it );
}
return result;
}
bool AddressBook::addCustomField( const QString &label, int category,
const QString &key, const QString &app )
{
if ( d->mAllFields.isEmpty() ) {
d->mAllFields = Field::allFields();
}
//US QString a = app.isNull() ? KGlobal::instance()->instanceName() : app;
QString a = app.isNull() ? KGlobal::getAppName() : app;
QString k = key.isNull() ? label : key;
Field *field = Field::createCustomField( label, category, k, a );
if ( !field ) return false;
d->mAllFields.append( field );
return true;
}
QDataStream &KABC::operator<<( QDataStream &s, const AddressBook &ab )
{
if (!ab.d) return s;
return s << ab.d->mAddressees;
}
QDataStream &KABC::operator>>( QDataStream &s, AddressBook &ab )
{
if (!ab.d) return s;
s >> ab.d->mAddressees;
return s;
}
bool AddressBook::addResource( Resource *resource )
{
if ( !resource->open() ) {
kdDebug(5700) << "AddressBook::addResource(): can't add resource" << endl;
return false;
}
resource->setAddressBook( this );
d->mManager->add( resource );
return true;
}
void AddressBook::removeResources()
{
//remove all possible resources. This should cleanup the configfile.
QPtrList<KABC::Resource> mResources = resources();
QPtrListIterator<KABC::Resource> it(mResources);
for ( ; it.current(); ++it ) {
KABC::Resource *res = it.current();
removeResource(res);
}
}
bool AddressBook::removeResource( Resource *resource )
{
resource->close();
if ( resource == standardResource() )
d->mManager->setStandardResource( 0 );
resource->setAddressBook( 0 );
d->mManager->remove( resource );
return true;
}
QPtrList<Resource> AddressBook::resources()
{
QPtrList<Resource> list;
// qDebug("AddressBook::resources() 1");
KRES::Manager<Resource>::ActiveIterator it;
for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it )
list.append( *it );
return list;
}
/*US
void AddressBook::setErrorHandler( ErrorHandler *handler )
{
delete d->mErrorHandler;
d->mErrorHandler = handler;
}
*/
void AddressBook::error( const QString& msg )
{
/*US
if ( !d->mErrorHandler ) // create default error handler
d->mErrorHandler = new ConsoleErrorHandler;
if ( d->mErrorHandler )
d->mErrorHandler->error( msg );
else
kdError(5700) << "no error handler defined" << endl;
*/
kdDebug(5700) << "msg" << endl;
qDebug(msg);
}
void AddressBook::deleteRemovedAddressees()
{
Addressee::List::Iterator it;
for ( it = d->mRemovedAddressees.begin(); it != d->mRemovedAddressees.end(); ++it ) {
Resource *resource = (*it).resource();
if ( resource && !resource->readOnly() && resource->isOpen() )
resource->removeAddressee( *it );
}
d->mRemovedAddressees.clear();
}
void AddressBook::setStandardResource( Resource *resource )
{
// qDebug("AddressBook::setStandardResource 1");
d->mManager->setStandardResource( resource );
}
Resource *AddressBook::standardResource()
{
return d->mManager->standardResource();
}
KRES::Manager<Resource> *AddressBook::resourceManager()
{
return d->mManager;
}
void AddressBook::cleanUp()
{
KRES::Manager<Resource>::ActiveIterator it;
for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) {
if ( !(*it)->readOnly() && (*it)->isOpen() )
(*it)->cleanUp();
}
}
diff --git a/kabc/addressbook.h b/kabc/addressbook.h
index e6daa5e..a8a9fc1 100644
--- a/kabc/addressbook.h
+++ b/kabc/addressbook.h
@@ -1,350 +1,351 @@
/*
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( );
bool saveABphone( QString fileName );
void smplifyAddressees();
void removeSyncInfo( QString syncProfile);
void preparePhoneSync( QString currentSyncDevice, bool isPreSync );
void export2File( QString fileName, QString resourceName = "" );
bool export2PhoneFormat( QStringList uids ,QString fileName );
int importFromFile( QString fileName, bool replaceLabel = false, bool removeOld = false, QString resource = "" );
void setUntagged( bool setNonSyncTagged = false, QString resource = "" );
void removeUntagged();
void findNewExtIds( QString fileName, QString currentSyncDevice );
/**
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, 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.
*/
void removeResources();
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, bool isSubset );
const Addressee findByExternUid( const QString& uid , const QString& profile ) const;
bool containsExternalUid( const QString& uid );
void preExternSync( AddressBook* aBook, const QString& csd, bool isSubset );
+ void preOLSync( AddressBook* aBook, const QString& csd);
void postExternSync( AddressBook* aBook, const QString& csd , bool setID );
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/kabc/addressee.cpp b/kabc/addressee.cpp
index 6cfac80..e8e440c 100644
--- a/kabc/addressee.cpp
+++ b/kabc/addressee.cpp
@@ -1,2286 +1,2355 @@
/*** Warning! This file has been generated by the script makeaddressee ***/
/*
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$
*/
#include <kconfig.h>
#include <ksharedptr.h>
#include <kdebug.h>
#include <kapplication.h>
#include <klocale.h>
+#include <kmessagebox.h>
#include <kidmanager.h>
//US
#include <kstandarddirs.h>
#include <libkcal/syncdefines.h>
//US #include "resource.h"
#include "addressee.h"
using namespace KABC;
static bool matchBinaryPattern( int value, int pattern );
static bool matchBinaryPatternA( int value, int pattern );
static bool matchBinaryPatternP( int value, int pattern );
struct Addressee::AddresseeData : public KShared
{
QString uid;
QString name;
QString formattedName;
QString familyName;
QString givenName;
QString additionalName;
QString prefix;
QString suffix;
QString nickName;
QDateTime birthday;
QString mailer;
TimeZone timeZone;
Geo geo;
QString title;
QString role;
QString organization;
QString note;
QString productId;
QDateTime revision;
QString sortString;
QString externalUID;
QString originalExternalUID;
KURL url;
Secrecy secrecy;
Picture logo;
Picture photo;
Sound sound;
Agent agent;
QString mExternalId;
PhoneNumber::List phoneNumbers;
Address::List addresses;
Key::List keys;
QStringList emails;
QStringList categories;
QStringList custom;
int mTempSyncStat;
Resource *resource;
bool empty :1;
bool changed :1;
bool tagged :1;
};
Addressee::Addressee()
{
mData = new AddresseeData;
mData->empty = true;
mData->changed = false;
mData->resource = 0;
mData->mExternalId = ":";
mData->revision = QDateTime ( QDate( 2003,1,1));
mData->mTempSyncStat = SYNC_TEMPSTATE_INITIAL;
}
Addressee::~Addressee()
{
}
Addressee::Addressee( const Addressee &a )
{
mData = a.mData;
}
Addressee &Addressee::operator=( const Addressee &a )
{
mData = a.mData;
return (*this);
}
Addressee Addressee::copy()
{
Addressee a;
*(a.mData) = *mData;
return a;
}
void Addressee::detach()
{
if ( mData.count() == 1 ) return;
*this = copy();
}
bool Addressee::operator==( const Addressee &a ) const
{
if ( uid() != a.uid() ) return false;
if ( mData->name != a.mData->name ) return false;
if ( mData->formattedName != a.mData->formattedName ) return false;
if ( mData->familyName != a.mData->familyName ) return false;
if ( mData->givenName != a.mData->givenName ) return false;
if ( mData->additionalName != a.mData->additionalName ) return false;
if ( mData->prefix != a.mData->prefix ) return false;
if ( mData->suffix != a.mData->suffix ) return false;
if ( mData->nickName != a.mData->nickName ) return false;
if ( mData->birthday != a.mData->birthday ) return false;
if ( mData->mailer != a.mData->mailer ) return false;
if ( mData->timeZone != a.mData->timeZone ) return false;
if ( mData->geo != a.mData->geo ) return false;
if ( mData->title != a.mData->title ) return false;
if ( mData->role != a.mData->role ) return false;
if ( mData->organization != a.mData->organization ) return false;
if ( mData->note != a.mData->note ) return false;
if ( mData->productId != a.mData->productId ) return false;
//if ( mData->revision != a.mData->revision ) return false;
if ( mData->sortString != a.mData->sortString ) return false;
if ( mData->secrecy != a.mData->secrecy ) return false;
if ( mData->logo != a.mData->logo ) return false;
if ( mData->photo != a.mData->photo ) return false;
if ( mData->sound != a.mData->sound ) return false;
if ( mData->agent != a.mData->agent ) return false;
if ( ( mData->url.isValid() || a.mData->url.isValid() ) &&
( mData->url != a.mData->url ) ) return false;
if ( mData->phoneNumbers != a.mData->phoneNumbers ) return false;
if ( mData->addresses != a.mData->addresses ) return false;
if ( mData->keys != a.mData->keys ) return false;
if ( mData->emails != a.mData->emails ) return false;
if ( mData->categories != a.mData->categories ) return false;
if ( mData->custom != a.mData->custom ) return false;
return true;
}
bool Addressee::operator!=( const Addressee &a ) const
{
return !( a == *this );
}
bool Addressee::isEmpty() const
{
return mData->empty;
}
ulong Addressee::getCsum4List( const QStringList & attList)
{
int max = attList.count();
ulong cSum = 0;
int j,k,i;
int add;
for ( i = 0; i < max ; ++i ) {
QString s = attList[i];
if ( ! s.isEmpty() ){
j = s.length();
for ( k = 0; k < j; ++k ) {
int mul = k +1;
add = s[k].unicode ();
if ( k < 16 )
mul = mul * mul;
int ii = i+1;
add = add * mul *ii*ii*ii;
cSum += add;
//qDebug("csum: %d %d %d", i,k,cSum);
}
}
}
//QString dump = attList.join(",");
//qDebug("csum: %d %s", cSum,dump.latin1());
return cSum;
}
void Addressee::computeCsum(const QString &dev)
{
QStringList l;
//if ( !mData->name.isEmpty() ) l.append(mData->name);
- //if ( !mData->formattedName.isEmpty() ) l.append(mData->formattedName );
+ if ( !mData->formattedName.isEmpty() ) l.append(mData->formattedName );
if ( !mData->familyName.isEmpty() ) l.append( mData->familyName );
if ( !mData->givenName.isEmpty() ) l.append(mData->givenName );
if ( !mData->additionalName.isEmpty() ) l.append( mData->additionalName );
if ( !mData->prefix.isEmpty() ) l.append( mData->prefix );
if ( !mData->suffix.isEmpty() ) l.append( mData->suffix );
if ( !mData->nickName.isEmpty() ) l.append( mData->nickName );
if ( mData->birthday.isValid() ) l.append( mData->birthday.toString() );
if ( !mData->mailer.isEmpty() ) l.append( mData->mailer );
if ( mData->timeZone.isValid() ) l.append( mData->timeZone.asString() );
if ( mData->geo.isValid() ) l.append( mData->geo.asString() );
if ( !mData->title .isEmpty() ) l.append( mData->title );
if ( !mData->role.isEmpty() ) l.append( mData->role );
if ( !mData->organization.isEmpty() ) l.append( mData->organization );
if ( !mData->note.isEmpty() ) l.append( mData->note );
if ( !mData->productId.isEmpty() ) l.append(mData->productId );
if ( !mData->sortString.isEmpty() ) l.append( mData->sortString );
if ( mData->secrecy.isValid() ) l.append( mData->secrecy.asString());
if ( !mData->logo.undefined() ) {
if ( !mData->logo.isIntern() )
l.append( mData->logo.url() );
else
l.append( QString::number(mData->logo.data().width()* mData->logo.data().height()));
} else {
l.append( "nologo");
}
if ( !mData->photo.undefined() ) {
if ( !mData->photo.isIntern() )
l.append( mData->photo.url() );
else
l.append( QString::number(mData->photo.data().width()* mData->photo.data().height()));
} else {
l.append( "nophoto");
}
#if 0
if ( !mData->sound.undefined() ) {
if ( !mData->sound.isIntern() )
l.append( mData->sound.url() );
else
l.append( QString(mData->sound.data().with()* mData->sound.data().height()));
} else {
l.append( "nosound");
}
#endif
//if ( !mData->agent.isEmpty() ) l.append( );
if ( mData->url.isValid() )
if ( ! mData->url.path().isEmpty()) l.append( mData->url.path() );
KABC::PhoneNumber::List phoneNumbers;
KABC::PhoneNumber::List::Iterator phoneIter;
QStringList t;
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter )
t.append( ( *phoneIter ).number()+QString::number( ( *phoneIter ).type() ) );
t.sort();
uint iii;
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
t = mData->emails;
t.sort();
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
t = mData->categories;
t.sort();
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
t = mData->custom;
t.sort();
for ( iii = 0; iii < t.count(); ++iii)
if ( t[iii].left( 25 ) != "KADDRESSBOOK-X-ExternalID" ) {
int find = t[iii].find (':')+1;
//qDebug("lennnn %d %d ", find, t[iii].length());
if ( find < t[iii].length())
l.append( t[iii] );
}
KABC::Address::List::Iterator addressIter;
for ( addressIter = mData->addresses.begin(); addressIter != mData->addresses.end();
++addressIter ) {
t = (*addressIter).asList();
t.sort();
for ( iii = 0; iii < t.count(); ++iii)
l.append( t[iii] );
}
uint cs = getCsum4List(l);
#if 0
for ( iii = 0; iii < l.count(); ++iii)
qDebug("%d***%s***",iii,l[iii].latin1());
qDebug("CSUM computed %d %s %s", cs,QString::number (cs ).latin1(), uid().latin1() );
#endif
setCsum( dev, QString::number (cs ));
}
bool Addressee::matchAddress( QRegExp* re ) const
{
KABC::Address::List::Iterator addressIter;
for ( addressIter = mData->addresses.begin(); addressIter != mData->addresses.end();
++addressIter ) {
if ( (*addressIter).matchAddress( re ) )
return true;
}
return false;
}
bool Addressee::matchPhoneNumber( QRegExp* re ) const
{
KABC::PhoneNumber::List::Iterator phoneIter;
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end(); ++phoneIter ) {
#if QT_VERSION >= 0x030000
if (re->search( (*phoneIter).number() ) == 0)
#else
if (re->match( (*phoneIter).number() ) == 0)
#endif
return true;
}
return false;
}
+void Addressee::mergeOLContact( const Addressee& ad )
+{
+ if ( mData->formattedName.isEmpty() ) mData->formattedName = ad.mData->formattedName;
+ if ( mData->mailer.isEmpty() ) mData->mailer = ad.mData->mailer;
+ if ( !mData->timeZone.isValid() ) mData->timeZone = ad.mData->timeZone;
+ if ( !mData->geo.isValid() ) mData->geo = ad.mData->geo;
+ if ( mData->logo.undefined() && !ad.mData->logo.undefined() ) mData->logo = ad.mData->logo;
+ if ( mData->photo.undefined() && !ad.mData->photo.undefined() ) mData->photo = ad.mData->photo;
+ if ( !mData->sound.isIntern() ) {
+ if ( mData->sound.url().isEmpty() ) {
+ mData->sound = ad.mData->sound;
+ }
+ }
+ if ( !mData->agent.isIntern() ) {
+ if ( mData->agent.url().isEmpty() ) {
+ mData->agent = ad.mData->agent;
+ }
+ }
+ {
+ Key::List::Iterator itA;
+ for( itA = ad.mData->keys.begin(); itA != ad.mData->keys.end(); ++itA ) {
+ bool found = false;
+ Key::List::Iterator it;
+ for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
+ if ( (*it) == (*itA)) {
+ found = true;
+ break;
+
+ }
+ }
+ if ( ! found ) {
+ mData->keys.append( *itA );
+ }
+ }
+ }
+
+ KABC::Address addthis = otherAddress();
+ KABC::Address addother = ad.otherAddress();
+ if ( !addthis.isEmpty() && !addother.isEmpty() )
+ addthis.setType( addother.type() );
+ //qDebug("merge contact %s ", ad.uid().latin1());
+ setUid( ad.uid() );
+ setRevision( ad.revision() );
+
+
+}
+
void Addressee::mergeContact( const Addressee& ad , bool isSubSet) // = false)
{
// merge all standard non-outlook fields.
//if isSubSet (e.g. mobile phone sync) merge all fields
detach();
if ( isSubSet ) {
if ( mData->name.isEmpty() ) mData->name = ad.mData->name;
if ( mData->formattedName.isEmpty() ) mData->formattedName = ad.mData->formattedName;
if ( mData->familyName.isEmpty() ) mData->familyName = ad.mData->familyName;
if ( mData->givenName.isEmpty() ) mData->givenName = ad.mData->givenName ;
if ( mData->additionalName ) mData->additionalName = ad.mData->additionalName;
if ( mData->prefix.isEmpty() ) mData->prefix = ad.mData->prefix;
if ( mData->suffix.isEmpty() ) mData->suffix = ad.mData->suffix;
if ( mData->title .isEmpty() ) mData->title = ad.mData->title ;
if ( mData->role.isEmpty() ) mData->role = ad.mData->role ;
if ( mData->nickName.isEmpty() ) mData->nickName = ad.mData->nickName;
if ( mData->organization.isEmpty() ) mData->organization = ad.mData->organization ;
if ( mData->note.isEmpty() ) mData->note = ad.mData->note ;
if ( !mData->secrecy.isValid() ) mData->secrecy = ad.mData->secrecy;
if ( ( !mData->url.isValid() && ad.mData->url.isValid() ) ) mData->url = ad.mData->url ;
if ( !mData->birthday.isValid() )
if ( ad.mData->birthday.isValid())
mData->birthday = ad.mData->birthday;
}
if ( mData->mailer.isEmpty() ) mData->mailer = ad.mData->mailer;
if ( !mData->timeZone.isValid() ) mData->timeZone = ad.mData->timeZone;
if ( !mData->geo.isValid() ) mData->geo = ad.mData->geo;
if ( mData->productId.isEmpty() ) mData->productId = ad.mData->productId;
if ( mData->sortString.isEmpty() ) mData->sortString = ad.mData->sortString;
QStringList t;
QStringList tAD;
uint iii;
// ********** phone numbers
if ( isSubSet ) {
PhoneNumber::List phoneAD = ad.phoneNumbers();
PhoneNumber::List::Iterator phoneItAD;
for ( phoneItAD = phoneAD.begin(); phoneItAD != phoneAD.end(); ++phoneItAD ) {
bool found = false;
PhoneNumber::List::Iterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( ( *phoneItAD ).contains( (*it) ) ) {
found = true;
(*it).setType( ( *phoneItAD ).type() );
(*it).setNumber( ( *phoneItAD ).number() );
break;
}
}
// if ( isSubSet && ! found )
if ( ! found ) // LR try this one...
mData->phoneNumbers.append( *phoneItAD );
}
} else {
PhoneNumber::List phoneAD = ad.phoneNumbers();
PhoneNumber::List::Iterator phoneItAD;
for ( phoneItAD = phoneAD.begin(); phoneItAD != phoneAD.end(); ++phoneItAD ) {
bool found = false;
PhoneNumber::List::Iterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( ( *phoneItAD ).contains( (*it) ) ) {
found = true;
(*it).setType( ( *phoneItAD ).type() );
(*it).setNumber( ( *phoneItAD ).number() );
break;
}
}
if ( ! found ) { // append numbers which do not have work or home type
if ( ! ( ( *phoneItAD ).type() & (PhoneNumber::Work | PhoneNumber::Home) ) )
mData->phoneNumbers.append( *phoneItAD );
}
}
}
if ( isSubSet ) {
// ************* emails;
t = mData->emails;
tAD = ad.mData->emails;
for ( iii = 0; iii < tAD.count(); ++iii)
if ( !t.contains(tAD[iii] ) )
mData->emails.append( tAD[iii] );
}
// ************* categories;
if ( isSubSet ) {
t = mData->categories;
tAD = ad.mData->categories;
for ( iii = 0; iii < tAD.count(); ++iii)
if ( !t.contains(tAD[iii] ) )
mData->categories.append( tAD[iii] );
}
QStringList::ConstIterator it;
for( it = ad.mData->custom.begin(); it != ad.mData->custom.end(); ++it ) {
QString qualifiedName = (*it).left( (*it).find( ":" ));
bool found = false;
QStringList::ConstIterator itL;
for( itL = mData->custom.begin(); itL != mData->custom.end(); ++itL ) {
if ( (*itL).startsWith( qualifiedName ) ) {
found = true;
break;
}
}
if ( ! found ) {
mData->custom.append( *it );
}
}
if ( mData->logo.undefined() && !ad.mData->logo.undefined() ) mData->logo = ad.mData->logo;
if ( mData->photo.undefined() && !ad.mData->photo.undefined() ) mData->photo = ad.mData->photo;
if ( !mData->sound.isIntern() ) {
if ( mData->sound.url().isEmpty() ) {
mData->sound = ad.mData->sound;
}
}
if ( !mData->agent.isIntern() ) {
if ( mData->agent.url().isEmpty() ) {
mData->agent = ad.mData->agent;
}
}
{
Key::List::Iterator itA;
for( itA = ad.mData->keys.begin(); itA != ad.mData->keys.end(); ++itA ) {
bool found = false;
Key::List::Iterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it) == (*itA)) {
found = true;
break;
}
}
if ( ! found ) {
mData->keys.append( *itA );
}
}
}
if ( isSubSet ) {
KABC::Address::List::Iterator addressIterA;
for ( addressIterA = ad.mData->addresses.begin(); addressIterA != ad.mData->addresses.end(); ++addressIterA ) {
bool found = false;
KABC::Address::List::Iterator addressIter;
for ( addressIter = mData->addresses.begin(); addressIter != mData->addresses.end();
++addressIter ) {
if ( (*addressIter) == (*addressIterA)) {
found = true;
(*addressIter).setType( (*addressIterA).type() );
break;
}
}
if ( isSubSet && ! found ) {
mData->addresses.append( *addressIterA );
}
}
}
//qDebug("merge contact %s ", ad.uid().latin1());
setUid( ad.uid() );
setRevision( ad.revision() );
}
bool Addressee::removeVoice()
{
PhoneNumber::List phoneN = phoneNumbers();
PhoneNumber::List::Iterator phoneIt;
bool found = false;
for ( phoneIt = phoneN.begin(); phoneIt != phoneN.end(); ++phoneIt ) {
if ( (*phoneIt).type() & PhoneNumber::Voice) { // voice found
if ((*phoneIt).type() - PhoneNumber::Voice ) {
(*phoneIt).setType((*phoneIt).type() - PhoneNumber::Voice );
insertPhoneNumber( (*phoneIt) );
found = true;
}
}
}
return found;
}
bool Addressee::containsAdr(const Addressee& ad )
{
if ( ! ad.mData->familyName.isEmpty() ) if ( mData->familyName != ad.mData->familyName) return false;
if ( ! ad.mData->givenName.isEmpty() )if ( mData->givenName != ad.mData->givenName ) return false;
if ( ad.mData->url.isValid() ) if (mData->url != ad.mData->url) return false ;
if ( ! ad.mData->role.isEmpty() ) if (mData->role != ad.mData->role) return false ;
if ( ! ad.mData->organization.isEmpty() ) if (mData->organization != ad.mData->organization) return false ;
if ( ! ad.mData->note.isEmpty() ) if (mData->note != ad.mData->note) return false ;
if ( ! ad.mData->title .isEmpty() ) if (mData->title != ad.mData->title ) return false ;
// compare phone numbers
PhoneNumber::List phoneN = ad.phoneNumbers();
PhoneNumber::List::Iterator phoneIt;
bool found = false;
for ( phoneIt = phoneN.begin(); phoneIt != phoneN.end(); ++phoneIt ) {
bool found = false;
PhoneNumber::List phoneL = ad.phoneNumbers();
PhoneNumber::List::Iterator phoneItL;
for ( phoneItL = phoneL.begin(); phoneItL != phoneL.end(); ++phoneItL ) {
if ( ( *phoneItL ).number() == ( *phoneIt ).number() ) {
found = true;
break;
}
}
if ( ! found )
return false;
}
return true;
}
void Addressee::simplifyAddresses()
{
Address::List list;
Address::List::Iterator it;
Address::List::Iterator it2;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
it2 = it;
++it2;
for( ; it2 != mData->addresses.end(); ++it2 ) {
if ( (*it) == (*it2) ) {
list.append( *it );
break;
}
}
}
for( it = list.begin(); it != list.end(); ++it ) {
removeAddress( (*it) );
}
list.clear();
int max = 2;
if ( mData->url.isValid() )
max = 1;
if ( mData->addresses.count() <= max ) return ;
int count = 0;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( count >= max )
list.append( *it );
++count;
}
for( it = list.begin(); it != list.end(); ++it ) {
removeAddress( (*it) );
}
}
// removes all emails but the first
// needed by phone sync
void Addressee::simplifyEmails()
{
if ( mData->emails.count() == 0 ) return ;
QString email = mData->emails.first();
detach();
mData->emails.clear();
mData->emails.append( email );
}
void Addressee::makePhoneNumbersOLcompatible()
{
KABC::PhoneNumber::List::Iterator phoneIter;
KABC::PhoneNumber::List::Iterator phoneIter2;
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter ) {
( *phoneIter ).makeCompat();
}
int hasHome = hasPhoneNumberType( PhoneNumber::Home | PhoneNumber::Pref );
int hasHome2 = hasPhoneNumberType( PhoneNumber::Home );
int hasWork = hasPhoneNumberType( PhoneNumber::Work | PhoneNumber::Pref );
int hasWork2 = hasPhoneNumberType( PhoneNumber::Work );
int hasCell = hasPhoneNumberType( PhoneNumber::Cell );
int hasCell2 = hasPhoneNumberType( PhoneNumber::Car );
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter ) {
if ( (*phoneIter).type() == PhoneNumber::Home && ! hasHome ) {
(*phoneIter).setType( PhoneNumber::Home | PhoneNumber::Pref );
++hasHome;
if ( hasHome2 ) --hasHome2;
} else if ( ( (*phoneIter).type() == PhoneNumber::Home | PhoneNumber::Pref) && hasHome>1 && !hasHome2 ) {
(*phoneIter).setType( PhoneNumber::Home );
--hasHome;
++hasHome2;
} else if ( (*phoneIter).type() == PhoneNumber::Work && ! hasWork ) {
(*phoneIter).setType( PhoneNumber::Work | PhoneNumber::Pref );
++hasWork;
if ( hasWork2 ) --hasWork2;
} else if ( ( (*phoneIter).type() == PhoneNumber::Work | PhoneNumber::Pref) && hasWork > 1 && ! hasWork2 ) {
(*phoneIter).setType( PhoneNumber::Work );
--hasWork;
++hasWork2;
} else if ( (*phoneIter).type() == PhoneNumber::Cell && hasCell > 1 && !hasCell2) {
(*phoneIter).setType( PhoneNumber::Car );
++hasCell2;
--hasCell;
} else if ( (*phoneIter).type() == PhoneNumber::Car && hasCell2 > 1 && !hasCell) {
(*phoneIter).setType( PhoneNumber::Cell );
++hasCell;
--hasCell2;
} else{
phoneIter2 = phoneIter;
++phoneIter2;
for ( ; phoneIter2 != mData->phoneNumbers.end();
++phoneIter2 ) {
if ( (*phoneIter2).type() == (*phoneIter).type() ) {
(*phoneIter2).setType( PhoneNumber::Voice );
}
}
}
}
}
void Addressee::simplifyPhoneNumbers()
{
int max = 4;
int inList = mData->phoneNumbers.count();
KABC::PhoneNumber::List removeNumbers;
KABC::PhoneNumber::List::Iterator phoneIter;
if ( inList > max ) {
// delete non-preferred numbers
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter ) {
if ( inList > max ) {
if ( ! (( *phoneIter ).type() & PhoneNumber::Pref )) {
removeNumbers.append( ( *phoneIter ) );
--inList;
}
} else
break;
}
for ( phoneIter = removeNumbers.begin(); phoneIter != removeNumbers.end();
++phoneIter ) {
removePhoneNumber(( *phoneIter ));
}
// delete preferred numbers
if ( inList > max ) {
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter ) {
if ( inList > max ) {
removeNumbers.append( ( *phoneIter ) );
--inList;
} else
break;
}
for ( phoneIter = removeNumbers.begin(); phoneIter != removeNumbers.end();
++phoneIter ) {
removePhoneNumber(( *phoneIter ));
}
}
}
// remove non-numeric characters
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter ) {
if ( ! ( *phoneIter ).simplifyNumber() )
removeNumbers.append( ( *phoneIter ) );
}
for ( phoneIter = removeNumbers.begin(); phoneIter != removeNumbers.end();
++phoneIter ) {
removePhoneNumber(( *phoneIter ));
}
}
void Addressee::simplifyPhoneNumberTypes()
{
KABC::PhoneNumber::List::Iterator phoneIter;
for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end();
++phoneIter )
( *phoneIter ).simplifyType();
}
void Addressee::removeID(const QString &prof)
{
detach();
if ( prof.isEmpty() )
mData->mExternalId = ":";
else
mData->mExternalId = KIdManager::removeId ( mData->mExternalId, prof);
}
void Addressee::setID( const QString & prof , const QString & id )
{
detach();
mData->mExternalId = KIdManager::setId ( mData->mExternalId, prof, id );
//qDebug("setID2 %s %s %s",mData->mExternalId.latin1(), prof.latin1(), id.latin1() );
}
void Addressee::setTempSyncStat( int id )
{
if ( mData->mTempSyncStat == id ) return;
detach();
mData->mTempSyncStat = id;
}
int Addressee::tempSyncStat() const
{
return mData->mTempSyncStat;
}
const QString Addressee::getID( const QString & prof) const
{
return KIdManager::getId ( mData->mExternalId, prof );
}
void Addressee::setCsum( const QString & prof , const QString & id )
{
detach();
//qDebug("setcsum1 %s %s %s",mData->mExternalId.latin1(), prof.latin1(), id.latin1() );
mData->mExternalId = KIdManager::setCsum ( mData->mExternalId, prof, id );
//qDebug("setcsum2 %s ",mData->mExternalId.latin1() );
}
const QString Addressee::getCsum( const QString & prof) const
{
return KIdManager::getCsum ( mData->mExternalId, prof );
}
void Addressee::setIDStr( const QString & s )
{
detach();
mData->mExternalId = s;
}
const QString Addressee::IDStr() const
{
return mData->mExternalId;
}
void Addressee::setExternalUID( const QString &id )
{
if ( id == mData->externalUID ) return;
detach();
mData->empty = false;
mData->externalUID = id;
}
const QString Addressee::externalUID() const
{
return mData->externalUID;
}
void Addressee::setOriginalExternalUID( const QString &id )
{
if ( id == mData->originalExternalUID ) return;
detach();
mData->empty = false;
//qDebug("*******Set orig uid %s ", id.latin1());
mData->originalExternalUID = id;
}
QString Addressee::originalExternalUID() const
{
return mData->originalExternalUID;
}
void Addressee::setUid( const QString &id )
{
if ( id == mData->uid ) return;
detach();
//qDebug("****setuid %s ", id.latin1());
mData->empty = false;
mData->uid = id;
}
const QString Addressee::uid() const
{
if ( mData->uid.isEmpty() )
mData->uid = KApplication::randomString( 10 );
return mData->uid;
}
QString Addressee::uidLabel()
{
return i18n("Unique Identifier");
}
void Addressee::setName( const QString &name )
{
if ( name == mData->name ) return;
detach();
mData->empty = false;
mData->name = name;
}
QString Addressee::name() const
{
return mData->name;
}
QString Addressee::nameLabel()
{
return i18n("Name");
}
void Addressee::setFormattedName( const QString &formattedName )
{
if ( formattedName == mData->formattedName ) return;
detach();
mData->empty = false;
mData->formattedName = formattedName;
}
QString Addressee::formattedName() const
{
return mData->formattedName;
}
QString Addressee::formattedNameLabel()
{
return i18n("Formatted Name");
}
void Addressee::setFamilyName( const QString &familyName )
{
if ( familyName == mData->familyName ) return;
detach();
mData->empty = false;
mData->familyName = familyName;
}
QString Addressee::familyName() const
{
return mData->familyName;
}
QString Addressee::familyNameLabel()
{
return i18n("Family Name");
}
void Addressee::setGivenName( const QString &givenName )
{
if ( givenName == mData->givenName ) return;
detach();
mData->empty = false;
mData->givenName = givenName;
}
QString Addressee::givenName() const
{
return mData->givenName;
}
QString Addressee::givenNameLabel()
{
return i18n("Given Name");
}
void Addressee::setAdditionalName( const QString &additionalName )
{
if ( additionalName == mData->additionalName ) return;
detach();
mData->empty = false;
mData->additionalName = additionalName;
}
QString Addressee::additionalName() const
{
return mData->additionalName;
}
QString Addressee::additionalNameLabel()
{
return i18n("Additional Names");
}
void Addressee::setPrefix( const QString &prefix )
{
if ( prefix == mData->prefix ) return;
detach();
mData->empty = false;
mData->prefix = prefix;
}
QString Addressee::prefix() const
{
return mData->prefix;
}
QString Addressee::prefixLabel()
{
return i18n("Honorific Prefixes");
}
void Addressee::setSuffix( const QString &suffix )
{
if ( suffix == mData->suffix ) return;
detach();
mData->empty = false;
mData->suffix = suffix;
}
QString Addressee::suffix() const
{
return mData->suffix;
}
QString Addressee::suffixLabel()
{
return i18n("Honorific Suffixes");
}
void Addressee::setNickName( const QString &nickName )
{
if ( nickName == mData->nickName ) return;
detach();
mData->empty = false;
mData->nickName = nickName;
}
QString Addressee::nickName() const
{
return mData->nickName;
}
QString Addressee::nickNameLabel()
{
return i18n("Nick Name");
}
void Addressee::setBirthday( const QDateTime &birthday )
{
if ( birthday == mData->birthday ) return;
detach();
mData->empty = false;
mData->birthday = birthday;
}
QDateTime Addressee::birthday() const
{
return mData->birthday;
}
QString Addressee::birthdayLabel()
{
return i18n("Birthday");
}
QString Addressee::homeAddressStreetLabel()
{
return i18n("Home Address Street");
}
QString Addressee::homeAddressLocalityLabel()
{
return i18n("Home Address Locality");
}
QString Addressee::homeAddressRegionLabel()
{
return i18n("Home Address Region");
}
QString Addressee::homeAddressPostalCodeLabel()
{
return i18n("Home Address Postal Code");
}
QString Addressee::homeAddressCountryLabel()
{
return i18n("Home Address Country");
}
QString Addressee::homeAddressLabelLabel()
{
return i18n("Home Address Label");
}
QString Addressee::businessAddressStreetLabel()
{
return i18n("Business Address Street");
}
QString Addressee::businessAddressLocalityLabel()
{
return i18n("Business Address Locality");
}
QString Addressee::businessAddressRegionLabel()
{
return i18n("Business Address Region");
}
QString Addressee::businessAddressPostalCodeLabel()
{
return i18n("Business Address Postal Code");
}
QString Addressee::businessAddressCountryLabel()
{
return i18n("Business Address Country");
}
QString Addressee::businessAddressLabelLabel()
{
return i18n("Business Address Label");
}
QString Addressee::homePhoneLabel()
{
return i18n("Home Phone");
}
QString Addressee::businessPhoneLabel()
{
return i18n("Work Phone");
}
QString Addressee::mobilePhoneLabel()
{
return i18n("Mobile");
}
QString Addressee::mobileWorkPhoneLabel()
{
return i18n("Mobile2");
}
QString Addressee::homeFaxLabel()
{
return i18n("Fax (Home)");
}
QString Addressee::businessFaxLabel()
{
return i18n("Fax (Work)");
}
QString Addressee::isdnLabel()
{
return i18n("ISDN");
}
QString Addressee::pagerLabel()
{
return i18n("Pager");
}
QString Addressee::otherPhoneLabel()
{
return i18n("Other Phone");
}
QString Addressee::sipLabel()
{
return i18n("SiP");
}
QString Addressee::emailLabel()
{
return i18n("Email Address");
}
void Addressee::setMailer( const QString &mailer )
{
if ( mailer == mData->mailer ) return;
detach();
mData->empty = false;
mData->mailer = mailer;
}
QString Addressee::mailer() const
{
return mData->mailer;
}
QString Addressee::mailerLabel()
{
return i18n("Mail Client");
}
void Addressee::setTimeZone( const TimeZone &timeZone )
{
if ( timeZone == mData->timeZone ) return;
detach();
mData->empty = false;
mData->timeZone = timeZone;
}
TimeZone Addressee::timeZone() const
{
return mData->timeZone;
}
QString Addressee::timeZoneLabel()
{
return i18n("Time Zone");
}
void Addressee::setGeo( const Geo &geo )
{
if ( geo == mData->geo ) return;
detach();
mData->empty = false;
mData->geo = geo;
}
Geo Addressee::geo() const
{
return mData->geo;
}
QString Addressee::geoLabel()
{
return i18n("Geographic Position");
}
void Addressee::setTitle( const QString &title )
{
if ( title == mData->title ) return;
detach();
mData->empty = false;
mData->title = title;
}
QString Addressee::title() const
{
return mData->title;
}
QString Addressee::titleLabel()
{
return i18n("Title");
}
void Addressee::setRole( const QString &role )
{
if ( role == mData->role ) return;
detach();
mData->empty = false;
mData->role = role;
}
QString Addressee::role() const
{
return mData->role;
}
QString Addressee::roleLabel()
{
return i18n("Role");
}
void Addressee::setOrganization( const QString &organization )
{
if ( organization == mData->organization ) return;
detach();
mData->empty = false;
mData->organization = organization;
}
QString Addressee::organization() const
{
return mData->organization;
}
QString Addressee::organizationLabel()
{
return i18n("Organization");
}
void Addressee::setNote( const QString &note )
{
if ( note == mData->note ) return;
detach();
mData->empty = false;
mData->note = note;
}
QString Addressee::note() const
{
return mData->note;
}
QString Addressee::noteLabel()
{
return i18n("Note");
}
void Addressee::setProductId( const QString &productId )
{
if ( productId == mData->productId ) return;
detach();
mData->empty = false;
mData->productId = productId;
}
QString Addressee::productId() const
{
return mData->productId;
}
QString Addressee::productIdLabel()
{
return i18n("Product Identifier");
}
void Addressee::setRevision( const QDateTime &revision )
{
if ( revision == mData->revision ) return;
detach();
mData->empty = false;
mData->revision = QDateTime( revision.date(),
QTime (revision.time().hour(),
revision.time().minute(),
revision.time().second()));
}
QDateTime Addressee::revision() const
{
return mData->revision;
}
QString Addressee::revisionLabel()
{
return i18n("Revision Date");
}
void Addressee::setSortString( const QString &sortString )
{
if ( sortString == mData->sortString ) return;
detach();
mData->empty = false;
mData->sortString = sortString;
}
QString Addressee::sortString() const
{
return mData->sortString;
}
QString Addressee::sortStringLabel()
{
return i18n("Sort String");
}
void Addressee::setUrl( const KURL &url )
{
if ( url == mData->url ) return;
detach();
mData->empty = false;
mData->url = url;
}
KURL Addressee::url() const
{
return mData->url;
}
QString Addressee::urlLabel()
{
return i18n("URL");
}
void Addressee::setSecrecy( const Secrecy &secrecy )
{
if ( secrecy == mData->secrecy ) return;
detach();
mData->empty = false;
mData->secrecy = secrecy;
}
Secrecy Addressee::secrecy() const
{
return mData->secrecy;
}
QString Addressee::secrecyLabel()
{
return i18n("Security Class");
}
void Addressee::setLogo( const Picture &logo )
{
if ( logo == mData->logo ) return;
detach();
mData->empty = false;
mData->logo = logo;
}
Picture Addressee::logo() const
{
return mData->logo;
}
QString Addressee::logoLabel()
{
return i18n("Logo");
}
void Addressee::setPhoto( const Picture &photo )
{
if ( photo == mData->photo ) return;
detach();
mData->empty = false;
mData->photo = photo;
}
Picture Addressee::photo() const
{
return mData->photo;
}
QString Addressee::photoLabel()
{
return i18n("Photo");
}
void Addressee::setSound( const Sound &sound )
{
if ( sound == mData->sound ) return;
detach();
mData->empty = false;
mData->sound = sound;
}
Sound Addressee::sound() const
{
return mData->sound;
}
QString Addressee::soundLabel()
{
return i18n("Sound");
}
void Addressee::setAgent( const Agent &agent )
{
if ( agent == mData->agent ) return;
detach();
mData->empty = false;
mData->agent = agent;
}
Agent Addressee::agent() const
{
return mData->agent;
}
QString Addressee::agentLabel()
{
return i18n("Agent");
}
void Addressee::setNameFromString( const QString &str )
{
setFormattedName( str );
setName( str );
static bool first = true;
static QStringList titles;
static QStringList suffixes;
static QStringList prefixes;
if ( first ) {
first = false;
titles += i18n( "Dr." );
titles += i18n( "Miss" );
titles += i18n( "Mr." );
titles += i18n( "Mrs." );
titles += i18n( "Ms." );
titles += i18n( "Prof." );
suffixes += i18n( "I" );
suffixes += i18n( "II" );
suffixes += i18n( "III" );
suffixes += i18n( "Jr." );
suffixes += i18n( "Sr." );
prefixes += "van";
prefixes += "von";
prefixes += "de";
KConfig config( locateLocal( "config", "kabcrc") );
config.setGroup( "General" );
titles += config.readListEntry( "Prefixes" );
titles.remove( "" );
prefixes += config.readListEntry( "Inclusions" );
prefixes.remove( "" );
suffixes += config.readListEntry( "Suffixes" );
suffixes.remove( "" );
}
// clear all name parts
setPrefix( "" );
setGivenName( "" );
setAdditionalName( "" );
setFamilyName( "" );
setSuffix( "" );
if ( str.isEmpty() )
return;
int i = str.find(',');
if( i < 0 ) {
QStringList parts = QStringList::split( " ", str );
int leftOffset = 0;
int rightOffset = parts.count() - 1;
QString suffix;
while ( rightOffset >= 0 ) {
if ( suffixes.contains( parts[ rightOffset ] ) ) {
suffix.prepend(parts[ rightOffset ] + (suffix.isEmpty() ? "" : " "));
rightOffset--;
} else
break;
}
setSuffix( suffix );
if ( rightOffset < 0 )
return;
if ( rightOffset - 1 >= 0 && prefixes.contains( parts[ rightOffset - 1 ].lower() ) ) {
setFamilyName( parts[ rightOffset - 1 ] + " " + parts[ rightOffset ] );
rightOffset--;
} else
setFamilyName( parts[ rightOffset ] );
QString prefix;
while ( leftOffset < rightOffset ) {
if ( titles.contains( parts[ leftOffset ] ) ) {
prefix.append( ( prefix.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
} else
break;
}
setPrefix( prefix );
if ( leftOffset < rightOffset ) {
setGivenName( parts[ leftOffset ] );
leftOffset++;
}
QString additionalName;
while ( leftOffset < rightOffset ) {
additionalName.append( ( additionalName.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
}
setAdditionalName( additionalName );
} else {
QString part1 = str.left( i );
QString part2 = str.mid( i + 1 );
QStringList parts = QStringList::split( " ", part1 );
int leftOffset = 0;
int rightOffset = parts.count() - 1;
QString suffix;
while ( rightOffset >= 0 ) {
if ( suffixes.contains( parts[ rightOffset ] ) ) {
suffix.prepend(parts[ rightOffset ] + (suffix.isEmpty() ? "" : " "));
rightOffset--;
} else
break;
}
setSuffix( suffix );
if ( rightOffset - 1 >= 0 && prefixes.contains( parts[ rightOffset - 1 ].lower() ) ) {
setFamilyName( parts[ rightOffset - 1 ] + " " + parts[ rightOffset ] );
rightOffset--;
} else
setFamilyName( parts[ rightOffset ] );
QString prefix;
while ( leftOffset < rightOffset ) {
if ( titles.contains( parts[ leftOffset ] ) ) {
prefix.append( ( prefix.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
} else
break;
}
parts = QStringList::split( " ", part2 );
leftOffset = 0;
rightOffset = parts.count();
while ( leftOffset < rightOffset ) {
if ( titles.contains( parts[ leftOffset ] ) ) {
prefix.append( ( prefix.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
} else
break;
}
setPrefix( prefix );
if ( leftOffset < rightOffset ) {
setGivenName( parts[ leftOffset ] );
leftOffset++;
}
QString additionalName;
while ( leftOffset < rightOffset ) {
additionalName.append( ( additionalName.isEmpty() ? "" : " ") + parts[ leftOffset ] );
leftOffset++;
}
setAdditionalName( additionalName );
}
}
QString Addressee::realName() const
{
if ( !formattedName().isEmpty() )
return formattedName();
QString n = assembledName();
if ( n.isEmpty() )
n = name();
if ( n.isEmpty() )
n = organization();
return n;
}
QString Addressee::assembledName() const
{
QString name = prefix() + " " + givenName() + " " + additionalName() + " " +
familyName() + " " + suffix();
return name.simplifyWhiteSpace();
}
QString Addressee::fullEmail( const QString &email ) const
{
QString e;
if ( email.isNull() ) {
e = preferredEmail();
} else {
e = email;
}
if ( e.isEmpty() ) return QString::null;
QString text;
if ( realName().isEmpty() )
text = e;
else
text = assembledName() + " <" + e + ">";
return text;
}
void Addressee::insertEmail( const QString &email, bool preferred )
{
detach();
QStringList::Iterator it = mData->emails.find( email );
if ( it != mData->emails.end() ) {
if ( !preferred || it == mData->emails.begin() ) return;
mData->emails.remove( it );
mData->emails.prepend( email );
} else {
if ( preferred ) {
mData->emails.prepend( email );
} else {
mData->emails.append( email );
}
}
}
void Addressee::removeEmail( const QString &email )
{
detach();
QStringList::Iterator it = mData->emails.find( email );
if ( it == mData->emails.end() ) return;
mData->emails.remove( it );
}
QString Addressee::preferredEmail() const
{
if ( mData->emails.count() == 0 ) return QString::null;
else return mData->emails.first();
}
QStringList Addressee::emails() const
{
return mData->emails;
}
void Addressee::setEmails( const QStringList& emails ) {
detach();
mData->emails = emails;
}
void Addressee::insertPhoneNumber( const PhoneNumber &phoneNumber )
{
detach();
mData->empty = false;
-
PhoneNumber::List::Iterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( (*it).id() == phoneNumber.id() ) {
*it = phoneNumber;
return;
}
}
mData->phoneNumbers.append( phoneNumber );
}
void Addressee::removePhoneNumber( const PhoneNumber &phoneNumber )
{
detach();
PhoneNumber::List::Iterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( (*it).id() == phoneNumber.id() ) {
mData->phoneNumbers.remove( it );
return;
}
}
}
PhoneNumber Addressee::phoneNumber( int type ) const
{
PhoneNumber phoneNumber( "", type );
PhoneNumber::List::ConstIterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( matchBinaryPatternP( (*it).type(), type ) ) {
if ( (*it).type() & PhoneNumber::Pref )
return (*it);
else if ( phoneNumber.number().isEmpty() )
phoneNumber = (*it);
}
}
return phoneNumber;
}
PhoneNumber::List Addressee::phoneNumbers() const
{
return mData->phoneNumbers;
}
int Addressee::hasPhoneNumberType( int type )
{
int retval = 0;
PhoneNumber::List::ConstIterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( (*it).type() == type )
++retval;
}
return retval;
}
PhoneNumber::List Addressee::phoneNumbers( int type ) const
{
PhoneNumber::List list;
PhoneNumber::List::ConstIterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( matchBinaryPattern( (*it).type(), type ) ) {
list.append( *it );
}
}
return list;
}
+QString Addressee::phoneNumberString( int type ) const
+{
+
+ PhoneNumber::List::ConstIterator it;
+ for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
+ if ((*it).type() == type ) {
+ return ( *it ).number();
+ }
+ }
+ return "";
+}
PhoneNumber Addressee::findPhoneNumber( const QString &id ) const
{
PhoneNumber::List::ConstIterator it;
for( it = mData->phoneNumbers.begin(); it != mData->phoneNumbers.end(); ++it ) {
if ( (*it).id() == id ) {
return *it;
}
}
return PhoneNumber();
}
void Addressee::insertKey( const Key &key )
{
detach();
mData->empty = false;
Key::List::Iterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).id() == key.id() ) {
*it = key;
return;
}
}
mData->keys.append( key );
}
void Addressee::removeKey( const Key &key )
{
detach();
Key::List::Iterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).id() == key.id() ) {
mData->keys.remove( key );
return;
}
}
}
Key Addressee::key( int type, QString customTypeString ) const
{
Key::List::ConstIterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).type() == type ) {
if ( type == Key::Custom ) {
if ( customTypeString.isEmpty() ) {
return *it;
} else {
if ( (*it).customTypeString() == customTypeString )
return (*it);
}
} else {
return *it;
}
}
}
return Key( QString(), type );
}
void Addressee::setKeys( const Key::List& list ) {
detach();
mData->keys = list;
}
Key::List Addressee::keys() const
{
return mData->keys;
}
Key::List Addressee::keys( int type, QString customTypeString ) const
{
Key::List list;
Key::List::ConstIterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).type() == type ) {
if ( type == Key::Custom ) {
if ( customTypeString.isEmpty() ) {
list.append(*it);
} else {
if ( (*it).customTypeString() == customTypeString )
list.append(*it);
}
} else {
list.append(*it);
}
}
}
return list;
}
Key Addressee::findKey( const QString &id ) const
{
Key::List::ConstIterator it;
for( it = mData->keys.begin(); it != mData->keys.end(); ++it ) {
if ( (*it).id() == id ) {
return *it;
}
}
return Key();
}
QString Addressee::asString() const
{
return "Smith, agent Smith...";
}
void Addressee::dump() const
{
return;
#if 0
kdDebug(5700) << "Addressee {" << endl;
kdDebug(5700) << " Uid: '" << uid() << "'" << endl;
kdDebug(5700) << " Name: '" << name() << "'" << endl;
kdDebug(5700) << " FormattedName: '" << formattedName() << "'" << endl;
kdDebug(5700) << " FamilyName: '" << familyName() << "'" << endl;
kdDebug(5700) << " GivenName: '" << givenName() << "'" << endl;
kdDebug(5700) << " AdditionalName: '" << additionalName() << "'" << endl;
kdDebug(5700) << " Prefix: '" << prefix() << "'" << endl;
kdDebug(5700) << " Suffix: '" << suffix() << "'" << endl;
kdDebug(5700) << " NickName: '" << nickName() << "'" << endl;
kdDebug(5700) << " Birthday: '" << birthday().toString() << "'" << endl;
kdDebug(5700) << " Mailer: '" << mailer() << "'" << endl;
kdDebug(5700) << " TimeZone: '" << timeZone().asString() << "'" << endl;
kdDebug(5700) << " Geo: '" << geo().asString() << "'" << endl;
kdDebug(5700) << " Title: '" << title() << "'" << endl;
kdDebug(5700) << " Role: '" << role() << "'" << endl;
kdDebug(5700) << " Organization: '" << organization() << "'" << endl;
kdDebug(5700) << " Note: '" << note() << "'" << endl;
kdDebug(5700) << " ProductId: '" << productId() << "'" << endl;
kdDebug(5700) << " Revision: '" << revision().toString() << "'" << endl;
kdDebug(5700) << " SortString: '" << sortString() << "'" << endl;
kdDebug(5700) << " Url: '" << url().url() << "'" << endl;
kdDebug(5700) << " Secrecy: '" << secrecy().asString() << "'" << endl;
kdDebug(5700) << " Logo: '" << logo().asString() << "'" << endl;
kdDebug(5700) << " Photo: '" << photo().asString() << "'" << endl;
kdDebug(5700) << " Sound: '" << sound().asString() << "'" << endl;
kdDebug(5700) << " Agent: '" << agent().asString() << "'" << endl;
kdDebug(5700) << " Emails {" << endl;
QStringList e = emails();
QStringList::ConstIterator it;
for( it = e.begin(); it != e.end(); ++it ) {
kdDebug(5700) << " " << (*it) << endl;
}
kdDebug(5700) << " }" << endl;
kdDebug(5700) << " PhoneNumbers {" << endl;
PhoneNumber::List p = phoneNumbers();
PhoneNumber::List::ConstIterator it2;
for( it2 = p.begin(); it2 != p.end(); ++it2 ) {
kdDebug(5700) << " Type: " << int((*it2).type()) << " Number: " << (*it2).number() << endl;
}
kdDebug(5700) << " }" << endl;
Address::List a = addresses();
Address::List::ConstIterator it3;
for( it3 = a.begin(); it3 != a.end(); ++it3 ) {
(*it3).dump();
}
kdDebug(5700) << " Keys {" << endl;
Key::List k = keys();
Key::List::ConstIterator it4;
for( it4 = k.begin(); it4 != k.end(); ++it4 ) {
kdDebug(5700) << " Type: " << int((*it4).type()) <<
" Key: " << (*it4).textData() <<
" CustomString: " << (*it4).customTypeString() << endl;
}
kdDebug(5700) << " }" << endl;
kdDebug(5700) << "}" << endl;
#endif
}
void Addressee::insertAddress( const Address &address )
{
detach();
mData->empty = false;
Address::List::Iterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( (*it).id() == address.id() ) {
*it = address;
return;
}
}
mData->addresses.append( address );
}
void Addressee::removeAddress( const Address &address )
{
detach();
Address::List::Iterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( (*it).id() == address.id() ) {
mData->addresses.remove( it );
return;
}
}
}
-
+Address Addressee::otherAddress() const
+{
+ Address::List::ConstIterator it;
+ for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
+ if ( matchBinaryPatternA( (*it).type(), KABC::Address::Work ) )
+ continue;
+ if ( matchBinaryPatternA( (*it).type(), KABC::Address::Home ) )
+ continue;
+ return (*it);
+ }
+ return Address();
+}
Address Addressee::address( int type ) const
{
Address address( type );
Address::List::ConstIterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( matchBinaryPatternA( (*it).type(), type ) ) {
if ( (*it).type() & Address::Pref )
return (*it);
else if ( address.isEmpty() )
address = (*it);
}
}
return address;
}
Address::List Addressee::addresses() const
{
return mData->addresses;
}
Address::List Addressee::addresses( int type ) const
{
Address::List list;
Address::List::ConstIterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( matchBinaryPattern( (*it).type(), type ) ) {
list.append( *it );
}
}
return list;
}
Address Addressee::findAddress( const QString &id ) const
{
Address::List::ConstIterator it;
for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) {
if ( (*it).id() == id ) {
return *it;
}
}
return Address();
}
void Addressee::insertCategory( const QString &c )
{
detach();
mData->empty = false;
if ( mData->categories.contains( c ) ) return;
mData->categories.append( c );
}
void Addressee::removeCategory( const QString &c )
{
detach();
QStringList::Iterator it = mData->categories.find( c );
if ( it == mData->categories.end() ) return;
mData->categories.remove( it );
}
bool Addressee::hasCategory( const QString &c ) const
{
return ( mData->categories.contains( c ) );
}
void Addressee::setCategories( const QStringList &c )
{
detach();
mData->empty = false;
mData->categories = c;
}
QStringList Addressee::categories() const
{
return mData->categories;
}
void Addressee::insertCustom( const QString &app, const QString &name,
const QString &value )
{
if ( value.isNull() || name.isEmpty() || app.isEmpty() ) return;
detach();
mData->empty = false;
QString qualifiedName = app + "-" + name + ":";
QStringList::Iterator it;
for( it = mData->custom.begin(); it != mData->custom.end(); ++it ) {
if ( (*it).startsWith( qualifiedName ) ) {
(*it) = qualifiedName + value;
return;
}
}
mData->custom.append( qualifiedName + value );
}
void Addressee::removeCustom( const QString &app, const QString &name)
{
detach();
QString qualifiedName = app + "-" + name + ":";
QStringList::Iterator it;
for( it = mData->custom.begin(); it != mData->custom.end(); ++it ) {
if ( (*it).startsWith( qualifiedName ) ) {
mData->custom.remove( it );
return;
}
}
}
QString Addressee::custom( const QString &app, const QString &name ) const
{
QString qualifiedName = app + "-" + name + ":";
QString value;
QStringList::ConstIterator it;
for( it = mData->custom.begin(); it != mData->custom.end(); ++it ) {
if ( (*it).startsWith( qualifiedName ) ) {
value = (*it).mid( (*it).find( ":" ) + 1 );
break;
}
}
return value;
}
void Addressee::setCustoms( const QStringList &l )
{
detach();
mData->empty = false;
mData->custom = l;
}
QStringList Addressee::customs() const
{
return mData->custom;
}
void Addressee::parseEmailAddress( const QString &rawEmail, QString &fullName,
QString &email)
{
int startPos, endPos, len;
QString partA, partB, result;
char endCh = '>';
startPos = rawEmail.find('<');
if (startPos < 0)
{
startPos = rawEmail.find('(');
endCh = ')';
}
if (startPos < 0)
{
// We couldn't find any separators, so we assume the whole string
// is the email address
email = rawEmail;
fullName = "";
}
else
{
// We have a start position, try to find an end
endPos = rawEmail.find(endCh, startPos+1);
if (endPos < 0)
{
// We couldn't find the end of the email address. We can only
// assume the entire string is the email address.
email = rawEmail;
fullName = "";
}
else
{
// We have a start and end to the email address
// Grab the name part
fullName = rawEmail.left(startPos).stripWhiteSpace();
// grab the email part
email = rawEmail.mid(startPos+1, endPos-startPos-1).stripWhiteSpace();
// Check that we do not have any extra characters on the end of the
// strings
len = fullName.length();
if (fullName[0]=='"' && fullName[len-1]=='"')
fullName = fullName.mid(1, len-2);
else if (fullName[0]=='<' && fullName[len-1]=='>')
fullName = fullName.mid(1, len-2);
else if (fullName[0]=='(' && fullName[len-1]==')')
fullName = fullName.mid(1, len-2);
}
}
}
void Addressee::setResource( Resource *resource )
{
detach();
mData->resource = resource;
}
Resource *Addressee::resource() const
{
return mData->resource;
}
//US
QString Addressee::resourceLabel()
{
return i18n("Resource");
}
QString Addressee::categoryLabel()
{
return i18n("Category");
}
void Addressee::setChanged( bool value )
{
detach();
mData->changed = value;
}
bool Addressee::changed() const
{
return mData->changed;
}
void Addressee::setTagged( bool value )
{
detach();
mData->tagged = value;
}
bool Addressee::tagged() const
{
return mData->tagged;
}
QDataStream &KABC::operator<<( QDataStream &s, const Addressee &a )
{
if (!a.mData) return s;
s << a.uid();
s << a.mData->name;
s << a.mData->formattedName;
s << a.mData->familyName;
s << a.mData->givenName;
s << a.mData->additionalName;
s << a.mData->prefix;
s << a.mData->suffix;
s << a.mData->nickName;
s << a.mData->birthday;
s << a.mData->mailer;
s << a.mData->timeZone;
s << a.mData->geo;
s << a.mData->title;
s << a.mData->role;
s << a.mData->organization;
s << a.mData->note;
s << a.mData->productId;
s << a.mData->revision;
s << a.mData->sortString;
s << a.mData->url;
s << a.mData->secrecy;
s << a.mData->logo;
s << a.mData->photo;
s << a.mData->sound;
s << a.mData->agent;
s << a.mData->phoneNumbers;
s << a.mData->addresses;
s << a.mData->emails;
s << a.mData->categories;
s << a.mData->custom;
s << a.mData->keys;
return s;
}
QDataStream &KABC::operator>>( QDataStream &s, Addressee &a )
{
if (!a.mData) return s;
s >> a.mData->uid;
s >> a.mData->name;
s >> a.mData->formattedName;
s >> a.mData->familyName;
s >> a.mData->givenName;
s >> a.mData->additionalName;
s >> a.mData->prefix;
s >> a.mData->suffix;
s >> a.mData->nickName;
s >> a.mData->birthday;
s >> a.mData->mailer;
s >> a.mData->timeZone;
s >> a.mData->geo;
s >> a.mData->title;
s >> a.mData->role;
s >> a.mData->organization;
s >> a.mData->note;
s >> a.mData->productId;
s >> a.mData->revision;
s >> a.mData->sortString;
s >> a.mData->url;
s >> a.mData->secrecy;
s >> a.mData->logo;
s >> a.mData->photo;
s >> a.mData->sound;
s >> a.mData->agent;
s >> a.mData->phoneNumbers;
s >> a.mData->addresses;
s >> a.mData->emails;
s >> a.mData->categories;
s >> a.mData->custom;
s >> a.mData->keys;
a.mData->empty = false;
return s;
}
bool matchBinaryPattern( int value, int pattern )
{
/**
We want to match all telephonnumbers/addresses which have the bits in the
pattern set. More are allowed.
if pattern == 0 we have a special handling, then we want only those with
exactly no bit set.
*/
if ( pattern == 0 )
return ( value == 0 );
else
return ( pattern == ( pattern & value ) );
}
bool matchBinaryPatternP( int value, int pattern )
{
if ( pattern == 0 )
return ( value == 0 );
else
return ( (pattern |PhoneNumber::Pref ) == ( value |PhoneNumber::Pref ) );
}
bool matchBinaryPatternA( int value, int pattern )
{
if ( pattern == 0 )
return ( value == 0 );
else
return ( (pattern | Address::Pref) == ( value | Address::Pref ) );
}
diff --git a/kabc/addressee.h b/kabc/addressee.h
index aac78dc..0ea1803 100644
--- a/kabc/addressee.h
+++ b/kabc/addressee.h
@@ -1,856 +1,858 @@
/*** Warning! This file has been generated by the script makeaddressee ***/
/*
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_ADDRESSEE_H
#define KABC_ADDRESSEE_H
#include <qdatetime.h>
#include <qstring.h>
#include <qregexp.h>
#include <qstringlist.h>
#include <qvaluelist.h>
#include <ksharedptr.h>
#include <kurl.h>
#include "address.h"
#include "agent.h"
#include "geo.h"
#include "key.h"
#include "phonenumber.h"
#include "picture.h"
#include "secrecy.h"
#include "sound.h"
#include "timezone.h"
namespace KABC {
class Resource;
/**
@short address book entry
This class represents an entry in the address book.
The data of this class is implicitly shared. You can pass this class by value.
If you need the name of a field for presenting it to the user you should use
the functions ending in Label(). They return a translated string which can be
used as label for the corresponding field.
About the name fields:
givenName() is the first name and familyName() the last name. In some
countries the family name comes first, that's the reason for the
naming. formattedName() is the full name with the correct formatting.
It is used as an override, when the correct formatting can't be generated
from the other name fields automatically.
realName() returns a fully formatted name(). It uses formattedName, if set,
otherwise it constucts the name from the name fields. As fallback, if
nothing else is set it uses name().
name() is the NAME type of RFC2426. It can be used as internal name for the
data enty, but shouldn't be used for displaying the data to the user.
*/
class Addressee
{
friend QDataStream &operator<<( QDataStream &, const Addressee & );
friend QDataStream &operator>>( QDataStream &, Addressee & );
public:
typedef QValueList<Addressee> List;
/**
Construct an empty address book entry.
*/
Addressee();
~Addressee();
Addressee( const Addressee & );
Addressee &operator=( const Addressee & );
bool operator==( const Addressee & ) const;
bool operator!=( const Addressee & ) const;
// sync stuff
void setTempSyncStat(int id);
int tempSyncStat() const;
void setIDStr( const QString & );
const QString IDStr() const;
void setID( const QString &, const QString & );
const QString getID( const QString & ) const;
void setCsum( const QString &, const QString & );
const QString getCsum( const QString & ) const ;
void removeID(const QString &);
void computeCsum(const QString &dev);
ulong getCsum4List( const QStringList & attList);
/**
Return, if the address book entry is empty.
*/
bool isEmpty() const;
void setExternalUID( const QString &id );
const QString externalUID() const;
void setOriginalExternalUID( const QString &id );
QString originalExternalUID() const;
void mergeContact( const Addressee& ad, bool isSubSet );
+ void mergeOLContact( const Addressee& ad );
void simplifyEmails();
void simplifyAddresses();
void simplifyPhoneNumbers();
void simplifyPhoneNumberTypes();
void makePhoneNumbersOLcompatible();
int hasPhoneNumberType( int type );
bool removeVoice();
bool containsAdr(const Addressee& addr );
/**
Set unique identifier.
*/
void setUid( const QString &uid );
/**
Return unique identifier.
*/
const QString uid() const;
/**
Return translated label for uid field.
*/
static QString uidLabel();
/**
Set name.
*/
void setName( const QString &name );
/**
Return name.
*/
QString name() const;
/**
Return translated label for name field.
*/
static QString nameLabel();
/**
Set formatted name.
*/
void setFormattedName( const QString &formattedName );
/**
Return formatted name.
*/
QString formattedName() const;
/**
Return translated label for formattedName field.
*/
static QString formattedNameLabel();
/**
Set family name.
*/
void setFamilyName( const QString &familyName );
/**
Return family name.
*/
QString familyName() const;
/**
Return translated label for familyName field.
*/
static QString familyNameLabel();
/**
Set given name.
*/
void setGivenName( const QString &givenName );
/**
Return given name.
*/
QString givenName() const;
/**
Return translated label for givenName field.
*/
static QString givenNameLabel();
/**
Set additional names.
*/
void setAdditionalName( const QString &additionalName );
/**
Return additional names.
*/
QString additionalName() const;
/**
Return translated label for additionalName field.
*/
static QString additionalNameLabel();
/**
Set honorific prefixes.
*/
void setPrefix( const QString &prefix );
/**
Return honorific prefixes.
*/
QString prefix() const;
/**
Return translated label for prefix field.
*/
static QString prefixLabel();
/**
Set honorific suffixes.
*/
void setSuffix( const QString &suffix );
/**
Return honorific suffixes.
*/
QString suffix() const;
/**
Return translated label for suffix field.
*/
static QString suffixLabel();
/**
Set nick name.
*/
void setNickName( const QString &nickName );
/**
Return nick name.
*/
QString nickName() const;
/**
Return translated label for nickName field.
*/
static QString nickNameLabel();
/**
Set birthday.
*/
void setBirthday( const QDateTime &birthday );
/**
Return birthday.
*/
QDateTime birthday() const;
/**
Return translated label for birthday field.
*/
static QString birthdayLabel();
/**
Return translated label for homeAddressStreet field.
*/
static QString homeAddressStreetLabel();
/**
Return translated label for homeAddressLocality field.
*/
static QString homeAddressLocalityLabel();
/**
Return translated label for homeAddressRegion field.
*/
static QString homeAddressRegionLabel();
/**
Return translated label for homeAddressPostalCode field.
*/
static QString homeAddressPostalCodeLabel();
/**
Return translated label for homeAddressCountry field.
*/
static QString homeAddressCountryLabel();
/**
Return translated label for homeAddressLabel field.
*/
static QString homeAddressLabelLabel();
/**
Return translated label for businessAddressStreet field.
*/
static QString businessAddressStreetLabel();
/**
Return translated label for businessAddressLocality field.
*/
static QString businessAddressLocalityLabel();
/**
Return translated label for businessAddressRegion field.
*/
static QString businessAddressRegionLabel();
/**
Return translated label for businessAddressPostalCode field.
*/
static QString businessAddressPostalCodeLabel();
/**
Return translated label for businessAddressCountry field.
*/
static QString businessAddressCountryLabel();
/**
Return translated label for businessAddressLabel field.
*/
static QString businessAddressLabelLabel();
/**
Return translated label for homePhone field.
*/
static QString homePhoneLabel();
/**
Return translated label for businessPhone field.
*/
static QString businessPhoneLabel();
/**
Return translated label for mobilePhone field.
*/
static QString mobilePhoneLabel();
static QString mobileWorkPhoneLabel();
/**
Return translated label for homeFax field.
*/
static QString homeFaxLabel();
/**
Return translated label for businessFax field.
*/
static QString businessFaxLabel();
/**
Return translated label for isdn field.
*/
static QString isdnLabel();
/**
Return translated label for pager field.
*/
static QString pagerLabel();
static QString otherPhoneLabel();
/**
Return translated label for sip field.
*/
static QString sipLabel();
/**
Return translated label for email field.
*/
static QString emailLabel();
/**
Set mail client.
*/
void setMailer( const QString &mailer );
/**
Return mail client.
*/
QString mailer() const;
/**
Return translated label for mailer field.
*/
static QString mailerLabel();
/**
Set time zone.
*/
void setTimeZone( const TimeZone &timeZone );
/**
Return time zone.
*/
TimeZone timeZone() const;
/**
Return translated label for timeZone field.
*/
static QString timeZoneLabel();
/**
Set geographic position.
*/
void setGeo( const Geo &geo );
/**
Return geographic position.
*/
Geo geo() const;
/**
Return translated label for geo field.
*/
static QString geoLabel();
/**
Set title.
*/
void setTitle( const QString &title );
/**
Return title.
*/
QString title() const;
/**
Return translated label for title field.
*/
static QString titleLabel();
/**
Set role.
*/
void setRole( const QString &role );
/**
Return role.
*/
QString role() const;
/**
Return translated label for role field.
*/
static QString roleLabel();
/**
Set organization.
*/
void setOrganization( const QString &organization );
/**
Return organization.
*/
QString organization() const;
/**
Return translated label for organization field.
*/
static QString organizationLabel();
/**
Set note.
*/
void setNote( const QString &note );
/**
Return note.
*/
QString note() const;
/**
Return translated label for note field.
*/
static QString noteLabel();
/**
Set product identifier.
*/
void setProductId( const QString &productId );
/**
Return product identifier.
*/
QString productId() const;
/**
Return translated label for productId field.
*/
static QString productIdLabel();
/**
Set revision date.
*/
void setRevision( const QDateTime &revision );
/**
Return revision date.
*/
QDateTime revision() const;
/**
Return translated label for revision field.
*/
static QString revisionLabel();
/**
Set sort string.
*/
void setSortString( const QString &sortString );
/**
Return sort string.
*/
QString sortString() const;
/**
Return translated label for sortString field.
*/
static QString sortStringLabel();
/**
Set URL.
*/
void setUrl( const KURL &url );
/**
Return URL.
*/
KURL url() const;
/**
Return translated label for url field.
*/
static QString urlLabel();
/**
Set security class.
*/
void setSecrecy( const Secrecy &secrecy );
/**
Return security class.
*/
Secrecy secrecy() const;
/**
Return translated label for secrecy field.
*/
static QString secrecyLabel();
/**
Set logo.
*/
void setLogo( const Picture &logo );
/**
Return logo.
*/
Picture logo() const;
/**
Return translated label for logo field.
*/
static QString logoLabel();
/**
Set photo.
*/
void setPhoto( const Picture &photo );
/**
Return photo.
*/
Picture photo() const;
/**
Return translated label for photo field.
*/
static QString photoLabel();
/**
Set sound.
*/
void setSound( const Sound &sound );
/**
Return sound.
*/
Sound sound() const;
/**
Return translated label for sound field.
*/
static QString soundLabel();
/**
Set agent.
*/
void setAgent( const Agent &agent );
/**
Return agent.
*/
Agent agent() const;
/**
Return translated label for agent field.
*/
static QString agentLabel();
/**
Set name fields by parsing the given string and trying to associate the
parts of the string with according fields. This function should probably
be a bit more clever.
*/
void setNameFromString( const QString & );
/**
Return the name of the addressee. This is calculated from all the name
fields.
*/
QString realName() const;
/**
Return the name that consists of all name parts.
*/
QString assembledName() const;
/**
Return email address including real name.
@param email Email address to be used to construct the full email string.
If this is QString::null the preferred email address is used.
*/
QString fullEmail( const QString &email=QString::null ) const;
/**
Insert an email address. If the email address already exists in this
addressee it is not duplicated.
@param email Email address
@param preferred Set to true, if this is the preferred email address of
the addressee.
*/
void insertEmail( const QString &email, bool preferred=false );
/**
Remove email address. If the email address doesn't exist, nothing happens.
*/
void removeEmail( const QString &email );
/**
Return preferred email address. This is the first email address or the
last one added with @ref insertEmail() with a set preferred parameter.
*/
QString preferredEmail() const;
/**
Return list of all email addresses.
*/
QStringList emails() const;
/**
Set the emails to @param.
The first email address gets the preferred one!
@param list The list of email addresses.
*/
void setEmails( const QStringList& list);
/**
Insert a phone number. If a phone number with the same id already exists
in this addressee it is not duplicated.
*/
void insertPhoneNumber( const PhoneNumber &phoneNumber );
/**
Remove phone number. If no phone number with the given id exists for this
addresse nothing happens.
*/
void removePhoneNumber( const PhoneNumber &phoneNumber );
/**
Return phone number, which matches the given type.
*/
PhoneNumber phoneNumber( int type ) const;
+ QString phoneNumberString( int type ) const;
bool matchPhoneNumber( QRegExp* searchExp ) const;
bool matchAddress( QRegExp* searchExp ) const;
/**
Return list of all phone numbers.
*/
PhoneNumber::List phoneNumbers() const;
/**
Return list of phone numbers with a special type.
*/
PhoneNumber::List phoneNumbers( int type ) const;
/**
Return phone number with the given id.
*/
PhoneNumber findPhoneNumber( const QString &id ) const;
/**
Insert a key. If a key with the same id already exists
in this addressee it is not duplicated.
*/
void insertKey( const Key &key );
/**
Remove a key. If no key with the given id exists for this
addresse nothing happens.
*/
void removeKey( const Key &key );
/**
Return key, which matches the given type.
If @p type == Key::Custom you can specify a string
that should match. If you leave the string empty, the first
key with a custom value is returned.
*/
Key key( int type, QString customTypeString = QString::null ) const;
/**
Return list of all keys.
*/
Key::List keys() const;
/**
Set the list of keys
@param keys The keys to be set.
*/
void setKeys( const Key::List& keys);
/**
Return list of keys with a special type.
If @p type == Key::Custom you can specify a string
that should match. If you leave the string empty, all custom
keys will be returned.
*/
Key::List keys( int type, QString customTypeString = QString::null ) const;
/**
Return key with the given id.
*/
Key findKey( const QString &id ) const;
/**
Insert an address. If an address with the same id already exists
in this addressee it is not duplicated.
*/
void insertAddress( const Address &address );
/**
Remove address. If no address with the given id exists for this
addresse nothing happens.
*/
void removeAddress( const Address &address );
/**
Return address, which matches the given type.
*/
Address address( int type ) const;
/**
Return list of all addresses.
*/
Address::List addresses() const;
-
+ Address otherAddress() const;
/**
Return list of addresses with a special type.
*/
Address::List addresses( int type ) const;
/**
Return address with the given id.
*/
Address findAddress( const QString &id ) const;
/**
Insert category. If the category already exists it is not duplicated.
*/
void insertCategory( const QString & );
/**
Remove category.
*/
void removeCategory( const QString & );
/**
Return, if addressee has the given category.
*/
bool hasCategory( const QString & ) const;
/**
Set categories to given value.
*/
void setCategories( const QStringList & );
/**
Return list of all set categories.
*/
QStringList categories() const;
/**
Insert custom entry. The entry is identified by the name of the inserting
application and a unique name. If an entry with the given app and name
already exists its value is replaced with the new given value.
*/
void insertCustom( const QString &app, const QString &name,
const QString &value );
/**
Remove custom entry.
*/
void removeCustom( const QString &app, const QString &name );
/**
Return value of custom entry, identified by app and entry name.
*/
QString custom( const QString &app, const QString &name ) const;
/**
Set all custom entries.
*/
void setCustoms( const QStringList & );
/**
Return list of all custom entries.
*/
QStringList customs() const;
/**
Parse full email address. The result is given back in fullName and email.
*/
static void parseEmailAddress( const QString &rawEmail, QString &fullName,
QString &email );
/**
Debug output.
*/
void dump() const;
/**
Returns string representation of the addressee.
*/
QString asString() const;
/**
Set resource where the addressee is from.
*/
void setResource( Resource *resource );
/**
Return pointer to resource.
*/
Resource *resource() const;
/**
Return resourcelabel.
*/
//US
static QString resourceLabel();
static QString categoryLabel();
/**
Mark addressee as changed.
*/
void setChanged( bool value );
/**
Return whether the addressee is changed.
*/
bool changed() const;
void setTagged( bool value );
bool tagged() const;
private:
Addressee copy();
void detach();
struct AddresseeData;
mutable KSharedPtr<AddresseeData> mData;
};
QDataStream &operator<<( QDataStream &, const Addressee & );
QDataStream &operator>>( QDataStream &, Addressee & );
}
#endif
diff --git a/kabc/phonenumber.cpp b/kabc/phonenumber.cpp
index 12b9b09..1752745 100644
--- a/kabc/phonenumber.cpp
+++ b/kabc/phonenumber.cpp
@@ -1,374 +1,398 @@
/*
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$
*/
#include <kapplication.h>
#include <klocale.h>
#include "phonenumber.h"
using namespace KABC;
PhoneNumber::PhoneNumber() :
mType( Home )
{
init();
}
PhoneNumber::PhoneNumber( const QString &number, int type ) :
mType( type ), mNumber( number )
{
init();
}
PhoneNumber::~PhoneNumber()
{
}
void PhoneNumber::init()
{
mId = KApplication::randomString( 8 );
}
bool PhoneNumber::operator==( const PhoneNumber &p ) const
{
if ( mNumber != p.mNumber ) return false;
if ( mType != p.mType ) return false;
return true;
}
bool PhoneNumber::operator!=( const PhoneNumber &p ) const
{
return !( p == *this );
}
void PhoneNumber::makeCompat()
{
mType = getCompatType( mType );
}
int PhoneNumber::getCompatType( int type )
{
if ((type & Cell) == Cell) {
if ((type & Work) == Work)
return Car;
return Cell;
}
if ((type & Home) == Home) {
if ((type & Pref) == Pref)
return (Home | Pref);
if ((type & Fax) == Fax)
return (Home | Fax);
return (Home);
}
if ((type & Work) == Work) {
if ((type & Pref) == Pref)
return (Work| Pref);
if ((type & Fax) == Fax)
return (Fax |Work);
if ((type & Msg) == Msg) {
if ((type & Voice) == Voice)
return ( Msg | Voice |Work);
return ( Msg | Work);
}
return Work;
}
if ((type & Pcs) == Pcs) {
if ((type & Pref) == Pref)
return Pcs | Pref;
if ((type & Voice) == Voice)
return Pcs | Voice;
return Pcs;
}
if ((type & Car) == Car)
return Car;
if ((type & Pager) == Pager)
return Pager;
if ((type & Isdn) == Isdn)
return Isdn;
#if 0
if ((type & Video) == Video)
return Video;
#endif
if ((type & Msg) == Msg)
return Msg;
if ((type & Fax) == Fax)
return Fax;
if ((type & Pref) == Pref)
return Pref;
return Voice;
}
bool PhoneNumber::simplifyNumber()
{
QString Number;
int i;
Number = mNumber.stripWhiteSpace ();
mNumber = "";
for ( i = 0; i < Number.length(); ++i) {
if ( Number.at(i).isDigit() || Number.at(i) == '+'|| Number.at(i) == '*'|| Number.at(i) == '#' )
mNumber += Number.at(i);
}
return ( mNumber.length() > 0 );
}
// make cellphone compatible
void PhoneNumber::simplifyType()
{
if ( mType & Fax ) mType = Fax;
else if ( mType & Cell ) mType = Cell;
else if ( mType & Work ) mType = Work ;
else if ( mType & Home ) mType = Home;
else mType = Pref;
}
bool PhoneNumber::contains( const PhoneNumber &p )
{
PhoneNumber myself;
PhoneNumber other;
myself = *this;
other = p;
myself.simplifyNumber();
other.simplifyNumber();
if ( myself.number() != other.number ())
return false;
myself.simplifyType();
other.simplifyType();
if ( myself.type() == other.type())
return true;
return false;
}
void PhoneNumber::setId( const QString &id )
{
mId = id;
}
QString PhoneNumber::id() const
{
return mId;
}
void PhoneNumber::setNumber( const QString &number )
{
mNumber = number;
}
QString PhoneNumber::number() const
{
return mNumber;
}
void PhoneNumber::setType( int type )
{
mType = type;
}
int PhoneNumber::type() const
{
return mType;
}
QString PhoneNumber::typeLabel() const
{
QString label;
bool first = true;
TypeList list = typeList();
TypeList::Iterator it;
for ( it = list.begin(); it != list.end(); ++it ) {
if ( ( type() & (*it) ) && ( (*it) != Pref ) ) {
label.append( ( first ? "" : "/" ) + typeLabel( *it ) );
if ( first )
first = false;
}
}
return label;
}
QString PhoneNumber::label() const
{
return typeLabel( type() );
}
PhoneNumber::TypeList PhoneNumber::typeList()
{
TypeList list;
list << Home << Work << Msg << Pref << Voice << Fax << Cell << Video
<< Bbs << Modem << Car << Isdn << Pcs << Pager;
return list;
}
PhoneNumber::TypeList PhoneNumber::supportedTypeList()
{
static TypeList list;
if ( list.count() == 0 )
list << (Home| Pref) << (Work| Pref) << Cell <<(Pcs|Pref)<< (Pcs|Voice)<< Home << Work << Car << Pcs <<(Work| Msg | Voice) << (Work| Msg) << (Home | Fax) << (Work| Fax) << Fax<< Pager << Isdn << Msg << Pref << Voice;
return list;
}
+
+#if 0
+Home| Pref i18n("Home") Home
+Work| Pref i18n("Work") Business
+Cell i18n("Mobile") Mobile
+Pcs|Pref i18n("SiP") Radio
+Pcs|Voice i18n("VoIP") TTY/TTD
+Home i18n("Home2") Home 2
+Work i18n("Work2") Business 2
+Car i18n("Mobile2") Car
+Pcs i18n("SiP2") Telex
+Work| Msg | Voice i18n("Assistent") Assistent
+Work| Msg i18n("Company") Company
+Home | Fax i18n("Fax (Home)") Home Fax
+Work| Fax i18n("Fax (Work)") Business Fax
+Fax i18n("Fax (Other)") Other Fax
+Pager i18n("Pager") Pager
+Isdn i18n("ISDN") Isdn
+Msg i18n("Callback") Callback
+Pref i18n("Primary") Primary
+Voice; i18n("Other") Other
+
+#endif
+
QStringList PhoneNumber::supportedTypeListNames()
{
static QStringList list;
if ( list.count() == 0 )
list << i18n("Home") << i18n("Work") << i18n("Mobile") << i18n("SiP") << i18n("VoIP") <<i18n("Home2")<< i18n("Work2") << i18n("Mobile2") << i18n("SiP2") << i18n("Assistent") << i18n("Company") << i18n("Fax (Home)") << i18n("Fax (Work)") << i18n("Fax (Other)") << i18n("Pager") << i18n("ISDN") << i18n("Callback") << i18n("Primary")<< i18n("Other");
return list;
}
int PhoneNumber::typeListIndex4Type(int type )
{
TypeList list = supportedTypeList();
int i = 0;
while ( i < list.count() ) {
if ( list [i] == type )
return i;
++i;
}
return list.count()-1;
}
QString PhoneNumber::label( int type )
{
return typeLabel( type );
}
QString PhoneNumber::typeLabel( int type )
{
if ((type & Cell) == Cell)
return i18n("Mobile");
if ((type & Home) == Home) {
if ((type & Pref) == Pref)
return i18n("Home");
if ((type & Fax) == Fax)
return i18n("Fax (Home)");
return i18n("Home2");
}
if ((type & Work) == Work) {
if ((type & Pref) == Pref)
return i18n("Work");
if ((type & Fax) == Fax)
return i18n("Fax (Work)");
if ((type & Msg) == Msg) {
if ((type & Voice) == Voice)
return i18n("Assistent");
return i18n("Company");
}
return i18n("Work2");
}
if ((type & Pcs) == Pcs) {
if ((type & Pref) == Pref)
return i18n("SiP");
if ((type & Voice) == Voice)
return i18n("VoIP");
return i18n("SiP2");
}
if ((type & Car) == Car)
return i18n("Mobile2");
if ((type & Pager) == Pager)
return i18n("Pager");
if ((type & Isdn) == Isdn)
return i18n("ISDN");
if ((type & Video) == Video)
return i18n("Video");
if ((type & Msg) == Msg)
return i18n("Callback");
if ((type & Fax) == Fax)
return i18n("Fax (Other)");
if ((type & Pref) == Pref)
return i18n("Primary");
return i18n("Other");
#if 0
QString typeString;
if ((type & Cell) == Cell)
typeString += i18n("Mobile") +" ";
if ((type & Home) == Home)
typeString += i18n("Home")+" ";
else if ((type & Work) == Work)
typeString += i18n("Work")+" ";
if ((type & Sip) == Sip)
typeString += i18n("SIP")+" ";
if ((type & Car) == Car)
typeString += i18n("Car")+" ";
if ((type & Fax) == Fax)
typeString += i18n("Fax");
else if ((type & Msg) == Msg)
typeString += i18n("Messenger");
else if ((type & Video) == Video)
typeString += i18n("Video");
else if ((type & Bbs) == Bbs)
typeString += i18n("Mailbox");
else if ((type & Modem) == Modem)
typeString += i18n("Modem");
else if ((type & Isdn) == Isdn)
typeString += i18n("ISDN");
else if ((type & Pcs) == Pcs)
typeString += i18n("PCS");
else if ((type & Pager) == Pager)
typeString += i18n("Pager");
// add the prefered flag
/*
if ((type & Pref) == Pref)
typeString += i18n("(p)");
*/
//if we still have no match, return "other"
if (typeString.isEmpty()) {
if ((type & Voice) == Voice)
return i18n("Voice");
else
return i18n("Other");
}
return typeString.stripWhiteSpace();
#endif
}
QDataStream &KABC::operator<<( QDataStream &s, const PhoneNumber &phone )
{
return s << phone.mId << phone.mType << phone.mNumber;
}
QDataStream &KABC::operator>>( QDataStream &s, PhoneNumber &phone )
{
s >> phone.mId >> phone.mType >> phone.mNumber;
return s;
}
diff --git a/kaddressbook/kabcore.cpp b/kaddressbook/kabcore.cpp
index 7d8586a..ab2824c 100644
--- a/kaddressbook/kabcore.cpp
+++ b/kaddressbook/kabcore.cpp
@@ -1,3500 +1,3586 @@
/*
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.
Async 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.
*/
/*s
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
#include "kabcore.h"
#include <stdaddressbook.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <qtimer.h>
#include <qlabel.h>
#include <qregexp.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qpushbutton.h>
#include <qprogressbar.h>
#include <libkdepim/phoneaccess.h>
#ifndef KAB_EMBEDDED
#include <qclipboard.h>
#include <qdir.h>
#include <qfile.h>
#include <qapplicaton.h>
#include <qprogressbar.h>
#include <qlayout.h>
#include <qregexp.h>
#include <qvbox.h>
#include <kabc/addresseelist.h>
#include <kabc/errorhandler.h>
#include <kabc/resource.h>
#include <kabc/vcardconverter.h>
#include <kapplication.h>
#include <kactionclasses.h>
#include <kcmultidialog.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <kkeydialog.h>
#include <kmessagebox.h>
#include <kprinter.h>
#include <kprotocolinfo.h>
#include <kresources/selectdialog.h>
#include <kstandarddirs.h>
#include <ktempfile.h>
#include <kxmlguiclient.h>
#include <kaboutdata.h>
#include <libkdepim/categoryselectdialog.h>
#include "addresseeutil.h"
#include "addresseeeditordialog.h"
#include "extensionmanager.h"
#include "kstdaction.h"
#include "kaddressbookservice.h"
#include "ldapsearchdialog.h"
#include "printing/printingwizard.h"
#else // KAB_EMBEDDED
#include <kapplication.h>
#include "KDGanttMinimizeSplitter.h"
#include "kaddressbookmain.h"
#include "kactioncollection.h"
#include "addresseedialog.h"
//US
#include <addresseeview.h>
#include <qapp.h>
#include <qmenubar.h>
//#include <qtoolbar.h>
#include <qmessagebox.h>
#include <kdebug.h>
#include <kiconloader.h> // needed for SmallIcon
#include <kresources/kcmkresources.h>
#include <ktoolbar.h>
#include <kprefsdialog.h>
//#include <qlabel.h>
#ifndef DESKTOP_VERSION
#include <qpe/ir.h>
#include <qpe/qpemenubar.h>
#include <qtopia/qcopenvelope_qws.h>
#else
#include <qmenubar.h>
#endif
#endif // KAB_EMBEDDED
#include "kcmconfigs/kcmkabconfig.h"
#include "kcmconfigs/kcmkdepimconfig.h"
#include "kpimglobalprefs.h"
#include "externalapphandler.h"
#include "xxportselectdialog.h"
#include <kresources/selectdialog.h>
#include <kmessagebox.h>
#include <picture.h>
#include <resource.h>
//US#include <qsplitter.h>
#include <qmap.h>
#include <qdir.h>
#include <qfile.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qclipboard.h>
#include <qtextstream.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <libkdepim/categoryselectdialog.h>
#include <libkdepim/categoryeditdialog.h>
#include <kabc/vcardconverter.h>
#include "addresseeutil.h"
#include "undocmds.h"
#include "addresseeeditordialog.h"
#include "viewmanager.h"
#include "details/detailsviewcontainer.h"
#include "kabprefs.h"
#include "xxportmanager.h"
#include "incsearchwidget.h"
#include "jumpbuttonbar.h"
#include "extensionmanager.h"
#include "addresseeconfig.h"
#include "nameeditdialog.h"
#include <kcmultidialog.h>
#ifdef _WIN32_
#ifdef _OL_IMPORT_
#include "kaimportoldialog.h"
+#include <libkdepim/ol_access.h>
#endif
#else
#include <unistd.h>
#endif
// sync includes
#include <libkdepim/ksyncprofile.h>
#include <libkdepim/ksyncprefsdialog.h>
class KABCatPrefs : public QDialog
{
public:
KABCatPrefs( QWidget *parent=0, const char *name=0 ) :
QDialog( parent, name, true )
{
setCaption( i18n("Manage new Categories") );
QVBoxLayout* lay = new QVBoxLayout( this );
lay->setSpacing( 3 );
lay->setMargin( 3 );
QLabel * lab = new QLabel( i18n("After importing/loading/syncing\nthere may be new categories in\naddressees\nwhich are not in the category list.\nPlease choose what to do:\n "), this );
lay->addWidget( lab );
QButtonGroup* format = new QButtonGroup( 1, Horizontal, i18n("New categories not in list:"), this );
lay->addWidget( format );
format->setExclusive ( true ) ;
addCatBut = new QRadioButton(i18n("Add to category list"), format );
new QRadioButton(i18n("Remove from addressees"), format );
addCatBut->setChecked( true );
QPushButton * ok = new QPushButton( i18n("OK"), this );
lay->addWidget( ok );
QPushButton * cancel = new QPushButton( i18n("Cancel"), this );
lay->addWidget( cancel );
connect ( ok,SIGNAL(clicked() ),this , SLOT ( accept() ) );
connect (cancel, SIGNAL(clicked() ), this, SLOT ( reject()) );
resize( 200, 200 );
}
bool addCat() { return addCatBut->isChecked(); }
private:
QRadioButton* addCatBut;
};
class KABFormatPrefs : public QDialog
{
public:
KABFormatPrefs( QWidget *parent=0, const char *name=0 ) :
QDialog( parent, name, true )
{
setCaption( i18n("Set formatted name") );
QVBoxLayout* lay = new QVBoxLayout( this );
lay->setSpacing( 3 );
lay->setMargin( 3 );
QLabel * lab = new QLabel( i18n("You can set the formatted name\nfor a list of contacts in one go."), this );
lay->addWidget( lab );
QButtonGroup* format = new QButtonGroup( 1, Horizontal, i18n("Set formatted name to:"), this );
lay->addWidget( format );
format->setExclusive ( true ) ;
simple = new QRadioButton(i18n("Simple: James Bond"), format );
full = new QRadioButton(i18n("Full: Mr. James 007 Bond I"), format );
reverse = new QRadioButton(i18n("Reverse: Bond, James"), format );
company = new QRadioButton(i18n("Organization: MI6"), format );
simple->setChecked( true );
setCompany = new QCheckBox(i18n("Set formatted name to\norganization, if name empty"), this);
lay->addWidget( setCompany );
QPushButton * ok = new QPushButton( i18n("Select contact list"), this );
lay->addWidget( ok );
QPushButton * cancel = new QPushButton( i18n("Cancel"), this );
lay->addWidget( cancel );
connect ( ok,SIGNAL(clicked() ),this , SLOT ( accept() ) );
connect (cancel, SIGNAL(clicked() ), this, SLOT ( reject()) );
//resize( 200, 200 );
}
public:
QRadioButton* simple, *full, *reverse, *company;
QCheckBox* setCompany;
};
class KAex2phonePrefs : public QDialog
{
public:
KAex2phonePrefs( QWidget *parent=0, const char *name=0 ) :
QDialog( parent, name, true )
{
setCaption( i18n("Export to phone options") );
QVBoxLayout* lay = new QVBoxLayout( this );
lay->setSpacing( 3 );
lay->setMargin( 3 );
QLabel *lab;
lay->addWidget(lab = new QLabel( i18n("Please read Help-Sync Howto\nto know what settings to use."), this ) );
lab->setAlignment (AlignHCenter );
QHBox* temphb;
temphb = new QHBox( this );
new QLabel( i18n("I/O device: "), temphb );
mPhoneDevice = new QLineEdit( temphb);
lay->addWidget( temphb );
temphb = new QHBox( this );
new QLabel( i18n("Connection: "), temphb );
mPhoneConnection = new QLineEdit( temphb);
lay->addWidget( temphb );
temphb = new QHBox( this );
new QLabel( i18n("Model(opt.): "), temphb );
mPhoneModel = new QLineEdit( temphb);
lay->addWidget( temphb );
// mWriteToSim = new QCheckBox( i18n("Write Contacts to SIM card\n(if not, write to phone memory)"), this );
// lay->addWidget( mWriteToSim );
lay->addWidget(lab = new QLabel( i18n("NOTE: This will remove all old\ncontact data on phone!"), this ) );
lab->setAlignment (AlignHCenter);
QPushButton * ok = new QPushButton( i18n("Export to mobile phone!"), this );
lay->addWidget( ok );
QPushButton * cancel = new QPushButton( i18n("Cancel"), this );
lay->addWidget( cancel );
connect ( ok,SIGNAL(clicked() ),this , SLOT ( accept() ) );
connect (cancel, SIGNAL(clicked() ), this, SLOT ( reject()) );
resize( 220, 240 );
}
public:
QLineEdit* mPhoneConnection, *mPhoneDevice, *mPhoneModel;
QCheckBox* mWriteToSim;
};
bool pasteWithNewUid = true;
#ifdef KAB_EMBEDDED
KABCore::KABCore( KAddressBookMain *client, bool readWrite, QWidget *parent, const char *name )
: QWidget( parent, name ), KSyncInterface(), mGUIClient( client ), mViewManager( 0 ),
mExtensionManager( 0 ),mConfigureDialog( 0 ),/*US mLdapSearchDialog( 0 ),*/
mReadWrite( readWrite ), mModified( false ), mMainWindow(client)
#else //KAB_EMBEDDED
KABCore::KABCore( KXMLGUIClient *client, bool readWrite, QWidget *parent, const char *name )
: QWidget( parent, name ), KSyncInterface(), mGUIClient( client ), mViewManager( 0 ),
mExtensionManager( 0 ), mConfigureDialog( 0 ), mLdapSearchDialog( 0 ),
mReadWrite( readWrite ), mModified( false )
#endif //KAB_EMBEDDED
{
// syncManager = new KSyncManager((QWidget*)this, (KSyncInterface*)this, KSyncManager::KAPI, KABPrefs::instance(), syncMenu);
// syncManager->setBlockSave(false);
mIncSearchWidget = 0;
mMiniSplitter = 0;
mExtensionBarSplitter = 0;
mIsPart = !parent->inherits( "KAddressBookMain" );
mAddressBook = KABC::StdAddressBook::selfNoLoad();
KABC::StdAddressBook::setAutomaticSave( false );
#ifndef KAB_EMBEDDED
mAddressBook->setErrorHandler( new KABC::GUIErrorHandler );
#endif //KAB_EMBEDDED
connect( mAddressBook, SIGNAL( addressBookChanged( AddressBook * ) ),
SLOT( addressBookChanged() ) );
#if 0
// LR moved to addressbook init method
mAddressBook->addCustomField( i18n( "Department" ), KABC::Field::Organization,
"X-Department", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Profession" ), KABC::Field::Organization,
"X-Profession", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Assistant's Name" ), KABC::Field::Organization,
"X-AssistantsName", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Manager's Name" ), KABC::Field::Organization,
"X-ManagersName", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Spouse's Name" ), KABC::Field::Personal,
"X-SpousesName", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Office" ), KABC::Field::Personal,
"X-Office", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "IM Address" ), KABC::Field::Personal,
"X-IMAddress", "KADDRESSBOOK" );
mAddressBook->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.
mAddressBook->addCustomField( i18n( "Gender" ), KABC::Field::Personal,
"X-Gender", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "Children" ), KABC::Field::Personal,
"X-Children", "KADDRESSBOOK" );
mAddressBook->addCustomField( i18n( "FreeBusyUrl" ), KABC::Field::Personal,
"X-FreeBusyUrl", "KADDRESSBOOK" );
#endif
initGUI();
mIncSearchWidget->setFocus();
connect( mViewManager, SIGNAL( selected( const QString& ) ),
SLOT( setContactSelected( const QString& ) ) );
connect( mViewManager, SIGNAL( executed( const QString& ) ),
SLOT( executeContact( const QString& ) ) );
connect( mViewManager, SIGNAL( deleteRequest( ) ),
SLOT( deleteContacts( ) ) );
connect( mViewManager, SIGNAL( modified() ),
SLOT( setModified() ) );
connect( mExtensionManager, SIGNAL( modified( const KABC::Addressee::List& ) ), this, SLOT( extensionModified( const KABC::Addressee::List& ) ) );
connect( mExtensionManager, SIGNAL( changedActiveExtension( int ) ), this, SLOT( extensionChanged( int ) ) );
connect( mXXPortManager, SIGNAL( modified() ),
SLOT( setModified() ) );
connect( mJumpButtonBar, SIGNAL( jumpToLetter( const QString& ) ),
SLOT( incrementalSearchJump( const QString& ) ) );
connect( mIncSearchWidget, SIGNAL( fieldChanged() ),
mJumpButtonBar, SLOT( recreateButtons() ) );
connect( mDetails, SIGNAL( sendEmail( const QString& ) ),
SLOT( sendMail( const QString& ) ) );
connect( ExternalAppHandler::instance(), SIGNAL (requestForNameEmailUidList(const QString&, const QString&)),this, SLOT(requestForNameEmailUidList(const QString&, const QString&)));
connect( ExternalAppHandler::instance(), SIGNAL (requestForDetails(const QString&, const QString&, const QString&, const QString&, const QString&)),this, SLOT(requestForDetails(const QString&, const QString&, const QString&, const QString&, const QString&)));
connect( ExternalAppHandler::instance(), SIGNAL (requestForBirthdayList(const QString&, const QString&)),this, SLOT(requestForBirthdayList(const QString&, const QString&)));
connect( ExternalAppHandler::instance(), SIGNAL (nextView()),this, SLOT(setDetailsToggle()));
connect( ExternalAppHandler::instance(), SIGNAL (doRingSync()),this, SLOT( doRingSync()));
connect( ExternalAppHandler::instance(), SIGNAL (callContactdialog()),this, SLOT(callContactdialog()));
#ifndef KAB_EMBEDDED
connect( mViewManager, SIGNAL( urlDropped( const KURL& ) ),
mXXPortManager, SLOT( importVCard( const KURL& ) ) );
connect( mDetails, SIGNAL( browse( const QString& ) ),
SLOT( browse( const QString& ) ) );
mAddressBookService = new KAddressBookService( this );
#endif //KAB_EMBEDDED
mMessageTimer = new QTimer( this );
connect( mMessageTimer, SIGNAL( timeout() ), this, SLOT( setCaptionBack() ) );
mEditorDialog = 0;
createAddresseeEditorDialog( this );
setModified( false );
mBRdisabled = false;
#ifndef DESKTOP_VERSION
infrared = 0;
#endif
//toggleBeamReceive( );
mMainWindow->toolBar()->show();
// we have a toolbar repainting error on the Zaurus when starting KA/Pi
//QTimer::singleShot( 10, this , SLOT ( updateToolBar()));
QTimer::singleShot( 100, this, SLOT ( loadDataAfterStart() ));
}
void KABCore::receiveStart( const QCString& cmsg, const QByteArray& data )
{
//qDebug("KO: QCOP start message received: %s ", cmsg.data() );
mCStringMess = cmsg;
mByteData = data;
}
void KABCore::loadDataAfterStart()
{
//qDebug("KABCore::loadDataAfterStart() ");
((StdAddressBook*)mAddressBook)->init( true );
mViewManager->refreshView();
#ifndef DESKTOP_VERSION
disconnect(qApp, SIGNAL (appMessage ( const QCString &, const QByteArray & )), this, SLOT (receiveStart ( const QCString &, const QByteArray & )));
QObject::connect(qApp, SIGNAL (appMessage ( const QCString &, const QByteArray & )), ExternalAppHandler::instance(), SLOT (appMessage ( const QCString &, const QByteArray & )));
if ( !mCStringMess.isEmpty() )
ExternalAppHandler::instance()->appMessage( mCStringMess, mByteData );
#endif
// QTimer::singleShot( 10, this , SLOT ( updateToolBar()));
setCaptionBack();
}
void KABCore::updateToolBar()
{
static int iii = 0;
++iii;
mMainWindow->toolBar()->repaintMe();
if ( iii < 4 )
QTimer::singleShot( 100*iii, this , SLOT ( updateToolBar()));
}
KABCore::~KABCore()
{
// save();
//saveSettings();
//KABPrefs::instance()->writeConfig();
delete AddresseeConfig::instance();
mAddressBook = 0;
KABC::StdAddressBook::close();
delete syncManager;
#ifndef DESKTOP_VERSION
if ( infrared )
delete infrared;
#endif
}
void KABCore::receive( const QCString& cmsg, const QByteArray& data )
{
//qDebug("KA: QCOP message received: %s ", cmsg.data() );
if ( cmsg == "setDocument(QString)" ) {
QDataStream stream( data, IO_ReadOnly );
QString fileName;
stream >> fileName;
recieve( fileName );
return;
}
}
void KABCore::toggleBeamReceive( )
{
if ( mBRdisabled )
return;
#ifndef DESKTOP_VERSION
if ( infrared ) {
qDebug("KA: AB disable BeamReceive ");
delete infrared;
infrared = 0;
mActionBR->setChecked(false);
return;
}
qDebug("KA: AB enable BeamReceive ");
mActionBR->setChecked(true);
infrared = new QCopChannel("QPE/Application/addressbook",this, "channelAB" ) ;
QObject::connect( infrared, SIGNAL (received ( const QCString &, const QByteArray & )),this, SLOT(receive( const QCString&, const QByteArray& )));
#endif
}
void KABCore::disableBR(bool b)
{
#ifndef DESKTOP_VERSION
if ( b ) {
if ( infrared ) {
toggleBeamReceive( );
}
mBRdisabled = true;
} else {
if ( mBRdisabled ) {
mBRdisabled = false;
//toggleBeamReceive( );
}
}
#endif
}
void KABCore::recieve( QString fn )
{
//qDebug("KABCore::recieve ");
int count = mAddressBook->importFromFile( fn, true );
if ( count )
setModified( true );
mViewManager->refreshView();
message(i18n("%1 contact(s) received!").arg( count ));
topLevelWidget()->showMaximized();
topLevelWidget()->raise();
}
void KABCore::restoreSettings()
{
mMultipleViewsAtOnce = KABPrefs::instance()->mMultipleViewsAtOnce;
bool state;
if (mMultipleViewsAtOnce)
state = KABPrefs::instance()->mDetailsPageVisible;
else
state = false;
mActionDetails->setChecked( state );
setDetailsVisible( state );
state = KABPrefs::instance()->mJumpButtonBarVisible;
mActionJumpBar->setChecked( state );
setJumpButtonBarVisible( state );
/*US
QValueList<int> splitterSize = KABPrefs::instance()->mDetailsSplitter;
if ( splitterSize.count() == 0 ) {
splitterSize.append( width() / 2 );
splitterSize.append( width() / 2 );
}
mMiniSplitter->setSizes( splitterSize );
if ( mExtensionBarSplitter ) {
splitterSize = KABPrefs::instance()->mExtensionsSplitter;
if ( splitterSize.count() == 0 ) {
splitterSize.append( width() / 2 );
splitterSize.append( width() / 2 );
}
mExtensionBarSplitter->setSizes( splitterSize );
}
*/
mViewManager->restoreSettings();
mIncSearchWidget->setCurrentItem( KABPrefs::instance()->mCurrentIncSearchField );
mExtensionManager->restoreSettings();
#ifdef DESKTOP_VERSION
int wid = width();
if ( wid < 10 )
wid = 400;
#else
int wid = QApplication::desktop()->width();
if ( wid < 640 )
wid = QApplication::desktop()->height();
#endif
QValueList<int> splitterSize;// = KABPrefs::instance()->mDetailsSplitter;
if ( true /*splitterSize.count() == 0*/ ) {
splitterSize.append( wid / 2 );
splitterSize.append( wid / 2 );
}
mMiniSplitter->setSizes( splitterSize );
if ( mExtensionBarSplitter ) {
//splitterSize = KABPrefs::instance()->mExtensionsSplitter;
if ( true /*splitterSize.count() == 0*/ ) {
splitterSize.append( wid / 2 );
splitterSize.append( wid / 2 );
}
mExtensionBarSplitter->setSizes( splitterSize );
}
#ifdef DESKTOP_VERSION
KConfig *config = KABPrefs::instance()->getConfig();
config->setGroup("WidgetLayout");
QStringList list;
list = config->readListEntry("MainLayout");
int x,y,w,h;
if ( ! list.isEmpty() ) {
x = list[0].toInt();
y = list[1].toInt();
w = list[2].toInt();
h = list[3].toInt();
KApplication::testCoords( &x,&y,&w,&h );
topLevelWidget()->setGeometry(x,y,w,h);
} else {
topLevelWidget()->setGeometry( 40 ,40 , 640, 440);
}
#endif
}
void KABCore::saveSettings()
{
KABPrefs::instance()->mJumpButtonBarVisible = mActionJumpBar->isChecked();
if ( mExtensionBarSplitter )
KABPrefs::instance()->mExtensionsSplitter = mExtensionBarSplitter->sizes();
KABPrefs::instance()->mDetailsPageVisible = mActionDetails->isChecked();
KABPrefs::instance()->mDetailsSplitter = mMiniSplitter->sizes();
#ifndef KAB_EMBEDDED
KABPrefs::instance()->mExtensionsSplitter = mExtensionBarSplitter->sizes();
KABPrefs::instance()->mDetailsSplitter = mDetailsSplitter->sizes();
#endif //KAB_EMBEDDED
mExtensionManager->saveSettings();
mViewManager->saveSettings();
KABPrefs::instance()->mCurrentIncSearchField = mIncSearchWidget->currentItem();
KABPrefs::instance()->writeConfig();
//qDebug("KA: KABCore::saveSettings() ");
}
KABC::AddressBook *KABCore::addressBook() const
{
return mAddressBook;
}
KConfig *KABCore::config()
{
#ifndef KAB_EMBEDDED
return KABPrefs::instance()->config();
#else //KAB_EMBEDDED
return KABPrefs::instance()->getConfig();
#endif //KAB_EMBEDDED
}
KActionCollection *KABCore::actionCollection() const
{
return mGUIClient->actionCollection();
}
KABC::Field *KABCore::currentSearchField() const
{
if (mIncSearchWidget)
return mIncSearchWidget->currentField();
else
return 0;
}
QStringList KABCore::selectedUIDs() const
{
return mViewManager->selectedUids();
}
KABC::Resource *KABCore::requestResource( QWidget *parent )
{
QPtrList<KABC::Resource> kabcResources = addressBook()->resources();
QPtrList<KRES::Resource> kresResources;
QPtrListIterator<KABC::Resource> resIt( kabcResources );
KABC::Resource *resource;
while ( ( resource = resIt.current() ) != 0 ) {
++resIt;
if ( !resource->readOnly() ) {
KRES::Resource *res = static_cast<KRES::Resource*>( resource );
if ( res )
kresResources.append( res );
}
}
KRES::Resource *res = KRES::SelectDialog::getResource( kresResources, parent );
return static_cast<KABC::Resource*>( res );
}
#ifndef KAB_EMBEDDED
KAboutData *KABCore::createAboutData()
#else //KAB_EMBEDDED
void KABCore::createAboutData()
#endif //KAB_EMBEDDED
{
QString version;
#include <../version>
QMessageBox::about( this, "About KAddressbook/Pi",
"KAddressbook/Platform-independent\n"
"(KA/Pi) " +version + " - " +
#ifdef DESKTOP_VERSION
"Desktop Edition\n"
#else
"PDA-Edition\n"
"for: Zaurus 5500 / 7x0 / 8x0\n"
#endif
"(c) 2004 Ulf Schenk\n"
"(c) 2004-2005 Lutz Rogowski\nrogowski@kde.org\n"
"(c) 1997-2003, The KDE PIM Team\n"
"Tobias Koenig Maintainer\n"
"Don Sanders Original author\n"
"Cornelius Schumacher Co-maintainer\n"
"Mike Pilone GUI and framework redesign\n"
"Greg Stern DCOP interface\n"
"Mark Westcot Contact pinning\n"
"Michel Boyer de la Giroday LDAP Lookup\n"
"Steffen Hansen LDAP Lookup"
#ifdef _WIN32_
"(c) 2004 Lutz Rogowski Import from OL\nrogowski@kde.org\n"
#endif
);
}
void KABCore::setContactSelected( const QString &uid )
{
KABC::Addressee addr = mAddressBook->findByUid( uid );
if ( !mDetails->isHidden() )
mDetails->setAddressee( addr );
if ( !addr.isEmpty() ) {
emit contactSelected( addr.formattedName() );
KABC::Picture pic = addr.photo();
if ( pic.isIntern() ) {
//US emit contactSelected( pic.data() );
//US instead use:
QPixmap px;
if (pic.data().isNull() != true)
{
px.convertFromImage(pic.data());
}
emit contactSelected( px );
}
}
mExtensionManager->setSelectionChanged();
// update the actions
bool selected = !uid.isEmpty();
if ( mReadWrite ) {
mActionCut->setEnabled( selected );
mActionPaste->setEnabled( selected );
}
mActionCopy->setEnabled( selected );
mActionDelete->setEnabled( selected );
mActionEditAddressee->setEnabled( selected );
mActionMail->setEnabled( selected );
mActionMailVCard->setEnabled( selected );
//if (mActionBeam)
//mActionBeam->setEnabled( selected );
mActionWhoAmI->setEnabled( selected );
}
void KABCore::sendMail()
{
sendMail( mViewManager->selectedEmails().join( ", " ) );
}
void KABCore::sendMail( const QString& emaillist )
{
// the parameter has the form "name1 <abc@aol.com>,name2 <abc@aol.com>;... "
if (emaillist.contains(",") > 0)
ExternalAppHandler::instance()->mailToMultipleContacts( emaillist, QString::null );
else
ExternalAppHandler::instance()->mailToOneContact( emaillist );
}
void KABCore::mailVCard()
{
QStringList uids = mViewManager->selectedUids();
if ( !uids.isEmpty() )
mailVCard( uids );
}
void KABCore::mailVCard( const QStringList& uids )
{
QStringList urls;
// QString tmpdir = locateLocal("tmp", KGlobal::getAppName());
QString dirName = "/tmp/" + KApplication::randomString( 8 );
QDir().mkdir( dirName, true );
for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) {
KABC::Addressee a = mAddressBook->findByUid( *it );
if ( a.isEmpty() )
continue;
QString name = a.givenName() + "_" + a.familyName() + ".vcf";
QString fileName = dirName + "/" + name;
QFile outFile(fileName);
if ( outFile.open(IO_WriteOnly) ) { // file opened successfully
KABC::VCardConverter converter;
QString vcard;
converter.addresseeToVCard( a, vcard );
QTextStream t( &outFile ); // use a text stream
t.setEncoding( QTextStream::UnicodeUTF8 );
t << vcard;
outFile.close();
urls.append( fileName );
}
}
bool result = ExternalAppHandler::instance()->mailToMultipleContacts( QString::null, urls.join(", ") );
/*US
kapp->invokeMailer( QString::null, QString::null, QString::null,
QString::null, // subject
QString::null, // body
QString::null,
urls ); // attachments
*/
}
/**
Beams the "WhoAmI contact.
*/
void KABCore::beamMySelf()
{
KABC::Addressee a = KABC::StdAddressBook::self()->whoAmI();
if (!a.isEmpty())
{
QStringList uids;
uids << a.uid();
beamVCard(uids);
} else {
KMessageBox::information( this, i18n( "Your personal contact is\nnot set! Please select it\nand set it with menu:\nSettings - Set Who Am I\n" ) );
}
}
void KABCore::updateMainWindow()
{
mMainWindow->showMaximized();
//mMainWindow->repaint();
}
void KABCore::resizeEvent(QResizeEvent* e )
{
if ( !mMiniSplitter ) {
QWidget::resizeEvent( e );
return;
}
#ifndef DESKTOP_VERSION
static int desktop_width = 0;
//qDebug("KABCore::resizeEvent %d %d ",desktop_width,QApplication::desktop()->width() );
if ( desktop_width != QApplication::desktop()->width() )
if ( QApplication::desktop()->width() >= 480 ) {
if (QApplication::desktop()->width() == 640 ) { // e.g. 640x480
//qDebug("640 ");
if ( mMiniSplitter->orientation() == Qt::Vertical ) {
//qDebug("switch V->H ");
mMiniSplitter->setOrientation( Qt::Horizontal);
mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Right );
}
if ( QApplication::desktop()->width() <= 640 ) {
bool shot = mMainWindow->isVisible();
mMainWindow->showMinimized();
//mMainWindow->setMaximumSize( QApplication::desktop()->size() );
mViewManager->getFilterAction()->setComboWidth( 150 );
if ( mIncSearchWidget )
mIncSearchWidget->setSize();
if ( shot )
QTimer::singleShot( 1, this , SLOT ( updateMainWindow()));
}
} else if (QApplication::desktop()->width() == 480 ){// e.g. 480x640
//qDebug("480 ");
if ( mMiniSplitter->orientation() == Qt::Horizontal ) {
//qDebug("switch H->V ");
mMiniSplitter->setOrientation( Qt::Vertical );
mMiniSplitter->setMinimizeDirection ( KDGanttMinimizeSplitter::Down );
}
if ( QApplication::desktop()->width() <= 640 ) {
//mMainWindow->setMaximumSize( QApplication::desktop()->size() );
bool shot = mMainWindow->isVisible();
mMainWindow->showMinimized();
if ( KABPrefs::instance()->mHideSearchOnSwitch ) {
if ( mIncSearchWidget ) {
mIncSearchWidget->setSize();
}
} else {
mViewManager->getFilterAction()->setComboWidth( 0 );
}
if ( shot )
QTimer::singleShot( 1, this , SLOT ( updateMainWindow()));
}
}
}
desktop_width = QApplication::desktop()->width();
#endif
QWidget::resizeEvent( e );
}
void KABCore::export2phone()
{
QStringList uids;
XXPortSelectDialog dlg( this, false, this );
if ( dlg.exec() )
uids = dlg.uids();
else
return;
if ( uids.isEmpty() )
return;
// qDebug("count %d ", uids.count());
KAex2phonePrefs ex2phone;
ex2phone.mPhoneConnection->setText( KPimGlobalPrefs::instance()->mEx2PhoneConnection );
ex2phone.mPhoneDevice->setText( KPimGlobalPrefs::instance()->mEx2PhoneDevice );
ex2phone.mPhoneModel->setText( KPimGlobalPrefs::instance()->mEx2PhoneModel );
if ( !ex2phone.exec() ) {
return;
}
KPimGlobalPrefs::instance()->mEx2PhoneConnection = ex2phone.mPhoneConnection->text();
KPimGlobalPrefs::instance()->mEx2PhoneDevice = ex2phone.mPhoneDevice->text();
KPimGlobalPrefs::instance()->mEx2PhoneModel = ex2phone.mPhoneModel->text();
PhoneAccess::writeConfig( KPimGlobalPrefs::instance()->mEx2PhoneDevice,
KPimGlobalPrefs::instance()->mEx2PhoneConnection,
KPimGlobalPrefs::instance()->mEx2PhoneModel );
QString fileName = getPhoneFile();
if ( ! mAddressBook->export2PhoneFormat( uids ,fileName ) )
return;
message(i18n("Exporting to phone..."));
QTimer::singleShot( 1, this , SLOT ( writeToPhone()));
}
QString KABCore::getPhoneFile()
{
#ifdef DESKTOP_VERSION
return locateLocal("tmp", "phonefile.vcf");
#else
return "/tmp/phonefile.vcf";
#endif
}
void KABCore::writeToPhone( )
{
if ( PhoneAccess::writeToPhone( getPhoneFile() ) )
message(i18n("Export to phone finished!"));
else
qDebug(i18n("KA: Error exporting to phone"));
}
void KABCore::beamVCard()
{
QStringList uids;
XXPortSelectDialog dlg( this, false, this );
if ( dlg.exec() )
uids = dlg.uids();
else
return;
if ( uids.isEmpty() )
return;
beamVCard( uids );
}
void KABCore::beamVCard(const QStringList& uids)
{
// LR: we should use the /tmp dir on the Zaurus,
// because: /tmp = RAM, (HOME)/kdepim = flash memory
#ifdef DESKTOP_VERSION
QString fileName = locateLocal("tmp", "kapibeamfile.vcf");
#else
QString fileName = "/tmp/kapibeamfile.vcf";
#endif
KABC::VCardConverter converter;
QString description;
QString datastream;
for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) {
KABC::Addressee a = mAddressBook->findByUid( *it );
if ( a.isEmpty() )
continue;
if (description.isEmpty())
description = a.formattedName();
QString vcard;
converter.addresseeToVCard( a, vcard );
int start = 0;
int next;
while ( (next = vcard.find("TYPE=", start) )>= 0 ) {
int semi = vcard.find(";", next);
int dopp = vcard.find(":", next);
int sep;
if ( semi < dopp && semi >= 0 )
sep = semi ;
else
sep = dopp;
datastream +=vcard.mid( start, next - start);
datastream +=vcard.mid( next+5,sep -next -5 ).upper();
start = sep;
}
datastream += vcard.mid( start,vcard.length() );
}
#ifndef DESKTOP_VERSION
QFile outFile(fileName);
if ( outFile.open(IO_WriteOnly) ) {
datastream.replace ( QRegExp("VERSION:3.0") , "VERSION:2.1" );
QTextStream t( &outFile ); // use a text stream
//t.setEncoding( QTextStream::UnicodeUTF8 );
t.setEncoding( QTextStream::Latin1 );
t <<datastream.latin1();
outFile.close();
Ir *ir = new Ir( this );
connect( ir, SIGNAL( done(Ir*) ), this, SLOT( beamDone(Ir*) ) );
ir->send( fileName, description, "text/x-vCard" );
} else {
qDebug("KA: Error open temp beam file ");
return;
}
#endif
}
void KABCore::beamDone( Ir *ir )
{
#ifndef DESKTOP_VERSION
delete ir;
#endif
topLevelWidget()->raise();
message( i18n("Beaming finished!") );
}
void KABCore::browse( const QString& url )
{
#ifndef KAB_EMBEDDED
kapp->invokeBrowser( url );
#else //KAB_EMBEDDED
qDebug("KABCore::browse must be fixed");
#endif //KAB_EMBEDDED
}
void KABCore::selectAllContacts()
{
mViewManager->setSelected( QString::null, true );
}
void KABCore::deleteContacts()
{
QStringList uidList = mViewManager->selectedUids();
deleteContacts( uidList );
}
void KABCore::deleteContacts( const QStringList &uids )
{
if ( uids.count() > 0 ) {
if ( KABPrefs::instance()->mAskForDelete ) {
int count = uids.count();
if ( count > 5 ) count = 5;
QString cNames;
int i;
for ( i = 0; i < count ; ++i ) {
cNames += KGlobal::formatMessage( mAddressBook->findByUid( uids[i] ).realName() ,0) + "\n";
}
if ( uids.count() > 5 )
cNames += i18n("...and %1 more\ncontact(s) selected").arg( uids.count() - 5 );
QString text = i18n( "Do you really\nwant to delete the\nsetected contact(s)?\n\n" ) + cNames ;
if ( KMessageBox::questionYesNo( this, text ) != KMessageBox::Yes )
return;
}
PwDeleteCommand *command = new PwDeleteCommand( mAddressBook, uids );
UndoStack::instance()->push( command );
RedoStack::instance()->clear();
// now if we deleted anything, refresh
setContactSelected( QString::null );
setModified( true );
}
}
void KABCore::copyContacts()
{
KABC::Addressee::List addrList = mViewManager->selectedAddressees();
QString clipText = AddresseeUtil::addresseesToClipboard( addrList );
kdDebug(5720) << "KABCore::copyContacts: " << clipText << endl;
QClipboard *cb = QApplication::clipboard();
cb->setText( clipText );
}
void KABCore::cutContacts()
{
QStringList uidList = mViewManager->selectedUids();
//US if ( uidList.size() > 0 ) {
if ( uidList.count() > 0 ) {
PwCutCommand *command = new PwCutCommand( mAddressBook, uidList );
UndoStack::instance()->push( command );
RedoStack::instance()->clear();
setModified( true );
}
}
void KABCore::pasteContacts()
{
QClipboard *cb = QApplication::clipboard();
KABC::Addressee::List list = AddresseeUtil::clipboardToAddressees( cb->text() );
pasteContacts( list );
}
void KABCore::pasteContacts( KABC::Addressee::List &list )
{
KABC::Resource *resource = requestResource( this );
KABC::Addressee::List::Iterator it;
for ( it = list.begin(); it != list.end(); ++it )
(*it).setResource( resource );
PwPasteCommand *command = new PwPasteCommand( this, list );
UndoStack::instance()->push( command );
RedoStack::instance()->clear();
setModified( true );
}
void KABCore::setWhoAmI()
{
KABC::Addressee::List addrList = mViewManager->selectedAddressees();
if ( addrList.count() > 1 ) {
KMessageBox::sorry( this, i18n( "Please select only one contact." ) );
return;
}
QString text( i18n( "<qt>Do you really want to use <b>%1</b> as your new personal contact?</qt>" ) );
if ( KMessageBox::questionYesNo( this, text.arg( addrList[ 0 ].realName() ) ) == KMessageBox::Yes )
static_cast<KABC::StdAddressBook*>( KABC::StdAddressBook::self() )->setWhoAmI( addrList[ 0 ] );
}
void KABCore::editCategories()
{
KPIM::CategoryEditDialog dlg ( KABPrefs::instance(), this, "", true );
dlg.exec();
}
void KABCore::setCategories()
{
QStringList uids;
XXPortSelectDialog dlgx( this, false, this );
if ( dlgx.exec() )
uids = dlgx.uids();
else
return;
if ( uids.isEmpty() )
return;
// qDebug("count %d ", uids.count());
KPIM::CategorySelectDialog dlg( KABPrefs::instance(), this, "", true );
if ( !dlg.exec() ) {
message( i18n("Setting categories cancelled") );
return;
}
bool merge = false;
QString msg = i18n( "Merge with existing categories?" );
if ( KMessageBox::questionYesNo( this, msg ) == KMessageBox::Yes )
merge = true;
message( i18n("Setting categories ... please wait!") );
QStringList categories = dlg.selectedCategories();
//QStringList uids = mViewManager->selectedUids();
QStringList::Iterator it;
for ( it = uids.begin(); it != uids.end(); ++it ) {
KABC::Addressee addr = mAddressBook->findByUid( *it );
if ( !addr.isEmpty() ) {
if ( !merge )
addr.setCategories( categories );
else {
QStringList addrCategories = addr.categories();
QStringList::Iterator catIt;
for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) {
if ( !addrCategories.contains( *catIt ) )
addrCategories.append( *catIt );
}
addr.setCategories( addrCategories );
}
mAddressBook->insertAddressee( addr );
}
}
if ( uids.count() > 0 )
setModified( true );
message( i18n("Setting categories completed!") );
}
void KABCore::setSearchFields( const KABC::Field::List &fields )
{
mIncSearchWidget->setFields( fields );
}
void KABCore::incrementalSearch( const QString& text )
{
QString stext;
if ( KABPrefs::instance()->mAutoSearchWithWildcard ) {
stext = "*" + text;
} else {
stext = text;
}
mViewManager->doSearch( stext, mIncSearchWidget->currentField() );
}
void KABCore::incrementalSearchJump( const QString& text )
{
mViewManager->doSearch( text, mIncSearchWidget->currentField() );
}
void KABCore::setModified()
{
setModified( true );
}
void KABCore::setModifiedWOrefresh()
{
// qDebug("KABCore::setModifiedWOrefresh() ");
mModified = true;
mActionSave->setEnabled( mModified );
}
void KABCore::setModified( bool modified )
{
mModified = modified;
mActionSave->setEnabled( mModified );
if ( modified )
mJumpButtonBar->recreateButtons();
mViewManager->refreshView();
}
bool KABCore::modified() const
{
return mModified;
}
void KABCore::contactModified( const KABC::Addressee &addr )
{
addrModified( addr );
#if 0 // debug only
KABC::Addressee ad = addr;
ad.computeCsum( "123");
#endif
}
void KABCore::addrModified( const KABC::Addressee &addr ,bool updateDetails )
{
Command *command = 0;
QString uid;
// check if it exists already
KABC::Addressee origAddr = mAddressBook->findByUid( addr.uid() );
if ( origAddr.isEmpty() )
command = new PwNewCommand( mAddressBook, addr );
else {
command = new PwEditCommand( mAddressBook, origAddr, addr );
uid = addr.uid();
}
UndoStack::instance()->push( command );
RedoStack::instance()->clear();
if ( updateDetails )
mDetails->setAddressee( addr );
setModified( true );
}
void KABCore::newContact()
{
QPtrList<KABC::Resource> kabcResources = mAddressBook->resources();
QPtrList<KRES::Resource> kresResources;
QPtrListIterator<KABC::Resource> it( kabcResources );
KABC::Resource *resource;
while ( ( resource = it.current() ) != 0 ) {
++it;
if ( !resource->readOnly() ) {
KRES::Resource *res = static_cast<KRES::Resource*>( resource );
if ( res )
kresResources.append( res );
}
}
KRES::Resource *res = KRES::SelectDialog::getResource( kresResources, this );
resource = static_cast<KABC::Resource*>( res );
if ( resource ) {
KABC::Addressee addr;
addr.setResource( resource );
mEditorDialog->setAddressee( addr );
mEditorDialog->setCaption( i18n("Edit new contact"));
KApplication::execDialog ( mEditorDialog );
} else
return;
// mEditorDict.insert( dialog->addressee().uid(), dialog );
}
void KABCore::addEmail( QString aStr )
{
#ifndef KAB_EMBEDDED
QString fullName, email;
KABC::Addressee::parseEmailAddress( aStr, fullName, email );
// Try to lookup the addressee matching the email address
bool found = false;
QStringList emailList;
KABC::AddressBook::Iterator it;
for ( it = mAddressBook->begin(); !found && (it != mAddressBook->end()); ++it ) {
emailList = (*it).emails();
if ( emailList.contains( email ) > 0 ) {
found = true;
(*it).setNameFromString( fullName );
editContact( (*it).uid() );
}
}
if ( !found ) {
KABC::Addressee addr;
addr.setNameFromString( fullName );
addr.insertEmail( email, true );
mAddressBook->insertAddressee( addr );
mViewManager->refreshView( addr.uid() );
editContact( addr.uid() );
}
#else //KAB_EMBEDDED
qDebug("KABCore::addEmail finsih method");
#endif //KAB_EMBEDDED
}
void KABCore::importVCard( const KURL &url, bool showPreview )
{
mXXPortManager->importVCard( url, showPreview );
}
void KABCore::importFromOL()
{
#ifdef _OL_IMPORT_
- KAImportOLdialog* idgl = new KAImportOLdialog( i18n("Import Contacts from OL"), mAddressBook, this );
- idgl->exec();
- KABC::Addressee::List list = idgl->getAddressList();
- if ( list.count() > 0 ) {
- KABC::Addressee::List listNew;
- KABC::Addressee::List listExisting;
- KABC::Addressee::List::Iterator it;
- KABC::AddressBook::Iterator iter;
- for ( it = list.begin(); it != list.end(); ++it ) {
- if ( mAddressBook->findByUid((*it).uid() ).isEmpty())
- listNew.append( (*it) );
- else
- listExisting.append( (*it) );
- }
- if ( listExisting.count() > 0 )
- KMessageBox::information( this, i18n("%1 contacts not added to addressbook\nbecause they were already in the addressbook!").arg( listExisting.count() ));
- if ( listNew.count() > 0 ) {
- pasteWithNewUid = false;
- pasteContacts( listNew );
- pasteWithNewUid = true;
+ KABC::Addressee::List list = OL_access::instance()->importOLcontacts();
+ if ( list.count() > 0 ) {
+ KABC::Addressee::List listNew;
+ KABC::Addressee::List listExisting;
+ KABC::Addressee::List::Iterator it;
+ KABC::AddressBook::Iterator iter;
+ for ( it = list.begin(); it != list.end(); ++it ) {
+ if ( mAddressBook->findByUid((*it).uid() ).isEmpty())
+ listNew.append( (*it) );
+ else
+ listExisting.append( (*it) );
+ }
+ QString mess = i18n("%1 contacts read from OL.\n\n%2 contacts added to addressbook!").arg( list.count()).arg( listNew.count() );
+ if ( listExisting.count() > 0 )
+ mess += "\n\n"+ i18n("%1 contacts not added to addressbook\nbecause they were already in the addressbook!").arg( listExisting.count() );
+
+ KMessageBox::information( this, mess );
+ if ( listNew.count() > 0 ) {
+ pasteWithNewUid = false;
+ pasteContacts( listNew );
+ pasteWithNewUid = true;
+ }
}
- }
- delete idgl;
#endif
}
+bool KABCore::readOLdata( KABC::AddressBook* local )
+{
+#ifdef _OL_IMPORT_
+ QStringList folderList = OL_access::instance()->getFolderSelection( OL_CONTACT_DATA , i18n("Select Folder to sync"));
+ KABC::Addressee::List list;
+ if ( folderList.count() ) {
+ OL_access::instance()->readContactData( OL_access::instance()->getFolderFromID( 0, folderList[1] ) , &list, true );
+ KABC::Addressee::List::Iterator it;
+ for ( it = list.begin(); it != list.end(); ++it ) {
+ (*it).setExternalUID( (*it).uid() );
+ (*it).setOriginalExternalUID( (*it).uid() );
+ (*it).setTempSyncStat( SYNC_TEMPSTATE_NEW_EXTERNAL );
+ local->insertAddressee( (*it) , false, false );
+ }
+ mOLsyncFolderID = folderList[1];
+ //KMessageBox::information( this, i18n("OLsync folder ID ") + mOLsyncFolderID );
+ }
+ return list.count() > 0;
+#else
+ return false;
+#endif
+}
+bool KABCore::writeOLdata( KABC::AddressBook* aBook )
+{
+#ifdef _OL_IMPORT_
+ if ( !OL_access::instance()->setSelectedFolder( mOLsyncFolderID ) )
+ return false;
+ KABC::AddressBook::Iterator it;
+ for ( it = aBook->begin(); it != aBook->end(); ++it ) {
+ if ( (*it).tempSyncStat() != SYNC_TEMPSTATE_NEW_EXTERNAL ) {
+ KABC::Addressee addressee = (*it);
+ if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_ADDED_EXTERNAL ) {
+ (*it) = OL_access::instance()->addAddressee( (*it) );
+ (*it).setTempSyncStat( SYNC_TEMPSTATE_NEW_ID );
+ } else if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_DELETE ) {
+ OL_access::instance()->deleteAddressee( (*it) );
+ } else if ( (*it).tempSyncStat() != SYNC_TEMPSTATE_NEW_EXTERNAL ) {
+ //changed
+ (*it) = OL_access::instance()->changeAddressee( (*it) );
+ (*it).setTempSyncStat( SYNC_TEMPSTATE_NEW_CSUM );
+ }
+ }
+ }
+ return true;
+#else
+ return false;
+#endif
+}
void KABCore::importVCard( const QString &vCard, bool showPreview )
{
mXXPortManager->importVCard( vCard, showPreview );
}
//US added a second method without defaultparameter
void KABCore::editContact2() {
editContact( QString::null );
}
void KABCore::editContact( const QString &uid )
{
if ( mExtensionManager->isQuickEditVisible() )
return;
// First, locate the contact entry
QString localUID = uid;
if ( localUID.isNull() ) {
QStringList uidList = mViewManager->selectedUids();
if ( uidList.count() > 0 )
localUID = *( uidList.at( 0 ) );
}
KABC::Addressee addr = mAddressBook->findByUid( localUID );
if ( !addr.isEmpty() ) {
mEditorDialog->setAddressee( addr );
KApplication::execDialog ( mEditorDialog );
}
}
/**
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 KABCore::executeContact( const QString &uid /*US = QString::null*/ )
{
if ( mMultipleViewsAtOnce )
{
editContact( uid );
}
else
{
setDetailsVisible( true );
mActionDetails->setChecked(true);
}
}
void KABCore::save()
{
if (syncManager->blockSave())
return;
if ( !mModified )
return;
syncManager->setBlockSave(true);
QString text = i18n( "There was an error while attempting to save\n the "
"address book. Please check that some \nother application is "
"not using it. " );
message(i18n("Saving ... please wait! "), false);
//qApp->processEvents();
#ifndef KAB_EMBEDDED
KABC::StdAddressBook *b = dynamic_cast<KABC::StdAddressBook*>( mAddressBook );
if ( !b || !b->save() ) {
KMessageBox::error( this, text, i18n( "Unable to Save" ) );
}
#else //KAB_EMBEDDED
KABC::StdAddressBook *b = (KABC::StdAddressBook*)( mAddressBook );
if ( !b || !b->save() ) {
QMessageBox::critical( this, i18n( "Unable to Save" ), text, i18n("Ok"));
}
#endif //KAB_EMBEDDED
message(i18n("Addressbook saved!"));
setModified( false );
syncManager->setBlockSave(false);
}
void KABCore::undo()
{
UndoStack::instance()->undo();
// Refresh the view
mViewManager->refreshView();
}
void KABCore::redo()
{
RedoStack::instance()->redo();
// Refresh the view
mViewManager->refreshView();
}
void KABCore::setJumpButtonBar( bool visible )
{
setJumpButtonBarVisible(visible );
saveSettings();
}
void KABCore::setJumpButtonBarVisible( bool visible )
{
if (mMultipleViewsAtOnce)
{
if ( visible )
mJumpButtonBar->show();
else
mJumpButtonBar->hide();
}
else
{
// show the jumpbar only if "the details are hidden" == "viewmanager are shown"
if (mViewManager->isVisible())
{
if ( visible )
mJumpButtonBar->show();
else
mJumpButtonBar->hide();
}
else
{
mJumpButtonBar->hide();
}
}
if ( visible ) {
if ( mIncSearchWidget->currentItem() == 0 ) {
message( i18n("Change search field enable jump bar") );
}
}
}
void KABCore::setDetailsToState()
{
setDetailsVisible( mActionDetails->isChecked() );
}
void KABCore::setDetailsToggle()
{
mActionDetails->setChecked( !mActionDetails->isChecked() );
setDetailsToState();
}
void KABCore::setDetailsVisible( bool visible )
{
if (visible && mDetails->isHidden())
{
KABC::Addressee::List addrList = mViewManager->selectedAddressees();
if ( addrList.count() > 0 )
mDetails->setAddressee( addrList[ 0 ] );
}
// mMultipleViewsAtOnce=false: mDetails is always visible. But we switch between
// the listview and the detailview. We do that by changing the splitbar size.
if (mMultipleViewsAtOnce)
{
if ( visible )
mDetails->show();
else
mDetails->hide();
}
else
{
if ( visible ) {
mViewManager->hide();
mDetails->show();
mIncSearchWidget->setFocus();
}
else {
mViewManager->show();
mDetails->hide();
mViewManager->setFocusAV();
}
setJumpButtonBarVisible( !visible );
}
}
void KABCore::extensionChanged( int id )
{
//change the details view only for non desktop systems
#ifndef DESKTOP_VERSION
if (id == 0)
{
//the user disabled the extension.
if (mMultipleViewsAtOnce)
{ // enable detailsview again
setDetailsVisible( true );
mActionDetails->setChecked( true );
}
else
{ //go back to the listview
setDetailsVisible( false );
mActionDetails->setChecked( false );
mActionDetails->setEnabled(true);
}
}
else
{
//the user enabled the extension.
setDetailsVisible( false );
mActionDetails->setChecked( false );
if (!mMultipleViewsAtOnce)
{
mActionDetails->setEnabled(false);
}
mExtensionManager->setSelectionChanged();
}
#endif// DESKTOP_VERSION
}
void KABCore::extensionModified( const KABC::Addressee::List &list )
{
if ( list.count() != 0 ) {
KABC::Addressee::List::ConstIterator it;
for ( it = list.begin(); it != list.end(); ++it )
mAddressBook->insertAddressee( *it );
if ( list.count() > 1 )
setModified();
else
setModifiedWOrefresh();
}
if ( list.count() == 0 )
mViewManager->refreshView();
else
mViewManager->refreshView( list[ 0 ].uid() );
}
QString KABCore::getNameByPhone( const QString &phone )
{
#ifndef KAB_EMBEDDED
QRegExp r( "[/*/-/ ]" );
QString localPhone( phone );
bool found = false;
QString ownerName = "";
KABC::AddressBook::Iterator iter;
KABC::PhoneNumber::List::Iterator phoneIter;
KABC::PhoneNumber::List phoneList;
for ( iter = mAddressBook->begin(); !found && ( iter != mAddressBook->end() ); ++iter ) {
phoneList = (*iter).phoneNumbers();
for ( phoneIter = phoneList.begin(); !found && ( phoneIter != phoneList.end() );
++phoneIter) {
// Get rid of separator chars so just the numbers are compared.
if ( (*phoneIter).number().replace( r, "" ) == localPhone.replace( r, "" ) ) {
ownerName = (*iter).formattedName();
found = true;
}
}
}
return ownerName;
#else //KAB_EMBEDDED
qDebug("KABCore::getNameByPhone finsih method");
return "";
#endif //KAB_EMBEDDED
}
void KABCore::openConfigGlobalDialog()
{
KPimPrefsGlobalDialog gc ( this );
gc.exec();
}
void KABCore::openConfigDialog()
{
KDialogBase * ConfigureDialog = new KDialogBase ( KDialogBase::Plain , i18n("Configure KA/Pi"), KDialogBase::Default |KDialogBase::Cancel | KDialogBase::Apply | KDialogBase::Ok, KDialogBase::Ok,0, "name", true, true);
KCMKabConfig* kabcfg = new KCMKabConfig( ConfigureDialog , "KCMKabConfig" );
ConfigureDialog->setMainWidget( kabcfg );
connect( ConfigureDialog, SIGNAL( applyClicked() ),
this, SLOT( configurationChanged() ) );
connect( ConfigureDialog, SIGNAL( applyClicked() ),
kabcfg, SLOT( save() ) );
connect( ConfigureDialog, SIGNAL( acceptClicked() ),
this, SLOT( configurationChanged() ) );
connect( ConfigureDialog, SIGNAL( acceptClicked() ),
kabcfg, SLOT( save() ) );
connect( ConfigureDialog, SIGNAL( defaultClicked() ),
kabcfg, SLOT( defaults() ) );
saveSettings();
kabcfg->load();
#ifndef DESKTOP_VERSION
if ( QApplication::desktop()->height() <= 480 )
ConfigureDialog->hideButtons();
ConfigureDialog->showMaximized();
#endif
if ( ConfigureDialog->exec() )
KMessageBox::information( this, i18n("Some changes are only\neffective after a restart!\n") );
delete ConfigureDialog;
}
void KABCore::openLDAPDialog()
{
#ifndef KAB_EMBEDDED
if ( !mLdapSearchDialog ) {
mLdapSearchDialog = new LDAPSearchDialog( mAddressBook, this );
connect( mLdapSearchDialog, SIGNAL( addresseesAdded() ), mViewManager,
SLOT( refreshView() ) );
connect( mLdapSearchDialog, SIGNAL( addresseesAdded() ), this,
SLOT( setModified() ) );
} else
mLdapSearchDialog->restoreSettings();
if ( mLdapSearchDialog->isOK() )
mLdapSearchDialog->exec();
#else //KAB_EMBEDDED
qDebug("KABCore::openLDAPDialog() finsih method");
#endif //KAB_EMBEDDED
}
void KABCore::print()
{
#ifndef KAB_EMBEDDED
KPrinter printer;
if ( !printer.setup( this ) )
return;
KABPrinting::PrintingWizard wizard( &printer, mAddressBook,
mViewManager->selectedUids(), this );
wizard.exec();
#else //KAB_EMBEDDED
qDebug("KABCore::print() finsih method");
#endif //KAB_EMBEDDED
}
void KABCore::addGUIClient( KXMLGUIClient *client )
{
if ( mGUIClient )
mGUIClient->insertChildClient( client );
else
KMessageBox::error( this, "no KXMLGUICLient");
}
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();
}
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 );
beamMenu= 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( request_file(const QString &) ), this, SLOT( syncFileRequest(const QString &) ) );
connect(syncManager , SIGNAL( getFile( bool ,const QString &)), this, SLOT(getFile( bool ,const QString &) ) );
QString sync_file = sentSyncFile();
//qDebug("KABCore::initGUI()::setting tmp sync file to:%s ",sync_file.latin1());
syncManager->setDefaultFileName( sync_file );
//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& ) ) );
connect( mIncSearchWidget, SIGNAL( scrollUP() ),mViewManager, SLOT( scrollUP() ) );
connect( mIncSearchWidget, SIGNAL( scrollDOWN() ),mViewManager, SLOT( scrollDOWN() ) );
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
mActionMail = KStdAction::mail( this, SLOT( sendMail() ), actionCollection() );
//mActionPrint = KStdAction::print( this, SLOT( print() ), actionCollection() );
mActionPrint = new KAction( i18n( "&Print View" ), "fileprint", CTRL + Key_P, mViewManager,
SLOT( printView() ), actionCollection(), "kaddressbook_print" );
mActionPrintDetails = new KAction( i18n( "&Print Details" ), "fileprint", 0, mDetails,
SLOT( printView() ), actionCollection(), "kaddressbook_print2" );
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( "Export 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 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" );
//US not implemented yet
//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 = new KAction( i18n( "&Configure KA/Pi..." ), "configure", 0, this,
SLOT( openConfigDialog() ), actionCollection(),
"kaddressbook_configure" );
mActionConfigGlobal = new KAction( i18n( "Global Settings..." ), "configure", 0, this,
SLOT( openConfigGlobalDialog() ), actionCollection(),
"kaddressbook_configure" );
}
mActionJumpBar = new KToggleAction( i18n( "Show Jump Bar" ), 0, 0,
actionCollection(), "options_show_jump_bar" );
connect( mActionJumpBar, SIGNAL( toggled( bool ) ), SLOT( setJumpButtonBar( bool ) ) );
mActionDetails = new KToggleAction( i18n( "Show Details" ), "listview", 0,
actionCollection(), "options_show_details" );
connect( mActionDetails, SIGNAL( toggled( bool ) ), SLOT( setDetailsVisible( bool ) ) );
mActionBR = new KToggleAction( i18n( "Beam receive enabled" ), "beam", 0, this,
SLOT( toggleBeamReceive() ), actionCollection(),
"kaddressbook_beam_rec" );
// 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 for Contacts..." ), 0, this,
SLOT( setCategories() ), actionCollection(),
"edit_set_categories" );
mActionEditCategories = new KAction( i18n( "Edit Category List..." ), 0, this,
SLOT( editCategories() ), actionCollection(),
"edit__categories" );
mActionRemoveVoice = new KAction( i18n( "Remove \"voice\"..." ), 0, this,
SLOT( removeVoice() ), actionCollection(),
"remove_voice" );
mActionSetFormattedName = new KAction( i18n( "Set formatted name..." ), 0, this,
SLOT( setFormattedName() ), actionCollection(),
"set_formatted" );
mActionManageCategories= new KAction( i18n( "Manage new categories..." ), 0, this,
SLOT( manageCategories() ), actionCollection(),
"remove_voice" );
mActionImportOL = new KAction( i18n( "Import from Outlook..." ), 0, this,
SLOT( importFromOL() ), actionCollection(),
"import_OL" );
#ifdef KAB_EMBEDDED
mActionLicence = new KAction( i18n( "Licence" ), 0,
this, SLOT( showLicence() ), actionCollection(),
"licence_about_data" );
mActionFaq = new KAction( i18n( "Faq" ), 0,
this, SLOT( faq() ), actionCollection(),
"faq_about_data" );
mActionWN = new KAction( i18n( "What's New?" ), 0,
this, SLOT( whatsnew() ), actionCollection(),
"wn" );
mActionStorageHowto = new KAction( i18n( "Storage HowTo" ), 0,
this, SLOT( storagehowto() ), actionCollection(),
"storage" );
mActionSyncHowto = new KAction( i18n( "Sync HowTo" ), 0,
this, SLOT( synchowto() ), actionCollection(),
"sync" );
mActionKdeSyncHowto = new KAction( i18n( "Kde Sync HowTo" ), 0,
this, SLOT( kdesynchowto() ), actionCollection(),
"kdesync" );
mActionMultiSyncHowto = new KAction( i18n( "Multi Sync HowTo" ), 0,
this, SLOT( multisynchowto() ), actionCollection(),
"multisync" );
mActionAboutKAddressbook = new KAction( i18n( "&About KAddressBook" ), "kaddressbook2", 0,
this, SLOT( createAboutData() ), actionCollection(),
"kaddressbook_about_data" );
#endif //KAB_EMBEDDED
clipboardDataChanged();
connect( UndoStack::instance(), SIGNAL( changed() ), SLOT( updateActionMenu() ) );
connect( RedoStack::instance(), SIGNAL( changed() ), SLOT( updateActionMenu() ) );
}
//US we need this function, to plug all actions into the correct menues.
// KDE uses a XML format to plug the actions, but we work her without this overhead.
void KABCore::addActionsManually()
{
//US qDebug("KABCore::initActions(): mIsPart %i", mIsPart);
#ifdef KAB_EMBEDDED
QPopupMenu *fileMenu = new QPopupMenu( this );
QPopupMenu *editMenu = new QPopupMenu( this );
QPopupMenu *helpMenu = new QPopupMenu( this );
KToolBar* tb = mMainWindow->toolBar();
mMainWindow->setToolBarsMovable (false );
#ifndef DESKTOP_VERSION
if ( KABPrefs::instance()->mFullMenuBarVisible ) {
#endif
QMenuBar* mb = mMainWindow->menuBar();
//US setup menubar.
//Disable the following block if you do not want to have a menubar.
mb->insertItem( i18n("&File"), fileMenu );
mb->insertItem( i18n("&Edit"), editMenu );
mb->insertItem( i18n("&View"), viewMenu );
mb->insertItem( i18n("&Settings"), settingsMenu );
#ifdef DESKTOP_VERSION
mb->insertItem( i18n("Synchronize"), syncMenu );
#else
mb->insertItem( i18n("Sync"), syncMenu );
#endif
//mb->insertItem( i18n("&Change"), changeMenu );
mb->insertItem( i18n("&Help"), helpMenu );
mIncSearchWidget = new IncSearchWidget( tb );
// tb->insertWidget(-1, 0, mIncSearchWidget);
#ifndef DESKTOP_VERSION
} else {
//US setup toolbar
QPEMenuBar *menuBarTB = new QPEMenuBar( tb );
QPopupMenu *popupBarTB = new QPopupMenu( this );
menuBarTB->insertItem( SmallIcon( "z_menu" ) , popupBarTB);
tb->insertWidget(-1, 0, menuBarTB);
mIncSearchWidget = new IncSearchWidget( tb );
tb->enableMoving(false);
popupBarTB->insertItem( i18n("&File"), fileMenu );
popupBarTB->insertItem( i18n("&Edit"), editMenu );
popupBarTB->insertItem( i18n("&View"), viewMenu );
popupBarTB->insertItem( i18n("&Settings"), settingsMenu );
popupBarTB->insertItem( i18n("Synchronize"), syncMenu );
mViewManager->getFilterAction()->plug ( popupBarTB);
//popupBarTB->insertItem( i18n("&Change selected"), changeMenu );
popupBarTB->insertItem( i18n("&Help"), helpMenu );
if (QApplication::desktop()->width() > 320 ) {
// mViewManager->getFilterAction()->plug ( tb);
}
}
#endif
mIncSearchWidget->setSize();
// mActionQuit->plug ( mMainWindow->toolBar());
//US Now connect the actions with the menue entries.
#ifdef DESKTOP_VERSION
mActionPrint->plug( fileMenu );
mActionPrintDetails->plug( fileMenu );
fileMenu->insertSeparator();
#endif
mActionMail->plug( fileMenu );
fileMenu->insertSeparator();
mActionNewContact->plug( editMenu );
mActionNewContact->plug( tb );
mActionEditAddressee->plug( editMenu );
editMenu->insertSeparator();
// if ((KGlobal::getDesktopSize() > KGlobal::Small ) ||
// (!KABPrefs::instance()->mMultipleViewsAtOnce ))
mActionEditAddressee->plug( tb );
// fileMenu->insertSeparator();
mActionSave->plug( fileMenu );
fileMenu->insertItem( "&Import", ImportMenu );
fileMenu->insertItem( "&Export", ExportMenu );
editMenu->insertItem( i18n("&Change"), changeMenu );
editMenu->insertSeparator();
#ifndef DESKTOP_VERSION
if ( Ir::supported() ) fileMenu->insertItem( i18n("&Beam"), beamMenu );
#endif
#if 0
// PENDING fix MailVCard
fileMenu->insertSeparator();
mActionMailVCard->plug( fileMenu );
#endif
#ifndef DESKTOP_VERSION
if ( Ir::supported() ) mActionBR->plug( beamMenu );
if ( Ir::supported() ) mActionBeamVCard->plug( beamMenu );
if ( Ir::supported() ) mActionBeam->plug( beamMenu );
#endif
fileMenu->insertSeparator();
mActionQuit->plug( fileMenu );
#ifdef _OL_IMPORT_
mActionImportOL->plug( ImportMenu );
#endif
// edit menu
mActionUndo->plug( editMenu );
mActionRedo->plug( editMenu );
editMenu->insertSeparator();
mActionCut->plug( editMenu );
mActionCopy->plug( editMenu );
mActionPaste->plug( editMenu );
mActionDelete->plug( editMenu );
editMenu->insertSeparator();
mActionSelectAll->plug( editMenu );
mActionSetFormattedName->plug( changeMenu );
mActionRemoveVoice->plug( changeMenu );
// settingsmings menu
//US special menuentry to configure the addressbook resources. On KDE
// you do that through the control center !!!
// settingsMenu->insertSeparator();
mActionConfigKAddressbook->plug( settingsMenu, 0 );
mActionConfigGlobal->plug( settingsMenu, 1 );
mActionConfigResources->plug( settingsMenu,2 );
settingsMenu->insertSeparator(3);
if ( mIsPart ) {
//US not implemented yet
//mActionConfigShortcuts->plug( settingsMenu );
//mActionConfigureToolbars->plug( settingsMenu );
} else {
//US not implemented yet
//mActionKeyBindings->plug( settingsMenu );
}
mActionEditCategories->plug( settingsMenu );
mActionManageCategories->plug( settingsMenu );
mActionJumpBar->plug( viewMenu,0 );
mActionDetails->plug( viewMenu,0 );
//if (!KABPrefs::instance()->mMultipleViewsAtOnce || KGlobal::getDesktopSize() == KGlobal::Desktop )
mActionDetails->plug( tb );
settingsMenu->insertSeparator();
#ifndef DESKTOP_VERSION
if ( Ir::supported() ) mActionBR->plug(settingsMenu );
settingsMenu->insertSeparator();
#endif
mActionWhoAmI->plug( settingsMenu );
//mActionEditCategories->plug( changeMenu );
mActionCategories->plug( changeMenu );
//mActionManageCategories->plug( changeMenu );
//mActionCategories->plug( settingsMenu );
mActionWN->plug( helpMenu );
mActionStorageHowto->plug( helpMenu );
mActionSyncHowto->plug( helpMenu );
mActionKdeSyncHowto->plug( helpMenu );
mActionMultiSyncHowto->plug( helpMenu );
mActionFaq->plug( helpMenu );
mActionLicence->plug( helpMenu );
mActionAboutKAddressbook->plug( helpMenu );
if (KGlobal::getDesktopSize() > KGlobal::Small ) {
mActionSave->plug( tb );
mViewManager->getFilterAction()->plug ( tb);
//LR hide filteraction on started in 480x640
if (QApplication::desktop()->width() == 480 ) {
mViewManager->getFilterAction()->setComboWidth( 0 );
}
mActionUndo->plug( tb );
mActionDelete->plug( tb );
mActionRedo->plug( tb );
} else {
mActionSave->plug( tb );
tb->enableMoving(false);
}
//mActionQuit->plug ( tb );
//tb->insertWidget(-1, 0, mIncSearchWidget, 6);
//US link the searchwidget first to this.
// The real linkage to the toolbar happens later.
//US mIncSearchWidget->reparent(tb, 0, QPoint(50,0), TRUE);
//US tb->insertItem( mIncSearchWidget );
/*US
mIncSearchWidget = new IncSearchWidget( tb );
connect( mIncSearchWidget, SIGNAL( doSearch( const QString& ) ),
SLOT( incrementalSearch( const QString& ) ) );
mJumpButtonBar = new JumpButtonBar( this, this );
//US topLayout->addWidget( mJumpButtonBar );
this->layout()->add( mJumpButtonBar );
*/
#endif //KAB_EMBEDDED
mActionExport2phone->plug( ExportMenu );
connect ( syncMenu, SIGNAL( activated ( int ) ), syncManager, SLOT (slotSyncMenu( int ) ) );
syncManager->fillSyncMenu();
}
void KABCore::showLicence()
{
KApplication::showLicence();
}
void KABCore::manageCategories( )
{
KABCatPrefs* cp = new KABCatPrefs();
cp->show();
int w =cp->sizeHint().width() ;
int h = cp->sizeHint().height() ;
int dw = QApplication::desktop()->width();
int dh = QApplication::desktop()->height();
cp->setGeometry( (dw-w)/2, (dh - h )/2 ,w,h );
if ( !cp->exec() ) {
delete cp;
return;
}
int count = 0;
int cc = 0;
message( i18n("Please wait, processing categories..."));
if ( cp->addCat() ) {
KABC::AddressBook::Iterator it;
QStringList catList = KABPrefs::instance()->mCustomCategories;
for( it = mAddressBook->begin(); it != mAddressBook->end(); ++it ) {
++cc;
if ( cc %10 == 0)
message(i18n("Processing contact #%1").arg(cc));
QStringList catIncList = (*it).categories();
int i;
for( i = 0; i< catIncList.count(); ++i ) {
if ( !catList.contains (catIncList[i])) {
catList.append( catIncList[i] );
//qDebug("add cat %s ", catIncList[i].latin1());
++count;
}
}
}
catList.sort();
KABPrefs::instance()->mCustomCategories = catList;
KABPrefs::instance()->writeConfig();
message(QString::number( count )+ i18n(" categories added to list! "));
} else {
QStringList catList = KABPrefs::instance()->mCustomCategories;
QStringList catIncList;
QStringList newCatList;
KABC::AddressBook::Iterator it;
for( it = mAddressBook->begin(); it != mAddressBook->end(); ++it ) {
++cc;
if ( cc %10 == 0)
message(i18n("Processing contact #%1").arg(cc));
QStringList catIncList = (*it).categories();
int i;
if ( catIncList.count() ) {
newCatList.clear();
for( i = 0; i< catIncList.count(); ++i ) {
if ( catList.contains (catIncList[i])) {
newCatList.append( catIncList[i] );
}
}
newCatList.sort();
(*it).setCategories( newCatList );
mAddressBook->insertAddressee( (*it) );
}
}
setModified( true );
mViewManager->refreshView();
message( i18n("Removing categories done!"));
}
delete cp;
}
void KABCore::removeVoice()
{
if ( KMessageBox::questionYesNo( this, i18n("After importing, phone numbers\nmay have two or more types.\n(E.g. work+voice)\nThese numbers are shown as \"other\".\nClick Yes to remove the voice type\nfrom numbers with more than one type.\n\nRemove voice type?") ) == KMessageBox::No )
return;
XXPortSelectDialog dlg( this, false, this );
if ( !dlg.exec() )
return;
mAddressBook->setUntagged();
dlg.tagSelected();
message(i18n("Removing voice..."), false );
KABC::AddressBook::Iterator it;
for ( it = mAddressBook->begin(); it != mAddressBook->end(); ++it ) {
if ( (*it).tagged() ) {
(*it).removeVoice();
}
}
message(i18n("Refreshing view...") );
mViewManager->refreshView( "" );
Addressee add;
mDetails->setAddressee( add );
message(i18n("Remove voice completed!") );
}
void KABCore::setFormattedName()
{
KABFormatPrefs setpref;
if ( !setpref.exec() ) {
return;
}
XXPortSelectDialog dlg( this, false, this );
if ( !dlg.exec() )
return;
mAddressBook->setUntagged();
dlg.tagSelected();
int count = 0;
KABC::AddressBook::Iterator it;
bool modified = false;
for ( it = mAddressBook->begin(); it != mAddressBook->end(); ++it ) {
if ( (*it).tagged() ) {
if ( (*it).uid().left( 2 ) == "la" )
if ( (*it).uid().left( 19 ) == QString("last-syncAddressee-") )
continue;
++count;
if ( count %10 == 0 )
message(i18n("Changing contact #%1").arg( count ) );
QString fName;
if ( setpref.simple->isChecked() )
fName = NameEditDialog::formattedName( (*it), NameEditDialog::SimpleName );
else if ( setpref.full->isChecked() )
fName = NameEditDialog::formattedName( (*it), NameEditDialog::FullName );
else if ( setpref.reverse->isChecked() )
fName = NameEditDialog::formattedName( (*it), NameEditDialog::ReverseName );
else
fName = (*it).organization();
if ( setpref.setCompany->isChecked() )
if ( fName.isEmpty() || fName =="," )
fName = (*it).organization();
(*it).setFormattedName( fName );
(*it).setChanged( true );
modified = true;
(*it).setRevision( QDateTime::currentDateTime() );
}
}
message(i18n("Refreshing view...") );
if ( modified )
setModified( true );
Addressee add;
mDetails->setAddressee( add );
if ( count == 0 )
message(i18n("No contact changed!") );
else
message(i18n("%1 contacts changed!").arg( count ) );
}
void KABCore::clipboardDataChanged()
{
if ( mReadWrite )
mActionPaste->setEnabled( !QApplication::clipboard()->text().isEmpty() );
}
void KABCore::updateActionMenu()
{
UndoStack *undo = UndoStack::instance();
RedoStack *redo = RedoStack::instance();
if ( undo->isEmpty() )
mActionUndo->setText( i18n( "Undo" ) );
else
mActionUndo->setText( i18n( "Undo %1" ).arg( undo->top()->name() ) );
mActionUndo->setEnabled( !undo->isEmpty() );
if ( !redo->top() )
mActionRedo->setText( i18n( "Redo" ) );
else
mActionRedo->setText( i18n( "Redo %1" ).arg( redo->top()->name() ) );
mActionRedo->setEnabled( !redo->isEmpty() );
}
void KABCore::configureKeyBindings()
{
#ifndef KAB_EMBEDDED
KKeyDialog::configure( actionCollection(), true );
#else //KAB_EMBEDDED
qDebug("KABCore::configureKeyBindings() not implemented");
#endif //KAB_EMBEDDED
}
#ifdef KAB_EMBEDDED
void KABCore::configureResources()
{
KRES::KCMKResources dlg( this, "" , 0 );
if ( !dlg.exec() )
return;
KMessageBox::information( this, i18n("Please restart to get the \nchanged resources (re)loaded!\n") );
}
#endif //KAB_EMBEDDED
/* this method will be called through the QCop interface from Ko/Pi to select addresses
* for the attendees list of an event.
*/
void KABCore::requestForNameEmailUidList(const QString& sourceChannel, const QString& uid)
{
qDebug("KABCore::requestForNameEmailUidList ");
bool ok = false;
mEmailSourceChannel = sourceChannel;
mEmailSourceUID = uid;
QTimer::singleShot( 10,this, SLOT ( callContactdialog() ) );
//callContactdialog();
#if 0
int wid = uid.toInt( &ok );
qDebug("UID %s ", uid.latin1());
if ( ok ) {
if ( wid != QApplication::desktop()->width() ) {
qDebug("KA/Pi: Request from different desktop geometry. Resizing ...");
message( i18n("Resizing, please wait...") );
mMainWindow->showMinimized();
/*
{
QCopEnvelope e("QPE/Application/kapi", "callContactdialog()");
}
*/
QTimer::singleShot( 1,this, SLOT ( resizeAndCallContactdialog() ) );
return;
}
} else {
qDebug("KABCore::requestForNameEmailUidList:: Got invalid uid ");
}
callContactdialog();
//QCopEnvelope e("QPE/Application/kapi", "callContactdialog()");
#endif
}
void KABCore::resizeAndCallContactdialog()
{
updateMainWindow();
QTimer::singleShot( 10,this, SLOT ( callContactdialog() ) );
}
void KABCore::doRingSync()
{
topLevelWidget()->raise();
syncManager->multiSync( false );
}
void KABCore::callContactdialog()
{
static bool running = false;
if (running) return;
running = true;
QStringList nameList;
QStringList emailList;
QStringList uidList;
qDebug(" KABCore::callContactdialog:DESKTOP WIDTH %d ", QApplication::desktop()->width() );
KABC::Addressee::List list = KABC::AddresseeDialog::getAddressees(this);
uint i=0;
for (i=0; i < list.count(); i++)
{
nameList.append(list[i].realName());
emailList.append(list[i].preferredEmail());
uidList.append(list[i].uid());
}
QString uid = mEmailSourceUID;
//qDebug("%s %s ", sourceChannel.latin1(), uid.latin1());
bool res = ExternalAppHandler::instance()->returnNameEmailUidListFromKAPI(mEmailSourceChannel, uid, nameList, emailList, uidList);
running = false;
}
/* this method will be called through the QCop interface from Ko/Pi to select birthdays
* to put them into the calendar.
*/
void KABCore::requestForBirthdayList(const QString& sourceChannel, const QString& uid)
{
// qDebug("KABCore::requestForBirthdayList");
QStringList birthdayList;
QStringList anniversaryList;
QStringList realNameList;
QStringList preferredEmailList;
QStringList assembledNameList;
QStringList uidList;
KABC::AddressBook::Iterator it;
int count = 0;
for( it = mAddressBook->begin(); it != mAddressBook->end(); ++it ) {
++count;
}
QProgressBar bar(count,0 );
int w = 300;
if ( QApplication::desktop()->width() < 320 )
w = 220;
int h = bar.sizeHint().height() ;
int dw = QApplication::desktop()->width();
int dh = QApplication::desktop()->height();
bar.setGeometry( (dw-w)/2, (dh - h )/2 ,w,h );
bar.show();
bar.setCaption (i18n("Collecting birthdays - close to abort!") );
qApp->processEvents();
QDate bday;
QString anni;
QString formattedbday;
for( it = mAddressBook->begin(); it != mAddressBook->end(); ++it )
{
if ( ! bar.isVisible() )
return;
bar.setProgress( count++ );
qApp->processEvents();
bday = (*it).birthday().date();
anni = (*it).custom("KADDRESSBOOK", "X-Anniversary" );
if ( bday.isValid() || !anni.isEmpty())
{
if (bday.isValid())
formattedbday = KGlobal::locale()->formatDate(bday, true, KLocale::ISODate);
else
formattedbday = "NOTVALID";
if (anni.isEmpty())
anni = "INVALID";
birthdayList.append(formattedbday);
anniversaryList.append(anni); //should be ISODate
realNameList.append((*it).realName());
preferredEmailList.append((*it).preferredEmail());
assembledNameList.append((*it).realName());
uidList.append((*it).uid());
//qDebug("found birthday in KA/Pi: %s,%s,%s,%s: %s, %s", (*it).realName().latin1(), (*it).preferredEmail().latin1(), (*it).assembledName().latin1(), (*it).uid().latin1(), formattedbday.latin1(), anni.latin1() );
}
}
bool res = ExternalAppHandler::instance()->returnBirthdayListFromKAPI(sourceChannel, uid, birthdayList, anniversaryList, realNameList, preferredEmailList, assembledNameList, uidList);
}
/* this method will be called through the QCop interface from other apps to show details of a contact.
*/
void KABCore::requestForDetails(const QString& sourceChannel, const QString& sessionuid, const QString& name, const QString& email, const QString& uid)
{
//qDebug("KABCore::requestForDetails %s %s %s %s %s", sourceChannel.latin1(), sessionuid.latin1(), name.latin1(), email.latin1(), uid.latin1());
QString foundUid = QString::null;
if ( ! uid.isEmpty() ) {
Addressee adrr = mAddressBook->findByUid( uid );
if ( !adrr.isEmpty() ) {
foundUid = uid;
}
if ( email == "sendbacklist" ) {
//qDebug("ssssssssssssssssssssssend ");
QStringList nameList;
QStringList emailList;
QStringList uidList;
nameList.append(adrr.realName());
emailList = adrr.emails();
uidList.append( adrr.preferredEmail());
bool res = ExternalAppHandler::instance()->returnNameEmailUidListFromKAPI("QPE/Application/ompi", uid, nameList, emailList, uidList);
return;
}
}
if ( email == "sendbacklist" )
return;
if (foundUid.isEmpty())
{
//find the uid of the person first
Addressee::List namelist;
Addressee::List emaillist;
if (!name.isEmpty())
namelist = mAddressBook->findByName( name );
if (!email.isEmpty())
emaillist = mAddressBook->findByEmail( email );
//qDebug("count %d %d ", namelist.count(),emaillist.count() );
//check if we have a match in Namelist and Emaillist
if ((namelist.count() == 0) && (emaillist.count() > 0)) {
foundUid = emaillist[0].uid();
}
else if ((namelist.count() > 0) && (emaillist.count() == 0))
foundUid = namelist[0].uid();
else
{
for (int i = 0; i < namelist.count(); i++)
{
for (int j = 0; j < emaillist.count(); j++)
{
if (namelist[i] == emaillist[j])
{
foundUid = namelist[i].uid();
}
}
}
}
}
else
{
foundUid = uid;
}
if (!foundUid.isEmpty())
{
// raise Ka/Pi if it is in the background
#ifndef DESKTOP_VERSION
#ifndef KORG_NODCOP
//QCopEnvelope e("QPE/Application/kapi", "raise()");
#endif
#endif
mMainWindow->showMaximized();
mMainWindow-> raise();
mViewManager->setSelected( "", false);
mViewManager->refreshView( "" );
mViewManager->setSelected( foundUid, true );
mViewManager->refreshView( foundUid );
if ( !mMultipleViewsAtOnce )
{
setDetailsVisible( true );
mActionDetails->setChecked(true);
}
}
}
void KABCore::storagehowto()
{
KApplication::showFile( "KDE-Pim/Pi Storage HowTo", "kdepim/storagehowto.txt" );
}
void KABCore::whatsnew()
{
KApplication::showFile( "KDE-Pim/Pi Version Info", "kdepim/WhatsNew.txt" );
}
void KABCore::synchowto()
{
KApplication::showFile( "KDE-Pim/Pi Synchronization HowTo", "kdepim/SyncHowto.txt" );
}
void KABCore::kdesynchowto()
{
KApplication::showFile( "KDE-Pim/Pi Synchronization HowTo", "kdepim/Zaurus-KDE_syncHowTo.txt" );
}
void KABCore::multisynchowto()
{
KApplication::showFile( "KDE-Pim/Pi Synchronization HowTo", "kdepim/MultiSyncHowTo.txt" );
}
void KABCore::faq()
{
KApplication::showFile( "KA/Pi FAQ", "kdepim/kaddressbook/kapiFAQ.txt" );
}
#include <libkcal/syncdefines.h>
KABC::Addressee KABCore::getLastSyncAddressee()
{
Addressee lse;
QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
//qDebug("CurrentSyncDevice %s ",mCurrentSyncDevice .latin1() );
lse = mAddressBook->findByUid( "last-syncAddressee-"+mCurrentSyncDevice );
if (lse.isEmpty()) {
qDebug("KA: Creating new last-syncAddressee ");
lse.setUid( "last-syncAddressee-"+mCurrentSyncDevice );
QString sum = "";
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL )
sum = "E: ";
lse.setFamilyName("!"+sum+mCurrentSyncDevice + i18n(" - sync event"));
lse.setRevision( mLastAddressbookSync );
lse.setCategories( i18n("SyncEvent") );
mAddressBook->insertAddressee( lse );
}
return lse;
}
int KABCore::takeAddressee( KABC::Addressee* local, KABC::Addressee* remote, int mode , bool full )
{
//void setZaurusId(int id);
// int zaurusId() const;
// void setZaurusUid(int id);
// int zaurusUid() const;
// void setZaurusStat(int id);
// int zaurusStat() const;
// 0 equal
// 1 take local
// 2 take remote
// 3 cancel
QDateTime lastSync = mLastAddressbookSync;
QDateTime localMod = local->revision();
QDateTime remoteMod = remote->revision();
QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
bool remCh, locCh;
remCh = ( remote->getCsum(mCurrentSyncDevice) != local->getCsum(mCurrentSyncDevice) );
//if ( remCh )
// qDebug("loc %s rem %s", local->getCsum(mCurrentSyncDevice).latin1(), remote->getCsum(mCurrentSyncDevice).latin1() );
locCh = ( localMod > mLastAddressbookSync );
//qDebug("cahnged rem %d loc %d",remCh, locCh );
if ( !remCh && ! locCh ) {
//qDebug("both not changed ");
lastSync = localMod.addDays(1);
if ( mode <= SYNC_PREF_ASK )
return 0;
} else {
if ( locCh ) {
//qDebug("loc changed %s %s", localMod.toString().latin1(), mLastAddressbookSync.toString().latin1());
lastSync = localMod.addDays( -1 );
if ( !remCh )
remoteMod =( lastSync.addDays( -1 ) );
} else {
//qDebug(" not loc changed ");
lastSync = localMod.addDays( 1 );
if ( remCh ) {
//qDebug("rem changed ");
remoteMod =( lastSync.addDays( 1 ) );
}
}
}
full = true;
if ( mode < SYNC_PREF_ASK )
mode = SYNC_PREF_ASK;
} else {
if ( localMod == remoteMod )
return 0;
}
//qDebug("%s %s --- %d %d", localMod.toString().latin1() , remoteMod.toString().latin1(), localMod.time().msec(), remoteMod.time().msec());
//qDebug("lastsync %s ", lastSync.toString().latin1() );
//full = true; //debug only
if ( full ) {
bool equ = ( (*local) == (*remote) );
if ( equ ) {
//qDebug("equal ");
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
local->setCsum( mCurrentSyncDevice, remote->getCsum(mCurrentSyncDevice) );
}
if ( mode < SYNC_PREF_FORCE_LOCAL )
return 0;
}//else //debug only
//qDebug("not equal %s %s ", local->summary().latin1(), remote->summary().latin1());
}
int result;
bool localIsNew;
//qDebug("%s -- %s mLastCalendarSync %s lastsync %s --- local %s remote %s ",local->summary().latin1(), remote->summary().latin1(),mLastCalendarSync.toString().latin1() ,lastSync.toString().latin1() , local->lastModified().toString().latin1() , remote->lastModified().toString().latin1() );
if ( full && mode < SYNC_PREF_NEWEST )
mode = SYNC_PREF_ASK;
switch( mode ) {
case SYNC_PREF_LOCAL:
if ( lastSync > remoteMod )
return 1;
if ( lastSync > localMod )
return 2;
return 1;
break;
case SYNC_PREF_REMOTE:
if ( lastSync > localMod )
return 2;
if ( lastSync > remoteMod )
return 1;
return 2;
break;
case SYNC_PREF_NEWEST:
if ( localMod > remoteMod )
return 1;
else
return 2;
break;
case SYNC_PREF_ASK:
//qDebug("lsy %s --- lo %s --- re %s ", lastSync.toString().latin1(), localMod.toString().latin1(), remoteMod.toString().latin1() );
if ( lastSync > remoteMod && lastSync > localMod)
return 0;
if ( lastSync > remoteMod )
return 1;
if ( lastSync > localMod ) {
return 2;
}
localIsNew = localMod >= remoteMod;
//qDebug("conflict! ************************************** ");
{
KABC::AddresseeChooser acd ( *local,*remote, localIsNew , this );
result = acd.executeD(localIsNew);
return result;
}
break;
case SYNC_PREF_FORCE_LOCAL:
return 1;
break;
case SYNC_PREF_FORCE_REMOTE:
return 2;
break;
default:
// SYNC_PREF_TAKE_BOTH not implemented
break;
}
return 0;
}
bool KABCore::synchronizeAddressbooks( KABC::AddressBook* local, KABC::AddressBook* remote,int mode)
{
bool syncOK = true;
int addedAddressee = 0;
int addedAddresseeR = 0;
int deletedAddresseeR = 0;
int deletedAddresseeL = 0;
int changedLocal = 0;
int changedRemote = 0;
int filteredIN = 0;
int filteredOUT = 0;
QString mCurrentSyncName = syncManager->getCurrentSyncName();
QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
//QPtrList<Addressee> el = local->rawAddressees();
Addressee addresseeR;
QString uid;
int take;
Addressee addresseeL;
Addressee addresseeRSync;
Addressee addresseeLSync;
// KABC::Addressee::List addresseeRSyncSharp = remote->getExternLastSyncAddressees();
//KABC::Addressee::List addresseeLSyncSharp = local->getExternLastSyncAddressees();
bool fullDateRange = false;
local->resetTempSyncStat();
mLastAddressbookSync = QDateTime::currentDateTime();
if ( syncManager->syncWithDesktop() ) {
// remote->removeSyncInfo( QString());//remove all info
if ( KSyncManager::mRequestedSyncEvent.isValid() ) {
mLastAddressbookSync = KSyncManager::mRequestedSyncEvent;
qDebug("KA: using extern time for calendar sync: %s ", mLastAddressbookSync.toString().latin1() );
} else {
qDebug("KA: KSyncManager::mRequestedSyncEvent has invalid datatime ");
}
}
QDateTime modifiedCalendar = mLastAddressbookSync;
addresseeLSync = getLastSyncAddressee();
qDebug("KA: Last Sync %s ", addresseeLSync.revision().toString().latin1());
addresseeR = remote->findByUid("last-syncAddressee-"+mCurrentSyncName );
if ( !addresseeR.isEmpty() ) {
addresseeRSync = addresseeR;
remote->removeAddressee(addresseeR );
} else {
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
addresseeRSync = addresseeLSync ;
} else {
//qDebug("FULLDATE 1");
fullDateRange = true;
Addressee newAdd;
addresseeRSync = newAdd;
addresseeRSync.setFamilyName(mCurrentSyncName + i18n(" - sync addressee"));
addresseeRSync.setUid("last-syncAddressee-"+mCurrentSyncName );
addresseeRSync.setRevision( mLastAddressbookSync );
addresseeRSync.setCategories( i18n("SyncAddressee") );
}
}
if ( addresseeLSync.revision() == mLastAddressbookSync ) {
// qDebug("FULLDATE 2");
fullDateRange = true;
}
if ( ! fullDateRange ) {
if ( addresseeLSync.revision() != addresseeRSync.revision() ) {
// qDebug("set fulldate to true %s %s" ,addresseeLSync->dtStart().toString().latin1(), addresseeRSync->dtStart().toString().latin1() );
//qDebug("%d %d %d %d ", addresseeLSync->dtStart().time().second(), addresseeLSync->dtStart().time().msec() , addresseeRSync->dtStart().time().second(), addresseeRSync->dtStart().time().msec());
fullDateRange = true;
//qDebug("FULLDATE 3 %s %s", addresseeLSync.revision().toString().latin1() , addresseeRSync.revision().toString().latin1() );
}
}
// fullDateRange = true; // debug only!
if ( fullDateRange )
mLastAddressbookSync = QDateTime::currentDateTime().addDays( -100*365);
else
mLastAddressbookSync = addresseeLSync.revision();
// for resyncing if own file has changed
// PENDING fixme later when implemented
#if 0
if ( mCurrentSyncDevice == "deleteaftersync" ) {
mLastAddressbookSync = loadedFileVersion;
qDebug("setting mLastAddressbookSync ");
}
#endif
// ********** setting filters ****************
Filter filterIN = mViewManager->getFilterByName( syncManager->mFilterInAB );
Filter filterOUT = mViewManager->getFilterByName( syncManager->mFilterOutAB );
//qDebug("*************************** ");
// qDebug("mLastAddressbookSync %s ",mLastAddressbookSync.toString().latin1() );
QStringList er = remote->uidList();
Addressee inR ;//= er.first();
Addressee inL;
syncManager->showProgressBar(0, i18n("Syncing - close to abort!"), er.count());
int modulo = (er.count()/10)+1;
int incCounter = 0;
while ( incCounter < er.count()) {
if (syncManager->isProgressBarCanceled())
return false;
if ( incCounter % modulo == 0 )
syncManager->showProgressBar(incCounter);
uid = er[ incCounter ];
bool skipIncidence = false;
if ( uid.left(19) == QString("last-syncAddressee-") )
skipIncidence = true;
QString idS,OidS;
qApp->processEvents();
if ( !skipIncidence ) {
inL = local->findByUid( uid );
inR = remote->findByUid( uid );
//inL.setResource( 0 );
//inR.setResource( 0 );
if ( !inL.isEmpty() ) { // maybe conflict - same uid in both calendars
if ( !inL.resource() || inL.resource()->includeInSync() ) {
if ( (take = takeAddressee( &inL, &inR, mode, fullDateRange )) ) {
//qDebug("take %d %s ", take, inL.summary().latin1());
if ( take == 3 )
return false;
if ( take == 1 ) {// take local **********************
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
inL.setCsum( mCurrentSyncDevice, inR.getCsum(mCurrentSyncDevice) );
inL.setID( mCurrentSyncDevice, inR.getID(mCurrentSyncDevice) );
local->insertAddressee( inL, false );
idS = inR.externalUID();
OidS = inR.originalExternalUID();
}
else
idS = inR.IDStr();
remote->removeAddressee( inR );
inR = inL;
inR.setTempSyncStat( SYNC_TEMPSTATE_INITIAL );
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
inR.setOriginalExternalUID( OidS );
inR.setExternalUID( idS );
if ( syncManager->syncWithDesktop() ) {
inR.setIDStr("changed" );
}
//inR.insertCustom( "KADDRESSBOOK", "X-KDESYNC","changed" );
} else {
inR.setIDStr( idS );
}
inR.setResource( 0 );
remote->insertAddressee( inR , false);
++changedRemote;
} else { // take == 2 take remote **********************
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
if ( inR.revision().date().year() < 2004 )
inR.setRevision( modifiedCalendar );
}
idS = inL.IDStr();
local->removeAddressee( inL );
inL = inR;
inL.setIDStr( idS );
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
inL.setCsum( mCurrentSyncDevice, inR.getCsum(mCurrentSyncDevice) );
inL.setID( mCurrentSyncDevice, inR.getID(mCurrentSyncDevice) );
}
inL.setResource( 0 );
local->insertAddressee( inL , false );
++changedLocal;
}
}
}
} else { // no conflict ********** add or delete remote
if ( filterIN.name().isEmpty() || filterIN.filterAddressee( inR ) ) {
if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) {
QString des = addresseeLSync.note();
if ( des.find( inR.getID(mCurrentSyncDevice) +"," ) >= 0 && mode != 5) { // delete it
inR.setTempSyncStat( SYNC_TEMPSTATE_DELETE );
remote->insertAddressee( inR, false );
++deletedAddresseeR;
} else {
inR.setRevision( modifiedCalendar );
remote->insertAddressee( inR, false );
inL = inR;
inL.setIDStr( ":" );
inL.setCsum( mCurrentSyncDevice, inR.getCsum(mCurrentSyncDevice) );
inL.setID( mCurrentSyncDevice, inR.getID(mCurrentSyncDevice) );
inL.setResource( 0 );
local->insertAddressee( inL , false);
++addedAddressee;
}
} else {
if ( inR.revision() > mLastAddressbookSync || mode == 5 ) {
inR.setRevision( modifiedCalendar );
remote->insertAddressee( inR, false );
inR.setResource( 0 );
local->insertAddressee( inR, false );
++addedAddressee;
} else {
// pending checkExternSyncAddressee(addresseeRSyncSharp, inR);
remote->removeAddressee( inR );
++deletedAddresseeR;
}
}
} else {
++filteredIN;
}
}
}
++incCounter;
}
er.clear();
QStringList el = local->uidList();
modulo = (el.count()/10)+1;
syncManager->showProgressBar(0, i18n("Add / remove addressees"), el.count());
incCounter = 0;
while ( incCounter < el.count()) {
qApp->processEvents();
if (syncManager->isProgressBarCanceled())
return false;
if ( incCounter % modulo == 0 )
syncManager->showProgressBar(incCounter);
uid = el[ incCounter ];
bool skipIncidence = false;
if ( uid.left(19) == QString("last-syncAddressee-") )
skipIncidence = true;
if ( !skipIncidence ) {
inL = local->findByUid( uid );
if ( !inL.resource() || inL.resource()->includeInSync() ) {
inR = remote->findByUid( uid );
if ( inR.isEmpty() ){
if ( filterOUT.name().isEmpty() || filterOUT.filterAddressee( inL ) ) {
// no conflict ********** add or delete local
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 ) {
//qDebug("data %s ", inL.revision().toString().latin1());
// pending checkExternSyncAddressee(addresseeLSyncSharp, inL);
local->removeAddressee( inL );
++deletedAddresseeL;
} else {
if ( ! syncManager->mWriteBackExistingOnly ) {
++addedAddresseeR;
inL.setRevision( modifiedCalendar );
local->insertAddressee( inL, false );
inR = inL;
inR.setIDStr( ":" );
inR.setResource( 0 );
remote->insertAddressee( inR, false );
}
}
}
} else {
++filteredOUT;
}
}
}
}
++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 %d incoming filtered out\n %d outgoing filtered out"),addedAddressee, addedAddresseeR, changedLocal, changedRemote, deletedAddresseeL, deletedAddresseeR, filteredIN, filteredOUT );
qDebug( mes );
mes = i18n("Local addressbook changed!\n") +mes;
if ( syncManager->mShowSyncSummary ) {
if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel(this, mes,
i18n("KA/Pi Synchronization"),i18n("Write back"))) {
qDebug("KA: WB cancelled ");
syncManager->mWriteBackFile = false;
return syncOK;
}
}
return syncOK;
}
//this is a overwritten callbackmethods from the syncinterface
bool KABCore::sync(KSyncManager* manager, QString filename, int mode,QString resource)
{
//pending prepare addresseeview for output
//pending detect, if remote file has REV field. if not switch to external sync
mGlobalSyncMode = SYNC_MODE_NORMAL;
if ( manager != syncManager )
qDebug("KABCore::sync:: ERROR! :: manager != syncManager ");
QString mCurrentSyncDevice = manager->getCurrentSyncDevice();
AddressBook abLocal(filename,"syncContact");
bool syncOK = false;
if ( abLocal.load() ) {
qDebug("KA: Sync::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, true );
} else {
external = !manager->mIsKapiFile;
if ( external ) {
qDebug("KA: Sync::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 );
syncManager->hideProgressBar();
if ( syncOK ) {
if ( syncManager->mWriteBackFile )
{
if ( external )
abLocal.removeSyncAddressees( !isXML);
qDebug("KA: Sync::Saving remote AB ");
if ( ! abLocal.saveAB())
qDebug("KA: sync::Error writing back AB to file ");
if ( external ) {
// afterwrite processing
abLocal.postExternSync( mAddressBook,mCurrentSyncDevice ,isXML);
}
}
}
setModified();
}
abLocal.removeResources();
if ( syncOK )
mViewManager->refreshView();
return syncOK;
}
void KABCore::removeSyncInfo( QString syncProfile)
{
qDebug("KA: AB:removeSyncInfo for profile %s ", syncProfile.latin1());
mAddressBook->removeSyncInfo( syncProfile );
setModified();
}
+bool KABCore::syncOL()
+{
+ disableBR( true );
+ QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
+ AddressBook abLocal;
+ if ( ! readOLdata( &abLocal ) )
+ return false;
+ bool syncOK = false;
+ message(i18n("Data from OL loaded..."), false);
+ mGlobalSyncMode = SYNC_MODE_EXTERNAL;
+ message(i18n("Sync preprocessing..."),false);
+ abLocal.preOLSync( mAddressBook ,mCurrentSyncDevice );
+ message(i18n("Synchronizing..."),false);
+ syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, syncManager->mSyncAlgoPrefs );
+ syncManager->hideProgressBar();
+ if ( syncOK ) {
+ if ( syncManager->mWriteBackFile ) {
+ abLocal.removeSyncAddressees( false );
+ message(i18n("Saving address data to OL..."),false);
+ //abLocal.saveAB();
+ writeOLdata( &abLocal );
+ message(i18n("Sync postprocessing..."),false);
+ abLocal.postExternSync( mAddressBook,mCurrentSyncDevice, true );
+ }
+ } else
+ message( i18n("Sync cancelled or failed.") );
+ setModified();
+ abLocal.removeResources();
+ if ( syncOK ) {
+ mViewManager->refreshView();
+ message(i18n("OL syncing finished."));
+ }
+ disableBR( false );
+ return syncOK;
+}
//this is a overwritten callbackmethods from the syncinterface
bool KABCore::syncExternal(KSyncManager* manager, QString resource)
{
if ( resource == "phone" )
return syncPhone();
+ if ( resource == "ol" )
+ return syncOL();
disableBR( true );
if ( manager != syncManager )
qDebug("KABCore::syncExternal:: ERROR! :: manager != syncManager ");
QString mCurrentSyncDevice = manager->getCurrentSyncDevice();
AddressBook abLocal( resource,"syncContact");
bool syncOK = false;
message(i18n("Loading DTM address data..."), false);
if ( abLocal.load() ) {
qDebug("KA: AB sharp loaded ,sync device %s",mCurrentSyncDevice.latin1());
mGlobalSyncMode = SYNC_MODE_EXTERNAL;
message(i18n("Sync preprocessing..."),false);
abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice, false );
message(i18n("Synchronizing..."),false);
syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, syncManager->mSyncAlgoPrefs );
syncManager->hideProgressBar();
if ( syncOK ) {
if ( syncManager->mWriteBackFile ) {
abLocal.removeSyncAddressees( false );
message(i18n("Saving DTM address data..."),false);
abLocal.saveAB();
message(i18n("Sync postprocessing..."),false);
abLocal.postExternSync( mAddressBook,mCurrentSyncDevice, true );
}
} else
message( i18n("Sync cancelled or failed.") );
setModified();
}
abLocal.removeResources();
if ( syncOK ) {
mViewManager->refreshView();
message(i18n("DTM syncing finished."));
}
disableBR( false );
return syncOK;
}
void KABCore::message( QString m, bool startTimer)
{
topLevelWidget()->setCaption( m );
qApp->processEvents();
if ( startTimer )
mMessageTimer->start( 15000, true );
else
mMessageTimer->stop();
}
bool KABCore::syncPhone()
{
QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice();
QString fileName = getPhoneFile();
if ( !PhoneAccess::readFromPhone( fileName) ) {
message(i18n("Phone access failed!"));
return false;
}
AddressBook abLocal( fileName,"syncContact");
bool syncOK = false;
{
abLocal.importFromFile( fileName );
qDebug("KA: AB phone loaded ,sync device %s",mCurrentSyncDevice.latin1());
mGlobalSyncMode = SYNC_MODE_EXTERNAL;
abLocal.preparePhoneSync( mCurrentSyncDevice, true );
abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice, true );
syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, syncManager->mSyncAlgoPrefs );
syncManager->hideProgressBar();
if ( syncOK ) {
if ( syncManager->mWriteBackFile ) {
abLocal.removeSyncAddressees( true );
abLocal.saveABphone( fileName );
abLocal.findNewExtIds( fileName, mCurrentSyncDevice );
//abLocal.preparePhoneSync( mCurrentSyncDevice, false );
abLocal.postExternSync( mAddressBook,mCurrentSyncDevice, true );
}
}
setModified();
}
abLocal.removeResources();
if ( syncOK )
mViewManager->refreshView();
return syncOK;
}
void KABCore::getFile( bool success ,const QString & resource)
{
if ( ! success ) {
message( i18n("Error receiving file. Nothing changed!") );
return;
}
int count = mAddressBook->importFromFile( sentSyncFile() , false, true ,resource);
if ( count )
setModified( true );
message( i18n("Pi-Sync successful!") );
mViewManager->refreshView();
}
void KABCore::syncFileRequest(const QString & resource)
{
if ( KABPrefs::instance()->mPassiveSyncWithDesktop ) {
syncManager->slotSyncMenu( 999 );
}
if ( resource == "ALL" ) {
mAddressBook->export2File( sentSyncFile() );
}
else
mAddressBook->export2File( sentSyncFile(), resource);
}
QString KABCore::sentSyncFile()
{
#ifdef DESKTOP_VERSION
return locateLocal( "tmp", "copysyncab.vcf" );
#else
return QString( "/tmp/copysyncab.vcf" );
#endif
}
void KABCore::setCaptionBack()
{
mMessageTimer->stop();
topLevelWidget()->setCaption( i18n("KA/Pi") );
}
diff --git a/kaddressbook/kabcore.h b/kaddressbook/kabcore.h
index e69cb60..ec6a9ec 100644
--- a/kaddressbook/kabcore.h
+++ b/kaddressbook/kabcore.h
@@ -1,535 +1,540 @@
/*
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.
*/
#ifndef KABCORE_H
#define KABCORE_H
#include <kabc/field.h>
#ifndef KAB_EMBEDDED
#endif //KAB_EMBEDDED
#include <qdict.h>
#include <qtimer.h>
#include <qwidget.h>
#include <qpopupmenu.h>
#include <ksyncmanager.h>
#ifndef DESKTOP_VERSION
#include <qcopchannel_qws.h>
#endif
namespace KABC {
class AddressBook;
}
#ifndef KAB_EMBEDDED
class KAboutData;
class KConfig;
class KAddressBookService;
class LDAPSearchDialog;
#else //KAB_EMBEDDED
class KAddressBookMain;
//US class QAction;
#endif //KAB_EMBEDDED
class KCMultiDialog;
class KXMLGUIClient;
class ExtensionManager;
class XXPortManager;
class JumpButtonBar;
class IncSearchWidget;
class KDGanttMinimizeSplitter;
class KAction;
class KActionCollection;
class KToggleAction;
class KSyncProfile;
class QAction;
class QMenuBar;
class QSplitter;
class ViewContainer;
class ViewManager;
class AddresseeEditorDialog;
class Ir;
class KABCore : public QWidget, public KSyncInterface
{
Q_OBJECT
public:
KABCore( KAddressBookMain *client, bool readWrite, QWidget *parent, const char *name = 0 );
~KABCore();
#ifdef KAB_EMBEDDED
//US added functionality
QPopupMenu* getViewMenu() {return viewMenu;}
QPopupMenu* getFilterMenu() {return filterMenu;}
QPopupMenu* getSettingsMenu() {return settingsMenu;}
void addActionsManually();
#endif //KAB_EMBEDDED
/**
Restores the global settings.
*/
void restoreSettings();
/**
Returns a pointer to the StdAddressBook of the application.
*/
KABC::AddressBook *addressBook() const;
/**
Returns a pointer to the KConfig object of the application.
*/
static KConfig *config();
/**
Returns a pointer to the global KActionCollection object. So
other classes can register their actions easily.
*/
KActionCollection *actionCollection() const;
/**
Returns the current search field of the Incremental Search Widget.
*/
KABC::Field *currentSearchField() const;
/**
Returns the uid list of the currently selected contacts.
*/
QStringList selectedUIDs() const;
/**
Displays the ResourceSelectDialog and returns the selected
resource or a null pointer if no resource was selected by
the user.
*/
KABC::Resource *requestResource( QWidget *parent );
#ifndef KAB_EMBEDDED
static KAboutData *createAboutData();
#endif //KAB_EMBEDDED
#ifdef KAB_EMBEDDED
inline QPopupMenu* getImportMenu() { return ImportMenu;}
inline QPopupMenu* getExportMenu() { return ExportMenu;}
#endif //KAB_EMBEDDED
public slots:
#ifdef KAB_EMBEDDED
void createAboutData();
#endif //KAB_EMBEDDED
void setDetailsToggle();
void showLicence();
void faq();
void whatsnew() ;
void synchowto() ;
void storagehowto() ;
void multisynchowto() ;
void kdesynchowto() ;
void writeToPhone();
/**
Is called whenever a contact is selected in the view.
*/
void setContactSelected( const QString &uid );
/**
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();
void manageCategories();
void editCategories();
/**
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 );
void incrementalSearchJump( 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 );
void addrModified( const KABC::Addressee &addr, bool updateDetails = true );
/**
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();
void openConfigGlobalDialog();
/**
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 loadDataAfterStart();
void recieve(QString cmsg );
void getFile( bool success,const QString & );
void syncFileRequest(const QString &);
void setDetailsVisible( bool visible );
void setDetailsToState();
void saveSettings();
private slots:
void updateToolBar();
void updateMainWindow();
void receive( const QCString& cmsg, const QByteArray& data );
void receiveStart( const QCString& cmsg, const QByteArray& data );
void toggleBeamReceive( );
void disableBR(bool);
void setJumpButtonBarVisible( bool visible );
void setJumpButtonBar( bool visible );
void setCaptionBack();
void resizeAndCallContactdialog();
void callContactdialog();
void doRingSync();
void importFromOL();
void extensionModified( const KABC::Addressee::List &list );
void extensionChanged( int id );
void clipboardDataChanged();
void updateActionMenu();
void configureKeyBindings();
void removeVoice();
void setFormattedName();
#ifdef KAB_EMBEDDED
void configureResources();
#endif //KAB_EMBEDDED
void slotEditorDestroyed( const QString &uid );
void configurationChanged();
void addressBookChanged();
private:
QCString mCStringMess;
QByteArray mByteData;
QString mEmailSourceChannel;
QString mEmailSourceUID;
void resizeEvent(QResizeEvent* e );
bool mBRdisabled;
#ifndef DESKTOP_VERSION
QCopChannel* infrared;
#endif
QTimer *mMessageTimer;
void initGUI();
void initActions();
QString getPhoneFile();
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;
KToggleAction *mActionBR;
KAction *mActionExport2phone;
KAction* mActionPrint;
KAction* mActionPrintDetails;
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 *mActionConfigGlobal;
KAction *mActionConfigKAddressbook;
KAction *mActionConfigShortcuts;
KAction *mActionConfigureToolbars;
KAction *mActionKeyBindings;
KToggleAction *mActionJumpBar;
KToggleAction *mActionDetails;
KAction *mActionWhoAmI;
KAction *mActionCategories;
KAction *mActionEditCategories;
KAction *mActionManageCategories;
KAction *mActionAboutKAddressbook;
KAction *mActionLicence;
KAction *mActionFaq;
KAction *mActionWN;
KAction *mActionSyncHowto;
KAction *mActionStorageHowto;
KAction *mActionKdeSyncHowto;
KAction *mActionMultiSyncHowto;
KAction *mActionDeleteView;
QPopupMenu *viewMenu;
QPopupMenu *filterMenu;
QPopupMenu *settingsMenu;
QPopupMenu *changeMenu;
QPopupMenu *beamMenu;
//US QAction *mActionSave;
QPopupMenu *ImportMenu;
QPopupMenu *ExportMenu;
//LR additional methods
KAction *mActionRemoveVoice;
KAction *mActionSetFormattedName;
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,QString resource);
virtual bool syncExternal(KSyncManager* manager, QString resource);
virtual void removeSyncInfo( QString syncProfile);
+ bool readOLdata( KABC::AddressBook* local );
+ bool writeOLdata( KABC::AddressBook* local );
+ bool syncOL();
bool syncPhone();
void message( QString m , bool startTimer = true);
// 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 );
// *********************
+ //OL sync stuff
+ QString mOLsyncFolderID;
};
#endif
diff --git a/kaddressbook/kaimportoldialog.cpp b/kaddressbook/kaimportoldialog.cpp
index 2f794d6..6afc288 100644
--- a/kaddressbook/kaimportoldialog.cpp
+++ b/kaddressbook/kaimportoldialog.cpp
@@ -1,735 +1,23 @@
/*
This file is part of KAddressbook/Pi.
Copyright (c) 2004 Lutz Rogowski <rogowski@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
-#include <qtooltip.h>
-#include <qframe.h>
-#include <qpixmap.h>
-#include <qlayout.h>
-#include <qprogressbar.h>
-#include <qprogressdialog.h>
-#include <qwidgetstack.h>
-#include <qdatetime.h>
-#include <qdir.h>
-#include <qregexp.h>
-#include <qapplication.h>
-#include <qhbox.h>
-#include <qheader.h>
-#include <qdatetime.h>
-#include <qlistview.h>
-
-#include <kdebug.h>
-#include <klocale.h>
-#include <kstandarddirs.h>
-#include <kmessagebox.h>
-#include <kfiledialog.h>
-
-#include <libkdepim/categoryselectdialog.h>
-#include <libkdepim/kinputdialog.h>
-
-#include <libkcal/calendarlocal.h>
-#include <libkcal/icalformat.h>
-
-#include <kabc/addresseelist.h>
-#include <kabc/phonenumber.h>
-
-#include "kaimportoldialog.h"
-
-#include "../outport/msoutl9.h"
-#include <ole2.h>
-#include <comutil.h>
-_Application gOlAppAB;
-
-QDateTime mDdate2Qdtr( DATE dt)
-{
- COleDateTime odt;
- SYSTEMTIME st;
- odt = dt;
- if ( odt.GetStatus() != 0 )
- return QDateTime();
- odt.GetAsSystemTime(st);
- if ( st.wYear > 4000 ) // this program as a year 4000 bug!
- return QDateTime();
- // it seems so, that 1.1.4501 indicates: DATE invalid
- QDateTime qdt (QDate(st.wYear, st.wMonth,st.wDay ),QTime( st.wHour, st.wMinute,st.wSecond ) );
- return qdt;
-}
-
-class OLEListViewItem : public QCheckListItem
-{
- public:
- OLEListViewItem( QListView *parent, QString text ) :
- QCheckListItem( parent, text, QCheckListItem::CheckBox ) { ; };
- OLEListViewItem( QListViewItem *after, QString text ) :
- QCheckListItem( after, text, QCheckListItem::CheckBox ) { ; };
- ~OLEListViewItem() {};
- void setData( DWORD data ) {mData= data; };
- DWORD data() { return mData ;};
- private:
- DWORD mData;
-};
-
-KAImportOLdialog::KAImportOLdialog( const QString &caption,
- KABC::AddressBook * aBook, QWidget *parent ) :
- KDialogBase( Plain, caption, User1 | Close, Ok,
- parent, caption, true, false, i18n("Import!") )
-{
- QHBox * mw = new QHBox( this );
- setMainWidget( mw );
- mListView = new QListView( mw );
- mListView->addColumn(i18n("Select Folder to import"));
- mListView->addColumn(i18n("Content Type"));
- mABook = aBook;
- connect( this, SIGNAL( user1Clicked() ),SLOT ( slotApply()));
- setupFolderView();
- resize( sizeHint().width()+50, sizeHint().height()+50 );
-}
-
-KAImportOLdialog::~KAImportOLdialog()
-{
-
-}
-
-KABC::Addressee::List KAImportOLdialog::getAddressList()
-{
- return mAList;
-}
-void KAImportOLdialog::setupFolderView()
-{
- SCODE sc = ::OleInitialize(NULL);
- if ( FAILED ( sc ) ) {
- KMessageBox::information(this,"OLE initialisation failed");
- return;
- }
-
- if(!gOlAppAB.CreateDispatch(_T("Outlook.Application"),NULL)){
- KMessageBox::information(this,"Sorry, cannot access Outlook");
- return ;
- }
- MAPIFolder mfInbox;
- MAPIFolder mfRoot;
- CString szName;
- _NameSpace olNS;
- olNS = gOlAppAB.GetNamespace(_T("MAPI"));
- mfInbox = olNS.GetDefaultFolder(6);
- mfRoot = mfInbox.GetParent();
- szName = mfRoot.GetName();
- long iType = mfRoot.GetDefaultItemType();
- QString mes;
- mes = QString::fromUcs2( szName.GetBuffer() );
- OLEListViewItem * root = new OLEListViewItem( mListView, mes );
- mfRoot.m_lpDispatch->AddRef();
- addFolder( root, mfRoot.m_lpDispatch );
- root->setOpen( true );
- mListView->setSortColumn( 0 );
- mListView->sort( );
-}
-
-
-void KAImportOLdialog::addFolder(OLEListViewItem* iParent, LPDISPATCH dispParent)
-{
- MAPIFolder mfParent(dispParent), mfChild;
- _Folders folders;
- _variant_t fndx((long)0);
- CString szName;
- long iType;
- OLEListViewItem* hChild;
-
- folders = mfParent.GetFolders();
- for(int i=1; i <= folders.GetCount(); ++i)
- {
- fndx = (long)i;
- mfChild = folders.Item(fndx.Detach());
- mfChild.m_lpDispatch->AddRef();
- szName = mfChild.GetName();
- iType = mfChild.GetDefaultItemType();
- hChild = new OLEListViewItem( iParent , QString::fromUcs2( szName.GetBuffer() ) );
- if ( iType != 2)
- hChild->setEnabled( false );
- QString ts;
- switch( iType ) {
- case 0:
- ts = i18n("Mail");
- break;
- case 1:
- ts = i18n("Calendar");
- break;
- case 2:
- ts = i18n("Contacts");
- break;
- case 3:
- ts = i18n("Todos");
- break;
- case 4:
- ts = i18n("Journals");
- break;
- case 5:
- ts = i18n("Notes");
- break;
- default:
- ts = i18n("Unknown");
- }
- hChild->setText( 1,ts);
- hChild->setData( (DWORD) mfChild.m_lpDispatch );
- mfChild.m_lpDispatch->AddRef();
- addFolder(hChild, mfChild.m_lpDispatch);
- }
-}
-
-void KAImportOLdialog::slotApply()
-{
- importedItems = 0;
- OLEListViewItem* child = (OLEListViewItem*) mListView->firstChild();
- while ( child ) {
- if ( child->isOn() )
- readContactData( child->data() );
- child = (OLEListViewItem*) child->itemBelow();
- }
- QString mes = i18n("Importing complete.\n\n%1 items imported.").arg( importedItems);
- KMessageBox::information(this,mes);
-}
-void KAImportOLdialog::readContactData( DWORD folder )
-{
-
- LPDISPATCH dispItem = (LPDISPATCH)folder;
- dispItem->AddRef();
- MAPIFolder mf(dispItem);
- mf.m_lpDispatch->AddRef();
- _Items folderItems;
- _variant_t indx((long)0);
- LPDISPATCH itm;
- int i;
- folderItems = mf.GetItems();
- QProgressDialog bar( i18n("Importing contact data"),i18n("Abort"), folderItems.GetCount(),this);
- bar.setCaption (i18n("Importing!") );
- int h = bar.sizeHint().height() ;
- int w = 300;
- int dw = QApplication::desktop()->width();
- int dh = QApplication::desktop()->height();
- //bar.setGeometry( (dw-w)/2, (dh - h )/2 ,w,h );
- bar.show();
- for(i=1; i <= folderItems.GetCount(); ++i)
- {
- qApp->processEvents();
- if ( ! bar.isVisible() )
- return ;
- bar.setProgress( i );
- indx = (long)i;
- itm = folderItems.Item(indx.Detach());
- _ContactItem * pItem = (_ContactItem *)&itm;
- ol2kapiContact( pItem );
- itm->Release();
- }
-}
-void KAImportOLdialog::slotOk()
-{
- QDialog::accept();
-}
-
-void KAImportOLdialog::ol2kapiContact( _ContactItem * aItem )
-{
- KABC::Addressee addressee;
-
- addressee.setUid( QString::fromUcs2(aItem->GetEntryID().GetBuffer()));
- //GetLastModificationTime()
- //addressee.setName( const QString &name );
- //addressee.setFormattedName( const QString &formattedName );
- addressee.setFamilyName( QString::fromUcs2(aItem->GetLastName().GetBuffer()) );
- addressee.setGivenName( QString::fromUcs2(aItem->GetFirstName().GetBuffer()) );
- addressee.setAdditionalName( QString::fromUcs2(aItem->GetMiddleName().GetBuffer()) );
- addressee.setPrefix(QString::fromUcs2(aItem->GetTitle().GetBuffer()) );
- addressee.setSuffix( QString::fromUcs2(aItem->GetSuffix().GetBuffer()) );
- addressee.setNickName( QString::fromUcs2(aItem->GetNickName().GetBuffer()) );
- QDateTime dtb = mDdate2Qdtr(aItem->GetBirthday());
- if ( dtb.isValid() )
- addressee.setBirthday( mDdate2Qdtr(aItem->GetBirthday()));
-
- //QString::fromUcs2(aItem->.GetBuffer())
- //addressee.setMailer( const QString &mailer );
- //addressee.setTimeZone( const TimeZone &timeZone );
- //addressee.setGeo( const Geo &geo );
- //addressee.setTitle( QString::fromUcs2(aItem->GetJobTitle().GetBuffer()) );// titel is the prefix
- addressee.setRole( QString::fromUcs2(aItem->GetJobTitle().GetBuffer()) );
- addressee.setOrganization( QString::fromUcs2(aItem->GetCompanyName().GetBuffer()).replace( QRegExp("\\r"), "") );
- QString notesStr = QString::fromUcs2(aItem->GetBody().GetBuffer());
- notesStr.replace( QRegExp("\\r"), "");
-
- addressee.setProductId( QString::fromUcs2(aItem->GetCustomerID().GetBuffer()) );
- //addressee.setRevision( const QDateTime &revision );
- // addressee.setSortString( const QString &sortString );
- addressee.setUrl( QString::fromUcs2(aItem->GetWebPage().GetBuffer()) );
-
- QString tempS;
- tempS = QString::fromUcs2(aItem->GetNetMeetingAlias().GetBuffer())+" AT SERVER: " +QString::fromUcs2(aItem->GetNetMeetingServer().GetBuffer());
- if ( tempS.length() > 12 )
- addressee.insertCustom( "KADDRESSBOOK", "X-IMAddress", tempS );
- tempS = QString::fromUcs2(aItem->GetSpouse().GetBuffer());
- if ( !tempS.isEmpty() )
- addressee.insertCustom( "KADDRESSBOOK", "X-SpousesName", tempS );
- tempS = QString::fromUcs2(aItem->GetManagerName().GetBuffer());
- if ( !tempS.isEmpty() )
- addressee.insertCustom( "KADDRESSBOOK", "X-ManagersName", tempS );
- tempS = QString::fromUcs2(aItem->GetAssistantName().GetBuffer());
- if ( !tempS.isEmpty() )
- addressee.insertCustom( "KADDRESSBOOK", "X-AssistantsName", tempS );
- tempS = QString::fromUcs2(aItem->GetDepartment().GetBuffer());
- if ( !tempS.isEmpty() )
- addressee.insertCustom( "KADDRESSBOOK", "X-Department", tempS );
- tempS = QString::fromUcs2(aItem->GetOfficeLocation().GetBuffer()).replace( QRegExp("\\r"), "");
- if ( !tempS.isEmpty() )
- addressee.insertCustom( "KADDRESSBOOK", "X-Office",tempS );
- tempS = QString::fromUcs2(aItem->GetProfession().GetBuffer());
- if ( !tempS.isEmpty() )
- addressee.insertCustom( "KADDRESSBOOK", "X-Profession", tempS );
- dtb = mDdate2Qdtr(aItem->GetAnniversary());
- if (dtb.isValid() ) {
- QString dt = KGlobal::locale()->formatDate( dtb.date() , true, KLocale::ISODate);
- addressee.insertCustom( "KADDRESSBOOK", "X-Anniversary", dt);
- }
- int sec = aItem->GetSensitivity() ;
- if ( sec > 1 )// mapping pers -> private
- --sec;
- addressee.setSecrecy( sec );
- //addressee.setLogo( const Picture &logo );
- //addressee.setPhoto( const Picture &photo );
- //addressee.setSound( const Sound &sound );
- //addressee.setAgent( const Agent &agent );
- QString cat = QString::fromUcs2( aItem->GetCategories().GetBuffer()).replace( QRegExp("\\r"), "");
- cat = cat.replace( QRegExp("; "), ";");
- addressee.setCategories( QStringList::split( ";", cat ));
-
- QString phoneS;
-
- phoneS = QString::fromUcs2( aItem->GetAssistantTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Work + KABC::PhoneNumber::Voice ) );
- phoneS = QString::fromUcs2( aItem->GetBusinessTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Work ) );
- phoneS = QString::fromUcs2( aItem->GetBusiness2TelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Work ) );
- phoneS = QString::fromUcs2( aItem->GetBusinessFaxNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Work + KABC::PhoneNumber::Fax ) );
- phoneS = QString::fromUcs2( aItem->GetCarTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Car ) );
- phoneS = QString::fromUcs2( aItem->GetHomeTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Home ) );
- phoneS = QString::fromUcs2( aItem->GetHome2TelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Home ) );
- phoneS = QString::fromUcs2( aItem->GetHomeFaxNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Home + KABC::PhoneNumber::Fax ) );
- phoneS = QString::fromUcs2( aItem->GetISDNNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Isdn ) );
- phoneS = QString::fromUcs2( aItem->GetMobileTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Cell ) );
- phoneS = QString::fromUcs2( aItem->GetOtherFaxNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Fax ) );
- phoneS = QString::fromUcs2( aItem->GetOtherTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Voice ) );
- phoneS = QString::fromUcs2( aItem->GetPagerNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Pager ) );
- phoneS = QString::fromUcs2( aItem->GetPrimaryTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Pref ) );
- phoneS = QString::fromUcs2( aItem->GetTTYTDDTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Modem ) );
- phoneS = QString::fromUcs2( aItem->GetTelexNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Fax + KABC::PhoneNumber::Bbs ) );
- phoneS = QString::fromUcs2( aItem->GetCompanyMainTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Work + KABC::PhoneNumber::Pref ) );
- phoneS = QString::fromUcs2( aItem->GetRadioTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Video ) );
- phoneS = QString::fromUcs2( aItem->GetCallbackTelephoneNumber().GetBuffer());
- if ( ! phoneS.isEmpty())
- addressee.insertPhoneNumber( KABC::PhoneNumber(phoneS ,KABC::PhoneNumber::Voice + KABC::PhoneNumber::Pref ) );
-
- bool preferred = true;
- phoneS = QString::fromUcs2( aItem->GetEmail1Address().GetBuffer());
- if ( ! phoneS.isEmpty()) {
- addressee.insertEmail(phoneS , preferred );
- preferred = false;
- }
- phoneS = QString::fromUcs2( aItem->GetEmail2Address().GetBuffer());
- if ( ! phoneS.isEmpty()) {
- addressee.insertEmail(phoneS , preferred );
- preferred = false;
- }
- phoneS = QString::fromUcs2( aItem->GetEmail3Address().GetBuffer());
- if ( ! phoneS.isEmpty()) {
- addressee.insertEmail(phoneS , preferred );
- preferred = false;
- }
- // is this the number of the preferred email?
- // long GetSelectedMailingAddress();???
-
- KABC::Address addressHome;
- KABC::Address* addressAdd = &addressHome;
- bool insert = false;
- phoneS = QString::fromUcs2( aItem->GetHomeAddressCountry().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setCountry(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetHomeAddressState().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setRegion(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetHomeAddressCity().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setLocality(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetHomeAddressPostalCode().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setPostalCode(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetHomeAddressPostOfficeBox().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setPostOfficeBox(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetHomeAddressStreet().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setStreet(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetHomeAddress().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- // redundant !addressAdd->setExtended(phoneS );
- // insert = true;
- }
- addressAdd->setType( KABC::Address::Home );
- if ( insert )
- addressee.insertAddress( *addressAdd );
- // ++++++++++++++++++++++ end of address
-
- KABC::Address addressWork;
- addressAdd = &addressWork;
- insert = false;
- phoneS = QString::fromUcs2( aItem->GetBusinessAddressCountry().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setCountry(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetBusinessAddressState().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setRegion(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetBusinessAddressCity().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setLocality(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetBusinessAddressPostalCode().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setPostalCode(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetBusinessAddressPostOfficeBox().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setPostOfficeBox(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetBusinessAddressStreet().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setStreet(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetBusinessAddress().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- // redundant !addressAdd->setExtended(phoneS );
- // insert = true;
- }
- addressAdd->setType( KABC::Address::Work );
- if ( insert )
- addressee.insertAddress( *addressAdd );
- // ++++++++++++++++++++++ end of address
-
- KABC::Address addressOther;
- addressAdd = &addressOther;
- insert = false;
- phoneS = QString::fromUcs2( aItem->GetOtherAddressCountry().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setCountry(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetOtherAddressState().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setRegion(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetOtherAddressCity().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setLocality(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetOtherAddressPostalCode().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setPostalCode(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetOtherAddressPostOfficeBox().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setPostOfficeBox(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetOtherAddressStreet().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setStreet(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetOtherAddress().GetBuffer());
- if ( ! phoneS.isEmpty()) {
- // redundant !addressAdd->setExtended(phoneS );
- //insert = true;
- }
- //addressAdd->setId( );
- if ( insert )
- addressee.insertAddress( *addressAdd );
- // ++++++++++++++++++++++ end of address
- KABC::Address addressMail;
- addressAdd = &addressMail;
- insert = false;
- phoneS = QString::fromUcs2( aItem->GetMailingAddressCountry().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setCountry(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetMailingAddressState().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setRegion(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetMailingAddressCity().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setLocality(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetMailingAddressPostalCode().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setPostalCode(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetMailingAddressPostOfficeBox().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setPostOfficeBox(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetMailingAddressStreet().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- addressAdd->setStreet(phoneS );
- insert = true;
- }
- phoneS = QString::fromUcs2( aItem->GetMailingAddress().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! phoneS.isEmpty()) {
- // redundant ! addressAdd->setExtended(phoneS );
- // insert = true;
- }
- addressAdd->setType( KABC::Address::Postal );
- if ( insert ) {
- addressee.insertAddress( *addressAdd );
- }
- // the following code is disabled
- // it does not seem to be useful
-#if 0
- if ( insert ) {
- addressAdd->setType( KABC::Address::Home );
- if ( addressMail == addressHome ) {
- addressHome.setType( KABC::Address::Postal+ KABC::Address::Home );
- addressee.insertAddress( addressHome );
- } else {
- addressAdd->setType( KABC::Address::Work );
- if ( addressMail == addressWork ){
- addressWork.setType( KABC::Address::Postal+ KABC::Address::Work );
- addressee.insertAddress( addressWork );
-
- } else {
- addressAdd->setType( 0 );
- if ( addressOther == addressMail ){
- addressOther.setType( KABC::Address::Postal );
- addressee.insertAddress( addressOther );
- } else {
- addressee.insertAddress( *addressAdd );
- }
- }
- }
- }
-#endif
- // ++++++++++++++++++++++ end of ALL addresses
- //GetUserProperties();
- tempS = QString::fromUcs2(aItem->GetInternetFreeBusyAddress().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( !tempS.isEmpty() )
- addressee.insertCustom( "KADDRESSBOOK", "X-FreeBusyUrl", tempS );
- tempS = QString::fromUcs2(aItem->GetChildren().GetBuffer());
- if ( !tempS.isEmpty() )
- addressee.insertCustom( "KADDRESSBOOK", "X-Children", tempS );
- int gen = aItem->GetGender();
- if ( gen != 0 ) { // 0 undef - 1 female - 2 male
- if ( gen == 1 )
- addressee.insertCustom( "KADDRESSBOOK", "X-Gender", "female" );
- else
- addressee.insertCustom( "KADDRESSBOOK", "X-Gender", "male" );
- }
- QString additionalInfo;
- QString tempAdd;
- tempAdd = QString::fromUcs2(aItem->GetLanguage().GetBuffer());
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nLanguage: ");
- additionalInfo += tempAdd;
- }
- tempAdd = QString::fromUcs2(aItem->GetHobby().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nHobby: ");
- additionalInfo += tempAdd;;
- }
- tempAdd =QString::fromUcs2(aItem->GetPersonalHomePage().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nHomepage: ");
- additionalInfo += tempAdd;;
- }
- tempAdd = QString::fromUcs2(aItem->GetBillingInformation().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nBilling information: ");
- additionalInfo += tempAdd;;
- }
- tempAdd = QString::fromUcs2(aItem->GetCustomerID().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nCustomer ID: ");
- additionalInfo += tempAdd;;
- }
- tempAdd = QString::fromUcs2(aItem->GetUser1().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nUser1: ");
- additionalInfo += tempAdd;;
- }
- tempAdd = QString::fromUcs2(aItem->GetUser2().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nUser2: ");
- additionalInfo += tempAdd;;
- }
- tempAdd = QString::fromUcs2(aItem->GetUser3().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nUser3: ");
- additionalInfo += tempAdd;;
- }
- tempAdd = QString::fromUcs2(aItem->GetUser4().GetBuffer());
- phoneS.replace( QRegExp("\\r"), "");
- if ( ! tempAdd.isEmpty() ) {
- additionalInfo += i18n("\nUser4: ");
- additionalInfo += tempAdd;;
- }
- if (!additionalInfo.isEmpty() ) {
- tempAdd = notesStr;
- notesStr = "+++++++++++++++++++++++++++\n";
- notesStr += i18n("Additonal fields created\nby KA/Pi Outlook import:");
- notesStr += additionalInfo;
- notesStr += i18n("\nEnd additonal fields created\nby KA/Pi Outlook import!\n");
- notesStr += "+++++++++++++++++++++++++++\n";
- notesStr += tempAdd;
- }
- addressee.setNote( notesStr );
-#if 0
- // pending
- - IM address: no clue where to get info about the helper ID
- -custom fields: difficult to implement - not implemented
- -keys: makes no sense
-#endif
-
- if ( addAddressee( addressee ))
- ++importedItems;
-}
-void KAImportOLdialog::slotCancel()
-{
- reject();
-}
-
-bool KAImportOLdialog::addAddressee( KABC::Addressee a )
-{
- bool add = true;
- KABC::Addressee::List::Iterator it;
- for ( it = mAList.begin(); it != mAList.end(); ++it ) {
- if ( (*it).uid() == a.uid() ) {
- add = false;
- break;
- }
- }
- if ( add ) {
- if ( mABook->findByUid(a.uid() ).isEmpty())
- mAList.append ( a );
- else
- add = false;
- }
- return add;
-}
diff --git a/kaddressbook/kaimportoldialog.h b/kaddressbook/kaimportoldialog.h
index 41ea5f8..278935b 100644
--- a/kaddressbook/kaimportoldialog.h
+++ b/kaddressbook/kaimportoldialog.h
@@ -1,85 +1,22 @@
/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <schumacher@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.
*/
-#ifndef KOINCIDENCEEDITOR_H
-#define KOINCIDENCEEDITOR_H
-
-#include <kdialogbase.h>
-
-#include <afxdisp.h>
-
-#include <kabc/addressee.h>
-#include <kabc/addressbook.h>
-
-class QDateTime;
-class QListView;
-class OLEListViewItem;
-class _ContactItem;
-
-
-//using namespace KABC;
-//class KABC::AddressBook;
-
-/**
- This is the base class for the calendar component editors.
-*/
-class KAImportOLdialog : public KDialogBase
-{
- Q_OBJECT
- public:
- /**
- Construct new IncidenceEditor.
- */
- KAImportOLdialog( const QString &caption, KABC::AddressBook * aBook,
- QWidget *parent );
- ~KAImportOLdialog();
-
- /** Initialize editor. This function creates the tab widgets. */
- void init();
- KABC::Addressee::List getAddressList();
- public slots:
-
-
- signals:
-
- protected slots:
- void slotApply();
- void slotOk();
- void slotCancel();
-
- protected:
- void setupFolderView();
- void addFolder(OLEListViewItem* iParent, LPDISPATCH dispParent);
- void readContactData( DWORD folder );
- void ol2kapiContact( _ContactItem * );
-
- KABC::AddressBook * mABook;
- QListView * mListView;
- KABC::Addressee::List mAList;
- bool addAddressee( KABC::Addressee a );
- private:
- int importedItems;
-};
-
-#endif
-
-
diff --git a/kaddressbook/phoneeditwidget.cpp b/kaddressbook/phoneeditwidget.cpp
index 5639aa2..df3b551 100644
--- a/kaddressbook/phoneeditwidget.cpp
+++ b/kaddressbook/phoneeditwidget.cpp
@@ -1,728 +1,731 @@
/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <mpilone@slac.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlayout.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qstring.h>
#include <qlistbox.h>
#include <qlistview.h>
#include <qbuttongroup.h>
#include <qhbox.h>
#include <qcursor.h>
#include <qtimer.h>
#include <qapplication.h>
#include <kbuttonbox.h>
#include <klistview.h>
#include <kapplication.h>
#include <qapplication.h>
#include <kconfig.h>
+#include <kmessagebox.h>
#include <klineedit.h>
#include <kcombobox.h>
#include <klocale.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kabc/phonenumber.h>
#include "typecombo.h"
#include "phoneeditwidget.h"
PhoneEditWidget::PhoneEditWidget( QWidget *parent, const char *name )
: QWidget(parent,name)
{
QGridLayout* gridLayout = new QGridLayout ( this, 2,2 );
QLabel *temp = new QLabel( "", this );
temp->setAlignment( Qt::AlignCenter );
temp->setPixmap( KGlobal::iconLoader()->loadIcon( "kaddressbook", KIcon::Desktop, 0 ) );
QPushButton *addBut = new QPushButton ( "add", this );
addBut->setPixmap ( SmallIcon("plus"));
addBut->setMaximumSize( addBut->sizeHint().height(),addBut->sizeHint().height() );
connect(addBut,SIGNAL(clicked ()),SLOT(addNumber()));
sv = new QScrollView( this );
sv->setFrameStyle ( QFrame::Plain );
sv->setLineWidth ( 0 );
sv->setMidLineWidth ( 0 );
mw = new QWidget ( sv->viewport() );
sv->addChild(mw);
sv->setResizePolicy( QScrollView::AutoOneFit );
mainLayout = new QVBoxLayout ( mw );
mainLayout->setMargin( 0 );
mainLayout->setSpacing( 0 );
gridLayout->setMargin( 2 );
gridLayout->setSpacing( 4 );
if ( QApplication::desktop()->width() == 240 || QApplication::desktop()->width() == 480 ) {
gridLayout->addWidget( addBut, 0, 0 );
gridLayout->addWidget( temp, 0, 1 );
gridLayout->addMultiCellWidget( sv, 1,1 , 0,1 );
} else {
gridLayout->addWidget( temp, 1, 0 );
gridLayout->addWidget( addBut, 0, 0 );
gridLayout->addMultiCellWidget( sv, 0, 1, 1,1 );
}
setDefaults();
mTypeNumberEditList.setAutoDelete( true );
mPopup = new QPopupMenu( this );
QStringList list = PhoneNumber::supportedTypeListNames();
mPopupCount = list.count();
int i = 0;
while ( i < mPopupCount ) {
mPopup->insertItem( list[ i ], i );
++i;
}
connect(mPopup,SIGNAL(activated(int)),this,SLOT(addNumberInt( int)));
}
PhoneEditWidget::~PhoneEditWidget()
{
}
void PhoneEditWidget::setDefaults()
{
mTypeNumberEditList.clear();
PhoneTypeNumberEdit* edit = appendEditCombo();
KABC::PhoneNumber phoneNumber;
phoneNumber.setType( KABC::PhoneNumber::Home | KABC::PhoneNumber::Pref );
edit->setPhoneNumber( phoneNumber );
edit = appendEditCombo();
- phoneNumber.setType( KABC::PhoneNumber::Work | KABC::PhoneNumber::Pref );
- edit->setPhoneNumber( phoneNumber );
+ KABC::PhoneNumber phoneNumber2;
+ phoneNumber2.setType( KABC::PhoneNumber::Work | KABC::PhoneNumber::Pref );
+ edit->setPhoneNumber( phoneNumber2 );
edit = appendEditCombo();
- phoneNumber.setType( KABC::PhoneNumber::Cell );
- edit->setPhoneNumber( phoneNumber );
+ KABC::PhoneNumber phoneNumber3;
+ phoneNumber3.setType( KABC::PhoneNumber::Cell );
+ edit->setPhoneNumber( phoneNumber3 );
}
void PhoneEditWidget::addNumberInt( int index )
{
PhoneTypeNumberEdit* edit = appendEditCombo();
KABC::PhoneNumber phoneNumber;
phoneNumber.setType( PhoneNumber::supportedTypeList()[index] );
edit->setPhoneNumber( phoneNumber );
//verticalScrollBar()->setValue( 1024);
QTimer::singleShot( 0, this, SLOT ( bottomVisible() ) );
}
void PhoneEditWidget::bottomVisible()
{
sv->setContentsPos ( 0, 1024 );
}
void PhoneEditWidget::addNumber()
{
int i = 0;
while ( i < mPopupCount ) {
mPopup->setItemEnabled( i, true );
++i;
}
PhoneTypeNumberEdit* edit = mTypeNumberEditList.first();
while ( edit ) {
if ( edit->currentType() < mPopupCount -1 )
mPopup->setItemEnabled( edit->currentType(), false );
edit = mTypeNumberEditList.next();
}
mPopup->popup( QCursor::pos() );
}
PhoneTypeNumberEdit* PhoneEditWidget::appendEditCombo()
{
PhoneTypeNumberEdit* edit = new PhoneTypeNumberEdit( mw );
connect ( edit, SIGNAL ( typeChange( int , int) ), this, SIGNAL ( typeChange( int , int)) );
connect ( edit, SIGNAL ( modified() ), this, SIGNAL ( modified() ) );
connect ( edit, SIGNAL ( deleteMe( PhoneTypeNumberEdit* ) ), this, SLOT ( deleteEdit( PhoneTypeNumberEdit*) ) );
connect ( this, SIGNAL ( typeChange( int , int)), edit, SLOT ( typeExternalChanged( int, int)) );
mainLayout->add( edit );
mTypeNumberEditList.append( edit );
return edit;
}
void PhoneEditWidget::deleteEdit( PhoneTypeNumberEdit* ew )
{
mPendingDelete = ew;
QTimer::singleShot( 0, this, SLOT ( pendingDelete() ) );
}
void PhoneEditWidget::pendingDelete()
{
mTypeNumberEditList.removeRef( mPendingDelete );
emit modified();
}
void PhoneEditWidget::setPhoneNumbers( const KABC::PhoneNumber::List &li )
{
if ( li.isEmpty() ) {
setDefaults();
return;
}
mTypeNumberEditList.clear();
KABC::PhoneNumber::List::Iterator it;
KABC::PhoneNumber::List list2 = li;
KABC::PhoneNumber::List list ;
PhoneNumber::TypeList tList = PhoneNumber::supportedTypeList();
int i = 0;
int max = tList.count();
while ( i < max-1 ) {
for ( it = list2.begin(); it != list2.end(); ++it ) {
if ( (*it).type() == tList[i] ) {
list.append( (*it ) );
break;
}
}
++i;
}
for ( it = list2.begin(); it != list2.end(); ++it ) {
if ( (*it).type() == tList[ max-1 ] )
list.append( (*it ) );
}
for ( it = list.begin(); it != list.end(); ++it ) {
PhoneTypeNumberEdit* editNew = appendEditCombo();
editNew->setPhoneNumber( (*it ) );
}
}
KABC::PhoneNumber::List PhoneEditWidget::phoneNumbers()
{
KABC::PhoneNumber::List retList;
PhoneTypeNumberEdit* edit = mTypeNumberEditList.first();
while ( edit ) {
if ( edit->isValid() ) {
retList.append( edit->phoneNumber());
}
edit = mTypeNumberEditList.next();
}
return retList;
}
#if 0
PhoneEditWidget::PhoneEditWidget( QWidget *parent, const char *name )
: QWidget( parent, name )
{
QGridLayout *layout = new QGridLayout( this, 4, 1 );
//US layout->setSpacing( KDialog::spacingHint() );
layout->setSpacing( KDialogBase::spacingHintSmall() );
QLabel* label = new QLabel( this );
//US loadIcon call is ambiguous. Add one more parameter
//US label->setPixmap( KGlobal::iconLoader()->loadIcon( "kaddressbook", KIcon::Desktop ) );
label->setPixmap( KGlobal::iconLoader()->loadIcon( "kaddressbook", KIcon::Desktop, 0 ) );
label->setAlignment( AlignCenter );
//US layout->addMultiCellWidget( label, 0, 1, 3, 3 );
layout->addWidget( label, 0, 0 );
QPushButton *editButton = new QPushButton( i18n( "Edit Phone Numbers..." ),
this );
if ( QApplication::desktop()->width() < 640 )
layout->addWidget( editButton, 0, 1 );
else
layout->addMultiCellWidget( editButton, 0, 0, 1, 3);
mPrefCombo = new PhoneTypeCombo( mPhoneList, this );
mPrefEdit = new KLineEdit( this );
//mPrefEdit->setMinimumWidth( int(mPrefEdit->sizeHint().width() * 1.5) );
mPrefCombo->setLineEdit( mPrefEdit );
layout->addWidget( mPrefCombo, 1, 0 );
layout->addWidget( mPrefEdit, 1, 1 );
int x = 1, y = 2;
if ( QApplication::desktop()->width() < 640 ) {
++x;
y = 0;
}
mSecondCombo = new PhoneTypeCombo( mPhoneList, this );
mSecondEdit = new KLineEdit( this );
mSecondCombo->setLineEdit( mSecondEdit );
layout->addWidget( mSecondCombo, x, y++ );
layout->addWidget( mSecondEdit, x, y++ );
y = 0;
++x;
mThirdCombo = new PhoneTypeCombo( mPhoneList, this );
mThirdEdit = new KLineEdit( this );
mThirdCombo->setLineEdit( mThirdEdit );
layout->addWidget( mThirdCombo, x, y++ );
layout->addWidget( mThirdEdit, x, y++ );
if ( QApplication::desktop()->width() < 640 ) {
++x;
y = 0;
}
mFourthCombo = new PhoneTypeCombo( mPhoneList, this );
mFourthEdit = new KLineEdit( this );
mFourthCombo->setLineEdit( mFourthEdit );
layout->addWidget( mFourthCombo, x, y++ );
layout->addWidget( mFourthEdit, x, y++ );
// Four numbers don't fit in the current dialog
if ( QApplication::desktop()->width() < 640 ) {
mFourthCombo->hide();
mFourthEdit->hide();
} else {
QFontMetrics fm ( font () ) ;
int wid = fm.width( "Messenger" ) +60;
mPrefCombo->setMaximumWidth( wid );
mSecondCombo->setMaximumWidth( wid );
mThirdCombo->setMaximumWidth( wid );
mFourthCombo->setMaximumWidth( wid );
}
connect( mPrefEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotPrefEditChanged() ) );
connect( mSecondEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotSecondEditChanged() ) );
connect( mThirdEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotThirdEditChanged() ) );
connect( mFourthEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotFourthEditChanged() ) );
connect( editButton, SIGNAL( clicked() ), SLOT( edit() ) );
connect( mPrefCombo, SIGNAL( activated( int ) ),
SLOT( updatePrefEdit() ) );
connect( mSecondCombo, SIGNAL( activated( int ) ),
SLOT( updateSecondEdit() ) );
connect( mThirdCombo, SIGNAL( activated( int ) ),
SLOT( updateThirdEdit() ) );
connect( mFourthCombo, SIGNAL( activated( int ) ),
SLOT( updateFourthEdit() ) );
}
PhoneEditWidget::~PhoneEditWidget()
{
}
void PhoneEditWidget::setPhoneNumbers( const KABC::PhoneNumber::List &list )
{
mPhoneList.clear();
// Insert types for existing numbers.
mPrefCombo->insertTypeList( list );
QValueList<int> defaultTypes;
defaultTypes << KABC::PhoneNumber::Home;
defaultTypes << KABC::PhoneNumber::Work;
defaultTypes << KABC::PhoneNumber::Cell;
defaultTypes << ( KABC::PhoneNumber::Work | KABC::PhoneNumber::Fax );
defaultTypes << ( KABC::PhoneNumber::Home | KABC::PhoneNumber::Fax );
// Insert default types.
// Doing this for mPrefCombo is enough because the list is shared by all
// combos.
QValueList<int>::ConstIterator it;
for( it = defaultTypes.begin(); it != defaultTypes.end(); ++it ) {
if ( !mPrefCombo->hasType( *it ) )
mPrefCombo->insertType( list, *it, PhoneNumber( "", *it ) );
}
updateCombos();
mPrefCombo->selectType( defaultTypes[ 0 ] );
mSecondCombo->selectType( defaultTypes[ 1 ] );
mThirdCombo->selectType( defaultTypes[ 2 ] );
mFourthCombo->selectType( defaultTypes[ 3 ] );
updateLineEdits();
}
void PhoneEditWidget::updateLineEdits()
{
updatePrefEdit();
updateSecondEdit();
updateThirdEdit();
updateFourthEdit();
}
void PhoneEditWidget::updateCombos()
{
mPrefCombo->updateTypes();
mSecondCombo->updateTypes();
mThirdCombo->updateTypes();
mFourthCombo->updateTypes();
}
KABC::PhoneNumber::List PhoneEditWidget::phoneNumbers()
{
KABC::PhoneNumber::List retList;
KABC::PhoneNumber::List::Iterator it;
for ( it = mPhoneList.begin(); it != mPhoneList.end(); ++it )
if ( !(*it).number().isEmpty() )
retList.append( *it );
return retList;
}
void PhoneEditWidget::edit()
{
PhoneEditDialog dlg( mPhoneList, this );
if ( dlg.exec() ) {
if ( dlg.changed() ) {
KABC::PhoneNumber::List list = dlg.phoneNumbers();
setPhoneNumbers( list );
updateCombos();
updateLineEdits();
emit modified();
}
}
}
void PhoneEditWidget::updatePrefEdit()
{
updateEdit( mPrefCombo );
}
void PhoneEditWidget::updateSecondEdit()
{
updateEdit( mSecondCombo );
}
void PhoneEditWidget::updateThirdEdit()
{
updateEdit( mThirdCombo );
}
void PhoneEditWidget::updateFourthEdit()
{
updateEdit( mFourthCombo );
}
void PhoneEditWidget::updateEdit( PhoneTypeCombo *combo )
{
QLineEdit *edit = combo->lineEdit();
if ( !edit )
return;
#if 0
if ( edit == mPrefEdit ) kdDebug(5720) << " prefEdit" << endl;
if ( edit == mSecondEdit ) kdDebug(5720) << " secondEdit" << endl;
if ( edit == mThirdEdit ) kdDebug(5720) << " thirdEdit" << endl;
if ( edit == mFourthEdit ) kdDebug(5720) << " fourthEdit" << endl;
#endif
PhoneNumber::List::Iterator it = combo->selectedElement();
if ( it != mPhoneList.end() ) {
edit->setText( (*it).number() );
} else {
kdDebug(5720) << "PhoneEditWidget::updateEdit(): no selected element" << endl;
}
}
void PhoneEditWidget::slotPrefEditChanged()
{
updatePhoneNumber( mPrefCombo );
}
void PhoneEditWidget::slotSecondEditChanged()
{
updatePhoneNumber( mSecondCombo );
}
void PhoneEditWidget::slotThirdEditChanged()
{
updatePhoneNumber( mThirdCombo );
}
void PhoneEditWidget::slotFourthEditChanged()
{
updatePhoneNumber( mFourthCombo );
}
void PhoneEditWidget::updatePhoneNumber( PhoneTypeCombo *combo )
{
QLineEdit *edit = combo->lineEdit();
if ( !edit ) return;
PhoneNumber::List::Iterator it = combo->selectedElement();
if ( it != mPhoneList.end() ) {
(*it).setNumber( edit->text() );
}
updateOtherEdit( combo, mPrefCombo );
updateOtherEdit( combo, mSecondCombo );
updateOtherEdit( combo, mThirdCombo );
updateOtherEdit( combo, mFourthCombo );
emit modified();
}
void PhoneEditWidget::updateOtherEdit( PhoneTypeCombo *combo, PhoneTypeCombo *otherCombo )
{
if ( combo == otherCombo ) return;
if ( combo->currentItem() == otherCombo->currentItem() ) {
updateEdit( otherCombo );
}
}
///////////////////////////////////////////
// PhoneEditDialog
class PhoneViewItem : public QListViewItem
{
public:
PhoneViewItem( QListView *parent, const KABC::PhoneNumber &number );
void setPhoneNumber( const KABC::PhoneNumber &number )
{
mPhoneNumber = number;
makeText();
}
QString key() { return mPhoneNumber.id(); }
QString country() { return ""; }
QString region() { return ""; }
QString number() { return ""; }
KABC::PhoneNumber phoneNumber() { return mPhoneNumber; }
private:
void makeText();
KABC::PhoneNumber mPhoneNumber;
};
PhoneViewItem::PhoneViewItem( QListView *parent, const KABC::PhoneNumber &number )
: QListViewItem( parent ), mPhoneNumber( number )
{
#ifdef DESKTOP_VERSION
setRenameEnabled ( 0, true );
#endif
makeText();
}
void PhoneViewItem::makeText()
{
/**
* Will be used in future versions of kaddressbook/libkabc
setText( 0, mPhoneNumber.country() );
setText( 1, mPhoneNumber.region() );
setText( 2, mPhoneNumber.number() );
setText( 3, mPhoneNumber.typeLabel() );
*/
setText( 0, mPhoneNumber.number() );
setText( 1, mPhoneNumber.typeLabel() );
}
PhoneEditDialog::PhoneEditDialog( const KABC::PhoneNumber::List &list, QWidget *parent, const char *name )
: KDialogBase( KDialogBase::Plain, i18n( "Edit Phone Numbers" ),
KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
parent, name, true)
{
mPhoneNumberList = list;
QWidget *page = plainPage();
QGridLayout *layout = new QGridLayout( page, 1, 2 );
layout->setSpacing( spacingHint() );
mListView = new KListView( page );
mListView->setAllColumnsShowFocus( true );
mListView->addColumn( i18n( "Number" ) );
mListView->addColumn( i18n( "Type" ) );
KButtonBox *buttonBox = new KButtonBox( page, Vertical );
buttonBox->addButton( i18n( "&Add..." ), this, SLOT( slotAddPhoneNumber() ) );
mEditButton = buttonBox->addButton( i18n( "&Edit..." ), this, SLOT( slotEditPhoneNumber() ) );
mEditButton->setEnabled( false );
mRemoveButton = buttonBox->addButton( i18n( "&Remove" ), this, SLOT( slotRemovePhoneNumber() ) );
mRemoveButton->setEnabled( false );
buttonBox->layout();
layout->addWidget( mListView, 0, 0 );
layout->addWidget( buttonBox, 0, 1 );
connect( mListView, SIGNAL(selectionChanged()), SLOT(slotSelectionChanged()) );
connect( mListView, SIGNAL(doubleClicked( QListViewItem *, const QPoint &, int )), this, SLOT( slotEditPhoneNumber()));
KABC::PhoneNumber::List::Iterator it;
for ( it = mPhoneNumberList.begin(); it != mPhoneNumberList.end(); ++it )
new PhoneViewItem( mListView, *it );
if (QApplication::desktop()->width() < 480 )
showMaximized();
else
resize( 400, 400 );
mChanged = false;
}
PhoneEditDialog::~PhoneEditDialog()
{
qDebug("PhoneEditDialog::~PhoneEditDialog() ");
}
void PhoneEditDialog::slotAddPhoneNumber()
{
KABC::PhoneNumber tmp( "", 0 );
PhoneTypeDialog dlg( tmp, this );
if ( dlg.exec() ) {
QListViewItem* i = mListView->firstChild();
KABC::PhoneNumber phoneNumber = dlg.phoneNumber();
bool insert = true;
while ( i ) {
PhoneViewItem* p = ( PhoneViewItem* ) i;
KABC::PhoneNumber pn = p->phoneNumber();
if ( (pn.type() | KABC::PhoneNumber::Pref) == (phoneNumber.type() | KABC::PhoneNumber::Pref) ) {
if ( p->text(0).isEmpty()) {
p->setPhoneNumber( phoneNumber );
mPhoneNumberList.remove( pn );
mPhoneNumberList.append( phoneNumber );
insert = false;
break;
}
}
i = i->nextSibling();
}
if ( insert ) {
mPhoneNumberList.append( phoneNumber );
new PhoneViewItem( mListView, phoneNumber );
}
mChanged = true;
}
}
void PhoneEditDialog::slotRemovePhoneNumber()
{
PhoneViewItem *item = static_cast<PhoneViewItem*>( mListView->currentItem() );
if ( !item )
return;
mPhoneNumberList.remove( item->phoneNumber() );
QListViewItem *currItem = mListView->currentItem();
mListView->takeItem( currItem );
delete currItem;
mChanged = true;
}
void PhoneEditDialog::slotEditPhoneNumber()
{
PhoneViewItem *item = static_cast<PhoneViewItem*>( mListView->currentItem() );
if ( !item )
return;
PhoneTypeDialog dlg( item->phoneNumber(), this );
if ( dlg.exec() ) {
slotRemovePhoneNumber();
KABC::PhoneNumber phoneNumber = dlg.phoneNumber();
mPhoneNumberList.append( phoneNumber );
new PhoneViewItem( mListView, phoneNumber );
mChanged = true;
}
}
void PhoneEditDialog::slotSelectionChanged()
{
bool state = ( mListView->currentItem() != 0 );
mRemoveButton->setEnabled( state );
mEditButton->setEnabled( state );
}
const KABC::PhoneNumber::List &PhoneEditDialog::phoneNumbers()
{
return mPhoneNumberList;
}
bool PhoneEditDialog::changed() const
{
return mChanged;
}
///////////////////////////////////////////
// PhoneTypeDialog
PhoneTypeDialog::PhoneTypeDialog( const KABC::PhoneNumber &phoneNumber,
QWidget *parent, const char *name)
: KDialogBase( KDialogBase::Plain, i18n( "Edit Phone Number" ),
KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
parent, name, true), mPhoneNumber( phoneNumber )
{
QWidget *page = plainPage();
QLabel *label = 0;
QGridLayout *layout = new QGridLayout( page, 3, 2, marginHint(), spacingHint() );
label = new QLabel( i18n( "Number:" ), page );
layout->addWidget( label, 0, 0 );
mNumber = new KLineEdit( page );
layout->addWidget( mNumber, 0, 1 );
mPreferredBox = new QCheckBox( i18n( "This is the preferred phone number" ), page );
layout->addMultiCellWidget( mPreferredBox, 1, 1, 0, 1 );
mGroup = new QButtonGroup( 2, Horizontal, i18n( "Types" ), page );
layout->addMultiCellWidget( mGroup, 2, 2, 0, 1 );
// fill widgets
mNumber->setText( mPhoneNumber.number() );
mTypeList = KABC::PhoneNumber::typeList();
mTypeList.remove( KABC::PhoneNumber::Pref );
KABC::PhoneNumber::TypeList::Iterator it;
for ( it = mTypeList.begin(); it != mTypeList.end(); ++it )
new QCheckBox( KABC::PhoneNumber::typeLabel( *it ), mGroup );
for ( int i = 0; i < mGroup->count(); ++i ) {
int type = mPhoneNumber.type();
QCheckBox *box = (QCheckBox*)mGroup->find( i );
box->setChecked( type & mTypeList[ i ] );
}
mPreferredBox->setChecked( mPhoneNumber.type() & KABC::PhoneNumber::Pref );
mNumber->setFocus();
mNumber->setSelection( 0, 1024);
}
KABC::PhoneNumber PhoneTypeDialog::phoneNumber()
{
mPhoneNumber.setNumber( mNumber->text() );
int type = 0;
for ( int i = 0; i < mGroup->count(); ++i ) {
QCheckBox *box = (QCheckBox*)mGroup->find( i );
if ( box->isChecked() )
type += mTypeList[ i ];
}
if ( mPreferredBox->isChecked() )
mPhoneNumber.setType( type | KABC::PhoneNumber::Pref );
else
mPhoneNumber.setType( type & ~KABC::PhoneNumber::Pref );
return mPhoneNumber;
}
#endif
#ifndef KAB_EMBEDDED
#include "phoneeditwidget.moc"
#endif //KAB_EMBEDDED
diff --git a/korganizer/journalentry.h b/korganizer/journalentry.h
index a69846c..ee17da8 100644
--- a/korganizer/journalentry.h
+++ b/korganizer/journalentry.h
@@ -1,89 +1,90 @@
/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <schumacher@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.
*/
#ifndef JOURNALENTRY_H
#define JOURNALENTRY_H
//
// Widget showing one Journal entry
#include <qframe.h>
#include <libkcal/calendar.h>
class QLabel;
class KTextEdit;
class QComboBox;
class KLineEdit;
class KOLocationBox;
using namespace KCal;
class JournalEntry : public QFrame {
Q_OBJECT
public:
JournalEntry(Calendar *,QWidget *parent);
virtual ~JournalEntry();
void setJournal(Journal *, bool saveJournal = true );
Journal *journal() const;
void setDate(const QDate &);
void clear();
void flushEntry();
void setShowOnly();
QSize sizeHint() const;
void setVisibleMode( bool b ) { visibleMode = b;}
void fillCalendar( int id = 0 );
void resizeEvent(QResizeEvent* e ) ;
+ KTextEdit * editor() {return mEditor;};
protected slots:
void slotSaveTemplate();
void slotLoadTemplate();
void toggleShowJournal();
void setVisibleOn();
signals:
void deleteJournal(Journal *);
void newJournal();
void showJournalOnly( Journal * );
protected:
bool eventFilter( QObject *o, QEvent *e );
void writeJournal();
private:
int mMaxWidDiff;
int mDeskWid;
bool visibleMode;
bool showOnlyMode;
Calendar *mCalendar;
Journal *mJournal;
QDate mDate;
void keyPressEvent ( QKeyEvent * ) ;
QComboBox *mCalendarBox;
KOLocationBox * mTitle;
KTextEdit *mEditor;
int heiHint;
};
#endif
diff --git a/korganizer/kojournalview.cpp b/korganizer/kojournalview.cpp
index a23a3b2..406df5a 100644
--- a/korganizer/kojournalview.cpp
+++ b/korganizer/kojournalview.cpp
@@ -1,241 +1,250 @@
/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <schumacher@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.
*/
//
// View of Journal entries
#include <qlayout.h>
#include <qscrollview.h>
#include <qpopupmenu.h>
#include <qhbox.h>
#include <qpushbutton.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qapplication.h>
#include <klocale.h>
#include <kdebug.h>
#include "koprefs.h"
#include <kglobal.h>
+#include <ktextedit.h>
#include <libkcal/calendar.h>
#include "journalentry.h"
#include "kojournalview.h"
using namespace KOrg;
KOJournalView::KOJournalView(Calendar *calendar, QWidget *parent,
const char *name)
: KOrg::BaseView(calendar, parent, name)
{
mCalendar = calendar;
QHBox * vb = new QHBox ( this );
QPushButton * newJournal = new QPushButton( vb );
QPixmap icon;
if ( QApplication::desktop()->width() < 321 )
icon = SmallIcon("ko16old");
else
icon = SmallIcon("ko24old");
newJournal->setPixmap (icon ) ;
int size = newJournal->sizeHint().height();
newJournal->setFixedSize( size, size );
mDateLabel = new QLabel ( vb );
mDateLabel->setMargin(1);
mDateLabel->setAlignment(AlignCenter);
QScrollView * sv = new QScrollView( this );
QVBoxLayout * hbl = new QVBoxLayout( this );
hbl->addWidget( vb );
hbl->addWidget( sv );
parWid = new QWidget( sv->viewport() );
sv->addChild(parWid);
sv->setResizePolicy( QScrollView:: AutoOneFit );
mTopLayout = new QVBoxLayout(parWid);
connect( newJournal, SIGNAL( clicked() ), this , SLOT( newJournal() ) );
getNewEntry();
}
KOJournalView::~KOJournalView()
{
}
int KOJournalView::currentDateCount()
{
return 0;
}
JournalEntry* KOJournalView::getNewEntry()
{
JournalEntry* Entry = new JournalEntry(mCalendar,parWid);
jEntries.append( Entry );
mTopLayout->addWidget(Entry);
Entry->setFont ( KOPrefs::instance()->mJornalViewFont );
connect ( Entry,SIGNAL(deleteJournal(Journal *) ),this ,SIGNAL(deleteJournal(Journal *) ) ) ;
connect ( Entry,SIGNAL(newJournal() ),this ,SLOT(newJournal() ) ) ;
connect ( Entry,SIGNAL(showJournalOnly( Journal * ) ),this ,SLOT(showOnly ( Journal* ) ) ) ;
return Entry;
}
QPtrList<Incidence> KOJournalView::selectedIncidences()
{
QPtrList<Incidence> eventList;
return eventList;
}
void KOJournalView::updateConfig()
{
JournalEntry* mEntry = jEntries.first();
while ( mEntry ) {
mEntry->setFont ( KOPrefs::instance()->mJornalViewFont );
mEntry = jEntries.next();
}
}
void KOJournalView::updateView()
{
JournalEntry* mEntry = jEntries.first();
while ( mEntry ) {
mEntry->setFont ( KOPrefs::instance()->mJornalViewFont );
mEntry = jEntries.next();
}
showDates( mDate, QDate() );
}
void KOJournalView::checkModified()
{
flushView();
}
void KOJournalView::flushView()
{
static bool ff = false;
if ( ff ) return;
ff = true;
JournalEntry* mEntry = jEntries.first();
while ( mEntry ) {
mEntry->flushEntry();
mEntry = jEntries.next();
}
ff = false;
}
void KOJournalView::clearList()
{
JournalEntry* mEntry = jEntries.first();
while ( mEntry ) {
mEntry->clear();
mEntry = jEntries.next();
}
}
void KOJournalView::newJournal()
{
//qDebug(" KOJournalView::newJournal()");
flushView();
Journal* mJournal = new Journal;
mJournal->setDtStart(QDateTime(mDate,QTime(0,0,0)));
mCalendar->addJournal(mJournal);
showDates( mDate, QDate() );
}
void KOJournalView::showOnly ( Journal* j )
{
//qDebug("showOnly %x ", j);
flushView();
if ( j == 0 ) {
showDates( mDate, QDate() );
return;
}
QPtrList<Journal> jl;
jl.append ( j );
showList( jl );
JournalEntry* mEntry = jEntries.first();
mEntry->setShowOnly();
}
void KOJournalView::showList(QPtrList<Journal> jl)
{
static bool ff = false;
if ( ff ) return;
ff = true;
//qDebug("KOJournalView::showList %d",jl.count() );
JournalEntry* mEntry = jEntries.first();
JournalEntry* firstEntry = mEntry;
int count = jl.count();
int iii = 0;
+ QWidget* fw = qApp->focusWidget ();
while ( iii < count ) {
if ( !mEntry ) {
mEntry = getNewEntry();
mEntry->setVisibleMode( true );
mEntry->setDate(mDate);
mEntry->setJournal(jl.at(iii), false);
mEntry->setVisibleMode( true );
mEntry->show();
mEntry = 0;
} else {
+ int xxx = -1, yyy = -1;
+ if ( ((QWidget*) mEntry->editor() ) == fw ) {
+ mEntry->editor()->getCursorPosition( &xxx,&yyy);
+ }
mEntry->setVisibleMode( true );
mEntry->setDate(mDate);
mEntry->setJournal(jl.at(iii), false);
mEntry->setVisibleMode( true );
mEntry->show();
+ if ( xxx > -1 && yyy > -1 ) {
+ mEntry->editor()->setCursorPosition( xxx, yyy );
+ }
mEntry = jEntries.next();
}
++iii;
}
while ( mEntry ) {
mEntry->setDate(mDate);
mEntry->clear();
if ( mEntry != firstEntry ) {
mEntry->hide();
mEntry->setVisibleMode( false );
}
else {
mEntry->setVisibleMode( true );
mEntry->show();
}
mEntry = jEntries.next();
}
ff = false;
}
void KOJournalView::showDates(const QDate &start, const QDate &)
{
mDate = start;
mDateLabel->setText(KGlobal::locale()->formatDate(mDate));
QPtrList<Journal> jl = calendar()->journals4Date( start );
showList( jl );
}
void KOJournalView::showEvents(QPtrList<Event>)
{
// After new creation of list view no events are selected.
// emit incidenceSelected( 0 );
}
void KOJournalView::changeEventDisplay(Event *, int /*action*/)
{
updateView();
}
void KOJournalView::keyPressEvent ( QKeyEvent * e )
{
//qDebug("keyPressEven ");
if ( e->state() == Qt::ControlButton ) {
if ( e->key () == Qt::Key_Right || e->key () == Qt::Key_Left )
e->ignore();
}
}
diff --git a/libkdepim/externalapphandler.cpp b/libkdepim/externalapphandler.cpp
index 59be506..f376e6c 100644
--- a/libkdepim/externalapphandler.cpp
+++ b/libkdepim/externalapphandler.cpp
@@ -1,1319 +1,1321 @@
/*
This file is part of libkdepim.
Copyright (c) 2002 Cornelius Schumacher <schumacher@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 <stdlib.h>
#include <qfile.h>
#include <qtimer.h>
#include <qmap.h>
#include <qregexp.h>
#ifndef DESKTOP_VERSION
#include <qpe/qpeapplication.h>
#include <qtopia/qcopenvelope_qws.h>
#else
#include <qapplication.h>
#include <qprocess.h>
#endif
#include <kstaticdeleter.h>
#include <kmessagebox.h>
#include "externalapphandler.h"
#include "kpimglobalprefs.h"
//uncomment line to get debug output
//#define DEBUG_EXT_APP_HANDLER
/*********************************************************************************
*
********************************************************************************/
QCopTransferItem::QCopTransferItem(int usedSourceParameters, const QString& sourceMessage, const QString& targetChannel, const QString& targetMessage)
: _usedSourceParameters(usedSourceParameters), _sourceMessage(sourceMessage), _targetChannel(targetChannel), _targetMessage(targetMessage)
{
//sourceMessage passes later three parameters: sourceChannel, uid, param1
if (_usedSourceParameters == 0)
_sourceMessageParameters = "QString,QString)";
else if (_usedSourceParameters == 1)
_sourceMessageParameters = "(QString,QString,QString)";
else if (_usedSourceParameters == 2)
_sourceMessageParameters = "(QString,QString,QString,QString)";
else if (_usedSourceParameters == 3)
_sourceMessageParameters = "(QString,QString,QString,QString,QString)";
}
/*********************************************************************************/
QCopTransferItem::QCopTransferItem()
{
}
/*********************************************************************************/
bool QCopTransferItem::sendMessageToTarget(const QString& uid, const QString& param1, const QString& param2, const QString& param3)
{
#ifndef DESKTOP_VERSION
//sourceMessage passes two parameters: sourceChannel, uid
QString sourceMessage = _sourceMessage + _sourceMessageParameters;
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("1Using QCopEnvelope e(\"%s\",\"%s\")", _targetChannel.latin1(), sourceMessage.latin1());
qDebug("passing sourcechannel(%s), uid(%s), param1(%s), param2(%s), param3(%s) as parameter to QCopEnvelope", _sourceChannel.latin1(), uid.latin1(), param1.latin1(), param2.latin1(), param3.latin1());
#endif
QCopEnvelope e(_targetChannel.latin1(), sourceMessage.latin1());
e << _sourceChannel << uid;
if (_usedSourceParameters == 1)
e << param1;
else if (_usedSourceParameters == 2)
e << param1 << param2;
else if (_usedSourceParameters == 3)
e << param1 << param2 << param3;
qApp->processEvents();
return true;
#else
KMessageBox::sorry( 0, i18n( "This version does not support QCop." ) );
return false;
#endif
}
/*********************************************************************************/
void QCopTransferItem::setSourceChannel(const QString& sourceChannel)
{
if ( !sourceChannel.isEmpty())
_sourceChannel = sourceChannel;
}
/*********************************************************************************/
bool QCopTransferItem::appMessage( const QCString& cmsg, const QByteArray& data )
{
// copied from old mail2
/*
static int ii = 0;
// block second call
if ( ii < 2 ) {
++ii;
if ( ii > 1 ) {
qDebug("qcop call blocked ");
return true;
}
}
*/
// qDebug("QCopTransferItem- QCOP message received: %s ", cmsg.data() );
//we are in the target and get a request from the source
if ( (_sourceMessage + _sourceMessageParameters) == cmsg.data())
{
QDataStream stream( data, IO_ReadOnly );
QString sourceChannel;
QString uid;
QString param1;
QString param2;
QString param3;
stream >> sourceChannel >> uid;
if (_usedSourceParameters == 0)
{
emit receivedMessageFromSource(sourceChannel, uid);
}
else if (_usedSourceParameters == 1)
{
stream >> param1;
emit receivedMessageFromSource(sourceChannel, uid, param1);
}
else if (_usedSourceParameters == 2)
{
stream >> param1 >> param2;
emit receivedMessageFromSource(sourceChannel, uid, param1, param2);
}
else if (_usedSourceParameters == 3)
{
stream >> param1 >> param2 >> param3;
emit receivedMessageFromSource(sourceChannel, uid, param1, param2, param3);
}
return true;
}
return false;
}
/*********************************************************************************
*
********************************************************************************/
QCopMapTransferItem::QCopMapTransferItem(int usedSourceParameters, const QString& sourceMessage, const QString& targetChannel, const QString& targetMessage)
: QCopTransferItem(usedSourceParameters, sourceMessage, targetChannel,targetMessage)
{
//targetMessage returns later two parameters: uid, and map<qstring,qstring>
_targetMessageParameters = "(QString,QMAP<QString,QString>)";
}
/*********************************************************************************/
bool QCopMapTransferItem::sendMessageToSource(const QString& uid, const QMap<QString,QString>& nameEmailMap)
{
#ifndef DESKTOP_VERSION
//targetMessage passes two parameters: uid, map
QString targetMessage = _targetMessage + _targetMessageParameters;
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("2Using QCopEnvelope e(\"%s\",\"%s\")", _sourceChannel.latin1(), targetMessage.latin1());
qDebug("passing uid(%s) and map as parameter to QCopEnvelope", uid.latin1());
#endif
QCopEnvelope e(_sourceChannel.latin1(), targetMessage.latin1());
//US we need no names in the To field. The emailadresses are enough
e << uid << nameEmailMap;
qApp->processEvents();
return true;
#else
KMessageBox::sorry( 0, i18n( "This version does not support QCop." ) );
return false;
#endif
}
/*********************************************************************************/
bool QCopMapTransferItem::appMessage( const QCString& cmsg, const QByteArray& data )
{
bool res = QCopTransferItem::appMessage( cmsg, data );
if (res == false)
{
QDataStream stream( data, IO_ReadOnly );
// qDebug("QCopMapTransferItem- QCOP message received: %s ", cmsg.data() );
//we are in the source and get an answer from the target
if ((_targetMessage + _targetMessageParameters) == cmsg.data())
{
QMap<QString,QString> adrMap;
QString uid;
stream >> uid >> adrMap;
emit receivedMessageFromTarget(uid, adrMap);
return true;
}
}
return false;
}
/*********************************************************************************
*
********************************************************************************/
QCopListTransferItem::~QCopListTransferItem()
{
}
QCopListTransferItem::QCopListTransferItem(int usedSourceParameters, const QString& sourceMessage, const QString& targetChannel, const QString& targetMessage)
: QCopTransferItem(usedSourceParameters, sourceMessage, targetChannel,targetMessage)
{
//targetMessage returns later two parameters: uid, and three lists
_targetMessageParameters = "(QString,QStringList,QStringList,QStringList,QStringList,QStringList,QStringList)";
}
/*********************************************************************************/
bool QCopListTransferItem::sendMessageToSource(const QString& uid, const QStringList& list1, const QStringList& list2, const QStringList& list3, const QStringList& list4, const QStringList& list5, const QStringList& list6)
{
#ifndef DESKTOP_VERSION
//targetMessage passes two parameters: uid, map
QString targetMessage = _targetMessage + _targetMessageParameters;
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("3Using QCopEnvelope e(\"%s\",\"%s\")", _sourceChannel.latin1(), targetMessage.latin1());
qDebug("passing uid(%s) and list1, list2, list3, list4, list5, list6 as parameter to QCopEnvelope", uid.latin1());
for ( int i = 0; i < list3.count(); i++)
qDebug("listentry list3: %s",list3[i].latin1());
#endif
QCopEnvelope e(_sourceChannel.latin1(), targetMessage.latin1());
//US we need no names in the To field. The emailadresses are enough
e << uid << list1 << list2 << list3 << list4 << list5 << list6;
qApp->processEvents();
return true;
#else
KMessageBox::sorry( 0, i18n( "This version does not support QCop." ) );
return false;
#endif
}
/*********************************************************************************/
bool QCopListTransferItem::appMessage( const QCString& cmsg, const QByteArray& data )
{
bool res = QCopTransferItem::appMessage( cmsg, data );
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("1QCopListTransferItem- QCOP message received: %s ", cmsg.data() );
#endif
if (res == false)
{
QDataStream stream( data, IO_ReadOnly );
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("2QCopListTransferItem- QCOP message received: %s ", cmsg.data() );
#endif
//we are in the source and get an answer from the target
if ((_targetMessage + _targetMessageParameters) == cmsg.data())
{
QStringList list1;
QStringList list2;
QStringList list3;
QStringList list4;
QStringList list5;
QStringList list6;
QString uid;
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("3QCopListTransferItem- QCOP message received: %s ", cmsg.data() );
#endif
stream >> uid >> list1 >> list2 >> list3 >> list4 >> list5 >> list6;
emit receivedMessageFromTarget(uid, list1, list2, list3, list4, list5, list6);
return true;
}
}
return false;
}
/*********************************************************************************
*
********************************************************************************/
ExternalAppHandler *ExternalAppHandler::sInstance = 0;
static KStaticDeleter<ExternalAppHandler> staticDeleter;
ExternalAppHandler::ExternalAppHandler()
{
mDefaultItems.setAutoDelete(true);
mNameEmailUidListFromKAPITransfer = new QCopListTransferItem(0, "requestNameEmailUIDListFromKAPI", "QPE/Application/kapi", "receiveNameEmailUIDList");
connect(mNameEmailUidListFromKAPITransfer, SIGNAL (receivedMessageFromSource(const QString&, const QString&)), this, SIGNAL (requestForNameEmailUidList(const QString&, const QString&)));
connect(mNameEmailUidListFromKAPITransfer, SIGNAL (receivedMessageFromTarget(const QString&, const QStringList&, const QStringList&, const QStringList&, const QStringList&, const QStringList&, const QStringList&)), this, SLOT (receivedNameEmailUidList_Slot(const QString&, const QStringList&, const QStringList&, const QStringList&, const QStringList&, const QStringList&, const QStringList&)));
//US mFindByEmailFromKAPITransfer = new QCopListTransferItem(1, "requestFindByEmailFromKAPI", "QPE/Application/kapi", "receiveFindByEmailNameEmailUIDList");
//US connect(mFindByEmailFromKAPITransfer, SIGNAL (receivedMessageFromSource(const QString&, const QString&, const QString&)), this, SIGNAL (requestForFindByEmail(const QString&, const QString&, const QString&)));
//US connect(mFindByEmailFromKAPITransfer, SIGNAL (receivedMessageFromTarget(const QString&, const QStringList&, const QStringList&, const QStringList&)), this, SIGNAL (receivedFindByEmailEvent(const QString&, const QStringList&, const QStringList&, const QStringList&)));
mDisplayDetails = new QCopListTransferItem(3, "requestDisplayDetailsFromKAPI", "QPE/Application/kapi", "");
connect(mDisplayDetails, SIGNAL (receivedMessageFromSource(const QString&, const QString&, const QString&, const QString&, const QString&)), this, SIGNAL (requestForDetails(const QString&, const QString&, const QString&, const QString&, const QString&)));
mBirthdayListFromKAPITransfer = new QCopListTransferItem(0, "requestBirthdayListFromKAPI", "QPE/Application/kapi", "receiveBirthdayList");
connect(mBirthdayListFromKAPITransfer, SIGNAL (receivedMessageFromSource(const QString&, const QString&)), this, SIGNAL (requestForBirthdayList(const QString&, const QString&)));
connect(mBirthdayListFromKAPITransfer, SIGNAL (receivedMessageFromTarget(const QString&, const QStringList&, const QStringList&, const QStringList&, const QStringList&, const QStringList&, const QStringList&)), this, SIGNAL (receivedBirthdayListEvent(const QString&, const QStringList&, const QStringList&, const QStringList&, const QStringList&, const QStringList&, const QStringList&)));
}
ExternalAppHandler::~ExternalAppHandler()
{
delete mNameEmailUidListFromKAPITransfer;
//delete mFindByEmailFromKAPITransfer;
delete mDisplayDetails;
delete mBirthdayListFromKAPITransfer;
}
void ExternalAppHandler::receivedNameEmailUidList_Slot(const QString& uid,
const QStringList& nameList,
const QStringList& emailList,
const QStringList& uidList,
const QStringList&,
const QStringList&,
const QStringList& )
{
// this method is a conevnient way to reduce the number of parameters I have to pass
emit receivedNameEmailUidListEvent(uid, nameList, emailList, uidList);
}
void ExternalAppHandler::loadConfig()
{
mDefaultItems.clear();
mEmailAppAvailable = UNDEFINED;
mPhoneAppAvailable = UNDEFINED;
mFaxAppAvailable = UNDEFINED;
mSMSAppAvailable = UNDEFINED;
mPagerAppAvailable = UNDEFINED;
mSIPAppAvailable = UNDEFINED;
QString opiepath = QString::fromLatin1( getenv("OPIEDIR") );
QString qtopiapath = QString::fromLatin1( getenv("QPEDIR") );
QString qtpath = QString::fromLatin1( getenv("QTDIR") );
//if qtopiapath is not set, fallback to qt
if (qtopiapath.isEmpty())
qtopiapath = qtpath;
//if opiepath is not set, fallback to qtopia
if (opiepath.isEmpty())
opiepath = qtopiapath;
//mailclients
QString mailmsg1 = "writeMail(QString,QString)";
QString mailmsg2 = "writeMail(QMap(QString,QString))";
QString undefined = "";
addDefaultAppItem(ExternalAppHandler::EMAIL, KPimGlobalPrefs::NONE_EMC, "No email client installed", undefined, undefined, undefined, undefined, undefined);
addDefaultAppItem(ExternalAppHandler::EMAIL, KPimGlobalPrefs::OTHER_EMC, "Userdefined email client", undefined, undefined, undefined, undefined, undefined);
#ifdef DESKTOP_VERSION
QString appPath;
#ifdef _WIN32_
appPath = "C:\\Programme\\Mozilla Thunderbird\\thunderbird.exe";
#else
appPath = "/usr/bin/thunderbird";
#endif
addDefaultAppItem(ExternalAppHandler::EMAIL, KPimGlobalPrefs::OMPI_EMC, "Mozilla Thunderbird", appPath, "-compose", "to=%1 <%2>", ",", "subject=%1");
#ifdef _WIN32_
appPath = "C:\\Programme\\Mozilla\\mozilla.exe";
#else
appPath = "/usr/bin/mozilla";
#endif
addDefaultAppItem(ExternalAppHandler::EMAIL, KPimGlobalPrefs::QTOPIA_EMC, "Mozilla Suite", appPath, "-mail -compose", "to=%1 <%2>", ",", "subject=%1");
#else
if (( QFile::exists( qtopiapath + "/bin/ompi" )) ||
( QFile::exists( opiepath + "/bin/ompi" )) ||
( QFile::exists( qtpath + "/bin/ompi" )))
addDefaultAppItem(ExternalAppHandler::EMAIL, KPimGlobalPrefs::OMPI_EMC, "OM/Pi email client", "QPE/Application/ompi", mailmsg1, "%1;%2", mailmsg2, "TO=%1;ATTACHMENT=%2");
if (( QFile::exists( qtopiapath + "/bin/qtmail" )) ||
( QFile::exists( qtpath + "/bin/qtmail" )))
addDefaultAppItem(ExternalAppHandler::EMAIL, KPimGlobalPrefs::QTOPIA_EMC, "Qtopia email client", "QPE/Application/qtmail", mailmsg1, "%1;%2", mailmsg2, "TO=%1;ATTACHMENT=%2");
if ( QFile::exists( opiepath + "/bin/opiemail" ))
addDefaultAppItem(ExternalAppHandler::EMAIL, KPimGlobalPrefs::OPIE_EMC, "Opie email client", "QPE/Application/opiemail", mailmsg1, "%1;%2", mailmsg2, "TO=%1;ATTACHMENT=%2");
if ( QFile::exists( opiepath + "/bin/mailit" ))
addDefaultAppItem(ExternalAppHandler::EMAIL, KPimGlobalPrefs::OPIE_MAILIT_EMC, "Opie mailit email client", "QPE/Application/mailit", mailmsg1, "%1;%2", mailmsg2, "TO=%1;ATTACHMENT=%2");
#endif
//phoneclients
addDefaultAppItem(ExternalAppHandler::PHONE, KPimGlobalPrefs::NONE_PHC, "No phone client installed", undefined, undefined, undefined, undefined, undefined);
addDefaultAppItem(ExternalAppHandler::PHONE, KPimGlobalPrefs::OTHER_PHC, "Other phone client", undefined, undefined, undefined, undefined, undefined);
if (( QFile::exists( qtopiapath + "/bin/kppi" )) ||
( QFile::exists( opiepath + "/bin/kppi" )))
addDefaultAppItem(ExternalAppHandler::PHONE, KPimGlobalPrefs::KPPI_PHC, "KP/Pi phone client", "QPE/Application/kppi", "-ring:%1", "", undefined, undefined);
//faxclients
addDefaultAppItem(ExternalAppHandler::FAX, KPimGlobalPrefs::NONE_FAC, "No fax client installed", undefined, undefined, undefined, undefined, undefined);
addDefaultAppItem(ExternalAppHandler::FAX, KPimGlobalPrefs::OTHER_FAC, "Other fax client", undefined, undefined, undefined, undefined, undefined);
//smsclients
addDefaultAppItem(ExternalAppHandler::SMS, KPimGlobalPrefs::NONE_SMC, "No sms client installed", undefined, undefined, undefined, undefined, undefined);
addDefaultAppItem(ExternalAppHandler::SMS, KPimGlobalPrefs::OTHER_SMC, "Other sms client", undefined, undefined, undefined, undefined, undefined);
//pagerclients
addDefaultAppItem(ExternalAppHandler::PAGER, KPimGlobalPrefs::NONE_PAC, "No pager client installed", undefined, undefined, undefined, undefined, undefined);
addDefaultAppItem(ExternalAppHandler::PAGER, KPimGlobalPrefs::OTHER_PAC, "Other pager client", undefined, undefined, undefined, undefined, undefined);
//sipclients
addDefaultAppItem(ExternalAppHandler::SIP, KPimGlobalPrefs::NONE_SIC, "No SIP client installed", undefined, undefined, undefined, undefined, undefined);
addDefaultAppItem(ExternalAppHandler::SIP, KPimGlobalPrefs::OTHER_SIC, "Other SIP client", undefined, undefined, undefined, undefined, undefined);
if (( QFile::exists( qtopiapath + "/bin/kppi" )) ||
( QFile::exists( opiepath + "/bin/kppi" )))
addDefaultAppItem(ExternalAppHandler::SIP, KPimGlobalPrefs::KPPI_SIC, "KP/Pi SIP client", "QPE/Application/kppi", "-ring:%1", "", undefined, undefined);
}
ExternalAppHandler *ExternalAppHandler::instance()
{
if ( !sInstance ) {
sInstance = staticDeleter.setObject( new ExternalAppHandler() );
sInstance->loadConfig();
}
return sInstance;
}
void ExternalAppHandler::addDefaultAppItem(Types type, int id, const QString& label, const QString& channel, const QString& message, const QString& parameter, const QString& message2, const QString& parameter2)
{
DefaultAppItem* dai = new DefaultAppItem(type, id, label, channel, message, parameter, message2, parameter2);
// qDebug("%d %d %s %s ", type, id, label.latin1(), channel.latin1() );
mDefaultItems.append(dai);
}
QList<DefaultAppItem> ExternalAppHandler::getAvailableDefaultItems(Types type)
{
QList<DefaultAppItem> list;
DefaultAppItem* dai;
for ( dai=mDefaultItems.first(); dai != 0; dai=mDefaultItems.next() )
{
if (dai->_type == type)
list.append(dai);
}
return list;
}
DefaultAppItem* ExternalAppHandler::getDefaultItem(Types type, int clientid)
{
DefaultAppItem* dai;
for ( dai=mDefaultItems.first(); dai != 0; dai=mDefaultItems.next() )
{
if (dai->_type == type && dai->_id == clientid)
return dai;
}
return 0;
}
bool ExternalAppHandler::isEmailAppAvailable()
{
if (mEmailAppAvailable == UNDEFINED)
{
int client = KPimGlobalPrefs::instance()->mEmailClient;
if (client == KPimGlobalPrefs::NONE_EMC)
mEmailAppAvailable = UNAVAILABLE;
else
mEmailAppAvailable = AVAILABLE;
}
return (mEmailAppAvailable == AVAILABLE);
}
bool ExternalAppHandler::isSMSAppAvailable()
{
#ifndef DESKTOP_VERSION
if (mSMSAppAvailable == UNDEFINED)
{
int client = KPimGlobalPrefs::instance()->mSMSClient;
if (client == KPimGlobalPrefs::NONE_SMC)
mSMSAppAvailable = UNAVAILABLE;
else
mSMSAppAvailable = AVAILABLE;
}
return (mSMSAppAvailable == AVAILABLE);
#else //DESKTOP_VERSION
return false;
#endif //DESKTOP_VERSION
}
bool ExternalAppHandler::isPhoneAppAvailable()
{
#ifndef DESKTOP_VERSION
if (mPhoneAppAvailable == UNDEFINED)
{
int client = KPimGlobalPrefs::instance()->mPhoneClient;
if (client == KPimGlobalPrefs::NONE_PHC)
mPhoneAppAvailable = UNAVAILABLE;
else
mPhoneAppAvailable = AVAILABLE;
}
return (mPhoneAppAvailable == AVAILABLE);
#else //DESKTOP_VERSION
return false;
#endif //DESKTOP_VERSION
}
bool ExternalAppHandler::isFaxAppAvailable()
{
#ifndef DESKTOP_VERSION
if (mFaxAppAvailable == UNDEFINED)
{
int client = KPimGlobalPrefs::instance()->mFaxClient;
if (client == KPimGlobalPrefs::NONE_FAC)
mFaxAppAvailable = UNAVAILABLE;
else
mFaxAppAvailable = AVAILABLE;
}
return (mFaxAppAvailable == AVAILABLE);
#else //DESKTOP_VERSION
return false;
#endif //DESKTOP_VERSION
}
bool ExternalAppHandler::isPagerAppAvailable()
{
#ifndef DESKTOP_VERSION
if (mPagerAppAvailable == UNDEFINED)
{
int client = KPimGlobalPrefs::instance()->mPagerClient;
if (client == KPimGlobalPrefs::NONE_PAC)
mPagerAppAvailable = UNAVAILABLE;
else
mPagerAppAvailable = AVAILABLE;
}
return (mPagerAppAvailable == AVAILABLE);
#else //DESKTOP_VERSION
return false;
#endif //DESKTOP_VERSION
}
bool ExternalAppHandler::isSIPAppAvailable()
{
#ifndef DESKTOP_VERSION
if (mSIPAppAvailable == UNDEFINED)
{
int client = KPimGlobalPrefs::instance()->mSipClient;
if (client == KPimGlobalPrefs::NONE_SIC)
mSIPAppAvailable = UNAVAILABLE;
else
mSIPAppAvailable = AVAILABLE;
}
return (mSIPAppAvailable == AVAILABLE);
#else //DESKTOP_VERSION
return false;
#endif //DESKTOP_VERSION
}
/**************************************************************************
*
**************************************************************************/
//calls the emailapplication with a number of attachments that need to be send (Seperated by Comma)
bool ExternalAppHandler::mailToMultipleContacts( const QString& emails, const QString& urls )
{
#ifndef DESKTOP_VERSION
QString channel;
QString message2;
QString parameters2;
int client = KPimGlobalPrefs::instance()->mEmailClient;
if (client == KPimGlobalPrefs::OTHER_EMC)
{
channel = KPimGlobalPrefs::instance()->mEmailOtherChannel;
message2 = KPimGlobalPrefs::instance()->mEmailOtherMessage;
parameters2 = KPimGlobalPrefs::instance()->mEmailOtherMessageParameters;
}
else
{
DefaultAppItem* dai = getDefaultItem(EMAIL, client);
if (!dai)
{
qDebug("could not find configured email application.");
return false;
}
channel = dai->_channel;
message2 = dai->_message2;
parameters2 = dai->_parameters2;
}
//first check if one of the mailers need the emails right in the message.
message2 = translateMessage(message2, emails, urls);
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("4Using QCopEnvelope e(\"%s\",\"%s\")", channel.latin1(), message2.latin1());
qDebug("passing emailadresses(%s), attachmenturls(%s) as parameters in the form %s to QCopEnvelope", emails.latin1() , urls.latin1(), parameters2.latin1());
#endif
QCopEnvelope e(channel.latin1(), message2.latin1());
//US we need no names in the To field. The emailadresses are enough
passParameters(&e, parameters2, emails, urls);
#else
//qDebug("mtmc %s %s ", emails.latin1(), urls.latin1());
QString channel;
QString message2;
QString parameters2;
QString message;
QString parameters;
int client = KPimGlobalPrefs::instance()->mEmailClient;
if (client == KPimGlobalPrefs::OTHER_EMC)
{
channel = KPimGlobalPrefs::instance()->mEmailOtherChannel;
message = KPimGlobalPrefs::instance()->mEmailOtherMessage;
message2 = KPimGlobalPrefs::instance()->mEmailOtherMessage2;
parameters = KPimGlobalPrefs::instance()->mEmailOtherMessageParameters;
parameters2 = KPimGlobalPrefs::instance()->mEmailOtherMessageParameters2;
}
else
{
DefaultAppItem* dai = getDefaultItem(EMAIL, client);
if (!dai)
{
qDebug("could not find configured email application.");
return false;
}
channel = dai->_channel;
message2 = dai->_message2;
parameters2 = dai->_parameters2;
message = dai->_message;
parameters = dai->_parameters;
}
//first check if one of the mailers need the emails right in the message.
message2 = translateMessage(message2, emails, urls);
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("4Using QCopEnvelope e(\"%s\",\"%s\")", channel.latin1(), message2.latin1());
qDebug("passing emailadresses(%s), attachmenturls(%s) as parameters in the form %s to QCopEnvelope", emails.latin1() , urls.latin1(), parameters2.latin1());
#endif
qDebug("%s --- %s %s --- %s %s", channel.latin1(), message.latin1(),message2.latin1(), parameters.latin1(), parameters2.latin1() );
//KMessageBox::sorry( 0, message2 );
QProcess * proc = new QProcess( this );
int i = 0;
proc->addArgument( channel );
if ( message.find (" " ) > 0 ) {
QStringList list = QStringList::split( " ", message );
int i = 0;
while ( i < list.count ( ) ) {
//qDebug("add%sdd ",list[i].latin1() );
proc->addArgument( list[i] );
//KMessageBox::sorry( 0,list[i]);
++i;
}
} else {
proc->addArgument(message );
//KMessageBox::sorry( 0, message );
}
parameters2 = translateMessage(parameters2, urls, "" );
QString arg = "to='%1'";
arg = arg.arg( emails ) + ","+parameters2;;
//KMessageBox::sorry( 0,arg );
//qDebug("2add%sdd ",arg.latin1() );
proc->addArgument( arg);
proc->launch("");
#endif
return true;
}
/**************************************************************************
*
**************************************************************************/
//calls the emailapplication and creates a mail with parameter emails as recipients
bool ExternalAppHandler::mailToOneContact( const QString& name, const QString& emailadress )
{
QString channel;
QString message;
QString parameters;
int client = KPimGlobalPrefs::instance()->mEmailClient;
if (client == KPimGlobalPrefs::OTHER_EMC)
{
channel = KPimGlobalPrefs::instance()->mEmailOtherChannel;
message = KPimGlobalPrefs::instance()->mEmailOtherMessage;
parameters = KPimGlobalPrefs::instance()->mEmailOtherMessageParameters;
}
else
{
DefaultAppItem* dai = ExternalAppHandler::getDefaultItem(EMAIL, client);
if (!dai)
{
qDebug("could not find configured email application.");
return false;
}
channel = dai->_channel;
message = dai->_message;
parameters = dai->_parameters;
}
#ifdef DESKTOP_VERSION
//message = channel + " " +message + " \""+ parameters + "\"";
#endif
//first check if one of the mailers need the emails right in the message.
message = translateMessage(message, name, emailadress);
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("5Using QCopEnvelope e(\"%s\",\"%s\")", channel.latin1(), message.latin1());
qDebug("passing name(%s), emailadresses(%s) as parameters in the form %s to QCopEnvelope", name.latin1(), emailadress.latin1(), parameters.latin1());
#endif
#ifndef DESKTOP_VERSION
QCopEnvelope e(channel.latin1(), message.latin1());
//US we need no names in the To field. The emailadresses are enough
passParameters(&e, parameters, name, emailadress);
#else // DESKTOP_VERSION
//KMessageBox::sorry( 0,channel );
QProcess * proc = new QProcess( this );
proc->addArgument( channel );
if ( message.find (" " ) > 0 ) {
QStringList list = QStringList::split( " ", message );
int i = 0;
while ( i < list.count ( ) ) {
//qDebug("add%sdd ",list[i].latin1() );
proc->addArgument( list[i] );
//KMessageBox::sorry( 0,list[i]);
++i;
}
} else {
proc->addArgument(message );
}
parameters = translateMessage(parameters, name, emailadress);
+
+ //KMessageBox::information(0,parameters);
proc->addArgument( parameters );
proc->launch("");
#endif
return true;
}
/**************************************************************************
*
**************************************************************************/
//calls the emailapplication and creates a mail with parameter as recipients
// parameters format is
// NAME <EMAIL>:SUBJECT
bool ExternalAppHandler::mailToOneContact( const QString& adressline )
{
QString line = adressline;
int first = line.find( "<");
int last = line.find( ">");
QString name = line.left(first);
QString emailadress = line.mid(first+1, last-first-1);
//Subject can not be handled right now.
return mailToOneContact( name, emailadress );
}
/**************************************************************************
*
**************************************************************************/
//calls the phoneapplication with the number
bool ExternalAppHandler::callByPhone( const QString& phonenumber )
{
#ifndef DESKTOP_VERSION
QString channel;
QString message;
QString parameters;
int client = KPimGlobalPrefs::instance()->mPhoneClient;
if (client == KPimGlobalPrefs::OTHER_PHC)
{
channel = KPimGlobalPrefs::instance()->mPhoneOtherChannel;
message = KPimGlobalPrefs::instance()->mPhoneOtherMessage;
parameters = KPimGlobalPrefs::instance()->mPhoneOtherMessageParameters;
}
else
{
DefaultAppItem* dai = ExternalAppHandler::getDefaultItem(PHONE, client);
if (!dai)
{
qDebug("could not find configured phone application.");
return false;
}
channel = dai->_channel;
message = dai->_message;
parameters = dai->_parameters;
}
//first check if one of the mailers need the emails right in the message.
message = translateMessage(message, phonenumber, "");
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("6Using QCopEnvelope e(\"%s\",\"%s\")", channel.latin1(), message.latin1());
qDebug("passing phonenumber(%s) as parameter in the form %s to QCopEnvelope", phonenumber.latin1(), parameters.latin1());
#endif
QCopEnvelope e(channel.latin1(), message.latin1());
//US we need no names in the To field. The emailadresses are enough
passParameters(&e, parameters, phonenumber, "");
#else
KMessageBox::sorry( 0, i18n( "This version does not support phonecalls." ) );
#endif
return true;
}
/**************************************************************************
*
**************************************************************************/
//calls the smsapplication with the number
bool ExternalAppHandler::callBySMS( const QString& phonenumber )
{
#ifndef DESKTOP_VERSION
QString channel;
QString message;
QString parameters;
int client = KPimGlobalPrefs::instance()->mSMSClient;
if (client == KPimGlobalPrefs::OTHER_SMC)
{
channel = KPimGlobalPrefs::instance()->mSMSOtherChannel;
message = KPimGlobalPrefs::instance()->mSMSOtherMessage;
parameters = KPimGlobalPrefs::instance()->mSMSOtherMessageParameters;
}
else
{
DefaultAppItem* dai = ExternalAppHandler::getDefaultItem(SMS, client);
if (!dai)
{
qDebug("could not find configured sms application.");
return false;
}
channel = dai->_channel;
message = dai->_message;
parameters = dai->_parameters;
}
//first check if one of the mailers need the emails right in the message.
message = translateMessage(message, phonenumber, "");
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("7Using QCopEnvelope e(\"%s\",\"%s\")", channel.latin1(), message.latin1());
qDebug("passing phonenumber(%s) as parameter in the form %s to QCopEnvelope", phonenumber.latin1(), parameters.latin1());
#endif
QCopEnvelope e(channel.latin1(), message.latin1());
//US we need no names in the To field. The emailadresses are enough
passParameters(&e, parameters, phonenumber, "");
#else
KMessageBox::sorry( 0, i18n( "This version does not support the sending of sms." ) );
#endif
return true;
}
/**************************************************************************
*
**************************************************************************/
//calls the pagerapplication with the number
bool ExternalAppHandler::callByPager( const QString& pagernumber )
{
#ifndef DESKTOP_VERSION
QString channel;
QString message;
QString parameters;
int client = KPimGlobalPrefs::instance()->mPagerClient;
if (client == KPimGlobalPrefs::OTHER_PAC)
{
channel = KPimGlobalPrefs::instance()->mPagerOtherChannel;
message = KPimGlobalPrefs::instance()->mPagerOtherMessage;
parameters = KPimGlobalPrefs::instance()->mPagerOtherMessageParameters;
}
else
{
DefaultAppItem* dai = ExternalAppHandler::getDefaultItem(PAGER, client);
if (!dai)
{
qDebug("could not find configured pager application.");
return false;
}
channel = dai->_channel;
message = dai->_message;
parameters = dai->_parameters;
}
//first check if one of the mailers need the emails right in the message.
message = translateMessage(message, pagernumber, "");
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("8Using QCopEnvelope e(\"%s\",\"%s\")", channel.latin1(), message.latin1());
qDebug("passing pagernumber(%s) as parameter in the form %s to QCopEnvelope", pagernumber.latin1(), parameters.latin1());
#endif
QCopEnvelope e(channel.latin1(), message.latin1());
//US we need no names in the To field. The emailadresses are enough
passParameters(&e, parameters, pagernumber, "");
#else
KMessageBox::sorry( 0, i18n( "This version does not support paging." ) );
#endif
return true;
}
/**************************************************************************
*
**************************************************************************/
//calls the faxapplication with the number
bool ExternalAppHandler::callByFax( const QString& faxnumber )
{
#ifndef DESKTOP_VERSION
QString channel;
QString message;
QString parameters;
int client = KPimGlobalPrefs::instance()->mFaxClient;
if (client == KPimGlobalPrefs::OTHER_FAC)
{
channel = KPimGlobalPrefs::instance()->mFaxOtherChannel;
message = KPimGlobalPrefs::instance()->mFaxOtherMessage;
parameters = KPimGlobalPrefs::instance()->mFaxOtherMessageParameters;
}
else
{
DefaultAppItem* dai = ExternalAppHandler::getDefaultItem(FAX, client);
if (!dai)
{
qDebug("could not find configured fax application.");
return false;
}
channel = dai->_channel;
message = dai->_message;
parameters = dai->_parameters;
}
//first check if one of the mailers need the emails right in the message.
message = translateMessage(message, faxnumber, "");
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("9Using QCopEnvelope e(\"%s\",\"%s\")", channel.latin1(), message.latin1());
qDebug("passing faxnumber(%s) as parameter in the form %s to QCopEnvelope", faxnumber.latin1(), parameters.latin1());
#endif
QCopEnvelope e(channel.latin1(), message.latin1());
//US we need no names in the To field. The emailadresses are enough
passParameters(&e, parameters, faxnumber, "");
#else
KMessageBox::sorry( 0, i18n( "This version does not support the sending of faxes." ) );
#endif
return true;
}
/**************************************************************************
*
**************************************************************************/
//calls the sipapplication with the number
bool ExternalAppHandler::callBySIP( const QString& sipnumber )
{
#ifndef DESKTOP_VERSION
QString channel;
QString message;
QString parameters;
int client = KPimGlobalPrefs::instance()->mSipClient;
if (client == KPimGlobalPrefs::OTHER_SIC)
{
channel = KPimGlobalPrefs::instance()->mSipOtherChannel;
message = KPimGlobalPrefs::instance()->mSipOtherMessage;
parameters = KPimGlobalPrefs::instance()->mSipOtherMessageParameters;
}
else
{
DefaultAppItem* dai = ExternalAppHandler::getDefaultItem(SIP, client);
if (!dai)
{
qDebug("could not find configured sip application.");
return false;
}
channel = dai->_channel;
message = dai->_message;
parameters = dai->_parameters;
}
//first check if one of the sip apps need the emails right in the message.
message = translateMessage(message, sipnumber, "");
#ifdef DEBUG_EXT_APP_HANDLER
qDebug("10Using QCopEnvelope e(\"%s\",\"%s\")", channel.latin1(), message.latin1());
qDebug("passing sipnumber(%s) as parameter in the form %s to QCopEnvelope", sipnumber.latin1(), parameters.latin1());
#endif
QCopEnvelope e(channel.latin1(), message.latin1());
//US we need no names in the To field. The emailadresses are enough
passParameters(&e, parameters, sipnumber, "");
#else
KMessageBox::sorry( 0, i18n( "This version does not support sip." ) );
#endif
return true;
}
/**************************************************************************
*
**************************************************************************/
QString& ExternalAppHandler::translateMessage(QString& message, const QString& param1, const QString& param2 ) const
{
message = message.replace( QRegExp("%1"), param1 );
return message.replace( QRegExp("%2"), param2 );
}
/**************************************************************************
*
**************************************************************************/
void ExternalAppHandler::passParameters(QCopEnvelope* e, const QString& parameters, const QString& param1 , const QString& param2) const
{
#ifndef DESKTOP_VERSION
QMap<QString, QString> valmap;
bool useValMap = false;
// first extract all parts of the parameters.
QStringList paramlist = QStringList::split(";", parameters);
//Now check how many parts we have.
//=0 :no params to pass
//>0 :parameters to pass
for ( QStringList::Iterator it = paramlist.begin(); it != paramlist.end(); ++it )
{
QString param = (*it);
QStringList keyvallist = QStringList::split("=", param);
//if we have keyvalue pairs, we assume that we pass a map to the envelope
QStringList::Iterator it2 = keyvallist.begin();
QString key = (*it2);
key = key.replace( QRegExp("%1"), param1 );
key = key.replace( QRegExp("%2"), param2 );
++it2;
if(it2 != keyvallist.end())
{
QString value = (*it2);
value = value.replace( QRegExp("%1"), param1 );
value = value.replace( QRegExp("%2"), param2 );
valmap.insert(key, value);
useValMap = true;
}
else
{
// qDebug("pass parameter << %s", key.latin1());
(*e) << key;
}
}
if (useValMap == true)
(*e) << valmap;
#endif
}
/**************************************************************************
*
**************************************************************************/
void ExternalAppHandler::appMessage( const QCString& cmsg, const QByteArray& data )
{
qDebug("ExternalAppHandler::appMessage %s %x", cmsg.data(), this);
if ( cmsg == "nextView()" ) {
qDebug("nextView()");
QTimer::singleShot( 0, this, SIGNAL ( nextView() ));
return;
}
if ( cmsg == "callContactdialog()" ) {
qDebug("callContactdialog()");
QTimer::singleShot( 0, this, SIGNAL ( callContactdialog() ));
return;
}
if ( cmsg == "doRingSync" ) {
qDebug("doRingSync");
QTimer::singleShot( 0, this, SIGNAL ( doRingSync() ));
return;
}
bool res = mNameEmailUidListFromKAPITransfer->appMessage( cmsg, data );
if (!res)
res = mBirthdayListFromKAPITransfer->appMessage( cmsg, data );
if (!res)
res = mDisplayDetails->appMessage( cmsg, data );
// if (!res)
// res = mNameEmailUidListFromKAPITransfer->appMessage( cmsg, data );
}
bool ExternalAppHandler::requestNameEmailUidListFromKAPI(const QString& sourceChannel, const QString& sessionuid)
{
mNameEmailUidListFromKAPITransfer->setSourceChannel(sourceChannel);
// maybe we are sending to KA/Pi fom a different worldd...
// it may be that the QAplication::desktop()->width() values in KA/Pi are not the same as in our application
// for that reason we send the current QApplication::desktop()->width() to KA/Pi
//qDebug("UID %s ", sessionuid.latin1());
//return mNameEmailUidListFromKAPITransfer->sendMessageToTarget(QString::number ( QApplication::desktop()->width() ));
return mNameEmailUidListFromKAPITransfer->sendMessageToTarget(sessionuid);
}
bool ExternalAppHandler::returnNameEmailUidListFromKAPI(const QString& sourceChannel, const QString& sessionuid, const QStringList& list1, const QStringList& list2, const QStringList& list3)
{
QStringList list4, list5, list6;
mNameEmailUidListFromKAPITransfer->setSourceChannel(sourceChannel);
return mNameEmailUidListFromKAPITransfer->sendMessageToSource(sessionuid, list1, list2, list3, list4, list5, list6);
}
bool ExternalAppHandler::requestFindByEmailFromKAPI(const QString& sourceChannel, const QString& sessionuid, const QString& email)
{
mFindByEmailFromKAPITransfer->setSourceChannel(sourceChannel);
return mFindByEmailFromKAPITransfer->sendMessageToTarget(sessionuid, email);
}
bool ExternalAppHandler::returnFindByEmailFromKAPI(const QString& sourceChannel, const QString& sessionuid, const QStringList& list1, const QStringList& list2, const QStringList& list3)
{
QStringList list4, list5, list6;
mFindByEmailFromKAPITransfer->setSourceChannel(sourceChannel);
return mFindByEmailFromKAPITransfer->sendMessageToSource(sessionuid, list1, list2, list3, list4, list5, list6);
}
bool ExternalAppHandler::requestDetailsFromKAPI(const QString& name, const QString& email, const QString& uid)
{
mDisplayDetails->setSourceChannel("");
return mDisplayDetails->sendMessageToTarget("", name, email, uid);
}
bool ExternalAppHandler::requestBirthdayListFromKAPI(const QString& sourceChannel, const QString& sessionuid)
{
mBirthdayListFromKAPITransfer->setSourceChannel(sourceChannel);
return mBirthdayListFromKAPITransfer->sendMessageToTarget(sessionuid);
}
bool ExternalAppHandler::returnBirthdayListFromKAPI(const QString& sourceChannel, const QString& sessionuid, const QStringList& list1, const QStringList& list2, const QStringList& list3, const QStringList& list4, const QStringList& list5, const QStringList& list6)
{
mBirthdayListFromKAPITransfer->setSourceChannel(sourceChannel);
return mBirthdayListFromKAPITransfer->sendMessageToSource(sessionuid, list1, list2, list3, list4, list5, list6);
}
diff --git a/libkdepim/ksyncmanager.cpp b/libkdepim/ksyncmanager.cpp
index b7929ec..5708dfc 100644
--- a/libkdepim/ksyncmanager.cpp
+++ b/libkdepim/ksyncmanager.cpp
@@ -1,1816 +1,1883 @@
/*
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$
#include "ksyncmanager.h"
#include <stdlib.h>
#ifndef _WIN32_
#include <unistd.h>
#endif
#include "ksyncprofile.h"
#include "ksyncprefsdialog.h"
#include "kpimprefs.h"
#include <kmessagebox.h>
#include <qdir.h>
#include <qprogressbar.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qtimer.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include <qlineedit.h>
#include <qdialog.h>
#include <qlayout.h>
#include <qtextcodec.h>
#include <qlabel.h>
#include <qcheckbox.h>
#include <qapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kfiledialog.h>
QDateTime KSyncManager::mRequestedSyncEvent;
KSyncManager::KSyncManager(QWidget* parent, KSyncInterface* implementation, TargetApp ta, KPimPrefs* prefs, QPopupMenu* syncmenu)
: QObject(), mPrefs(prefs ), mParent(parent),mImplementation(implementation), mTargetApp(ta), mSyncMenu(syncmenu)
{
mServerSocket = 0;
bar = new QProgressBar ( 1, 0 );
bar->setCaption ("");
mWriteBackInPast = 2;
}
KSyncManager::~KSyncManager()
{
delete bar;
}
void KSyncManager::setDefaultFileName( QString s)
{
mDefFileName = s ;
if ( mPrefs->mPassiveSyncAutoStart )
enableQuick( false );
}
void KSyncManager::fillSyncMenu()
{
if ( mSyncMenu->count() )
mSyncMenu->clear();
mSyncMenu->insertItem( i18n("Configure..."), 0 );
mSyncMenu->insertSeparator();
QPopupMenu *clearMenu = new QPopupMenu ( mSyncMenu );
mSyncMenu->insertItem( i18n("Remove sync info"),clearMenu, 5000 );
clearMenu->insertItem( i18n("For all profiles"), 1 );
clearMenu->insertSeparator();
connect ( clearMenu, SIGNAL( activated ( int ) ), this, SLOT (slotClearMenu( int ) ) );
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();
QString externalName;
#ifdef DESKTOP_VERSION
#ifdef _WIN32_
- externalName = "OutLook(not_implemented)";
+ externalName = "OutLook";
#else
externalName = "KDE_Desktop";
#endif
#else
externalName = "Sharp_DTM";
#endif
prof << externalName;
prof << i18n("Local_file");
prof << i18n("Last_file");
KSyncProfile* temp = new KSyncProfile ();
temp->setName( prof[0] );
temp->writeConfig(&config);
temp->setName( prof[1] );
temp->writeConfig(&config);
temp->setName( prof[2] );
temp->writeConfig(&config);
config.setGroup("General");
config.writeEntry("SyncProfileNames",prof);
config.writeEntry("ExternSyncProfiles",externalName);
config.sync();
delete temp;
}
mExternSyncProfiles = config.readListEntry("ExternSyncProfiles");
mSyncProfileNames = prof;
unsigned int i;
for ( i = 0; i < prof.count(); ++i ) {
QString insertText = prof[i];
if ( i == 0 ) {
#ifdef DESKTOP_VERSION
#ifdef _WIN32_
- insertText = "OutLook(not_implemented)";
+ insertText = "OutLook";
#else
insertText = "KDE_Desktop";
#endif
#else
insertText = "Sharp_DTM";
#endif
}
mSyncMenu->insertItem( insertText, 1000+i );
clearMenu->insertItem( insertText, 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 );
clearMenu->removeItem( 1000 );
}
#ifndef DESKTOP_VERSION
else if (!app_dir.exists(QDir::homeDirPath()+"/Applications/dtm" ) ) {
mSyncMenu->removeItem( 1000 );
clearMenu->removeItem( 1000 );
}
#endif
mSyncMenu->removeItem( 1002 );
clearMenu->removeItem( 1002 );
}
void KSyncManager::slotClearMenu( int action )
{
QString syncDevice;
if ( action > 999 ) {
syncDevice = mSyncProfileNames[action - 1000] ;
}
int result = 0;
QString sd;
if ( syncDevice.isEmpty() )
sd = i18n("Do you want to\nclear all sync info\nof all profiles?");
else
sd = i18n("Do you want to\nclear the sync\ninfo of profile\n%1?\n"). arg( syncDevice );
result = QMessageBox::warning( mParent, i18n("Warning!"),sd,i18n("OK"), i18n("Cancel"), 0,
0, 1 );
if ( result )
return;
mImplementation->removeSyncInfo( syncDevice );
}
void KSyncManager::slotSyncMenu( int action )
{
qDebug("KSM::syncaction %d ", action);
mCurrentResourceLocal = "";
emit multiResourceSyncStart( false );
if ( action == 5000 )
return;
mSyncWithDesktop = false;
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);
bool silent = false;
if ( action == 999 ) {
//special mode for silent syncing
action = 1000;
silent = 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);
if (silent) {
mAskForPreferences = false;
mShowSyncSummary = false;
mWriteBackFile = true;
mSyncAlgoPrefs = 2;// take newest
}
else {
mAskForPreferences = temp->getAskForPreferences();
mShowSyncSummary = temp->getShowSummaryAfterSync();
mWriteBackFile = temp->getWriteBackFile();
mSyncAlgoPrefs = temp->getSyncPrefs();
}
mWriteBackExistingOnly = temp->getWriteBackExisting();
mIsKapiFile = temp->getIsKapiFile();
mWriteBackInFuture = 0;
if ( temp->getWriteBackFuture() ) {
mWriteBackInFuture = temp->getWriteBackFutureWeeks( );
mWriteBackInPast = temp->getWriteBackPastWeeks( );
}
mFilterInCal = temp->getFilterInCal();
mFilterOutCal = temp->getFilterOutCal();
mFilterInAB = temp->getFilterInAB();
mFilterOutAB = temp->getFilterOutAB();
if ( action == 1000 ) {
mIsKapiFile = false;
#ifdef DESKTOP_VERSION
syncKDE();
#else
syncSharp();
#endif
} else if ( action == 1001 ) {
syncLocalFile();
} else if ( action == 1002 ) {
mWriteBackFile = false;
mAskForPreferences = false;
mShowSyncSummary = false;
mSyncAlgoPrefs = 3;
quickSyncLocalFile();
} else if ( action >= 1003 ) {
if ( temp->getIsLocalFileSync() ) {
switch(mTargetApp)
{
case (KAPI):
if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB();
break;
case (KOPI):
if ( syncWithFile( temp->getRemoteFileName( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileName();
break;
case (PWMPI):
if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNamePWM();
break;
default:
qDebug("KSM::slotSyncMenu: invalid apptype selected");
break;
}
} else {
if ( temp->getIsPhoneSync() ) {
mPhoneDevice = temp->getPhoneDevice( ) ;
mPhoneConnection = temp->getPhoneConnection( );
mPhoneModel = temp->getPhoneModel( );
syncPhone();
} else if ( temp->getIsPiSync()|| temp->getIsPiSyncSpec()) {
mSpecificResources.clear();
if ( mTargetApp == KAPI ) {
if ( temp->getIsPiSyncSpec() )
mSpecificResources = QStringList::split( ":", temp->getResSpecKapi(),true );
mPassWordPiSync = temp->getRemotePwAB();
mActiveSyncPort = temp->getRemotePortAB();
mActiveSyncIP = temp->getRemoteIPAB();
} else if ( mTargetApp == KOPI ) {
if ( temp->getIsPiSyncSpec() )
mSpecificResources = QStringList::split( ":", temp->getResSpecKopi(),true );
mPassWordPiSync = temp->getRemotePw();
mActiveSyncPort = temp->getRemotePort();
mActiveSyncIP = temp->getRemoteIP();
} else {
mPassWordPiSync = temp->getRemotePwPWM();
mActiveSyncPort = temp->getRemotePortPWM();
mActiveSyncIP = temp->getRemoteIPPWM();
}
syncPi();
while ( !mPisyncFinished ) {
//qDebug("waiting ");
qApp->processEvents();
}
} else
syncRemote( temp );
}
}
delete temp;
setBlockSave(false);
}
void KSyncManager::enableQuick( bool ask )
{
bool autoStart;
bool changed = false;
if ( ask ) {
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)\nValid range from 1 to 65535").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);
QCheckBox autostart(i18n("Automatically start\nat application startup"), &dia );
lay.addWidget( &autostart);
autostart.setChecked( mPrefs->mPassiveSyncAutoStart );
#ifdef DESKTOP_VERSION
#ifdef _WIN32_
QCheckBox syncdesktop( i18n("Automatically sync with Outlook\nwhen receiving sync request"),&dia );
syncdesktop.hide();// not implemented!
#else
QCheckBox syncdesktop( i18n("Automatically sync with KDE-Desktop\nwhen receiving sync request"),&dia );
#endif
lay.addWidget( &syncdesktop);
#else
mPrefs->mPassiveSyncWithDesktop = false;
QCheckBox syncdesktop( i18n("Automatically sync\nwith KDE-Desktop"),&dia );
syncdesktop.hide();
#endif
syncdesktop.setChecked( mPrefs->mPassiveSyncWithDesktop );
QPushButton pb ( "OK", &dia);
lay.addWidget( &pb );
connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
dia.resize( 230,120 );
dia.setCaption( i18n("Enter port for Pi-Sync") );
dia.show();
#ifndef DESKTOP_VERSION
int dw = QApplication::desktop()->width();
int dh = QApplication::desktop()->height();
dia.move( (dw-dia.width())/2, (dh - dia.height() )/2 );
#endif
if ( ! dia.exec() )
return;
dia.hide();
qApp->processEvents();
if ( mPrefs->mPassiveSyncPw != lepw.text() ) {
changed = true;
mPrefs->mPassiveSyncPw = lepw.text();
}
if ( mPrefs->mPassiveSyncPort != lab.text() ) {
mPrefs->mPassiveSyncPort = lab.text();
changed = true;
}
autoStart = autostart.isChecked();
if (mPrefs->mPassiveSyncWithDesktop != syncdesktop.isChecked() ) {
changed = true;
mPrefs->mPassiveSyncWithDesktop = syncdesktop.isChecked();
}
}
else
autoStart = mPrefs->mPassiveSyncAutoStart;
if ( autoStart != mPrefs->mPassiveSyncAutoStart )
changed = true;
bool ok;
mPrefs->mPassiveSyncAutoStart = false;
Q_UINT32 port_t = mPrefs->mPassiveSyncPort.toUInt(&ok);
if ( ! ok || port_t > 65535 ) {
KMessageBox::information( 0, i18n("No valid port number:\n%1").arg ( mPrefs->mPassiveSyncPort ), i18n("Pi-Sync Port Error"));
return;
}
Q_UINT16 port = port_t;
//qDebug("port %d ", port);
mServerSocket = new KServerSocket ( mPrefs->mPassiveSyncPw, port ,1 );
mServerSocket->setFileName( defaultFileName() );//bbb
if ( !mServerSocket->ok() ) {
QTimer::singleShot( 2000, this, SLOT ( displayErrorPort() ) );
delete mServerSocket;
mServerSocket = 0;
return;
}
mPrefs->mPassiveSyncAutoStart = autoStart;
if ( changed ) {
mPrefs->writeConfig();
}
//connect( mServerSocket, SIGNAL ( request_file() ),this, SIGNAL ( request_file() ) );
//connect( mServerSocket, SIGNAL ( file_received( bool ) ), this, SIGNAL ( getFile( bool ) ) );
connect( mServerSocket, SIGNAL ( request_file(const QString &) ),this, SIGNAL ( request_file(const QString &) ) );
connect( mServerSocket, SIGNAL ( file_received( bool ,const QString &) ), this, SIGNAL ( getFile( bool,const QString & ) ) );
}
void KSyncManager::displayErrorPort()
{
KMessageBox::information( 0, i18n("<b>Enabling Pi-Sync failed!</b> Failed to bind or listen to the port %1! Is another instance already listening to that port?").arg( mPrefs->mPassiveSyncPort) , i18n("Pi-Sync Port Error"));
}
void KSyncManager::syncLocalFile()
{
QString fn =mPrefs->mLastSyncedLocalFile;
QString ext;
switch(mTargetApp)
{
case (KAPI):
ext = "(*.vcf)";
break;
case (KOPI):
ext = "(*.ics/*.vcs)";
break;
case (PWMPI):
ext = "(*.pwm)";
break;
default:
qDebug("KSM::syncLocalFile: invalid apptype selected");
break;
}
fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename"+ext), mParent );
if ( fn == "" )
return;
if ( syncWithFile( fn, false ) ) {
qDebug("KSM::syncLocalFile() successful ");
}
}
bool KSyncManager::syncWithFile( QString fn , bool quick )
{
bool ret = false;
QFileInfo info;
info.setFile( fn );
QString mess;
if ( !info. exists() ) {
mess = i18n( "Sync file \n...%1\ndoes not exist!\nNothing synced!\n").arg(fn.right( 30) );
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 )
if ( !edit_sync_options()) {
mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") );
return false;
}
if ( result == 0 ) {
//qDebug("Now sycing ... ");
if ( ret = mImplementation->sync( this, fn, mSyncAlgoPrefs ,mCurrentResourceLocal ) )
mParent->topLevelWidget()->setCaption( i18n("Synchronization successful") );
else
mParent->topLevelWidget()->setCaption( i18n("Sync cancelled or failed.") );
if ( ! quick )
mPrefs->mLastSyncedLocalFile = fn;
}
return ret;
}
void KSyncManager::quickSyncLocalFile()
{
if ( syncWithFile( mPrefs->mLastSyncedLocalFile, true ) ) {
qDebug("KSM::quick syncLocalFile() successful ");
}
}
void KSyncManager::multiSync( bool askforPrefs )
{
if (blockSave())
return;
setBlockSave(true);
mCurrentResourceLocal = "";
if ( askforPrefs ) {
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("KDE-Pim Sync"),
question,
i18n("Yes"), i18n("No"),
0, 0 ) != 0 ) {
setBlockSave(false);
mParent->topLevelWidget()->setCaption(i18n("Aborted! Nothing synced!"));
return;
}
}
mCurrentSyncDevice = i18n("Multiple profiles") ;
mSyncAlgoPrefs = mPrefs->mRingSyncAlgoPrefs;
if ( askforPrefs ) {
if ( !edit_sync_options()) {
mParent->topLevelWidget()->setCaption( i18n("Syncing aborted.") );
return;
}
mPrefs->mRingSyncAlgoPrefs = mSyncAlgoPrefs;
}
mParent->topLevelWidget()->setCaption(i18n("Multiple sync started.") );
qApp->processEvents();
int num = ringSync() ;
if ( num > 1 )
ringSync();
setBlockSave(false);
if ( num )
emit save();
if ( num )
mParent->topLevelWidget()->setCaption(i18n("%1 profiles synced. Multiple sync complete!").arg(num) );
else
mParent->topLevelWidget()->setCaption(i18n("Nothing synced! No profiles defined for multisync!"));
return;
}
int KSyncManager::ringSync()
{
emit multiResourceSyncStart( false );
int syncedProfiles = 0;
unsigned int i;
QTime timer;
KConfig config ( locateLocal( "config","ksyncprofilesrc" ) );
QStringList syncProfileNames = mSyncProfileNames;
KSyncProfile* temp = new KSyncProfile ();
mAskForPreferences = false;
mCurrentResourceLocal = "";
for ( i = 0; i < syncProfileNames.count(); ++i ) {
mCurrentSyncProfile = i;
temp->setName(syncProfileNames[mCurrentSyncProfile]);
temp->readConfig(&config);
bool includeInRingSync = false;
switch(mTargetApp)
{
case (KAPI):
includeInRingSync = temp->getIncludeInRingSyncAB();
break;
case (KOPI):
includeInRingSync = temp->getIncludeInRingSync();
break;
case (PWMPI):
includeInRingSync = temp->getIncludeInRingSyncPWM();
break;
default:
qDebug("KSM::ringSync: invalid apptype selected");
break;
}
if ( includeInRingSync && ( i < 1 || i > 2 )) {
mParent->topLevelWidget()->setCaption(i18n("Profile ")+syncProfileNames[mCurrentSyncProfile]+ i18n(" is synced ... "));
++syncedProfiles;
mSyncWithDesktop = false;
// mAskForPreferences = temp->getAskForPreferences();
mWriteBackFile = temp->getWriteBackFile();
mWriteBackExistingOnly = temp->getWriteBackExisting();
mIsKapiFile = temp->getIsKapiFile();
mWriteBackInFuture = 0;
if ( temp->getWriteBackFuture() ) {
mWriteBackInFuture = temp->getWriteBackFutureWeeks( );
mWriteBackInPast = temp->getWriteBackPastWeeks( );
}
mFilterInCal = temp->getFilterInCal();
mFilterOutCal = temp->getFilterOutCal();
mFilterInAB = temp->getFilterInAB();
mFilterOutAB = temp->getFilterOutAB();
mShowSyncSummary = false;
mCurrentSyncDevice = syncProfileNames[i] ;
mCurrentSyncName = mLocalMachineName;
if ( i == 0 ) {
mIsKapiFile = false;
#ifdef DESKTOP_VERSION
syncKDE();
#else
syncSharp();
#endif
} else {
if ( temp->getIsLocalFileSync() ) {
switch(mTargetApp)
{
case (KAPI):
if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB();
break;
case (KOPI):
if ( syncWithFile( temp->getRemoteFileName( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileName();
break;
case (PWMPI):
if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNamePWM();
break;
default:
qDebug("KSM: invalid apptype selected");
break;
}
} else {
if ( temp->getIsPhoneSync() ) {
mPhoneDevice = temp->getPhoneDevice( ) ;
mPhoneConnection = temp->getPhoneConnection( );
mPhoneModel = temp->getPhoneModel( );
syncPhone();
} else if ( temp->getIsPiSync() || temp->getIsPiSyncSpec()) {
mSpecificResources.clear();
if ( mTargetApp == KAPI ) {
if ( temp->getIsPiSyncSpec() )
mSpecificResources = QStringList::split( ":", temp->getResSpecKapi(),true );
mPassWordPiSync = temp->getRemotePwAB();
mActiveSyncPort = temp->getRemotePortAB();
mActiveSyncIP = temp->getRemoteIPAB();
} else if ( mTargetApp == KOPI ) {
if ( temp->getIsPiSyncSpec() )
mSpecificResources = QStringList::split( ":", temp->getResSpecKopi(),true );
mPassWordPiSync = temp->getRemotePw();
mActiveSyncPort = temp->getRemotePort();
mActiveSyncIP = temp->getRemoteIP();
} else {
mPassWordPiSync = temp->getRemotePwPWM();
mActiveSyncPort = temp->getRemotePortPWM();
mActiveSyncIP = temp->getRemoteIPPWM();
}
syncPi();
while ( !mPisyncFinished ) {
//qDebug("waiting ");
qApp->processEvents();
}
timer.start();
while ( timer.elapsed () < 2000 ) {
qApp->processEvents();
}
} else
syncRemote( temp, false );
}
}
timer.start();
mParent->topLevelWidget()->setCaption(i18n("Multiple sync in progress ... please wait!") );
while ( timer.elapsed () < 2000 ) {
qApp->processEvents();
#ifndef _WIN32_
sleep (1);
#endif
}
}
}
delete temp;
return syncedProfiles;
}
void KSyncManager::syncRemote( KSyncProfile* prof, bool ask)
{
QString question;
if ( ask ) {
question = i18n("Do you really want\nto remote sync\nwith profile \n")+ prof->getName()+" ?\n";
if ( QMessageBox::information( mParent, i18n("Sync"),
question,
i18n("Yes"), i18n("No"),
0, 0 ) != 0 )
return;
}
QString preCommand;
QString localTempFile;
QString postCommand;
switch(mTargetApp)
{
case (KAPI):
preCommand = prof->getPreSyncCommandAB();
postCommand = prof->getPostSyncCommandAB();
localTempFile = prof->getLocalTempFileAB();
break;
case (KOPI):
preCommand = prof->getPreSyncCommand();
postCommand = prof->getPostSyncCommand();
localTempFile = prof->getLocalTempFile();
break;
case (PWMPI):
preCommand = prof->getPreSyncCommandPWM();
postCommand = prof->getPostSyncCommandPWM();
localTempFile = prof->getLocalTempFilePWM();
break;
default:
qDebug("KSM::syncRemote: invalid apptype selected");
break;
}
int fi;
if ( (fi = preCommand.find("$PWD$")) > 0 ) {
QString pwd = getPassword();
preCommand = preCommand.left( fi )+ pwd + preCommand.mid( fi+5 );
}
int maxlen = 30;
if ( QApplication::desktop()->width() > 320 )
maxlen += 25;
mParent->topLevelWidget()->setCaption ( i18n( "Copy remote file to local machine..." ) );
int result = system ( preCommand );
// 0 : okay
// 256: no such file or dir
//
qDebug("KSM::Sync: Remote copy result(0 = okay): %d ",result );
if ( result != 0 ) {
unsigned int len = maxlen;
while ( len < preCommand.length() ) {
preCommand.insert( len , "\n" );
len += maxlen +2;
}
question = i18n("Sorry, the copy command failed!\nCommand was:\n%1\n \nTry command on console to get more\ndetailed info about the reason.\n").arg (preCommand) ;
QMessageBox::information( mParent, i18n("Sync - ERROR"),
question,
i18n("Okay!")) ;
mParent->topLevelWidget()->setCaption ("KDE-Pim");
return;
}
mParent->topLevelWidget()->setCaption ( i18n( "Copying succeed." ) );
//qDebug(" file **%s** ",prof->getLocalTempFile().latin1() );
if ( syncWithFile( localTempFile, true ) ) {
if ( mWriteBackFile ) {
int fi;
if ( (fi = postCommand.find("$PWD$")) > 0 ) {
QString pwd = getPassword();
postCommand = postCommand.left( fi )+ pwd + postCommand.mid( fi+5 );
}
mParent->topLevelWidget()->setCaption ( i18n( "Writing back file ..." ) );
result = system ( postCommand );
qDebug("KSM::Sync:Writing back file result: %d ", result);
if ( result != 0 ) {
mParent->topLevelWidget()->setCaption ( i18n( "Writing back file result: " )+QString::number( result ) );
return;
} else {
mParent->topLevelWidget()->setCaption ( i18n( "Syncronization sucessfully completed" ) );
}
}
}
return;
}
bool KSyncManager::edit_pisync_options()
{
QDialog dia( mParent, "dia", true );
dia.setCaption( i18n("Pi-Sync options for device: " ) +mCurrentSyncDevice );
QVBoxLayout lay ( &dia );
lay.setSpacing( 5 );
lay.setMargin( 3 );
QLabel lab1 ( i18n("Password for remote access:"), &dia);
lay.addWidget( &lab1 );
QLineEdit le1 (&dia );
lay.addWidget( &le1 );
QLabel lab2 ( i18n("Remote IP address:"), &dia);
lay.addWidget( &lab2 );
QLineEdit le2 (&dia );
lay.addWidget( &le2 );
QLabel lab3 ( i18n("Remote port number:\n(May be: 1 - 65535)"), &dia);
lay.addWidget( &lab3 );
QLineEdit le3 (&dia );
lay.addWidget( &le3 );
QPushButton pb ( "OK", &dia);
lay.addWidget( &pb );
connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
le1.setText( mPassWordPiSync );
le2.setText( mActiveSyncIP );
le3.setText( mActiveSyncPort );
if ( dia.exec() ) {
mPassWordPiSync = le1.text();
mActiveSyncPort = le3.text();
mActiveSyncIP = le2.text();
return true;
}
return false;
}
bool KSyncManager::edit_sync_options()
{
QDialog dia( mParent, "dia", true );
dia.setCaption( i18n("Device: " ) +mCurrentSyncDevice );
QButtonGroup gr ( 1, Qt::Horizontal, i18n("Sync preferences"), &dia);
QVBoxLayout lay ( &dia );
lay.setSpacing( 2 );
lay.setMargin( 3 );
lay.addWidget(&gr);
QRadioButton loc ( i18n("Take local entry on conflict"), &gr );
QRadioButton rem ( i18n("Take remote entry on conflict"), &gr );
QRadioButton newest( i18n("Take newest entry on conflict"), &gr );
QRadioButton ask( i18n("Ask for every entry on conflict"), &gr );
QRadioButton f_loc( i18n("Force: Take local entry always"), &gr );
QRadioButton f_rem( i18n("Force: Take remote entry always"), &gr );
//QRadioButton both( i18n("Take both on conflict"), &gr );
QPushButton pb ( "OK", &dia);
lay.addWidget( &pb );
connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
switch ( mSyncAlgoPrefs ) {
case 0:
loc.setChecked( true);
break;
case 1:
rem.setChecked( true );
break;
case 2:
newest.setChecked( true);
break;
case 3:
ask.setChecked( true);
break;
case 4:
f_loc.setChecked( true);
break;
case 5:
f_rem.setChecked( true);
break;
case 6:
// both.setChecked( true);
break;
default:
break;
}
if ( dia.exec() ) {
mSyncAlgoPrefs = rem.isChecked()*1+newest.isChecked()*2+ ask.isChecked()*3+ f_loc.isChecked()*4+ f_rem.isChecked()*5;//+ both.isChecked()*6 ;
return true;
}
return false;
}
QString KSyncManager::getPassword( )
{
QString retfile = "";
QDialog dia ( mParent, "input-dialog", true );
QLineEdit lab ( &dia );
lab.setEchoMode( QLineEdit::Password );
QVBoxLayout lay( &dia );
lay.setMargin(7);
lay.setSpacing(7);
lay.addWidget( &lab);
dia.setFixedSize( 230,50 );
dia.setCaption( i18n("Enter password") );
QPushButton pb ( "OK", &dia);
lay.addWidget( &pb );
connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
dia.show();
int res = dia.exec();
if ( res )
retfile = lab.text();
dia.hide();
qApp->processEvents();
return retfile;
}
void KSyncManager::confSync()
{
static KSyncPrefsDialog* sp = 0;
if ( ! sp ) {
sp = new KSyncPrefsDialog( mParent, "syncprefs", true );
}
sp->usrReadConfig();
#ifndef DESKTOP_VERSION
sp->showMaximized();
#else
sp->show();
#endif
sp->exec();
QStringList oldSyncProfileNames = mSyncProfileNames;
mSyncProfileNames = sp->getSyncProfileNames();
mLocalMachineName = sp->getLocalMachineName ();
uint ii;
for ( ii = 0; ii < oldSyncProfileNames.count(); ++ii ) {
if ( ! mSyncProfileNames.contains( oldSyncProfileNames[ii] ) )
mImplementation->removeSyncInfo( oldSyncProfileNames[ii] );
}
QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) );
}
+void KSyncManager::syncOL()
+{
+ mSyncWithDesktop = true;
+ emit save();
+ switch(mTargetApp)
+ {
+ case (KAPI):
+ {
+ syncExternalApplication("ol");
+ }
+ break;
+ case (KOPI):
+ {
+#ifdef DESKTOP_VERSION
+ QString command = "kdecaldump33";
+ QString commandfile = "kdecaldump33";
+ QString commandpath = qApp->applicationDirPath () + "/";
+#else
+ QString command = "kdecaldump33";
+ QString commandfile = "kdecaldump33";
+ QString commandpath = QDir::homeDirPath ()+"/";
+#endif
+ if ( ! QFile::exists ( commandpath+commandfile ) )
+ command = commandfile;
+ else
+ command = commandpath+commandfile;
+
+ QString fileName = QDir::homeDirPath ()+"/.kdecalendardump.ics";
+ int result = system ( command.latin1());
+ qDebug("Cal dump 33 command call result result: %d ", result);
+ if ( result != 0 ) {
+ qDebug("Calling CAL dump version 33 failed. Trying 34... ");
+ commandfile = "kdecaldump34";
+ if ( ! QFile::exists ( commandpath+commandfile ) )
+ command = commandfile;
+ else
+ command = commandpath+commandfile;
+ result = system ( command.latin1());
+ qDebug("Cal dump 34 command call result result: %d ", result);
+ if ( result != 0 ) {
+ KMessageBox::error( 0, i18n("Error accessing KDE calendar data.\nMake sure the file\n%1kdecaldump3x\nexists ( x = 3 or 4 ).\nSupported KDE versions are 3.3 and 3.4.\nUsed version should be auto detected.\n").arg( commandpath ));
+ return;
+ }
+ }
+ if ( syncWithFile( fileName,true ) ) {
+ if ( mWriteBackFile ) {
+ command += " --read";
+ system ( command.latin1());
+ }
+ }
+
+ }
+ break;
+ case (PWMPI):
+
+ break;
+ default:
+ qDebug("KSM::slotSyncMenu: invalid apptype selected");
+ break;
+
+ }
+}
void KSyncManager::syncKDE()
{
+#ifdef _WIN32_
+ syncOL();
+#else
+
mSyncWithDesktop = true;
emit save();
switch(mTargetApp)
{
case (KAPI):
{
#ifdef DESKTOP_VERSION
QString command = "kdeabdump33";
QString commandfile = "kdeabdump33";
QString commandpath = qApp->applicationDirPath () + "/";
#else
QString command = "kdeabdump33";
QString commandfile = "kdeabdump33";
QString commandpath = QDir::homeDirPath ()+"/";
#endif
if ( ! QFile::exists ( commandpath+commandfile ) )
command = commandfile;
else
command = commandpath+commandfile;
QString fileName = QDir::homeDirPath ()+"/.kdeaddressbookdump.vcf";
int result = system ( command.latin1());
qDebug("AB dump 33 command call result: %d ", result);
if ( result != 0 ) {
qDebug("Calling AB dump version 33 failed. Trying 34... ");
commandfile = "kdeabdump34";
if ( ! QFile::exists ( commandpath+commandfile ) )
command = commandfile;
else
command = commandpath+commandfile;
result = system ( command.latin1());
qDebug("AB dump 34 command call result: %d ", result);
if ( result != 0 ) {
KMessageBox::error( 0, i18n("Error accessing KDE addressbook data.\nMake sure the file\n%1kdeabdump3x\nexists ( x = 3 or 4 ).\nSupported KDE versions are 3.3 and 3.4.\nUsed version should be auto detected.\n").arg( commandpath ));
return;
}
}
if ( syncWithFile( fileName,true ) ) {
if ( mWriteBackFile ) {
command += " --read";
system ( command.latin1());
}
}
}
break;
case (KOPI):
{
#ifdef DESKTOP_VERSION
QString command = "kdecaldump33";
QString commandfile = "kdecaldump33";
QString commandpath = qApp->applicationDirPath () + "/";
#else
QString command = "kdecaldump33";
QString commandfile = "kdecaldump33";
QString commandpath = QDir::homeDirPath ()+"/";
#endif
if ( ! QFile::exists ( commandpath+commandfile ) )
command = commandfile;
else
command = commandpath+commandfile;
QString fileName = QDir::homeDirPath ()+"/.kdecalendardump.ics";
int result = system ( command.latin1());
qDebug("Cal dump 33 command call result result: %d ", result);
if ( result != 0 ) {
qDebug("Calling CAL dump version 33 failed. Trying 34... ");
commandfile = "kdecaldump34";
if ( ! QFile::exists ( commandpath+commandfile ) )
command = commandfile;
else
command = commandpath+commandfile;
result = system ( command.latin1());
qDebug("Cal dump 34 command call result result: %d ", result);
if ( result != 0 ) {
KMessageBox::error( 0, i18n("Error accessing KDE calendar data.\nMake sure the file\n%1kdecaldump3x\nexists ( x = 3 or 4 ).\nSupported KDE versions are 3.3 and 3.4.\nUsed version should be auto detected.\n").arg( commandpath ));
return;
}
}
if ( syncWithFile( fileName,true ) ) {
if ( mWriteBackFile ) {
command += " --read";
system ( command.latin1());
}
}
}
break;
case (PWMPI):
break;
default:
qDebug("KSM::slotSyncMenu: invalid apptype selected");
break;
}
+#endif
}
void KSyncManager::syncSharp()
{
if ( ! syncExternalApplication("sharp") )
qDebug("KSM::ERROR sync sharp ");
}
bool KSyncManager::syncExternalApplication(QString resource)
{
emit save();
if ( mAskForPreferences )
if ( !edit_sync_options()) {
mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") );
return false;
}
qDebug("KSM::Sync extern %s", resource.latin1());
bool syncOK = mImplementation->syncExternal(this, resource);
return syncOK;
}
void KSyncManager::syncPhone()
{
syncExternalApplication("phone");
}
void KSyncManager::showProgressBar(int percentage, QString caption, int total)
{
if (!bar->isVisible())
{
int w = 300;
if ( QApplication::desktop()->width() < 320 )
w = 220;
int h = bar->sizeHint().height() ;
int dw = QApplication::desktop()->width();
int dh = QApplication::desktop()->height();
bar->setGeometry( (dw-w)/2, (dh - h )/2 ,w,h );
bar->setCaption (caption);
bar->setTotalSteps ( total ) ;
bar->show();
}
bar->raise();
bar->setProgress( percentage );
qApp->processEvents();
}
void KSyncManager::hideProgressBar()
{
bar->hide();
qApp->processEvents();
}
bool KSyncManager::isProgressBarCanceled()
{
return !bar->isVisible();
}
QString KSyncManager::syncFileName()
{
QString fn = "tempfile";
switch(mTargetApp)
{
case (KAPI):
fn = "tempsyncab.vcf";
break;
case (KOPI):
fn = "tempsynccal.ics";
break;
case (PWMPI):
fn = "tempsyncpw.pwm";
break;
default:
break;
}
#ifdef DESKTOP_VERSION
return locateLocal( "tmp", fn );
#else
return (QString( "/tmp/" )+ fn );
#endif
}
void KSyncManager::syncPi()
{
mIsKapiFile = true;
mPisyncFinished = false;
qApp->processEvents();
if ( mAskForPreferences )
if ( !edit_pisync_options()) {
mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") );
mPisyncFinished = true;
return;
}
bool ok;
Q_UINT16 port = mActiveSyncPort.toUInt(&ok);
if ( ! ok ) {
mParent->topLevelWidget()->setCaption( i18n("Sorry, no valid port.Syncing cancelled.") );
mPisyncFinished = true;
return;
}
mCurrentResourceLocal = "";
mCurrentResourceRemote = "";
if ( mSpecificResources.count() ) {
uint lastSyncRes = mSpecificResources.count()/2;
int ccc = mSpecificResources.count()-1;
while ( lastSyncRes > 0 && ccc > 0 && mSpecificResources[ ccc ].isEmpty() ) {
--ccc;
--lastSyncRes;
//qDebug ( "KSM: sync pi %d",ccc );
}
uint startLocal = 0;
uint startRemote = mSpecificResources.count()/2;
emit multiResourceSyncStart( true );
while ( startLocal < mSpecificResources.count()/2 ) {
if ( startLocal+1 >= lastSyncRes )
emit multiResourceSyncStart( false );
mPisyncFinished = false;
mCurrentResourceLocal = mSpecificResources[ startLocal ];
mCurrentResourceRemote = mSpecificResources[ startRemote ];
//qDebug ( "KSM: AAASyncing resources: Local: %s --- Remote: %s ",mCurrentResourceLocal.latin1(), mCurrentResourceRemote.latin1() );
if ( !mCurrentResourceRemote.isEmpty() ) {
qDebug ( "KSM: Syncing resources: Local: %s --- Remote: %s ",mCurrentResourceLocal.latin1(), mCurrentResourceRemote.latin1() );
KCommandSocket* commandSocket = new KCommandSocket( mCurrentResourceRemote, mPassWordPiSync, port, mActiveSyncIP, this, mParent->topLevelWidget() );
connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int )), this, SLOT(deleteCommandSocket(KCommandSocket*, int)) );
commandSocket->readFile( syncFileName() );
mParent->topLevelWidget()->setCaption( i18n("Syncing %1 <-> %2").arg( mCurrentResourceLocal ).arg( mCurrentResourceRemote ) );
while ( !mPisyncFinished ) {
//qDebug("waiting ");
qApp->processEvents();
}
if ( startLocal+1 < mSpecificResources.count()/2 ) {
mParent->topLevelWidget()->setCaption( i18n("Waiting a second before syncing next resource...") );
QTime timer;
timer.start();
while ( timer.elapsed () < 1000 ) {
qApp->processEvents();
}
}
}
++startRemote;
++startLocal;
mAskForPreferences = false;
}
mPisyncFinished = true;
mParent->topLevelWidget()->setCaption( i18n("Multi-resource Pi-sync finished") );
} else {
KCommandSocket* commandSocket = new KCommandSocket( "", mPassWordPiSync, port, mActiveSyncIP, this, mParent->topLevelWidget() );
connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int )), this, SLOT(deleteCommandSocket(KCommandSocket*, int)) );
commandSocket->readFile( syncFileName() );
}
}
void KSyncManager::deleteCommandSocket(KCommandSocket*s, int state)
{
//enum { success, errorW, errorR, quiet };
if ( state == KCommandSocket::errorR ||state == KCommandSocket::errorTO ||state == KCommandSocket::errorPW ||
state == KCommandSocket::errorCA ||state == KCommandSocket::errorFI ||state == KCommandSocket::errorUN||state == KCommandSocket::errorED ) {
if ( state == KCommandSocket::errorPW )
mParent->topLevelWidget()->setCaption( i18n("Wrong password: Receiving remote file failed.") );
else if ( state == KCommandSocket::errorR ||state == KCommandSocket::errorTO )
mParent->topLevelWidget()->setCaption( i18n("ERROR: Receiving remote file failed.") );
else if ( state == KCommandSocket::errorCA )
mParent->topLevelWidget()->setCaption( i18n("Sync cancelled from remote.") );
else if ( state == KCommandSocket::errorFI )
mParent->topLevelWidget()->setCaption( i18n("File error on remote.") );
else if ( state == KCommandSocket::errorED )
mParent->topLevelWidget()->setCaption( i18n("Please close error dialog on remote.") );
else if ( state == KCommandSocket::errorUN )
mParent->topLevelWidget()->setCaption( i18n("Unknown error on remote.") );
delete s;
if ( state == KCommandSocket::errorR ) {
KCommandSocket* commandSocket = new KCommandSocket( "",mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this, mParent->topLevelWidget());
connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) );
commandSocket->sendStop();
}
mPisyncFinished = true;
return;
} else if ( state == KCommandSocket::errorW ) {
mParent->topLevelWidget()->setCaption( i18n("ERROR:Writing back file failed.") );
mPisyncFinished = true;
} else if ( state == KCommandSocket::successR ) {
QTimer::singleShot( 1, this , SLOT ( readFileFromSocket()));
} else if ( state == KCommandSocket::successW ) {
mParent->topLevelWidget()->setCaption( i18n("Pi-Sync successful!") );
mPisyncFinished = true;
} else if ( state == KCommandSocket::quiet ){
qDebug("KSS: quiet ");
mPisyncFinished = true;
} else {
qDebug("KSS: Error: unknown state: %d ", state);
mPisyncFinished = true;
}
delete s;
}
void KSyncManager::readFileFromSocket()
{
QString fileName = syncFileName();
bool syncOK = true;
mParent->topLevelWidget()->setCaption( i18n("Remote file saved to temp file.") );
if ( ! syncWithFile( fileName , true ) ) {
mParent->topLevelWidget()->setCaption( i18n("Syncing failed.") );
syncOK = false;
}
KCommandSocket* commandSocket = new KCommandSocket( mCurrentResourceRemote,mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this, mParent->topLevelWidget() );
connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) );
if ( mWriteBackFile && syncOK ) {
mParent->topLevelWidget()->setCaption( i18n("Sending back file ...") );
commandSocket->writeFile( fileName );
}
else {
commandSocket->sendStop();
if ( syncOK )
mParent->topLevelWidget()->setCaption( i18n("Pi-Sync succesful!") );
mPisyncFinished = true;
}
}
KServerSocket:: KServerSocket ( QString pw, Q_UINT16 port, int backlog, QObject * parent, const char * name ) : QServerSocket( port, backlog, parent, name )
{
mPendingConnect = 0;
mPassWord = pw;
mSocket = 0;
mSyncActionDialog = 0;
blockRC = false;
mErrorMessage = 0;
}
void KServerSocket::waitForSocketFinish()
{
if ( mSocket ) {
//qDebug("KSS:: waiting for finish operation");
QTimer::singleShot( 250, this , SLOT ( waitForSocketFinish()));
return;
}
mSocket = new QSocket( this );
connect( mSocket , SIGNAL(readyRead()), this, SLOT(readClient()) );
connect( mSocket , SIGNAL(delayedCloseFinished()), this, SLOT(discardClient()) );
mSocket->setSocket( mPendingConnect );
mPendingConnect = 0;
}
void KServerSocket::newConnection ( int socket )
{
// qDebug("KServerSocket:New connection %d ", socket);
if ( mPendingConnect ) {
qDebug("KSS::Error : new Connection");
return;
}
if ( mSocket ) {
mPendingConnect = socket;
QTimer::singleShot( 250, this , SLOT ( waitForSocketFinish()));
return;
qDebug("KSS::newConnection Socket deleted! ");
delete mSocket;
mSocket = 0;
}
mPendingConnect = 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()
{
QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
}
void KServerSocket::deleteSocket()
{
//qDebug("KSS::deleteSocket");
if ( mSocket ) {
delete mSocket;
mSocket = 0;
}
if ( mErrorMessage )
QTimer::singleShot( 10, this , SLOT ( displayErrorMessage()));
}
void KServerSocket::readClient()
{
if ( blockRC )
return;
if ( mSocket == 0 ) {
qDebug("ERROR::KSS::readClient(): mSocket == 0 ");
return;
}
if ( mErrorMessage ) {
mErrorMessage = 999;
error_connect("ERROR_ED\r\n\r\n");
return;
}
mResource = "";
mErrorMessage = 0;
//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 );
bool ok = false;
QDateTime dt = KGlobal::locale()->readDateTime( tokens[2], KLocale::ISODate, &ok);
if ( ok ) {
KSyncManager::mRequestedSyncEvent = dt;
}
else
KSyncManager::mRequestedSyncEvent = QDateTime();
mResource =tokens[3];
send_file();
}
else {
mErrorMessage = 1;
error_connect("ERROR_PW\r\n\r\n");
}
}
if ( tokens[0] == "PUT" ) {
if ( tokens[1] == mPassWord ) {
//emit getFile( mSocket );
blockRC = true;
mResource =tokens[2];
get_file();
}
else {
mErrorMessage = 2;
error_connect("ERROR_PW\r\n\r\n");
end_connect();
}
}
if ( tokens[0] == "STOP" ) {
//emit endConnect();
end_connect();
}
}
}
void KServerSocket::displayErrorMessage()
{
if ( mErrorMessage == 1 ) {
KMessageBox::error( 0, i18n("Got send file request\nwith invalid password"), i18n("Pi-Sync Error"));
mErrorMessage = 0;
}
else if ( mErrorMessage == 2 ) {
KMessageBox::error( 0, i18n("Got receive file request\nwith invalid password"), i18n("Pi-Sync Error"));
mErrorMessage = 0;
}
}
void KServerSocket::error_connect( QString errmess )
{
QTextStream os( mSocket );
os.setEncoding( QTextStream::Latin1 );
os << errmess ;
mSocket->close();
if ( mSocket->state() == QSocket::Idle ) {
QTimer::singleShot( 0, this , SLOT ( discardClient()));
}
}
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 );
label->setAlignment ( Qt::AlignHCenter );
QVBoxLayout* lay = new QVBoxLayout( mSyncActionDialog );
lay->addWidget( label);
lay->setMargin(7);
lay->setSpacing(7);
if ( KSyncManager::mRequestedSyncEvent.isValid() ) {
int secs = QDateTime::currentDateTime().secsTo( KSyncManager::mRequestedSyncEvent );
//secs = 333;
if ( secs < 0 )
secs = secs * (-1);
if ( secs > 30 )
//if ( true )
{
QString warning = i18n("Clock skew of\nsyncing devices\nis %1 seconds!").arg( secs );
QLabel* label = new QLabel( warning, mSyncActionDialog );
label->setAlignment ( Qt::AlignHCenter );
lay->addWidget( label);
if ( secs > 180 )
{
if ( secs > 300 ) {
if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel(0, i18n("The clocks of the syncing\ndevices have a difference\nof more than 5 minutes.\nPlease adjust your clocks.\nYou may get wrong syncing results!\nPlease confirm synchronization!"), i18n("High clock skew!"),i18n("Synchronize!"))) {
qDebug("KSS::Sync cancelled ,cs");
mErrorMessage = 0;
end_connect();
error_connect("ERROR_CA\r\n\r\n");
return ;
}
}
QFont f = label->font();
f.setPointSize ( f.pointSize() *2 );
f. setBold (true );
QLabel* label = new QLabel( warning, mSyncActionDialog );
label->setFont( f );
warning = i18n("ADJUST\nYOUR\nCLOCKS!");
label->setText( warning );
label->setAlignment ( Qt::AlignHCenter );
lay->addWidget( label);
mSyncActionDialog->setFixedSize( 230, 300);
} else {
mSyncActionDialog->setFixedSize( 230, 200);
}
} else {
mSyncActionDialog->setFixedSize( 230, 120);
}
} else
mSyncActionDialog->setFixedSize( 230, 120);
mSyncActionDialog->show();
mSyncActionDialog->raise();
emit request_file(mResource);
//emit request_file();
qApp->processEvents();
QString fileName = mFileName;
QFile file( fileName );
if (!file.open( IO_ReadOnly ) ) {
mErrorMessage = 0;
end_connect();
error_connect("ERROR_FI\r\n\r\n");
return ;
}
mSyncActionDialog->setCaption( i18n("Sending file...") );
QTextStream ts( &file );
ts.setEncoding( QTextStream::Latin1 );
QTextStream os( mSocket );
os.setEncoding( QTextStream::Latin1 );
while ( ! ts.atEnd() ) {
os << ts.readLine() << "\r\n";
}
os << "\r\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("KSS:Error open read back file ");
piFileString = "";
emit file_received( false, mResource);
emit file_received( false);
blockRC = false;
return ;
}
// mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1));
QTextStream ts ( &file );
ts.setEncoding( QTextStream::Latin1 );
mSyncActionDialog->setCaption( i18n("Writing file to disk...") );
ts << piFileString;
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( discardClient()));
file.close();
piFileString = "";
emit file_received( true, mResource );
emit file_received( true);
delete mSyncActionDialog;
mSyncActionDialog = 0;
blockRC = false;
}
KCommandSocket::KCommandSocket ( QString remres, QString password, Q_UINT16 port, QString host, QObject * parent, QWidget * cap, const char * name ): QObject( parent, name )
{
mRemoteResource = remres;
if ( mRemoteResource.isEmpty() )
mRemoteResource = "ALL";
else
mRemoteResource.replace (QRegExp (" "),"_" );
mPassWord = password;
mSocket = 0;
mFirst = false;
mFirstLine = true;
mPort = port;
mHost = host;
tlw = cap;
mRetVal = quiet;
mTimerSocket = new QTimer ( this );
connect( mTimerSocket, SIGNAL ( timeout () ), this, SLOT ( updateConnectDialog() ) );
mConnectProgress.setCaption( i18n("Pi-Sync") );
connect( &mConnectProgress, SIGNAL ( cancelled () ), this, SLOT ( deleteSocket() ) );
mConnectCount = -1;
}
void KCommandSocket::sendFileRequest()
{
if ( tlw )
tlw->setCaption( i18n("Connected! Sending request for remote file ...") );
mConnectProgress.hide();
mConnectCount = 300;mConnectMax = 300;
mConnectProgress.setCaption( i18n("Pi-Sync: Connected!") );
mConnectProgress.setLabelText( i18n("Waiting for remote file...") );
mTimerSocket->start( 100, true );
QTextStream os( mSocket );
os.setEncoding( QTextStream::Latin1 );
QString curDt = " " +KGlobal::locale()->formatDateTime(QDateTime::currentDateTime().addSecs(-1),true, true,KLocale::ISODate );
os << "GET " << mPassWord << curDt << " " << mRemoteResource << "\r\n\r\n";
}
void KCommandSocket::readFile( QString fn )
{
if ( !mSocket ) {
mSocket = new QSocket( this );
//qDebug("KCS: read file - new socket");
connect( mSocket, SIGNAL(readyRead()), this, SLOT(startReadFileFromSocket()) );
connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
connect( mSocket, SIGNAL(connected ()), this, SLOT(sendFileRequest() ));
}
mFileString = "";
mFileName = fn;
mFirst = true;
if ( tlw )
tlw->setCaption( i18n("Trying to connect to remote...") );
mConnectCount = 30;mConnectMax = 30;
mTimerSocket->start( 1000, true );
mSocket->connectToHost( mHost, mPort );
//qDebug("KCS: Waiting for connection");
}
void KCommandSocket::updateConnectDialog()
{
if ( mConnectCount == mConnectMax ) {
//qDebug("MAXX %d", mConnectMax);
mConnectProgress.setTotalSteps ( 30 );
mConnectProgress.show();
mConnectProgress.setLabelText( i18n("Trying to connect to remote...") );
}
//qDebug("updateConnectDialog() %d", mConnectCount);
mConnectProgress.raise();
mConnectProgress.setProgress( (mConnectMax - mConnectCount)%30 );
--mConnectCount;
if ( mConnectCount > 0 )
mTimerSocket->start( 1000, true );
else
deleteSocket();
}
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 ;
mConnectCount = 30;mConnectMax = 30;
mTimerSocket->start( 1000, true );
mSocket->connectToHost( mHost, mPort );
}
void KCommandSocket::writeFileToSocket()
{
mTimerSocket->stop();
QFile file2( mFileName );
if (!file2.open( IO_ReadOnly ) ) {
mConnectProgress.hide();
mConnectCount = -1;
mRetVal= errorW;
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
return ;
}
mConnectProgress.setTotalSteps ( file2.size() );
mConnectProgress.show();
int count = 0;
mConnectProgress.setLabelText( i18n("Sending back synced file...") );
mConnectProgress.setProgress( count );
mConnectProgress.blockSignals( true );
QTextStream ts2( &file2 );
ts2.setEncoding( QTextStream::Latin1 );
QTextStream os2( mSocket );
os2.setEncoding( QTextStream::Latin1 );
os2 << "PUT " << mPassWord << " " << mRemoteResource << "\r\n\r\n";;
int byteCount = 0;
int byteMax = file2.size()/53;
while ( ! ts2.atEnd() ) {
qApp->processEvents();
if ( byteCount > byteMax ) {
byteCount = 0;
mConnectProgress.setProgress( count );
}
QString temp = ts2.readLine();
count += temp.length();
byteCount += temp.length();
os2 << temp << "\r\n";
}
file2.close();
mConnectProgress.hide();
mConnectCount = -1;
os2 << "\r\n";
mRetVal= successW;
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
mConnectProgress.blockSignals( false );
}
void KCommandSocket::sendStop()
{
if ( !mSocket ) {
mSocket = new QSocket( this );
connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
}
mSocket->connectToHost( mHost, mPort );
QTextStream os2( mSocket );
os2.setEncoding( QTextStream::Latin1 );
os2 << "STOP\r\n\r\n";
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
}
void KCommandSocket::startReadFileFromSocket()
{
if ( ! mFirst )
return;
mConnectProgress.setLabelText( i18n("Receiving file from remote...") );
mFirst = false;
mFileString = "";
mTime.start();
mFirstLine = true;
QTimer::singleShot( 1, this , SLOT (readFileFromSocket( ) ));
}
void KCommandSocket::readFileFromSocket()
{
//qDebug("readBackFileFromSocket() %d ", mTime.elapsed ());
while ( mSocket->canReadLine () ) {
mTime.restart();
QString line = mSocket->readLine ();
if ( mFirstLine ) {
mFirstLine = false;
if ( line.left( 6 ) == "ERROR_" ) {
mTimerSocket->stop();
mConnectCount = -1;
if ( line.left( 8 ) == "ERROR_PW" ) {
mRetVal = errorPW;
deleteSocket();
return ;
}
if ( line.left( 8 ) == "ERROR_CA" ) {
mRetVal = errorCA;
deleteSocket();
return ;
}
if ( line.left( 8 ) == "ERROR_FI" ) {
mRetVal = errorFI;
deleteSocket();
return ;
}
if ( line.left( 8 ) == "ERROR_ED" ) {
mRetVal = errorED;
deleteSocket();
return ;
}
mRetVal = errorUN;
deleteSocket();
return ;
}
}
mFileString += line;
//qDebug("readline: %s ", line.latin1());
}
if ( mTime.elapsed () < 3000 ) {
// wait for more
//qDebug("waitformore ");
QTimer::singleShot( 100, this , SLOT (readFileFromSocket( ) ));
return;
}
mTimerSocket->stop();
mConnectCount = -1;
mConnectProgress.hide();
QString fileName = mFileName;
QFile file ( fileName );
if (!file.open( IO_WriteOnly ) ) {
mFileString = "";
mRetVal = errorR;
qDebug("KSS:Error open temp sync file for writing: %s",fileName.latin1() );
deleteSocket();
return ;
}
// mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1));
QTextStream ts ( &file );
ts.setEncoding( QTextStream::Latin1 );
ts << mFileString;
file.close();
mFileString = "";
mRetVal = successR;
mSocket->close();
// if state is not idle, deleteSocket(); is called via
// connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
if ( mSocket->state() == QSocket::Idle )
deleteSocket();
}
void KCommandSocket::deleteSocket()
{
//qDebug("KCommandSocket::deleteSocket() ");
mConnectProgress.hide();
if ( mConnectCount >= 0 ) {
mTimerSocket->stop();
mRetVal = errorTO;
qDebug("KCS::Connection to remote host timed out");
if ( mSocket ) {
mSocket->close();
//if ( mSocket->state() == QSocket::Idle )
// deleteSocket();
delete mSocket;
mSocket = 0;
}
if ( mConnectCount == 0 )
KMessageBox::error( 0, i18n("Connection to remote\nhost timed out!\nDid you forgot to enable\nsyncing on remote host?"));
else if ( tlw )
tlw->setCaption( i18n("Connection to remote host cancelled!") );
emit commandFinished( this, mRetVal );
return;
}
//qDebug("KCommandSocket::deleteSocket() %d", mRetVal );
if ( mSocket)
delete mSocket;
mSocket = 0;
//qDebug("commandFinished ");
emit commandFinished( this, mRetVal );
}
diff --git a/libkdepim/ksyncmanager.h b/libkdepim/ksyncmanager.h
index 04cdade..71d17e9 100644
--- a/libkdepim/ksyncmanager.h
+++ b/libkdepim/ksyncmanager.h
@@ -1,249 +1,248 @@
/*
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>
#include <qprogressdialog.h>
#include <kdialog.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 file_received( bool );
void request_file();
void file_received( bool, const QString &);
void request_file(const QString &);
void saveFile();
void endConnect();
private slots:
void waitForSocketFinish();
void discardClient();
void deleteSocket();
void readClient();
void displayErrorMessage();
void readBackFileFromSocket();
private :
int mPendingConnect;
QString mResource;
int mErrorMessage;
bool blockRC;
void send_file();
void get_file();
void end_connect();
void error_connect( QString );
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, errorTO, errorPW, errorCA, errorFI, errorUN, errorED,quiet };
KCommandSocket (QString remoteResource, QString password, Q_UINT16 port, QString host, QObject * parent=0, QWidget* cap = 0, const char * name=0 );
void readFile( QString );
void writeFile( QString );
void sendStop();
private slots :
void sendFileRequest();
void updateConnectDialog();
signals:
void commandFinished( KCommandSocket*, int );
private slots:
void startReadFileFromSocket();
void readFileFromSocket();
void deleteSocket();
void writeFileToSocket();
private :
QString mRemoteResource;
int mConnectCount;
int mConnectMax;
KProgressDialog mConnectProgress;
QWidget* tlw;
QSocket* mSocket;
QString mPassWord;
Q_UINT16 mPort;
QString mHost;
QString mFileName;
QTimer* mTimerSocket;
int mRetVal;
QTime mTime;
QString mFileString;
bool mFirst;
bool mFirstLine;
};
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() ;
void multiSync( bool askforPrefs );
bool blockSave() { return mBlockSaveFlag; }
void setBlockSave(bool sa) { mBlockSaveFlag = sa; }
void setDefaultFileName( QString s) ;
QString defaultFileName() { return mDefFileName ;}
QString syncFileName();
void enableQuick( bool ask = true);
bool syncWithDesktop () { return mSyncWithDesktop;}
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 mIsKapiFile;
bool mWriteBackExistingOnly;
int mSyncAlgoPrefs;
bool mWriteBackFile;
int mWriteBackInFuture;
int mWriteBackInPast;
QString mPhoneDevice;
QString mPhoneConnection;
QString mPhoneModel;
QString mPassWordPiSync;
QString mActiveSyncPort;
QString mActiveSyncIP ;
QString mFilterInCal;
QString mFilterOutCal;
QString mFilterInAB;
QString mFilterOutAB;
static QDateTime mRequestedSyncEvent;
signals:
void save();
void request_file();
void getFile( bool );
void getFile( bool, const QString &);
void request_file(const QString &);
void multiResourceSyncStart( bool );
public slots:
void slotSyncMenu( int );
void slotClearMenu( int action );
void deleteCommandSocket(KCommandSocket*s, int state);
void readFileFromSocket();
void fillSyncMenu();
private:
void syncPi();
KServerSocket * mServerSocket;
KPimPrefs* mPrefs;
QString mDefFileName;
QString mCurrentSyncDevice;
QString mCurrentSyncName;
void quickSyncLocalFile();
bool syncWithFile( QString fn , bool quick );
void syncLocalFile();
void syncPhone();
void syncSharp();
void syncKDE();
+ void syncOL();
bool syncExternalApplication(QString);
int mCurrentSyncProfile ;
void syncRemote( KSyncProfile* prof, bool ask = true);
bool edit_sync_options();
bool edit_pisync_options();
int ringSync();
QString getPassword( );
bool mPisyncFinished;
QStringList mSpecificResources;
QString mCurrentResourceLocal;
QString mCurrentResourceRemote;
bool mBlockSaveFlag;
QWidget* mParent;
KSyncInterface* mImplementation;
TargetApp mTargetApp;
QPopupMenu* mSyncMenu;
QProgressBar* bar;
bool mSyncWithDesktop;
private slots:
void displayErrorPort();
void confSync();
};
class KSyncInterface
{
public :
virtual void removeSyncInfo( QString syncProfile) = 0;
virtual bool sync(KSyncManager* manager, QString filename, int mode, QString resource) = 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
diff --git a/libkdepim/libkdepim.pro b/libkdepim/libkdepim.pro
index 84af7ad..7160d0e 100644
--- a/libkdepim/libkdepim.pro
+++ b/libkdepim/libkdepim.pro
@@ -1,61 +1,76 @@
TEMPLATE = lib
CONFIG = qt warn_on
DEFINES +=KORG_NOKABC
TARGET = microkdepim
INCLUDEPATH += ../microkde ../microkde/kdecore ../microkde/kdeui . ..
DESTDIR=../bin
DEFINES += DESKTOP_VERSION
include( ../variables.pri )
unix : {
OBJECTS_DIR = obj/unix
MOC_DIR = moc/unix
}
win32: {
DEFINES += _WIN32_
OBJECTS_DIR = obj/win
MOC_DIR = moc/win
}
INTERFACES = \
HEADERS = \
categoryeditdialog.h \
categoryeditdialog_base.h \
categoryselectdialog.h \
categoryselectdialog_base.h \
externalapphandler.h \
kdateedit.h \
kdatepicker.h \
kinputdialog.h \
kpimprefs.h \
kpimglobalprefs.h \
kprefsdialog.h \
kprefswidget.h \
ksyncmanager.h \
ksyncprofile.h \
ksyncprefsdialog.h \
kcmconfigs/kcmkdepimconfig.h \
kcmconfigs/kdepimconfigwidget.h \
phoneaccess.h
SOURCES = \
categoryeditdialog.cpp \
categoryeditdialog_base.cpp \
categoryselectdialog.cpp \
categoryselectdialog_base.cpp \
externalapphandler.cpp \
kdateedit.cpp \
kdatepicker.cpp \
kinputdialog.cpp \
kpimprefs.cpp \
kpimglobalprefs.cpp \
kprefsdialog.cpp \
kprefswidget.cpp \
ksyncmanager.cpp \
ksyncprofile.cpp \
ksyncprefsdialog.cpp \
kcmconfigs/kcmkdepimconfig.cpp \
kcmconfigs/kdepimconfigwidget.cpp \
phoneaccess.cpp
+win32: {
+#olimport section
+importol {
+debug: {
+LIBS += mfc71ud.lib
+}
+release: {
+LIBS += mfc71u.lib
+}
+DEFINES += _OL_IMPORT_
+HEADERS += ol_access.h
+SOURCES += ol_access.cpp
+#olimport section end
+}
+}