-rw-r--r-- | libopie/pim/obackendfactory.h | 12 | ||||
-rw-r--r-- | libopie/pim/ocontact.cpp | 253 | ||||
-rw-r--r-- | libopie/pim/ocontact.h | 9 | ||||
-rw-r--r-- | libopie/pim/ocontactaccess.h | 11 | ||||
-rw-r--r-- | libopie/pim/ocontactaccessbackend.h | 14 | ||||
-rw-r--r-- | libopie/pim/ocontactaccessbackend_vcard.cpp | 22 | ||||
-rw-r--r-- | libopie/pim/ocontactaccessbackend_xml.cpp | 3 | ||||
-rw-r--r-- | libopie/pim/oconversion.h | 5 | ||||
-rw-r--r-- | libopie/pim/odatebookaccessbackend.h | 4 | ||||
-rw-r--r-- | libopie/pim/odatebookaccessbackend_xml.cpp | 6 | ||||
-rw-r--r-- | libopie/pim/opimaccessbackend.h | 4 | ||||
-rw-r--r-- | libopie/pim/opimaccesstemplate.h | 4 | ||||
-rw-r--r-- | libopie/pim/opimcache.h | 6 | ||||
-rw-r--r-- | libopie/pim/opimmainwindow.cpp | 14 | ||||
-rw-r--r-- | libopie/pim/opimxrefmanager.h | 2 | ||||
-rw-r--r-- | libopie/pim/orecordlist.h | 12 | ||||
-rw-r--r-- | libopie/pim/otemplatebase.h | 7 | ||||
-rw-r--r-- | libopie/pim/otodo.cpp | 16 | ||||
-rw-r--r-- | libopie/pim/otodo.h | 9 | ||||
-rw-r--r-- | libopie/pim/otodoaccessbackend.h | 4 | ||||
-rw-r--r-- | libopie/pim/otodoaccessvcal.cpp | 26 | ||||
-rw-r--r-- | libopie/pim/otodoaccessxml.cpp | 6 |
22 files changed, 327 insertions, 122 deletions
diff --git a/libopie/pim/obackendfactory.h b/libopie/pim/obackendfactory.h index ad6cf5a..f3c339d 100644 --- a/libopie/pim/obackendfactory.h +++ b/libopie/pim/obackendfactory.h @@ -1,154 +1,166 @@ /* * Class to manage Backends. * * Copyright (c) 2002 by Stefan Eilers (Eilers.Stefan@epost.de) * * ===================================================================== * This program 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. * ===================================================================== * ToDo: Use plugins * ===================================================================== * Version: $Id$ * ===================================================================== * History: * $Log$ + * Revision 1.7 2003/08/01 12:30:16 eilers + * Merging changes from BRANCH_1_0 to HEAD + * + * Revision 1.6.4.1 2003/06/30 14:34:19 eilers + * Patches from Zecke: + * Fixing and cleaning up extraMap handling + * Adding d_ptr for binary compatibility in the future + * * Revision 1.6 2003/04/13 18:07:10 zecke * More API doc * QString -> const QString& * QString = 0l -> QString::null * * Revision 1.5 2003/02/21 23:31:52 zecke * Add XML datebookresource * -clean up todoaccessxml header * -implement some more stuff in the oeven tester * -extend DefaultFactory to not crash and to use datebook * * -reading of OEvents is working nicely.. saving will be added * tomorrow * -fix spelling in ODateBookAcces * * Revision 1.4 2002/10/14 15:55:18 eilers * Redeactivate SQL.. ;) * * Revision 1.3 2002/10/10 17:08:58 zecke * The Cache is finally in place * I tested it with my todolist and it 'works' for 10.000 todos the hits are awesome ;) * The read ahead functionality does not make sense for XMLs backends because most of the stuff is already in memory. While using readahead on SQL makes things a lot faster.... * I still have to fully implement read ahead * This change is bic but sc * * Revision 1.2 2002/10/08 09:27:36 eilers * Fixed libopie.pro to include the new pim-API. * The SQL-Stuff is currently deactivated. Otherwise everyone who wants to * compile itself would need to install libsqlite, libopiesql... * Therefore, the backend currently uses XML only.. * * Revision 1.1 2002/10/07 17:35:01 eilers * added OBackendFactory for advanced backend access * * * ===================================================================== */ #ifndef OPIE_BACKENDFACTORY_H_ #define OPIE_BACKENDFACTORY_H_ #include <qstring.h> #include <qasciidict.h> #include <qpe/config.h> #include "otodoaccessxml.h" #include "ocontactaccessbackend_xml.h" #include "odatebookaccessbackend_xml.h" #ifdef __USE_SQL #include "otodoaccesssql.h" #endif +class OBackendPrivate; + /** * This class is our factory. It will give us the default implementations * of at least Todolist, Contacts and Datebook. In the future this class will * allow users to switch the backend with ( XML->SQLite ) without the need * to recompile.# * This class as the whole PIM Api is making use of templates * * <pre> * OTodoAccessBackend* backend = OBackEndFactory<OTodoAccessBackend>::Default("todo", QString::null ); * backend->load(); * </pre> * * @author Stefan Eilers * @version 0.1 */ template<class T> class OBackendFactory { public: OBackendFactory() {}; enum BACKENDS { TODO, CONTACT, DATE }; /** * Returns a backend implementation for backendName * @param backendName the type of the backend * @param appName will be passed on to the backend */ static T* Default( const QString backendName, const QString& appName ){ // __asm__("int3"); Config config( "pimaccess" ); config.setGroup ( backendName ); QString backend = config.readEntry( "usebackend" ); QAsciiDict<int> dict ( 3 ); dict.setAutoDelete ( TRUE ); dict.insert( "todo", new int (TODO) ); dict.insert( "contact", new int (CONTACT) ); dict.insert( "datebook", new int(DATE) ); qWarning ("TODO is: %d", TODO); qWarning ("CONTACT is: %d", CONTACT); int *find = dict[ backendName ]; if (!find ) return 0; switch ( *find ){ case TODO: #ifdef __USE_SQL if ( backend == "sql" ) return (T*) new OTodoAccessBackendSQL(""); #else if ( backend == "sql" ) qWarning ("OBackendFactory:: sql Backend not implemented! Using XML instead!"); #endif return (T*) new OTodoAccessXML( appName ); case CONTACT: if ( backend == "sql" ) qWarning ("OBackendFactory:: sql Backend not implemented! Using XML instead!"); return (T*) new OContactAccessBackend_XML( appName ); case DATE: if ( backend == "sql" ) qWarning("OBackendFactory:: sql Backend not implemented! Using XML instead!"); return (T*) new ODateBookAccessBackend_XML( appName ); default: return NULL; } } + private: + OBackendPrivate* d; }; #endif diff --git a/libopie/pim/ocontact.cpp b/libopie/pim/ocontact.cpp index be4ce0a..3473baa 100644 --- a/libopie/pim/ocontact.cpp +++ b/libopie/pim/ocontact.cpp @@ -1,1020 +1,1093 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** Copyright (C) 2002-2003 by Stefan Eilers (eilers.stefan@epost.de) ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #define QTOPIA_INTERNAL_CONTACT_MRE #include "ocontact.h" #include "opimresolver.h" +#include "oconversion.h" #include <qpe/stringutil.h> -#include "oconversion.h" #include <qpe/timestring.h> +#include <qpe/config.h> #include <qobject.h> #include <qregexp.h> #include <qstylesheet.h> #include <qfileinfo.h> #include <qmap.h> #include <stdio.h> /*! \class Contact contact.h \brief The Contact class holds the data of an address book entry. This data includes information the name of the person, contact information, and business information such as deparment and job title. \ingroup qtopiaemb \ingroup qtopiadesktop */ /*! Creates a new, empty contact. */ OContact::OContact() : OPimRecord(), mMap(), d( 0 ) { } /*! \internal Creates a new contact. The properties of the contact are set from \a fromMap. */ OContact::OContact( const QMap<int, QString> &fromMap ) : OPimRecord(), mMap( fromMap ), d( 0 ) { QString cats = mMap[ Qtopia::AddressCategory ]; if ( !cats.isEmpty() ) setCategories( idsFromString( cats ) ); QString uidStr = find( Qtopia::AddressUid ); if ( uidStr.isEmpty() || (uidStr.toInt() == 0) ){ qWarning( "Invalid UID found. Generate new one.." ); setUid( uidGen().generate() ); }else setUid( uidStr.toInt() ); // if ( !uidStr.isEmpty() ) // setUid( uidStr.toInt() ); } /*! Destroys a contact. */ OContact::~OContact() { } /*! \fn void OContact::setTitle( const QString &str ) Sets the title of the contact to \a str. */ /*! \fn void OContact::setFirstName( const QString &str ) Sets the first name of the contact to \a str. */ /*! \fn void OContact::setMiddleName( const QString &str ) Sets the middle name of the contact to \a str. */ /*! \fn void OContact::setLastName( const QString &str ) Sets the last name of the contact to \a str. */ /*! \fn void OContact::setSuffix( const QString &str ) Sets the suffix of the contact to \a str. */ /*! \fn void OContact::setFileAs( const QString &str ) Sets the contact to filed as \a str. */ /*! \fn void OContact::setDefaultEmail( const QString &str ) Sets the default email of the contact to \a str. */ /*! \fn void OContact::setHomeStreet( const QString &str ) Sets the home street address of the contact to \a str. */ /*! \fn void OContact::setHomeCity( const QString &str ) Sets the home city of the contact to \a str. */ /*! \fn void OContact::setHomeState( const QString &str ) Sets the home state of the contact to \a str. */ /*! \fn void OContact::setHomeZip( const QString &str ) Sets the home zip code of the contact to \a str. */ /*! \fn void OContact::setHomeCountry( const QString &str ) Sets the home country of the contact to \a str. */ /*! \fn void OContact::setHomePhone( const QString &str ) Sets the home phone number of the contact to \a str. */ /*! \fn void OContact::setHomeFax( const QString &str ) Sets the home fax number of the contact to \a str. */ /*! \fn void OContact::setHomeMobile( const QString &str ) Sets the home mobile phone number of the contact to \a str. */ /*! \fn void OContact::setHomeWebpage( const QString &str ) Sets the home webpage of the contact to \a str. */ /*! \fn void OContact::setCompany( const QString &str ) Sets the company for contact to \a str. */ /*! \fn void OContact::setJobTitle( const QString &str ) Sets the job title of the contact to \a str. */ /*! \fn void OContact::setDepartment( const QString &str ) Sets the department for contact to \a str. */ /*! \fn void OContact::setOffice( const QString &str ) Sets the office for contact to \a str. */ /*! \fn void OContact::setBusinessStreet( const QString &str ) Sets the business street address of the contact to \a str. */ /*! \fn void OContact::setBusinessCity( const QString &str ) Sets the business city of the contact to \a str. */ /*! \fn void OContact::setBusinessState( const QString &str ) Sets the business state of the contact to \a str. */ /*! \fn void OContact::setBusinessZip( const QString &str ) Sets the business zip code of the contact to \a str. */ /*! \fn void OContact::setBusinessCountry( const QString &str ) Sets the business country of the contact to \a str. */ /*! \fn void OContact::setBusinessPhone( const QString &str ) Sets the business phone number of the contact to \a str. */ /*! \fn void OContact::setBusinessFax( const QString &str ) Sets the business fax number of the contact to \a str. */ /*! \fn void OContact::setBusinessMobile( const QString &str ) Sets the business mobile phone number of the contact to \a str. */ /*! \fn void OContact::setBusinessPager( const QString &str ) Sets the business pager number of the contact to \a str. */ /*! \fn void OContact::setBusinessWebpage( const QString &str ) Sets the business webpage of the contact to \a str. */ /*! \fn void OContact::setProfession( const QString &str ) Sets the profession of the contact to \a str. */ /*! \fn void OContact::setAssistant( const QString &str ) Sets the assistant of the contact to \a str. */ /*! \fn void OContact::setManager( const QString &str ) Sets the manager of the contact to \a str. */ /*! \fn void OContact::setSpouse( const QString &str ) Sets the spouse of the contact to \a str. */ /*! \fn void OContact::setGender( const QString &str ) Sets the gender of the contact to \a str. */ /*! \fn void OContact::setNickname( const QString &str ) Sets the nickname of the contact to \a str. */ /*! \fn void OContact::setNotes( const QString &str ) Sets the notes about the contact to \a str. */ /*! \fn QString OContact::title() const Returns the title of the contact. */ /*! \fn QString OContact::firstName() const Returns the first name of the contact. */ /*! \fn QString OContact::middleName() const Returns the middle name of the contact. */ /*! \fn QString OContact::lastName() const Returns the last name of the contact. */ /*! \fn QString OContact::suffix() const Returns the suffix of the contact. */ /*! \fn QString OContact::fileAs() const Returns the string the contact is filed as. */ /*! \fn QString OContact::defaultEmail() const Returns the default email address of the contact. */ /*! \fn QString OContact::emails() const Returns the list of email address for a contact separated by ';'s in a single string. */ /*! \fn QString OContact::homeStreet() const Returns the home street address of the contact. */ /*! \fn QString OContact::homeCity() const Returns the home city of the contact. */ /*! \fn QString OContact::homeState() const Returns the home state of the contact. */ /*! \fn QString OContact::homeZip() const Returns the home zip of the contact. */ /*! \fn QString OContact::homeCountry() const Returns the home country of the contact. */ /*! \fn QString OContact::homePhone() const Returns the home phone number of the contact. */ /*! \fn QString OContact::homeFax() const Returns the home fax number of the contact. */ /*! \fn QString OContact::homeMobile() const Returns the home mobile number of the contact. */ /*! \fn QString OContact::homeWebpage() const Returns the home webpage of the contact. */ /*! \fn QString OContact::company() const Returns the company for the contact. */ /*! \fn QString OContact::department() const Returns the department for the contact. */ /*! \fn QString OContact::office() const Returns the office for the contact. */ /*! \fn QString OContact::jobTitle() const Returns the job title of the contact. */ /*! \fn QString OContact::profession() const Returns the profession of the contact. */ /*! \fn QString OContact::assistant() const Returns the assistant of the contact. */ /*! \fn QString OContact::manager() const Returns the manager of the contact. */ /*! \fn QString OContact::businessStreet() const Returns the business street address of the contact. */ /*! \fn QString OContact::businessCity() const Returns the business city of the contact. */ /*! \fn QString OContact::businessState() const Returns the business state of the contact. */ /*! \fn QString OContact::businessZip() const Returns the business zip of the contact. */ /*! \fn QString OContact::businessCountry() const Returns the business country of the contact. */ /*! \fn QString OContact::businessPhone() const Returns the business phone number of the contact. */ /*! \fn QString OContact::businessFax() const Returns the business fax number of the contact. */ /*! \fn QString OContact::businessMobile() const Returns the business mobile number of the contact. */ /*! \fn QString OContact::businessPager() const Returns the business pager number of the contact. */ /*! \fn QString OContact::businessWebpage() const Returns the business webpage of the contact. */ /*! \fn QString OContact::spouse() const Returns the spouse of the contact. */ /*! \fn QString OContact::gender() const Returns the gender of the contact. */ /*! \fn QString OContact::nickname() const Returns the nickname of the contact. */ /*! \fn QString OContact::children() const Returns the children of the contact. */ /*! \fn QString OContact::notes() const Returns the notes relating to the the contact. */ /*! \fn QString OContact::groups() const \internal Returns the groups for the contact. */ /*! \fn QStringList OContact::groupList() const \internal */ /*! \fn QString OContact::field(int) const \internal */ /*! \fn void OContact::saveJournal( journal_action, const QString & = QString::null ) \internal */ /*! \fn void OContact::setUid( int id ) \internal Sets the uid for this record to \a id. */ /*! \enum OContact::journal_action \internal */ /*! \internal */ QMap<int, QString> OContact::toMap() const { QMap<int, QString> map = mMap; QString cats = idsToString( categories() ); if ( !cats.isEmpty() ) map.insert( Qtopia::AddressCategory, cats ); return map; } /*! Returns a rich text formatted QString representing the contents the contact. */ QString OContact::toRichText() const { QString text; QString value, comp, state; QString str; bool marker = false; + Config cfg("qpe"); + cfg.setGroup("Appearance"); + int addressformat = cfg.readNumEntry( "AddressFormat", Zip_City_State ); + // name, jobtitle and company if ( !(value = fullName()).isEmpty() ) - text += "<b><h3><img src=\"addressbook/AddressBook\">" + Qtopia::escapeString(value) + "</h3></b>"; - + text += "<b><h3><img src=\"addressbook/AddressBook\"> " + Qtopia::escapeString(value) + "</h3></b>"; + if ( !(value = jobTitle()).isEmpty() ) - text += Qtopia::escapeString(value) + "<br>"; + text += Qtopia::escapeString(value); comp = company(); if ( !(value = department()).isEmpty() ) { text += Qtopia::escapeString(value); if ( comp ) text += ", "; else text += "<br>"; } if ( !comp.isEmpty() ) - text += Qtopia::escapeString(comp) + "<br>"; + text += Qtopia::escapeString(comp); - text += "<hr><br>"; + text += "<br><hr>"; // defailt email QString defEmail = defaultEmail(); - if ( !defEmail.isEmpty() ) - text += "<b><img src=\"addressbook/email\">" + QObject::tr("Default Email: ") + "</b>" - + Qtopia::escapeString(defEmail) + "<br>"; - - text += "<br>"; + if ( !defEmail.isEmpty() ){ + text += "<b><img src=\"addressbook/email\"> " + QObject::tr("Default Email: ") + "</b>" + + Qtopia::escapeString(defEmail); + marker = true; + } // business address if ( !businessStreet().isEmpty() || !businessCity().isEmpty() || !businessZip().isEmpty() || !businessCountry().isEmpty() ) { - text += QObject::tr( "<b>Work Address:</b>" ); - text += "<br>"; + text += QObject::tr( "<br><br><b>Work Address:</b>" ); marker = true; } - if ( !(value = businessStreet()).isEmpty() ) - text += Qtopia::escapeString(value) + "<br>"; - state = businessState(); - if ( !(value = businessZip()).isEmpty() ) - text += Qtopia::escapeString(value) + " "; - if ( !(value = businessCity()).isEmpty() ) { - text += Qtopia::escapeString(value); - if ( state ) - text += ", " + Qtopia::escapeString(state); - text += "<br>"; - } else if ( !state.isEmpty() ) - text += Qtopia::escapeString(state) + "<br>"; + if ( !(value = businessStreet()).isEmpty() ){ + text += "<br>" + Qtopia::escapeString(value); + marker = true; + } + + switch( addressformat ){ + case Zip_City_State:{ // Zip_Code City, State + state = businessState(); + if ( !(value = businessZip()).isEmpty() ){ + text += "<br>" + Qtopia::escapeString(value) + " "; + marker = true; + + } else + text += "<br>"; + + if ( !(value = businessCity()).isEmpty() ) { + marker = true; + text += Qtopia::escapeString(value); + if ( state ) + text += ", " + Qtopia::escapeString(state); + } else if ( !state.isEmpty() ){ + text += "<br>" + Qtopia::escapeString(state); + marker = true; + } + break; + } + case City_State_Zip:{ // City, State Zip_Code + state = businessState(); + if ( !(value = businessCity()).isEmpty() ) { + marker = true; + text += "<br>" + Qtopia::escapeString(value); + if ( state ) + text += ", " + Qtopia::escapeString(state); + } else if ( !state.isEmpty() ){ + text += "<br>" + Qtopia::escapeString(state); + marker = true; + } + if ( !(value = businessZip()).isEmpty() ){ + text += " " + Qtopia::escapeString(value); + marker = true; + } + break; + } + } - if ( !(value = businessCountry()).isEmpty() ) - text += Qtopia::escapeString(value) + "<br>"; + if ( !(value = businessCountry()).isEmpty() ){ + text += "<br>" + Qtopia::escapeString(value); + marker = true; + } // rest of Business data str = office(); if ( !str.isEmpty() ){ - text += "<b>" + QObject::tr("Office: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Office: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } str = businessWebpage(); if ( !str.isEmpty() ){ - text += "<b><img src=\"addressbook/webpagework\">" + QObject::tr("Business Web Page: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b><img src=\"addressbook/webpagework\"> " + QObject::tr("Business Web Page: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } str = businessPhone(); if ( !str.isEmpty() ){ - text += "<b><img src=\"addressbook/phonework\">" + QObject::tr("Business Phone: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b><img src=\"addressbook/phonework\"> " + QObject::tr("Business Phone: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } str = businessFax(); if ( !str.isEmpty() ){ - text += "<b><img src=\"addressbook/faxwork\">" + QObject::tr("Business Fax: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b><img src=\"addressbook/faxwork\"> " + QObject::tr("Business Fax: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } str = businessMobile(); if ( !str.isEmpty() ){ - text += "<b><img src=\"addressbook/mobilework\">" + QObject::tr("Business Mobile: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b><img src=\"addressbook/mobilework\"> " + QObject::tr("Business Mobile: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } str = businessPager(); if ( !str.isEmpty() ){ - text += "<b>" + QObject::tr("Business Pager: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Business Pager: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } text += "<br>"; // home address if ( !homeStreet().isEmpty() || !homeCity().isEmpty() || !homeZip().isEmpty() || !homeCountry().isEmpty() ) { - text += QObject::tr( "<b>Home Address:</b>" ); - text += "<br>"; + text += QObject::tr( "<br><br><b>Home Address:</b>" ); + marker = true; } - if ( !(value = homeStreet()).isEmpty() ) - text += Qtopia::escapeString(value) + "<br>"; - state = homeState(); - if ( !(value = homeZip()).isEmpty() ) - text += Qtopia::escapeString(value) + " "; - if ( !(value = homeCity()).isEmpty() ) { - text += Qtopia::escapeString(value); - if ( !state.isEmpty() ) - text += ", " + Qtopia::escapeString(state); - text += "<br>"; - } else if (!state.isEmpty()) - text += Qtopia::escapeString(state) + "<br>"; - if ( !(value = homeCountry()).isEmpty() ) - text += Qtopia::escapeString(value) + "<br>"; + if ( !(value = homeStreet()).isEmpty() ){ + text += "<br>" + Qtopia::escapeString(value); + marker = true; + } + + switch( addressformat ){ + case Zip_City_State:{ // Zip_Code City, State + state = homeState(); + if ( !(value = homeZip()).isEmpty() ){ + text += "<br>" + Qtopia::escapeString(value) + " "; + marker = true; + } else + text += "<br>"; + + if ( !(value = homeCity()).isEmpty() ) { + marker = true; + text += Qtopia::escapeString(value); + if ( !state.isEmpty() ) + text += ", " + Qtopia::escapeString(state); + } else if (!state.isEmpty()) { + text += "<br>" + Qtopia::escapeString(state); + marker = true; + } + break; + } + case City_State_Zip:{ // City, State Zip_Code + state = homeState(); + if ( !(value = homeCity()).isEmpty() ) { + marker = true; + text += "<br>" + Qtopia::escapeString(value); + if ( state ) + text += ", " + Qtopia::escapeString(state); + } else if ( !state.isEmpty() ){ + text += "<br>" + Qtopia::escapeString(state); + marker = true; + } + if ( !(value = homeZip()).isEmpty() ){ + text += " " + Qtopia::escapeString(value); + marker = true; + } + break; + } + } + + if ( !(value = homeCountry()).isEmpty() ){ + text += "<br>" + Qtopia::escapeString(value); + marker = true; + } // rest of Home data str = homeWebpage(); if ( !str.isEmpty() ){ - text += "<b><img src=\"addressbook/webpagehome\">" + QObject::tr("Home Web Page: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b><img src=\"addressbook/webpagehome\"> " + QObject::tr("Home Web Page: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } str = homePhone(); if ( !str.isEmpty() ){ - text += "<b><img src=\"addressbook/phonehome\">" + QObject::tr("Home Phone: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b><img src=\"addressbook/phonehome\"> " + QObject::tr("Home Phone: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } str = homeFax(); if ( !str.isEmpty() ){ - text += "<b><img src=\"addressbook/faxhome\">" + QObject::tr("Home Fax: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b><img src=\"addressbook/faxhome\"> " + QObject::tr("Home Fax: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } str = homeMobile(); if ( !str.isEmpty() ){ - text += "<b><img src=\"addressbook/mobilehome\">" + QObject::tr("Home Mobile: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b><img src=\"addressbook/mobilehome\"> " + QObject::tr("Home Mobile: ") + "</b>" + + Qtopia::escapeString(str); marker = true; } if ( marker ) - text += "<br><hr><br>"; - // the others... + text += "<br><hr>"; + + // the rest... str = emails(); if ( !str.isEmpty() && ( str != defEmail ) ) - text += "<b>" + QObject::tr("All Emails: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("All Emails: ") + "</b>" + + Qtopia::escapeString(str); str = profession(); if ( !str.isEmpty() ) - text += "<b>" + QObject::tr("Profession: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Profession: ") + "</b>" + + Qtopia::escapeString(str); str = assistant(); if ( !str.isEmpty() ) - text += "<b>" + QObject::tr("Assistant: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Assistant: ") + "</b>" + + Qtopia::escapeString(str); str = manager(); if ( !str.isEmpty() ) - text += "<b>" + QObject::tr("Manager: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Manager: ") + "</b>" + + Qtopia::escapeString(str); str = gender(); if ( !str.isEmpty() && str.toInt() != 0 ) { - if ( str.toInt() == 1 ) - str = QObject::tr( "Male" ); - else if ( str.toInt() == 2 ) - str = QObject::tr( "Female" ); - text += "<b>" + QObject::tr("Gender: ") + "</b>" + str + "<br>"; + text += "<br>"; + if ( str.toInt() == 1 ) + str = QObject::tr( "Male" ); + else if ( str.toInt() == 2 ) + str = QObject::tr( "Female" ); + text += "<b>" + QObject::tr("Gender: ") + "</b>" + str; } str = spouse(); if ( !str.isEmpty() ) - text += "<b>" + QObject::tr("Spouse: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Spouse: ") + "</b>" + + Qtopia::escapeString(str); if ( birthday().isValid() ){ str = TimeString::numberDateString( birthday() ); - text += "<b>" + QObject::tr("Birthday: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Birthday: ") + "</b>" + + Qtopia::escapeString(str); } if ( anniversary().isValid() ){ str = TimeString::numberDateString( anniversary() ); - text += "<b>" + QObject::tr("Anniversary: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Anniversary: ") + "</b>" + + Qtopia::escapeString(str); } str = children(); if ( !str.isEmpty() ) - text += "<b>" + QObject::tr("Children: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Children: ") + "</b>" + + Qtopia::escapeString(str); str = nickname(); if ( !str.isEmpty() ) - text += "<b>" + QObject::tr("Nickname: ") + "</b>" - + Qtopia::escapeString(str) + "<br>"; + text += "<br><b>" + QObject::tr("Nickname: ") + "</b>" + + Qtopia::escapeString(str); // categories if ( categoryNames("Contacts").count() ){ - text += "<b>" + QObject::tr( "Category:") + "</b> "; + text += "<br><b>" + QObject::tr( "Category:") + "</b> "; text += categoryNames("Contacts").join(", "); - text += "<br>"; } // notes last if ( !(value = notes()).isEmpty() ) { text += "<br><hr><b>" + QObject::tr( "Notes:") + "</b> "; QRegExp reg("\n"); //QString tmp = Qtopia::escapeString(value); QString tmp = QStyleSheet::convertFromPlainText(value); //tmp.replace( reg, "<br>" ); text += "<br>" + tmp + "<br>"; } return text; } /*! \internal */ void OContact::insert( int key, const QString &v ) { QString value = v.stripWhiteSpace(); if ( value.isEmpty() ) mMap.remove( key ); else mMap.insert( key, value ); } /*! \internal */ void OContact::replace( int key, const QString & v ) { QString value = v.stripWhiteSpace(); if ( value.isEmpty() ) mMap.remove( key ); else mMap.replace( key, value ); } /*! \internal */ QString OContact::find( int key ) const { return mMap[key]; } /*! \internal */ QString OContact::displayAddress( const QString &street, const QString &city, const QString &state, const QString &zip, const QString &country ) const { QString s = street; if ( !street.isEmpty() ) s+= "\n"; s += city; if ( !city.isEmpty() && !state.isEmpty() ) s += ", "; s += state; if ( !state.isEmpty() && !zip.isEmpty() ) s += " "; s += zip; if ( !country.isEmpty() && !s.isEmpty() ) s += "\n"; s += country; return s; } /*! \internal */ QString OContact::displayBusinessAddress() const { return displayAddress( businessStreet(), businessCity(), businessState(), businessZip(), businessCountry() ); } /*! \internal */ QString OContact::displayHomeAddress() const { return displayAddress( homeStreet(), homeCity(), homeState(), homeZip(), homeCountry() ); } /*! Returns the full name of the contact */ QString OContact::fullName() const { QString title = find( Qtopia::Title ); QString firstName = find( Qtopia::FirstName ); QString middleName = find( Qtopia::MiddleName ); QString lastName = find( Qtopia::LastName ); QString suffix = find( Qtopia::Suffix ); QString name = title; if ( !firstName.isEmpty() ) { if ( !name.isEmpty() ) name += " "; name += firstName; } if ( !middleName.isEmpty() ) { if ( !name.isEmpty() ) name += " "; name += middleName; } if ( !lastName.isEmpty() ) { if ( !name.isEmpty() ) name += " "; name += lastName; } if ( !suffix.isEmpty() ) { if ( !name.isEmpty() ) name += " "; name += suffix; } return name.simplifyWhiteSpace(); } /*! Returns a list of the names of the children of the contact. */ QStringList OContact::childrenList() const { return QStringList::split( " ", find( Qtopia::Children ) ); } /*! \fn void OContact::insertEmail( const QString &email ) Insert \a email into the email list. Ensures \a email can only be added once. If there is no default email address set, it sets it to the \a email. */ /*! \fn void OContact::removeEmail( const QString &email ) Removes the \a email from the email list. If the default email was \a email, then the default email address is assigned to the first email in the email list */ /*! \fn void OContact::clearEmails() Clears the email list. */ /*! \fn void OContact::insertEmails( const QStringList &emailList ) Appends the \a emailList to the exiting email list */ /*! Returns a list of email addresses belonging to the contact, including the default email address. */ QStringList OContact::emailList() const { QString emailStr = emails(); QStringList r; if ( !emailStr.isEmpty() ) { qDebug(" emailstr "); QStringList l = QStringList::split( emailSeparator(), emailStr ); for ( QStringList::ConstIterator it = l.begin();it != l.end();++it ) r += (*it).simplifyWhiteSpace(); } return r; } /*! \overload Generates the string for the contact to be filed as from the first, middle and last name of the contact. */ void OContact::setFileAs() { QString lastName, firstName, middleName, fileas; lastName = find( Qtopia::LastName ); firstName = find( Qtopia::FirstName ); middleName = find( Qtopia::MiddleName ); if ( !lastName.isEmpty() && !firstName.isEmpty() && !middleName.isEmpty() ) fileas = lastName + ", " + firstName + " " + middleName; else if ( !lastName.isEmpty() && !firstName.isEmpty() ) fileas = lastName + ", " + firstName; else if ( !lastName.isEmpty() || !firstName.isEmpty() || !middleName.isEmpty() ) fileas = firstName + ( firstName.isEmpty() ? "" : " " ) + middleName + ( middleName.isEmpty() ? "" : " " ) + lastName; replace( Qtopia::FileAs, fileas ); } /*! \internal Appends the contact information to \a buf. */ void OContact::save( QString &buf ) const { static const QStringList SLFIELDS = fields(); // I'm expecting "<Contact " in front of this... for ( QMap<int, QString>::ConstIterator it = mMap.begin(); it != mMap.end(); ++it ) { const QString &value = it.data(); int key = it.key(); if ( !value.isEmpty() ) { if ( key == Qtopia::AddressCategory || key == Qtopia::AddressUid) continue; key -= Qtopia::AddressCategory+1; buf += SLFIELDS[key]; buf += "=\"" + Qtopia::escapeString(value) + "\" "; } } buf += customToXml(); if ( categories().count() > 0 ) buf += "Categories=\"" + idsToString( categories() ) + "\" "; buf += "Uid=\"" + QString::number( uid() ) + "\" "; // You need to close this yourself } /*! \internal Returns the list of fields belonging to a contact Never change order of this list ! It has to be regarding enum AddressBookFields !! */ QStringList OContact::fields() { QStringList list; list.append( "Title" ); // Not Used! list.append( "FirstName" ); list.append( "MiddleName" ); list.append( "LastName" ); list.append( "Suffix" ); list.append( "FileAs" ); list.append( "JobTitle" ); list.append( "Department" ); list.append( "Company" ); list.append( "BusinessPhone" ); list.append( "BusinessFax" ); list.append( "BusinessMobile" ); list.append( "DefaultEmail" ); list.append( "Emails" ); list.append( "HomePhone" ); list.append( "HomeFax" ); list.append( "HomeMobile" ); list.append( "BusinessStreet" ); list.append( "BusinessCity" ); list.append( "BusinessState" ); list.append( "BusinessZip" ); list.append( "BusinessCountry" ); list.append( "BusinessPager" ); list.append( "BusinessWebPage" ); list.append( "Office" ); list.append( "Profession" ); list.append( "Assistant" ); list.append( "Manager" ); list.append( "HomeStreet" ); list.append( "HomeCity" ); list.append( "HomeState" ); list.append( "HomeZip" ); list.append( "HomeCountry" ); list.append( "HomeWebPage" ); list.append( "Spouse" ); list.append( "Gender" ); list.append( "Birthday" ); list.append( "Anniversary" ); list.append( "Nickname" ); list.append( "Children" ); list.append( "Notes" ); list.append( "Groups" ); return list; } /*! Sets the list of email address for contact to those contained in \a str. Email address should be separated by ';'s. */ void OContact::setEmails( const QString &str ) { replace( Qtopia::Emails, str ); if ( str.isEmpty() ) setDefaultEmail( QString::null ); } /*! Sets the list of children for the contact to those contained in \a str. */ void OContact::setChildren( const QString &str ) { replace( Qtopia::Children, str ); } /*! \overload Returns TRUE if the contact matches the regular expression \a regexp. Otherwise returns FALSE. */ bool OContact::match( const QRegExp &r ) const { setLastHitField( -1 ); bool match; match = false; QMap<int, QString>::ConstIterator it; for ( it = mMap.begin(); it != mMap.end(); ++it ) { if ( (*it).find( r ) > -1 ) { setLastHitField( it.key() ); match = true; break; } } return match; } QString OContact::toShortText() const { return ( fullName() ); } QString OContact::type() const { return QString::fromLatin1( "OContact" ); } class QString OContact::recordField( int pos ) const { QStringList SLFIELDS = fields(); // ?? why this ? (se) return SLFIELDS[pos]; } // In future releases, we should store birthday and anniversary // internally as QDate instead of QString ! // QString is always too complicate to interprete (DD.MM.YY, DD/MM/YY, MM/DD/YY, etc..)(se) /*! \fn void OContact::setBirthday( const QDate& date ) Sets the birthday for the contact to \a date. If date is null the current stored date will be removed. */ void OContact::setBirthday( const QDate &v ) { if ( v.isNull() ){ qWarning( "Remove Birthday"); replace( Qtopia::Birthday, QString::null ); return; } if ( v.isValid() ) replace( Qtopia::Birthday, OConversion::dateToString( v ) ); } /*! \fn void OContact::setAnniversary( const QDate &date ) Sets the anniversary of the contact to \a date. If date is null, the current stored date will be removed. */ void OContact::setAnniversary( const QDate &v ) { diff --git a/libopie/pim/ocontact.h b/libopie/pim/ocontact.h index dd2de17..9a1a8dc 100644 --- a/libopie/pim/ocontact.h +++ b/libopie/pim/ocontact.h @@ -1,240 +1,245 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** Copyright (C) 2002-2003 by Stefan Eilers (eilers.stefan@epost.de) ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef __OCONTACT_H__ #define __OCONTACT_H__ #include <opie/opimrecord.h> #include <qpe/recordfields.h> #include <qdatetime.h> #include <qstringlist.h> #if defined(QPC_TEMPLATEDLL) // MOC_SKIP_BEGIN QPC_TEMPLATEEXTERN template class QPC_EXPORT QMap<int, QString>; // MOC_SKIP_END #endif -class ContactPrivate; +class OContactPrivate; /** * OContact class represents a specialised PIM Record for contacts. * It does store all kind of persopn related information. * * @short Contact Container * @author TT, Stefan Eiler, Holger Freyther */ class QPC_EXPORT OContact : public OPimRecord { friend class DataSet; public: OContact(); OContact( const QMap<int, QString> &fromMap ); virtual ~OContact(); + enum DateFormat{ + Zip_City_State = 0, + City_State_Zip + }; + /* * do we need to inline them * if yes do we need to inline them this way? * -zecke */ void setTitle( const QString &v ) { replace( Qtopia::Title, v ); } void setFirstName( const QString &v ) { replace( Qtopia::FirstName, v ); } void setMiddleName( const QString &v ) { replace( Qtopia::MiddleName, v ); } void setLastName( const QString &v ) { replace( Qtopia::LastName, v ); } void setSuffix( const QString &v ) { replace( Qtopia::Suffix, v ); } void setFileAs( const QString &v ) { replace( Qtopia::FileAs, v ); } void setFileAs(); // default email address void setDefaultEmail( const QString &v ); // inserts email to list and ensure's doesn't already exist void insertEmail( const QString &v ); void removeEmail( const QString &v ); void clearEmails(); void insertEmails( const QStringList &v ); // home void setHomeStreet( const QString &v ) { replace( Qtopia::HomeStreet, v ); } void setHomeCity( const QString &v ) { replace( Qtopia::HomeCity, v ); } void setHomeState( const QString &v ) { replace( Qtopia::HomeState, v ); } void setHomeZip( const QString &v ) { replace( Qtopia::HomeZip, v ); } void setHomeCountry( const QString &v ) { replace( Qtopia::HomeCountry, v ); } void setHomePhone( const QString &v ) { replace( Qtopia::HomePhone, v ); } void setHomeFax( const QString &v ) { replace( Qtopia::HomeFax, v ); } void setHomeMobile( const QString &v ) { replace( Qtopia::HomeMobile, v ); } void setHomeWebpage( const QString &v ) { replace( Qtopia::HomeWebPage, v ); } // business void setCompany( const QString &v ) { replace( Qtopia::Company, v ); } void setBusinessStreet( const QString &v ) { replace( Qtopia::BusinessStreet, v ); } void setBusinessCity( const QString &v ) { replace( Qtopia::BusinessCity, v ); } void setBusinessState( const QString &v ) { replace( Qtopia::BusinessState, v ); } void setBusinessZip( const QString &v ) { replace( Qtopia::BusinessZip, v ); } void setBusinessCountry( const QString &v ) { replace( Qtopia::BusinessCountry, v ); } void setBusinessWebpage( const QString &v ) { replace( Qtopia::BusinessWebPage, v ); } void setJobTitle( const QString &v ) { replace( Qtopia::JobTitle, v ); } void setDepartment( const QString &v ) { replace( Qtopia::Department, v ); } void setOffice( const QString &v ) { replace( Qtopia::Office, v ); } void setBusinessPhone( const QString &v ) { replace( Qtopia::BusinessPhone, v ); } void setBusinessFax( const QString &v ) { replace( Qtopia::BusinessFax, v ); } void setBusinessMobile( const QString &v ) { replace( Qtopia::BusinessMobile, v ); } void setBusinessPager( const QString &v ) { replace( Qtopia::BusinessPager, v ); } void setProfession( const QString &v ) { replace( Qtopia::Profession, v ); } void setAssistant( const QString &v ) { replace( Qtopia::Assistant, v ); } void setManager( const QString &v ) { replace( Qtopia::Manager, v ); } // personal void setSpouse( const QString &v ) { replace( Qtopia::Spouse, v ); } void setGender( const QString &v ) { replace( Qtopia::Gender, v ); } void setBirthday( const QDate &v ); void setAnniversary( const QDate &v ); void setNickname( const QString &v ) { replace( Qtopia::Nickname, v ); } void setChildren( const QString &v ); // other void setNotes( const QString &v ) { replace( Qtopia::Notes, v); } virtual bool match( const QRegExp ®exp ) const; // // custom // void setCustomField( const QString &key, const QString &v ) // { replace(Custom- + key, v ); } // name QString fullName() const; QString title() const { return find( Qtopia::Title ); } QString firstName() const { return find( Qtopia::FirstName ); } QString middleName() const { return find( Qtopia::MiddleName ); } QString lastName() const { return find( Qtopia::LastName ); } QString suffix() const { return find( Qtopia::Suffix ); } QString fileAs() const { return find( Qtopia::FileAs ); } // email QString defaultEmail() const { return find( Qtopia::DefaultEmail ); } QStringList emailList() const; // home /* * OPimAddress address(enum Location)const; * would be some how nicer... * -zecke */ QString homeStreet() const { return find( Qtopia::HomeStreet ); } QString homeCity() const { return find( Qtopia::HomeCity ); } QString homeState() const { return find( Qtopia::HomeState ); } QString homeZip() const { return find( Qtopia::HomeZip ); } QString homeCountry() const { return find( Qtopia::HomeCountry ); } QString homePhone() const { return find( Qtopia::HomePhone ); } QString homeFax() const { return find( Qtopia::HomeFax ); } QString homeMobile() const { return find( Qtopia::HomeMobile ); } QString homeWebpage() const { return find( Qtopia::HomeWebPage ); } /** Multi line string containing all non-empty address info in the form * Street * City, State Zip * Country */ QString displayHomeAddress() const; // business QString company() const { return find( Qtopia::Company ); } QString businessStreet() const { return find( Qtopia::BusinessStreet ); } QString businessCity() const { return find( Qtopia::BusinessCity ); } QString businessState() const { return find( Qtopia::BusinessState ); } QString businessZip() const { return find( Qtopia::BusinessZip ); } QString businessCountry() const { return find( Qtopia::BusinessCountry ); } QString businessWebpage() const { return find( Qtopia::BusinessWebPage ); } QString jobTitle() const { return find( Qtopia::JobTitle ); } QString department() const { return find( Qtopia::Department ); } QString office() const { return find( Qtopia::Office ); } QString businessPhone() const { return find( Qtopia::BusinessPhone ); } QString businessFax() const { return find( Qtopia::BusinessFax ); } QString businessMobile() const { return find( Qtopia::BusinessMobile ); } QString businessPager() const { return find( Qtopia::BusinessPager ); } QString profession() const { return find( Qtopia::Profession ); } QString assistant() const { return find( Qtopia::Assistant ); } QString manager() const { return find( Qtopia::Manager ); } /** Multi line string containing all non-empty address info in the form * Street * City, State Zip * Country */ QString displayBusinessAddress() const; //personal QString spouse() const { return find( Qtopia::Spouse ); } QString gender() const { return find( Qtopia::Gender ); } QDate birthday() const; QDate anniversary() const; QString nickname() const { return find( Qtopia::Nickname ); } QString children() const { return find( Qtopia::Children ); } QStringList childrenList() const; // other QString notes() const { return find( Qtopia::Notes ); } QString groups() const { return find( Qtopia::Groups ); } QStringList groupList() const; // // custom // const QString &customField( const QString &key ) // { return find( Custom- + key ); } QString toRichText() const; QMap<int, QString> toMap() const; QString field( int key ) const { return find( key ); } void setUid( int i ); QString toShortText()const; QString OContact::type()const; QMap<QString,QString> OContact::toExtraMap() const; class QString OContact::recordField(int) const; // Why private ? (eilers,se) QString emailSeparator() const { return " "; } // the emails should be seperated by a comma void setEmails( const QString &v ); QString emails() const { return find( Qtopia::Emails ); } static int rtti(); private: // The XML-Backend needs some access to the private functions friend class OContactAccessBackend_XML; void insert( int key, const QString &value ); void replace( int key, const QString &value ); QString find( int key ) const; static QStringList fields(); void save( QString &buf ) const; QString displayAddress( const QString &street, const QString &city, const QString &state, const QString &zip, const QString &country ) const; QMap<int, QString> mMap; - ContactPrivate *d; + OContactPrivate *d; }; #endif diff --git a/libopie/pim/ocontactaccess.h b/libopie/pim/ocontactaccess.h index e90db32..9b0a719 100644 --- a/libopie/pim/ocontactaccess.h +++ b/libopie/pim/ocontactaccess.h @@ -1,170 +1,181 @@ /* * Class to manage the Contacts. * * Copyright (c) 2002 by Stefan Eilers (Eilers.Stefan@epost.de) * Copyright (c) 2002 by Holger Freyther (zecke@handhelds.org) * * ===================================================================== * This program 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. * ===================================================================== * ToDo: Define enum for query settings * ===================================================================== * Version: $Id$ * ===================================================================== * History: * $Log$ + * Revision 1.9 2003/08/01 12:30:16 eilers + * Merging changes from BRANCH_1_0 to HEAD + * + * Revision 1.8.2.1 2003/06/30 14:34:19 eilers + * Patches from Zecke: + * Fixing and cleaning up extraMap handling + * Adding d_ptr for binary compatibility in the future + * * Revision 1.8 2003/05/08 13:55:09 tille * search stuff * and match, toRichText & toShortText in oevent * * Revision 1.7 2003/04/13 18:07:10 zecke * More API doc * QString -> const QString& * QString = 0l -> QString::null * * Revision 1.6 2003/01/02 14:27:12 eilers * Improved query by example: Search by date is possible.. First step * for a today plugin for birthdays.. * * Revision 1.5 2002/11/13 14:14:51 eilers * Added sorted for Contacts.. * * Revision 1.4 2002/11/01 15:10:42 eilers * Added regExp-search in database for all fields in a contact. * * Revision 1.3 2002/10/16 10:52:40 eilers * Added some docu to the interface and now using the cache infrastucture by zecke.. :) * * Revision 1.2 2002/10/14 16:21:54 eilers * Some minor interface updates * * Revision 1.1 2002/09/27 17:11:44 eilers * Added API for accessing the Contact-Database ! It is compiling, but * please do not expect that anything is working ! * I will debug that stuff in the next time .. * Please read README_COMPILE for compiling ! * * ===================================================================== */ #ifndef _OCONTACTACCESS_H #define _OCONTACTACCESS_H #include <qobject.h> #include <qpe/qcopenvelope_qws.h> #include <qvaluelist.h> #include <qfileinfo.h> #include "ocontact.h" #include "ocontactaccessbackend.h" #include "opimaccesstemplate.h" /** * Class to access the contacts database. * This is just a frontend for the real database handling which is * done by the backend. * This class is used to access the Contacts on a system. This class as any OPIE PIM * class is backend independent. * @see OPimAccessTemplate */ class OContactAccess: public QObject, public OPimAccessTemplate<OContact> { Q_OBJECT public: /** * Create Database with contacts (addressbook). * @param appname Name of application which wants access to the database * (i.e. "todolist") * @param filename The name of the database file. If not set, the default one * is used. * @param backend Pointer to an alternative Backend. If not set, we will use * the default backend. * @param handlesync If <b>true</b> the database stores the current state * automatically if it receives the signals <i>flush()</i> and <i>reload()</i> * which are used before and after synchronisation. If the application wants * to react itself, it should be disabled by setting it to <b>false</b> * @see OContactAccessBackend */ OContactAccess (const QString appname, const QString filename = 0l, OContactAccessBackend* backend = 0l, bool handlesync = true); ~OContactAccess (); /** Constants for query. * Use this constants to set the query parameters. * Note: <i>query_IgnoreCase</i> just make sense with one of the other attributes ! * @see queryByExample() */ enum QuerySettings { WildCards = 0x0001, IgnoreCase = 0x0002, RegExp = 0x0004, ExactMatch = 0x0008, MatchOne = 0x0010, // Only one Entry must match DateDiff = 0x0020, // Find all entries from today until given date DateYear = 0x0040, // The year matches DateMonth = 0x0080, // The month matches DateDay = 0x0100, // The day matches }; /** Return all Contacts in a sorted manner. * @param ascending true: Sorted in acending order. * @param sortOrder Currently not implemented. Just defined to stay compatible to otodoaccess * @param sortFilter Currently not implemented. Just defined to stay compatible to otodoaccess * @param cat Currently not implemented. Just defined to stay compatible to otodoaccess */ List sorted( bool ascending, int sortOrder, int sortFilter, int cat ) const; /** Return all possible settings. * @return All settings provided by the current backend * (i.e.: query_WildCards & query_IgnoreCase) */ const uint querySettings(); /** Check whether settings are correct. * @return <i>true</i> if the given settings are correct and possible. */ bool hasQuerySettings ( int querySettings ) const; /** * if the resource was changed externally. * You should use the signal instead of polling possible changes ! */ bool wasChangedExternally()const; /** Save contacts database. * Save is more a "commit". After calling this function, all changes are public available. * @return true if successful */ bool save(); signals: /* Signal is emitted if the database was changed. Therefore * we may need to reload to stay consistent. * @param which Pointer to the database who created this event. This pointer * is useful if an application has to handle multiple databases at the same time. * @see reload() */ void signalChanged ( const OContactAccess *which ); private: // class OContactAccessPrivate; // OContactAccessPrivate* d; OContactAccessBackend *m_backEnd; bool m_loading:1; private slots: void copMessage( const QCString &msg, const QByteArray &data ); + private: + class Private; + Private *d; }; #endif diff --git a/libopie/pim/ocontactaccessbackend.h b/libopie/pim/ocontactaccessbackend.h index ebeb42d..280e05c 100644 --- a/libopie/pim/ocontactaccessbackend.h +++ b/libopie/pim/ocontactaccessbackend.h @@ -1,107 +1,119 @@ /** * The class responsible for managing a backend. * The implementation of this abstract class contains * the complete database handling. * * Copyright (c) 2002 by Stefan Eilers (Eilers.Stefan@epost.de) * Copyright (c) 2002 by Holger Freyther (zecke@handhelds.org) * * ===================================================================== * This program 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. * ===================================================================== * ToDo: Define enum for query settings * ===================================================================== * Version: $Id$ * ===================================================================== * History: * $Log$ + * Revision 1.6 2003/08/01 12:30:16 eilers + * Merging changes from BRANCH_1_0 to HEAD + * + * Revision 1.5.4.1 2003/06/30 14:34:19 eilers + * Patches from Zecke: + * Fixing and cleaning up extraMap handling + * Adding d_ptr for binary compatibility in the future + * * Revision 1.5 2003/04/13 18:07:10 zecke * More API doc * QString -> const QString& * QString = 0l -> QString::null * * Revision 1.4 2002/11/13 14:14:51 eilers * Added sorted for Contacts.. * * Revision 1.3 2002/11/01 15:10:42 eilers * Added regExp-search in database for all fields in a contact. * * Revision 1.2 2002/10/07 17:34:24 eilers * added OBackendFactory for advanced backend access * * Revision 1.1 2002/09/27 17:11:44 eilers * Added API for accessing the Contact-Database ! It is compiling, but * please do not expect that anything is working ! * I will debug that stuff in the next time .. * Please read README_COMPILE for compiling ! * * ===================================================================== * */ #ifndef _OCONTACTACCESSBACKEND_H_ #define _OCONTACTACCESSBACKEND_H_ #include "ocontact.h" #include "opimaccessbackend.h" #include <qregexp.h> /** * This class represents the interface of all Contact Backends. * Derivates of this class will be used to access the contacts. * As implementation currently XML and vCard exist. This class needs to be implemented * if you want to provide your own storage. * In all queries a list of uids is passed on instead of loading the actual record! * * @see OContactAccessBackend_VCard * @see OContactAccessBackend_XML */ class OContactAccessBackend: public OPimAccessBackend<OContact> { public: OContactAccessBackend() {} virtual ~OContactAccessBackend() {} /** * Return if database was changed externally. * This may just make sense on file based databases like a XML-File. * It is used to prevent to overwrite the current database content * if the file was already changed by something else ! * If this happens, we have to reload before save our data. * If we use real databases, this should be handled by the database * management system themselve, therefore this function should always return false in * this case. It is not our problem to handle this conflict ... * @return <i>true</i> if the database was changed and if save without reload will * be dangerous. <i>false</i> if the database was not changed or it is save to write * in this situation. */ virtual bool wasChangedExternally() = 0; virtual QArray<int> matchRegexp( const QRegExp &r ) const = 0; /** * Return all possible settings. * @return All settings provided by the current backend * (i.e.: query_WildCards & query_IgnoreCase) */ virtual const uint querySettings() = 0; /** * Check whether settings are correct. * @return <i>true</i> if the given settings are correct and possible. */ virtual bool hasQuerySettings (uint querySettings) const = 0; /** * FIXME!!! * Returns a sorted list of records either ascendinf or descending for a giving criteria and category */ virtual QArray<int> sorted( bool ascending, int sortOrder, int sortFilter, int cat ) = 0; - + + +private: + class Private; + Private *d; }; #endif diff --git a/libopie/pim/ocontactaccessbackend_vcard.cpp b/libopie/pim/ocontactaccessbackend_vcard.cpp index 270bef3..b60c5be 100644 --- a/libopie/pim/ocontactaccessbackend_vcard.cpp +++ b/libopie/pim/ocontactaccessbackend_vcard.cpp @@ -1,628 +1,646 @@ /* * VCard Backend for the OPIE-Contact Database. * * Copyright (C) 2000 Trolltech AS. All rights reserved. * Copyright (c) 2002 by Stefan Eilers (Eilers.Stefan@epost.de) * * ===================================================================== * This program 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. * ===================================================================== * ToDo: * * ===================================================================== * Version: $Id$ * ===================================================================== * History: * $Log$ + * Revision 1.11 2003/08/01 12:30:16 eilers + * Merging changes from BRANCH_1_0 to HEAD + * + * Revision 1.10.4.3 2003/07/23 08:54:37 eilers + * Default email was added to the list of all emails, which already contains + * the default email.. + * This closes bug #1045 + * + * Revision 1.10.4.2 2003/07/23 08:44:45 eilers + * Importing of Notes in vcard files wasn't implemented. + * Closes bug #1044 + * + * Revision 1.10.4.1 2003/06/02 13:37:49 eilers + * Fixing memory leak + * * Revision 1.10 2003/04/13 18:07:10 zecke * More API doc * QString -> const QString& * QString = 0l -> QString::null * * Revision 1.9 2003/03/21 10:33:09 eilers * Merged speed optimized xml backend for contacts to main. * Added QDateTime to querybyexample. For instance, it is now possible to get * all Birthdays/Anniversaries between two dates. This should be used * to show all birthdays in the datebook.. * This change is sourcecode backward compatible but you have to upgrade * the binaries for today-addressbook. * * Revision 1.8 2003/02/21 16:52:49 zecke * -Remove old Todo classes they're deprecated and today I already using the * new API * -Guard against self assignment in OTodo * -Add test apps for OPIM * -Opiefied Event classes * -Added TimeZone handling and pinning of TimeZones to OEvent * -Adjust ORecur and the widget to better timezone behaviour * * Revision 1.7 2003/02/16 22:25:46 zecke * 0000276 Fix for that bug.. or better temp workaround * A Preferred Number is HOME|VOICE * A CellPhone is HOME|VOICE|CELL the type & HOME|VOICE test * triggers both * and the cell phone number overrides the other entries.. * * as a temp I check that it's not equal to HOME|VOICE|CELL before setting the * number * * The right and final fix would be to reorder the if statement to make it * if else based and the less common thing put to the bottom * * OTodoAccessVcal fix the date for beaming * * Revision 1.6 2003/01/13 15:49:31 eilers * Fixing crash when businesscard.vcf is missing.. * * Revision 1.5 2002/12/07 13:26:22 eilers * Fixing bug in storing anniversary.. * * Revision 1.4 2002/11/13 14:14:51 eilers * Added sorted for Contacts.. * * Revision 1.3 2002/11/11 16:41:09 kergoth * no default arguments in implementation * * Revision 1.2 2002/11/10 15:41:53 eilers * Bugfixes.. * * Revision 1.1 2002/11/09 14:34:52 eilers * Added VCard Backend. * */ #include "ocontactaccessbackend_vcard.h" #include "../../library/backend/vobject_p.h" #include "../../library/backend/qfiledirect_p.h" #include <qpe/timeconversion.h> #include <qfile.h> OContactAccessBackend_VCard::OContactAccessBackend_VCard ( const QString& , const QString& filename ): m_dirty( false ), m_file( filename ) { load(); } bool OContactAccessBackend_VCard::load () { m_map.clear(); m_dirty = false; VObject* obj = 0l; if ( QFile::exists(m_file) ){ obj = Parse_MIME_FromFileName( QFile::encodeName(m_file).data() ); if ( !obj ) return false; }else{ qWarning("File \"%s\" not found !", m_file.latin1() ); return false; } while ( obj ) { OContact con = parseVObject( obj ); /* * if uid is 0 assign a new one * this at least happens on * Nokia6210 */ if ( con.uid() == 0 ){ con.setUid( 1 ); qWarning("assigned new uid %d",con.uid() ); } m_map.insert( con.uid(), con ); VObject *t = obj; obj = nextVObjectInList(obj); cleanVObject( t ); } return true; } bool OContactAccessBackend_VCard::reload() { return load(); } bool OContactAccessBackend_VCard::save() { if (!m_dirty ) return true; QFileDirect file( m_file ); if (!file.open(IO_WriteOnly ) ) return false; VObject *obj; obj = newVObject( VCCalProp ); addPropValue( obj, VCVersionProp, "1.0" ); VObject *vo; for(QMap<int, OContact>::ConstIterator it=m_map.begin(); it !=m_map.end(); ++it ){ vo = createVObject( *it ); writeVObject( file.directHandle() , vo ); cleanVObject( vo ); } cleanStrTbl(); + deleteVObject( obj ); m_dirty = false; return true; } void OContactAccessBackend_VCard::clear () { m_map.clear(); m_dirty = true; // ??? sure ? (se) } bool OContactAccessBackend_VCard::add ( const OContact& newcontact ) { m_map.insert( newcontact.uid(), newcontact ); m_dirty = true; return true; } bool OContactAccessBackend_VCard::remove ( int uid ) { m_map.remove( uid ); m_dirty = true; return true; } bool OContactAccessBackend_VCard::replace ( const OContact &contact ) { m_map.replace( contact.uid(), contact ); m_dirty = true; return true; } OContact OContactAccessBackend_VCard::find ( int uid ) const { return m_map[uid]; } QArray<int> OContactAccessBackend_VCard::allRecords() const { QArray<int> ar( m_map.count() ); QMap<int, OContact>::ConstIterator it; int i = 0; for ( it = m_map.begin(); it != m_map.end(); ++it ) { ar[i] = it.key(); i++; } return ar; } // Not implemented QArray<int> OContactAccessBackend_VCard::queryByExample ( const OContact&, int, const QDateTime& ) { QArray<int> ar(0); return ar; } // Not implemented QArray<int> OContactAccessBackend_VCard::matchRegexp( const QRegExp& ) const { QArray<int> ar(0); return ar; } const uint OContactAccessBackend_VCard::querySettings() { return 0; // No search possible } bool OContactAccessBackend_VCard::hasQuerySettings (uint ) const { return false; // No search possible, therefore all settings invalid ;) } bool OContactAccessBackend_VCard::wasChangedExternally() { return false; // Don't expect concurrent access } // Not implemented QArray<int> OContactAccessBackend_VCard::sorted( bool , int, int, int ) { QArray<int> ar(0); return ar; } // *** Private stuff *** OContact OContactAccessBackend_VCard::parseVObject( VObject *obj ) { OContact c; VObjectIterator it; initPropIterator( &it, obj ); while( moreIteration( &it ) ) { VObject *o = nextVObject( &it ); QCString name = vObjectName( o ); QCString value = vObjectStringZValue( o ); if ( name == VCNameProp ) { VObjectIterator nit; initPropIterator( &nit, o ); while( moreIteration( &nit ) ) { VObject *o = nextVObject( &nit ); QCString name = vObjectTypeInfo( o ); QString value = vObjectStringZValue( o ); if ( name == VCNamePrefixesProp ) c.setTitle( value ); else if ( name == VCNameSuffixesProp ) c.setSuffix( value ); else if ( name == VCFamilyNameProp ) c.setLastName( value ); else if ( name == VCGivenNameProp ) c.setFirstName( value ); else if ( name == VCAdditionalNamesProp ) c.setMiddleName( value ); } } else if ( name == VCAdrProp ) { bool work = TRUE; // default address is work address QString street; QString city; QString region; QString postal; QString country; VObjectIterator nit; initPropIterator( &nit, o ); while( moreIteration( &nit ) ) { VObject *o = nextVObject( &nit ); QCString name = vObjectName( o ); QString value = vObjectStringZValue( o ); if ( name == VCHomeProp ) work = FALSE; else if ( name == VCWorkProp ) work = TRUE; else if ( name == VCStreetAddressProp ) street = value; else if ( name == VCCityProp ) city = value; else if ( name == VCRegionProp ) region = value; else if ( name == VCPostalCodeProp ) postal = value; else if ( name == VCCountryNameProp ) country = value; } if ( work ) { c.setBusinessStreet( street ); c.setBusinessCity( city ); c.setBusinessCountry( country ); c.setBusinessZip( postal ); c.setBusinessState( region ); } else { c.setHomeStreet( street ); c.setHomeCity( city ); c.setHomeCountry( country ); c.setHomeZip( postal ); c.setHomeState( region ); } } else if ( name == VCTelephoneProp ) { enum { HOME = 0x01, WORK = 0x02, VOICE = 0x04, CELL = 0x08, FAX = 0x10, PAGER = 0x20, UNKNOWN = 0x80 }; int type = 0; VObjectIterator nit; initPropIterator( &nit, o ); while( moreIteration( &nit ) ) { VObject *o = nextVObject( &nit ); QCString name = vObjectTypeInfo( o ); if ( name == VCHomeProp ) type |= HOME; else if ( name == VCWorkProp ) type |= WORK; else if ( name == VCVoiceProp ) type |= VOICE; else if ( name == VCCellularProp ) type |= CELL; else if ( name == VCFaxProp ) type |= FAX; else if ( name == VCPagerProp ) type |= PAGER; else if ( name == VCPreferredProp ) ; else type |= UNKNOWN; } if ( (type & UNKNOWN) != UNKNOWN ) { if ( ( type & (HOME|WORK) ) == 0 ) // default type |= HOME; if ( ( type & (VOICE|CELL|FAX|PAGER) ) == 0 ) // default type |= VOICE; qWarning("value %s %d", value.data(), type ); if ( (type & (VOICE|HOME) ) == (VOICE|HOME) && (type & (CELL|HOME) ) != (CELL|HOME) ) c.setHomePhone( value ); if ( ( type & (FAX|HOME) ) == (FAX|HOME) ) c.setHomeFax( value ); if ( ( type & (CELL|HOME) ) == (CELL|HOME) ) c.setHomeMobile( value ); if ( ( type & (VOICE|WORK) ) == (VOICE|WORK) && (type & (CELL|WORK) ) != (CELL|WORK) ) c.setBusinessPhone( value ); if ( ( type & (FAX|WORK) ) == (FAX|WORK) ) c.setBusinessFax( value ); if ( ( type & (CELL|WORK) ) == (CELL|WORK) ) c.setBusinessMobile( value ); if ( ( type & (PAGER|WORK) ) == (PAGER|WORK) ) c.setBusinessPager( value ); } } else if ( name == VCEmailAddressProp ) { QString email = vObjectStringZValue( o ); bool valid = TRUE; VObjectIterator nit; initPropIterator( &nit, o ); while( moreIteration( &nit ) ) { VObject *o = nextVObject( &nit ); QCString name = vObjectTypeInfo( o ); if ( name != VCInternetProp && name != VCHomeProp && name != VCWorkProp && name != VCPreferredProp ) // ### preffered should map to default email valid = FALSE; } if ( valid ) { c.insertEmail( email ); } } else if ( name == VCURLProp ) { VObjectIterator nit; initPropIterator( &nit, o ); while( moreIteration( &nit ) ) { VObject *o = nextVObject( &nit ); QCString name = vObjectTypeInfo( o ); if ( name == VCHomeProp ) c.setHomeWebpage( value ); else if ( name == VCWorkProp ) c.setBusinessWebpage( value ); } } else if ( name == VCOrgProp ) { VObjectIterator nit; initPropIterator( &nit, o ); while( moreIteration( &nit ) ) { VObject *o = nextVObject( &nit ); QCString name = vObjectName( o ); QString value = vObjectStringZValue( o ); if ( name == VCOrgNameProp ) c.setCompany( value ); else if ( name == VCOrgUnitProp ) c.setDepartment( value ); else if ( name == VCOrgUnit2Prop ) c.setOffice( value ); } } else if ( name == VCTitleProp ) { c.setJobTitle( value ); } else if ( name == "X-Qtopia-Profession" ) { c.setProfession( value ); } else if ( name == "X-Qtopia-Manager" ) { c.setManager( value ); } else if ( name == "X-Qtopia-Assistant" ) { c.setAssistant( value ); } else if ( name == "X-Qtopia-Spouse" ) { c.setSpouse( value ); } else if ( name == "X-Qtopia-Gender" ) { c.setGender( value ); } else if ( name == "X-Qtopia-Anniversary" ) { c.setAnniversary( convVCardDateToDate( value ) ); } else if ( name == "X-Qtopia-Nickname" ) { c.setNickname( value ); } else if ( name == "X-Qtopia-Children" ) { c.setChildren( value ); } else if ( name == VCBirthDateProp ) { // Reading Birthdate regarding RFC 2425 (5.8.4) c.setBirthday( convVCardDateToDate( value ) ); } - + else if ( name == VCCommentProp ) { + c.setNotes( value ); + } #if 0 else { printf("Name: %s, value=%s\n", name.data(), vObjectStringZValue( o ) ); VObjectIterator nit; initPropIterator( &nit, o ); while( moreIteration( &nit ) ) { VObject *o = nextVObject( &nit ); QCString name = vObjectName( o ); QString value = vObjectStringZValue( o ); printf(" subprop: %s = %s\n", name.data(), value.latin1() ); } } #endif } c.setFileAs(); return c; } VObject* OContactAccessBackend_VCard::createVObject( const OContact &c ) { VObject *vcard = newVObject( VCCardProp ); safeAddPropValue( vcard, VCVersionProp, "2.1" ); safeAddPropValue( vcard, VCLastRevisedProp, TimeConversion::toISO8601( QDateTime::currentDateTime() ) ); safeAddPropValue( vcard, VCUniqueStringProp, QString::number(c.uid()) ); // full name safeAddPropValue( vcard, VCFullNameProp, c.fullName() ); // name properties VObject *name = safeAddProp( vcard, VCNameProp ); safeAddPropValue( name, VCFamilyNameProp, c.lastName() ); safeAddPropValue( name, VCGivenNameProp, c.firstName() ); safeAddPropValue( name, VCAdditionalNamesProp, c.middleName() ); safeAddPropValue( name, VCNamePrefixesProp, c.title() ); safeAddPropValue( name, VCNameSuffixesProp, c.suffix() ); // home properties VObject *home_adr= safeAddProp( vcard, VCAdrProp ); safeAddProp( home_adr, VCHomeProp ); safeAddPropValue( home_adr, VCStreetAddressProp, c.homeStreet() ); safeAddPropValue( home_adr, VCCityProp, c.homeCity() ); safeAddPropValue( home_adr, VCRegionProp, c.homeState() ); safeAddPropValue( home_adr, VCPostalCodeProp, c.homeZip() ); safeAddPropValue( home_adr, VCCountryNameProp, c.homeCountry() ); VObject *home_phone = safeAddPropValue( vcard, VCTelephoneProp, c.homePhone() ); safeAddProp( home_phone, VCHomeProp ); home_phone = safeAddPropValue( vcard, VCTelephoneProp, c.homeMobile() ); safeAddProp( home_phone, VCHomeProp ); safeAddProp( home_phone, VCCellularProp ); home_phone = safeAddPropValue( vcard, VCTelephoneProp, c.homeFax() ); safeAddProp( home_phone, VCHomeProp ); safeAddProp( home_phone, VCFaxProp ); VObject *url = safeAddPropValue( vcard, VCURLProp, c.homeWebpage() ); safeAddProp( url, VCHomeProp ); // work properties VObject *work_adr= safeAddProp( vcard, VCAdrProp ); safeAddProp( work_adr, VCWorkProp ); safeAddPropValue( work_adr, VCStreetAddressProp, c.businessStreet() ); safeAddPropValue( work_adr, VCCityProp, c.businessCity() ); safeAddPropValue( work_adr, VCRegionProp, c.businessState() ); safeAddPropValue( work_adr, VCPostalCodeProp, c.businessZip() ); safeAddPropValue( work_adr, VCCountryNameProp, c.businessCountry() ); VObject *work_phone = safeAddPropValue( vcard, VCTelephoneProp, c.businessPhone() ); safeAddProp( work_phone, VCWorkProp ); work_phone = safeAddPropValue( vcard, VCTelephoneProp, c.businessMobile() ); safeAddProp( work_phone, VCWorkProp ); safeAddProp( work_phone, VCCellularProp ); work_phone = safeAddPropValue( vcard, VCTelephoneProp, c.businessFax() ); safeAddProp( work_phone, VCWorkProp ); safeAddProp( work_phone, VCFaxProp ); work_phone = safeAddPropValue( vcard, VCTelephoneProp, c.businessPager() ); safeAddProp( work_phone, VCWorkProp ); safeAddProp( work_phone, VCPagerProp ); url = safeAddPropValue( vcard, VCURLProp, c.businessWebpage() ); safeAddProp( url, VCWorkProp ); VObject *title = safeAddPropValue( vcard, VCTitleProp, c.jobTitle() ); safeAddProp( title, VCWorkProp ); QStringList emails = c.emailList(); - emails.prepend( c.defaultEmail() ); + // emails.prepend( c.defaultEmail() ); Fix for bugreport #1045 for( QStringList::Iterator it = emails.begin(); it != emails.end(); ++it ) { VObject *email = safeAddPropValue( vcard, VCEmailAddressProp, *it ); safeAddProp( email, VCInternetProp ); } safeAddPropValue( vcard, VCNoteProp, c.notes() ); // Exporting Birthday regarding RFC 2425 (5.8.4) if ( c.birthday().isValid() ){ qWarning("Exporting birthday as: %s", convDateToVCardDate( c.birthday() ).latin1() ); safeAddPropValue( vcard, VCBirthDateProp, convDateToVCardDate( c.birthday() ) ); } if ( !c.company().isEmpty() || !c.department().isEmpty() || !c.office().isEmpty() ) { VObject *org = safeAddProp( vcard, VCOrgProp ); safeAddPropValue( org, VCOrgNameProp, c.company() ); safeAddPropValue( org, VCOrgUnitProp, c.department() ); safeAddPropValue( org, VCOrgUnit2Prop, c.office() ); } // some values we have to export as custom fields safeAddPropValue( vcard, "X-Qtopia-Profession", c.profession() ); safeAddPropValue( vcard, "X-Qtopia-Manager", c.manager() ); safeAddPropValue( vcard, "X-Qtopia-Assistant", c.assistant() ); safeAddPropValue( vcard, "X-Qtopia-Spouse", c.spouse() ); safeAddPropValue( vcard, "X-Qtopia-Gender", c.gender() ); if ( c.anniversary().isValid() ){ qWarning("Exporting anniversary as: %s", convDateToVCardDate( c.anniversary() ).latin1() ); safeAddPropValue( vcard, "X-Qtopia-Anniversary", convDateToVCardDate( c.anniversary() ) ); } safeAddPropValue( vcard, "X-Qtopia-Nickname", c.nickname() ); safeAddPropValue( vcard, "X-Qtopia-Children", c.children() ); return vcard; } QString OContactAccessBackend_VCard::convDateToVCardDate( const QDate& d ) const { QString str_rfc2425 = QString("%1-%2-%3") .arg( d.year() ) .arg( d.month(), 2 ) .arg( d.day(), 2 ); // Now replace spaces with "0"... int pos = 0; while ( ( pos = str_rfc2425.find (' ') ) > 0 ) str_rfc2425.replace( pos, 1, "0" ); return str_rfc2425; } QDate OContactAccessBackend_VCard::convVCardDateToDate( const QString& datestr ) { int monthPos = datestr.find('-'); int dayPos = datestr.find('-', monthPos+1 ); int sep_ignore = 1; if ( monthPos == -1 || dayPos == -1 ) { qDebug("fromString didn't find - in str = %s; mpos = %d ypos = %d", datestr.latin1(), monthPos, dayPos ); // Ok.. No "-" found, therefore we will try to read other format ( YYYYMMDD ) if ( datestr.length() == 8 ){ monthPos = 4; dayPos = 6; sep_ignore = 0; qDebug("Try with follwing positions str = %s; mpos = %d ypos = %d", datestr.latin1(), monthPos, dayPos ); } else { return QDate(); } } int y = datestr.left( monthPos ).toInt(); int m = datestr.mid( monthPos + sep_ignore, dayPos - monthPos - sep_ignore ).toInt(); int d = datestr.mid( dayPos + sep_ignore ).toInt(); qDebug("TimeConversion::fromString ymd = %s => %d %d %d; mpos = %d ypos = %d", datestr.latin1(), y, m, d, monthPos, dayPos); QDate date ( y,m,d ); return date; } VObject* OContactAccessBackend_VCard::safeAddPropValue( VObject *o, const char *prop, const QString &value ) { VObject *ret = 0; if ( o && !value.isEmpty() ) ret = addPropValue( o, prop, value.latin1() ); return ret; } VObject* OContactAccessBackend_VCard::safeAddProp( VObject *o, const char *prop) { VObject *ret = 0; if ( o ) ret = addProp( o, prop ); return ret; } diff --git a/libopie/pim/ocontactaccessbackend_xml.cpp b/libopie/pim/ocontactaccessbackend_xml.cpp index 097142b..1c21619 100644 --- a/libopie/pim/ocontactaccessbackend_xml.cpp +++ b/libopie/pim/ocontactaccessbackend_xml.cpp @@ -1,403 +1,406 @@ /* * XML Backend for the OPIE-Contact Database. * * Copyright (c) 2002 by Stefan Eilers (Eilers.Stefan@epost.de) * * ===================================================================== * This program 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. * ===================================================================== * ToDo: XML-Backend: Automatic reload if something was changed... * * * ===================================================================== * Version: $Id$ * ===================================================================== * History: * $Log$ + * Revision 1.7 2003/08/01 12:30:16 eilers + * Merging changes from BRANCH_1_0 to HEAD + * * Revision 1.6 2003/07/07 16:19:47 eilers * Fixing serious bug in hasQuerySettings() * * Revision 1.5 2003/04/13 18:07:10 zecke * More API doc * QString -> const QString& * QString = 0l -> QString::null * * Revision 1.4 2003/03/21 14:32:54 mickeyl * g++ compliance fix: default arguments belong into the declaration, but not the definition * * Revision 1.3 2003/03/21 12:26:28 eilers * Fixing small bug: If we search a birthday from today to today, it returned * every contact .. * * Revision 1.2 2003/03/21 10:33:09 eilers * Merged speed optimized xml backend for contacts to main. * Added QDateTime to querybyexample. For instance, it is now possible to get * all Birthdays/Anniversaries between two dates. This should be used * to show all birthdays in the datebook.. * This change is sourcecode backward compatible but you have to upgrade * the binaries for today-addressbook. * * Revision 1.1.2.2 2003/02/11 12:17:28 eilers * Speed optimization. Removed the sequential search loops. * * Revision 1.1.2.1 2003/02/10 15:31:38 eilers * Writing offsets to debug output.. * * Revision 1.1 2003/02/09 15:05:01 eilers * Nothing happened.. Just some cleanup before I will start.. * * Revision 1.12 2003/01/03 16:58:03 eilers * Reenable debug output * * Revision 1.11 2003/01/03 12:31:28 eilers * Bugfix for calculating data diffs.. * * Revision 1.10 2003/01/02 14:27:12 eilers * Improved query by example: Search by date is possible.. First step * for a today plugin for birthdays.. * * Revision 1.9 2002/12/08 12:48:57 eilers * Moved journal-enum from ocontact into i the xml-backend.. * * Revision 1.8 2002/11/14 17:04:24 eilers * Sorting will now work if fullname is identical on some entries * * Revision 1.7 2002/11/13 15:02:46 eilers * Small Bug in sorted fixed * * Revision 1.6 2002/11/13 14:14:51 eilers * Added sorted for Contacts.. * * Revision 1.5 2002/11/01 15:10:42 eilers * Added regExp-search in database for all fields in a contact. * * Revision 1.4 2002/10/16 10:52:40 eilers * Added some docu to the interface and now using the cache infrastucture by zecke.. :) * * Revision 1.3 2002/10/14 16:21:54 eilers * Some minor interface updates * * Revision 1.2 2002/10/07 17:34:24 eilers * added OBackendFactory for advanced backend access * * Revision 1.1 2002/09/27 17:11:44 eilers * Added API for accessing the Contact-Database ! It is compiling, but * please do not expect that anything is working ! * I will debug that stuff in the next time .. * Please read README_COMPILE for compiling ! * * */ #include "ocontactaccessbackend_xml.h" #include <qasciidict.h> #include <qdatetime.h> #include <qfile.h> #include <qfileinfo.h> #include <qregexp.h> #include <qarray.h> #include <qmap.h> #include <qdatetime.h> #include <qpe/global.h> #include <opie/xmltree.h> #include "ocontactaccessbackend.h" #include "ocontactaccess.h" #include <stdlib.h> #include <errno.h> using namespace Opie; OContactAccessBackend_XML::OContactAccessBackend_XML ( const QString& appname, const QString& filename ): m_changed( false ) { // Just m_contactlist should call delete if an entry // is removed. m_contactList.setAutoDelete( true ); m_uidToContact.setAutoDelete( false ); m_appName = appname; /* Set journalfile name ... */ m_journalName = getenv("HOME"); m_journalName +="/.abjournal" + appname; /* Expecting to access the default filename if nothing else is set */ if ( filename.isEmpty() ){ m_fileName = Global::applicationFileName( "addressbook","addressbook.xml" ); } else m_fileName = filename; /* Load Database now */ load (); } bool OContactAccessBackend_XML::save() { if ( !m_changed ) return true; QString strNewFile = m_fileName + ".new"; QFile f( strNewFile ); if ( !f.open( IO_WriteOnly|IO_Raw ) ) return false; int total_written; int idx_offset = 0; QString out; // Write Header out = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE Addressbook ><AddressBook>\n" " <Groups>\n" " </Groups>\n" " <Contacts>\n"; QCString cstr = out.utf8(); f.writeBlock( cstr.data(), cstr.length() ); idx_offset += cstr.length(); out = ""; // Write all contacts QListIterator<OContact> it( m_contactList ); for ( ; it.current(); ++it ) { qWarning(" Uid %d at Offset: %x", (*it)->uid(), idx_offset ); out += "<Contact "; (*it)->save( out ); out += "/>\n"; cstr = out.utf8(); total_written = f.writeBlock( cstr.data(), cstr.length() ); idx_offset += cstr.length(); if ( total_written != int(cstr.length()) ) { f.close(); QFile::remove( strNewFile ); return false; } out = ""; } out += " </Contacts>\n</AddressBook>\n"; // Write Footer cstr = out.utf8(); total_written = f.writeBlock( cstr.data(), cstr.length() ); if ( total_written != int( cstr.length() ) ) { f.close(); QFile::remove( strNewFile ); return false; } f.close(); // move the file over, I'm just going to use the system call // because, I don't feel like using QDir. if ( ::rename( strNewFile.latin1(), m_fileName.latin1() ) < 0 ) { qWarning( "problem renaming file %s to %s, errno: %d", strNewFile.latin1(), m_journalName.latin1(), errno ); // remove the tmp file... QFile::remove( strNewFile ); } /* The journalfile should be removed now... */ removeJournal(); m_changed = false; return true; } bool OContactAccessBackend_XML::load () { m_contactList.clear(); m_uidToContact.clear(); /* Load XML-File and journal if it exists */ if ( !load ( m_fileName, false ) ) return false; /* The returncode of the journalfile is ignored due to the * fact that it does not exist when this class is instantiated ! * But there may such a file exist, if the application crashed. * Therefore we try to load it to get the changes before the # * crash happened... */ load (m_journalName, true); return true; } void OContactAccessBackend_XML::clear () { m_contactList.clear(); m_uidToContact.clear(); m_changed = false; } bool OContactAccessBackend_XML::wasChangedExternally() { QFileInfo fi( m_fileName ); QDateTime lastmod = fi.lastModified (); return (lastmod != m_readtime); } QArray<int> OContactAccessBackend_XML::allRecords() const { QArray<int> uid_list( m_contactList.count() ); uint counter = 0; QListIterator<OContact> it( m_contactList ); for( ; it.current(); ++it ){ uid_list[counter++] = (*it)->uid(); } return ( uid_list ); } OContact OContactAccessBackend_XML::find ( int uid ) const { OContact foundContact; //Create empty contact OContact* found = m_uidToContact.find( QString().setNum( uid ) ); if ( found ){ foundContact = *found; } return ( foundContact ); } QArray<int> OContactAccessBackend_XML::queryByExample ( const OContact &query, int settings, const QDateTime& d ) { QArray<int> m_currentQuery( m_contactList.count() ); QListIterator<OContact> it( m_contactList ); uint arraycounter = 0; for( ; it.current(); ++it ){ /* Search all fields and compare them with query object. Store them into list * if all fields matches. */ QDate* queryDate = 0l; QDate* checkDate = 0l; bool allcorrect = true; for ( int i = 0; i < Qtopia::Groups; i++ ) { // Birthday and anniversary are special nonstring fields and should // be handled specially switch ( i ){ case Qtopia::Birthday: queryDate = new QDate( query.birthday() ); checkDate = new QDate( (*it)->birthday() ); case Qtopia::Anniversary: if ( queryDate == 0l ){ queryDate = new QDate( query.anniversary() ); checkDate = new QDate( (*it)->anniversary() ); } if ( queryDate->isValid() ){ if( checkDate->isValid() ){ if ( settings & OContactAccess::DateYear ){ if ( queryDate->year() != checkDate->year() ) allcorrect = false; } if ( settings & OContactAccess::DateMonth ){ if ( queryDate->month() != checkDate->month() ) allcorrect = false; } if ( settings & OContactAccess::DateDay ){ if ( queryDate->day() != checkDate->day() ) allcorrect = false; } if ( settings & OContactAccess::DateDiff ) { QDate current; // If we get an additional date, we // will take this date instead of // the current one.. if ( !d.date().isValid() ) current = QDate::currentDate(); else current = d.date(); // We have to equalize the year, otherwise // the search will fail.. checkDate->setYMD( current.year(), checkDate->month(), checkDate->day() ); if ( *checkDate < current ) checkDate->setYMD( current.year()+1, checkDate->month(), checkDate->day() ); // Check whether the birthday/anniversary date is between // the current/given date and the maximum date // ( maximum time range ) ! qWarning("Checking if %s is between %s and %s ! ", checkDate->toString().latin1(), current.toString().latin1(), queryDate->toString().latin1() ); if ( current.daysTo( *queryDate ) >= 0 ){ if ( !( ( *checkDate >= current ) && ( *checkDate <= *queryDate ) ) ){ allcorrect = false; qWarning (" Nope!.."); } } } } else{ // checkDate is invalid. Therefore this entry is always rejected allcorrect = false; } } delete queryDate; queryDate = 0l; delete checkDate; checkDate = 0l; break; default: /* Just compare fields which are not empty in the query object */ if ( !query.field(i).isEmpty() ){ switch ( settings & ~( OContactAccess::IgnoreCase | OContactAccess::DateDiff | OContactAccess::DateYear | OContactAccess::DateMonth | OContactAccess::DateDay | OContactAccess::MatchOne ) ){ case OContactAccess::RegExp:{ QRegExp expr ( query.field(i), !(settings & OContactAccess::IgnoreCase), false ); if ( expr.find ( (*it)->field(i), 0 ) == -1 ) allcorrect = false; } break; case OContactAccess::WildCards:{ QRegExp expr ( query.field(i), !(settings & OContactAccess::IgnoreCase), true ); if ( expr.find ( (*it)->field(i), 0 ) == -1 ) allcorrect = false; } break; case OContactAccess::ExactMatch:{ if (settings & OContactAccess::IgnoreCase){ if ( query.field(i).upper() != (*it)->field(i).upper() ) allcorrect = false; }else{ if ( query.field(i) != (*it)->field(i) ) allcorrect = false; } } break; } } } } diff --git a/libopie/pim/oconversion.h b/libopie/pim/oconversion.h index 13367e1..4c0a497 100644 --- a/libopie/pim/oconversion.h +++ b/libopie/pim/oconversion.h @@ -1,43 +1,48 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** Copyright (C) 2002-2003 by Stefan Eilers (eilers.stefan@epost.de) ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. **********************************************************************/ #ifndef __oconversion_h__ #define __oconversion_h__ /* #include <time.h> */ /* #include <sys/types.h> */ #include <qdatetime.h> /* FIXME namespace? -zecke */ class OConversion { public: static QString dateToString( const QDate &d ); static QDate dateFromString( const QString &datestr ); /** * simple function to store DateTime as string and read from string * no timezone changing is done * DDMMYYYYHHMMSS is the simple format */ static QString dateTimeToString( const QDateTime& ); static QDateTime dateTimeFromString( const QString& ); + +private: + class Private; + Private* d; + }; #endif // __oconversion_h__ diff --git a/libopie/pim/odatebookaccessbackend.h b/libopie/pim/odatebookaccessbackend.h index 86ff298..3c02c42 100644 --- a/libopie/pim/odatebookaccessbackend.h +++ b/libopie/pim/odatebookaccessbackend.h @@ -1,73 +1,77 @@ #ifndef OPIE_DATE_BOOK_ACCESS_BACKEND_H #define OPIE_DATE_BOOK_ACCESS_BACKEND_H #include <qarray.h> #include "opimaccessbackend.h" #include "oevent.h" /** * This class is the interface to the storage of Events. * @see OPimAccessBackend * */ class ODateBookAccessBackend : public OPimAccessBackend<OEvent> { public: typedef int UID; /** * c'tor without parameter */ ODateBookAccessBackend(); ~ODateBookAccessBackend(); /** * This method should return a list of UIDs containing * all events. No filter should be applied * @return list of events */ virtual QArray<UID> rawEvents()const = 0; /** * This method should return a list of UIDs containing * all repeating events. No filter should be applied * @return list of repeating events */ virtual QArray<UID> rawRepeats()const = 0; /** * This mthod should return a list of UIDs containing all non * repeating events. No filter should be applied * @return list of nonrepeating events */ virtual QArray<UID> nonRepeats() const = 0; /** * If you do not want to implement the effectiveEvents methods below * you need to supply it with directNonRepeats. * This method can return empty lists if effectiveEvents is implememted */ virtual OEvent::ValueList directNonRepeats() = 0; /** * Same as above but return raw repeats! */ virtual OEvent::ValueList directRawRepeats() = 0; /* is implemented by default but you can reimplement it*/ /** * Effective Events are special event occuring during a time frame. This method does calcualte * EffectiveEvents bases on the directNonRepeats and directRawRepeats. You may implement this method * yourself */ virtual OEffectiveEvent::ValueList effecticeEvents( const QDate& from, const QDate& to ); /** * this is an overloaded member function * @see effecticeEvents */ virtual OEffectiveEvent::ValueList effecticeEvents( const QDateTime& start ); +private: + class Private; + Private *d; + }; #endif diff --git a/libopie/pim/odatebookaccessbackend_xml.cpp b/libopie/pim/odatebookaccessbackend_xml.cpp index ab2eea4..5ea945c 100644 --- a/libopie/pim/odatebookaccessbackend_xml.cpp +++ b/libopie/pim/odatebookaccessbackend_xml.cpp @@ -49,558 +49,558 @@ char *strstrlen(const char *haystack, int hLen, const char* needle, int nLen) } } namespace { time_t start, end, created, rp_end; ORecur* rec; ORecur* recur() { if (!rec) rec = new ORecur; return rec; } int alarmTime; int snd; enum Attribute{ FDescription = 0, FLocation, FCategories, FUid, FType, FAlarm, FSound, FRType, FRWeekdays, FRPosition, FRFreq, FRHasEndDate, FREndDate, FRStart, FREnd, FNote, FCreated, FTimeZone, FRecParent, FRecChildren, FExceptions }; inline void save( const OEvent& ev, QString& buf ) { qWarning("Saving %d %s", ev.uid(), ev.description().latin1() ); buf += " description=\"" + Qtopia::escapeString(ev.description() ) + "\""; if (!ev.location().isEmpty() ) buf += " location=\"" + Qtopia::escapeString(ev.location() ) + "\""; buf += " categories=\""+ Qtopia::escapeString( Qtopia::Record::idsToString( ev.categories() ) ) + "\""; buf += " uid=\"" + QString::number( ev.uid() ) + "\""; if (ev.isAllDay() ) buf += " type=\"AllDay\""; if (ev.hasNotifiers() ) { OPimAlarm alarm = ev.notifiers().alarms()[0]; // take only the first int minutes = alarm.dateTime().secsTo( ev.startDateTime() ) / 60; buf += " alarm=\"" + QString::number(minutes) + "\" sound=\""; if ( alarm.sound() == OPimAlarm::Loud ) buf += "loud"; else buf += "silent"; buf += "\""; } if ( ev.hasRecurrence() ) { buf += ev.recurrence().toString(); } /* * fscking timezones :) well, we'll first convert * the QDateTime to a QDateTime in UTC time * and then we'll create a nice time_t */ OTimeZone zone( ev.timeZone().isEmpty() ? OTimeZone::current() : ev.timeZone() ); buf += " start=\"" + QString::number( zone.fromUTCDateTime( zone.toDateTime( ev.startDateTime(), OTimeZone::utc() ) ) ) + "\""; buf += " end=\"" + QString::number( zone.fromUTCDateTime( zone.toDateTime( ev.endDateTime() , OTimeZone::utc() ) ) ) + "\""; if (!ev.note().isEmpty() ) { buf += " note=\"" + Qtopia::escapeString( ev.note() ) + "\""; } buf += " timezone=\""; if ( ev.timeZone().isEmpty() ) buf += "None"; else buf += ev.timeZone(); buf += "\""; if (ev.parent() != 0 ) { buf += " recparent=\""+QString::number(ev.parent() )+"\""; } if (ev.children().count() != 0 ) { QArray<int> children = ev.children(); buf += " recchildren=\""; for ( uint i = 0; i < children.count(); i++ ) { if ( i != 0 ) buf += " "; buf += QString::number( children[i] ); } buf+= "\""; } // skip custom writing } inline bool forAll( const QMap<int, OEvent>& list, QFile& file ) { QMap<int, OEvent>::ConstIterator it; QString buf; QCString str; int total_written; for ( it = list.begin(); it != list.end(); ++it ) { buf = "<event"; save( it.data(), buf ); buf += " />\n"; str = buf.utf8(); total_written = file.writeBlock(str.data(), str.length() ); if ( total_written != int(str.length() ) ) return false; } return true; } } ODateBookAccessBackend_XML::ODateBookAccessBackend_XML( const QString& , const QString& fileName ) : ODateBookAccessBackend() { m_name = fileName.isEmpty() ? Global::applicationFileName( "datebook", "datebook.xml" ) : fileName; m_changed = false; } ODateBookAccessBackend_XML::~ODateBookAccessBackend_XML() { } bool ODateBookAccessBackend_XML::load() { return loadFile(); } bool ODateBookAccessBackend_XML::reload() { clear(); return load(); } bool ODateBookAccessBackend_XML::save() { if (!m_changed) return true; int total_written; QString strFileNew = m_name + ".new"; QFile f( strFileNew ); if (!f.open( IO_WriteOnly | IO_Raw ) ) return false; QString buf( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ); buf += "<!DOCTYPE DATEBOOK><DATEBOOK>\n"; buf += "<events>\n"; QCString str = buf.utf8(); total_written = f.writeBlock( str.data(), str.length() ); if ( total_written != int(str.length() ) ) { f.close(); QFile::remove( strFileNew ); return false; } if (!forAll( m_raw, f ) ) { f.close(); QFile::remove( strFileNew ); return false; } if (!forAll( m_rep, f ) ) { f.close(); QFile::remove( strFileNew ); return false; } buf = "</events>\n</DATEBOOK>\n"; str = buf.utf8(); total_written = f.writeBlock( str.data(), str.length() ); if ( total_written != int(str.length() ) ) { f.close(); QFile::remove( strFileNew ); return false; } f.close(); if ( ::rename( strFileNew, m_name ) < 0 ) { QFile::remove( strFileNew ); return false; } m_changed = false; return true; } QArray<int> ODateBookAccessBackend_XML::allRecords()const { QArray<int> ints( m_raw.count()+ m_rep.count() ); uint i = 0; QMap<int, OEvent>::ConstIterator it; for ( it = m_raw.begin(); it != m_raw.end(); ++it ) { ints[i] = it.key(); i++; } for ( it = m_rep.begin(); it != m_rep.end(); ++it ) { ints[i] = it.key(); i++; } return ints; } QArray<int> ODateBookAccessBackend_XML::queryByExample(const OEvent&, int, const QDateTime& ) { return QArray<int>(); } void ODateBookAccessBackend_XML::clear() { m_changed = true; m_raw.clear(); m_rep.clear(); } OEvent ODateBookAccessBackend_XML::find( int uid ) const{ if ( m_raw.contains( uid ) ) return m_raw[uid]; else return m_rep[uid]; } bool ODateBookAccessBackend_XML::add( const OEvent& ev ) { m_changed = true; if (ev.hasRecurrence() ) m_rep.insert( ev.uid(), ev ); else m_raw.insert( ev.uid(), ev ); return true; } bool ODateBookAccessBackend_XML::remove( int uid ) { m_changed = true; m_rep.remove( uid ); m_rep.remove( uid ); return true; } bool ODateBookAccessBackend_XML::replace( const OEvent& ev ) { replace( ev.uid() ); return add( ev ); } QArray<int> ODateBookAccessBackend_XML::rawEvents()const { return allRecords(); } QArray<int> ODateBookAccessBackend_XML::rawRepeats()const { QArray<int> ints( m_rep.count() ); uint i = 0; QMap<int, OEvent>::ConstIterator it; for ( it = m_rep.begin(); it != m_rep.end(); ++it ) { ints[i] = it.key(); i++; } return ints; } QArray<int> ODateBookAccessBackend_XML::nonRepeats()const { QArray<int> ints( m_raw.count() ); uint i = 0; QMap<int, OEvent>::ConstIterator it; for ( it = m_raw.begin(); it != m_raw.end(); ++it ) { ints[i] = it.key(); i++; } return ints; } OEvent::ValueList ODateBookAccessBackend_XML::directNonRepeats() { OEvent::ValueList list; QMap<int, OEvent>::ConstIterator it; for (it = m_raw.begin(); it != m_raw.end(); ++it ) list.append( it.data() ); return list; } OEvent::ValueList ODateBookAccessBackend_XML::directRawRepeats() { OEvent::ValueList list; QMap<int, OEvent>::ConstIterator it; for (it = m_rep.begin(); it != m_rep.end(); ++it ) list.append( it.data() ); return list; } bool ODateBookAccessBackend_XML::loadFile() { m_changed = false; int fd = ::open( QFile::encodeName(m_name).data(), O_RDONLY ); if ( fd < 0 ) return false; struct stat attribute; if ( ::fstat(fd, &attribute ) == -1 ) { ::close( fd ); return false; } void* map_addr = ::mmap(NULL, attribute.st_size, PROT_READ, MAP_SHARED, fd, 0 ); if ( map_addr == ( (caddr_t)-1) ) { ::close( fd ); return false; } ::madvise( map_addr, attribute.st_size, MADV_SEQUENTIAL ); ::close( fd ); QAsciiDict<int> dict(FExceptions+1); dict.setAutoDelete( true ); dict.insert( "description", new int(FDescription) ); dict.insert( "location", new int(FLocation) ); dict.insert( "categories", new int(FCategories) ); dict.insert( "uid", new int(FUid) ); dict.insert( "type", new int(FType) ); dict.insert( "alarm", new int(FAlarm) ); dict.insert( "sound", new int(FSound) ); dict.insert( "rtype", new int(FRType) ); dict.insert( "rweekdays", new int(FRWeekdays) ); dict.insert( "rposition", new int(FRPosition) ); dict.insert( "rfreq", new int(FRFreq) ); dict.insert( "rhasenddate", new int(FRHasEndDate) ); dict.insert( "enddt", new int(FREndDate) ); dict.insert( "start", new int(FRStart) ); dict.insert( "end", new int(FREnd) ); dict.insert( "note", new int(FNote) ); dict.insert( "created", new int(FCreated) ); dict.insert( "recparent", new int(FRecParent) ); dict.insert( "recchildren", new int(FRecChildren) ); dict.insert( "exceptions", new int(FExceptions) ); dict.insert( "timezone", new int(FTimeZone) ); char* dt = (char*)map_addr; int len = attribute.st_size; int i = 0; char* point; const char* collectionString = "<event "; int strLen = ::strlen(collectionString); int *find; while ( ( point = ::strstrlen( dt+i, len -i, collectionString, strLen ) ) != 0 ) { i = point -dt; i+= strLen; alarmTime = -1; snd = 0; // silent OEvent ev; rec = 0; while ( TRUE ) { while ( i < len && (dt[i] == ' ' || dt[i] == '\n' || dt[i] == '\r') ) ++i; if ( i >= len-2 || (dt[i] == '/' && dt[i+1] == '>') ) break; // we have another attribute, read it. int j = i; while ( j < len && dt[j] != '=' ) ++j; QCString attr( dt+i, j-i+1); i = ++j; // skip = // find the start of quotes while ( i < len && dt[i] != '"' ) ++i; j = ++i; bool haveUtf = FALSE; bool haveEnt = FALSE; while ( j < len && dt[j] != '"' ) { if ( ((unsigned char)dt[j]) > 0x7f ) haveUtf = TRUE; if ( dt[j] == '&' ) haveEnt = TRUE; ++j; } if ( i == j ) { // empty value i = j + 1; continue; } QCString value( dt+i, j-i+1 ); i = j + 1; QString str = (haveUtf ? QString::fromUtf8( value ) : QString::fromLatin1( value ) ); if ( haveEnt ) str = Qtopia::plainString( str ); /* * add key + value */ find = dict[attr.data()]; if (!find) - ev.setCustomField( attr, value ); + ev.setCustomField( attr, str ); else { - setField( ev, *find, value ); + setField( ev, *find, str ); } } /* time to finalize */ finalizeRecord( ev ); delete rec; } ::munmap(map_addr, attribute.st_size ); m_changed = false; // changed during add return true; } void ODateBookAccessBackend_XML::finalizeRecord( OEvent& ev ) { /* AllDay is alway in UTC */ if ( ev.isAllDay() ) { OTimeZone utc = OTimeZone::utc(); ev.setStartDateTime( utc.fromUTCDateTime( start ) ); ev.setEndDateTime ( utc.fromUTCDateTime( end ) ); ev.setTimeZone( "UTC"); // make sure it is really utc }else { /* to current date time */ - qWarning(" Start is %d", start ); + // qWarning(" Start is %d", start ); OTimeZone zone( ev.timeZone().isEmpty() ? OTimeZone::current() : ev.timeZone() ); QDateTime date = zone.toDateTime( start ); qWarning(" Start is %s", date.toString().latin1() ); ev.setStartDateTime( zone.toDateTime( date, OTimeZone::current() ) ); date = zone.toDateTime( end ); ev.setEndDateTime ( zone.toDateTime( date, OTimeZone::current() ) ); } if ( rec && rec->doesRecur() ) { OTimeZone utc = OTimeZone::utc(); ORecur recu( *rec ); // call copy c'tor; recu.setEndDate ( utc.fromUTCDateTime( rp_end ).date() ); recu.setCreatedDateTime( utc.fromUTCDateTime( created ) ); recu.setStart( ev.startDateTime().date() ); ev.setRecurrence( recu ); } if (alarmTime != -1 ) { QDateTime dt = ev.startDateTime().addSecs( -1*alarmTime*60 ); OPimAlarm al( snd , dt ); ev.notifiers().add( al ); } if ( m_raw.contains( ev.uid() ) || m_rep.contains( ev.uid() ) ) { qWarning("already contains assign uid"); ev.setUid( 1 ); } qWarning("addind %d %s", ev.uid(), ev.description().latin1() ); if ( ev.hasRecurrence() ) m_rep.insert( ev.uid(), ev ); else m_raw.insert( ev.uid(), ev ); } void ODateBookAccessBackend_XML::setField( OEvent& e, int id, const QString& value) { // qWarning(" setting %s", value.latin1() ); switch( id ) { case FDescription: e.setDescription( value ); break; case FLocation: e.setLocation( value ); break; case FCategories: e.setCategories( e.idsFromString( value ) ); break; case FUid: e.setUid( value.toInt() ); break; case FType: if ( value == "AllDay" ) { e.setAllDay( true ); e.setTimeZone( "UTC" ); } break; case FAlarm: alarmTime = value.toInt(); break; case FSound: snd = value == "loud" ? OPimAlarm::Loud : OPimAlarm::Silent; break; // recurrence stuff case FRType: if ( value == "Daily" ) recur()->setType( ORecur::Daily ); else if ( value == "Weekly" ) recur()->setType( ORecur::Weekly); else if ( value == "MonthlyDay" ) recur()->setType( ORecur::MonthlyDay ); else if ( value == "MonthlyDate" ) recur()->setType( ORecur::MonthlyDate ); else if ( value == "Yearly" ) recur()->setType( ORecur::Yearly ); else recur()->setType( ORecur::NoRepeat ); break; case FRWeekdays: recur()->setDays( value.toInt() ); break; case FRPosition: recur()->setPosition( value.toInt() ); break; case FRFreq: recur()->setFrequency( value.toInt() ); break; case FRHasEndDate: recur()->setHasEndDate( value.toInt() ); break; case FREndDate: { rp_end = (time_t) value.toLong(); break; } case FRStart: { start = (time_t) value.toLong(); break; } case FREnd: { end = ( (time_t) value.toLong() ); break; } case FNote: e.setNote( value ); break; case FCreated: created = value.toInt(); break; case FRecParent: e.setParent( value.toInt() ); break; case FRecChildren:{ QStringList list = QStringList::split(' ', value ); for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { e.addChild( (*it).toInt() ); } } break; case FExceptions:{ QStringList list = QStringList::split(' ', value ); for (QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { QDate date( (*it).left(4).toInt(), (*it).mid(4, 2).toInt(), (*it).right(2).toInt() ); qWarning("adding exception %s", date.toString().latin1() ); recur()->exceptions().append( date ); } } break; case FTimeZone: if ( value != "None" ) e.setTimeZone( value ); break; default: break; } } QArray<int> ODateBookAccessBackend_XML::matchRegexp( const QRegExp &r ) const { QArray<int> m_currentQuery( m_raw.count()+ m_rep.count() ); uint arraycounter = 0; QMap<int, OEvent>::ConstIterator it; for ( it = m_raw.begin(); it != m_raw.end(); ++it ) if ( it.data().match( r ) ) m_currentQuery[arraycounter++] = it.data().uid(); for ( it = m_rep.begin(); it != m_rep.end(); ++it ) if ( it.data().match( r ) ) m_currentQuery[arraycounter++] = it.data().uid(); // Shrink to fit.. m_currentQuery.resize(arraycounter); return m_currentQuery; } diff --git a/libopie/pim/opimaccessbackend.h b/libopie/pim/opimaccessbackend.h index f4bbe35..c3d91f7 100644 --- a/libopie/pim/opimaccessbackend.h +++ b/libopie/pim/opimaccessbackend.h @@ -1,159 +1,159 @@ #ifndef OPIE_PIM_ACCESS_BACKEND #define OPIE_PIM_ACCESS_BACKEND #include <qarray.h> #include <opie/otemplatebase.h> #include <opie/opimrecord.h> +class OPimAccessBackendPrivate; /** * OPimAccessBackend is the base class * for all private backends * it operates on OPimRecord as the base class * and it's responsible for fast manipulating * the resource the implementation takes care * of */ template <class T = OPimRecord> class OPimAccessBackend { public: typedef OTemplateBase<T> Frontend; /** The access hint from the frontend */ OPimAccessBackend(int access = 0); virtual ~OPimAccessBackend(); /** * load the resource */ virtual bool load() = 0; /** * reload the resource */ virtual bool reload() = 0; /** * save the resource and * all it's changes */ virtual bool save() = 0; /** * return an array of * all available uids */ virtual QArray<int> allRecords()const = 0; /** * return a List of records * that match the regex */ virtual QArray<int> matchRegexp(const QRegExp &r) const = 0; /** * queryByExample for T with the given Settings * */ virtual QArray<int> queryByExample( const T& t, int settings, const QDateTime& d = QDateTime() ) = 0; /** * find the OPimRecord with uid @param uid * returns T and T.isEmpty() if nothing was found */ virtual T find(int uid )const = 0; virtual T find(int uid, const QArray<int>& items, uint current, typename Frontend::CacheDirection )const ; /** * clear the back end */ virtual void clear() = 0; /** * add T */ virtual bool add( const T& t ) = 0; /** * remove */ virtual bool remove( int uid ) = 0; /** * replace a record with T.uid() */ virtual bool replace( const T& t ) = 0; /* * setTheFrontEnd!!! */ void setFrontend( Frontend* front ); /** * set the read ahead count */ void setReadAhead( uint count ); protected: int access()const; void cache( const T& t )const; /** * use a prime number here! */ void setSaneCacheSize( int ); uint readAhead()const; private: - class Private; - Private* d; + OPimAccessBackendPrivate *d; Frontend* m_front; uint m_read; int m_acc; }; template <class T> OPimAccessBackend<T>::OPimAccessBackend(int acc) : m_acc( acc ) { m_front = 0l; } template <class T> OPimAccessBackend<T>::~OPimAccessBackend() { } template <class T> void OPimAccessBackend<T>::setFrontend( Frontend* fr ) { m_front = fr; } template <class T> void OPimAccessBackend<T>::cache( const T& t )const { if (m_front ) m_front->cache( t ); } template <class T> void OPimAccessBackend<T>::setSaneCacheSize( int size) { if (m_front ) m_front->setSaneCacheSize( size ); } template <class T> T OPimAccessBackend<T>::find( int uid, const QArray<int>&, uint, typename Frontend::CacheDirection )const { return find( uid ); } template <class T> void OPimAccessBackend<T>::setReadAhead( uint count ) { m_read = count; } template <class T> uint OPimAccessBackend<T>::readAhead()const { return m_read; } template <class T> int OPimAccessBackend<T>::access()const { return m_acc; } #endif diff --git a/libopie/pim/opimaccesstemplate.h b/libopie/pim/opimaccesstemplate.h index 8ff205c..ecbeb68 100644 --- a/libopie/pim/opimaccesstemplate.h +++ b/libopie/pim/opimaccesstemplate.h @@ -1,298 +1,302 @@ #ifndef OPIE_PIM_ACCESS_TEMPLATE_H #define OPIE_PIM_ACCESS_TEMPLATE_H #include <qarray.h> #include <opie/opimrecord.h> #include <opie/opimaccessbackend.h> #include <opie/orecordlist.h> #include "opimcache.h" #include "otemplatebase.h" +class OPimAccessTemplatePrivate; /** * Thats the frontend to our OPIE PIM * Library. Either you want to use it's * interface or you want to implement * your own Access lib * Just create a OPimRecord and inherit from * the plugins */ template <class T = OPimRecord > class OPimAccessTemplate : public OTemplateBase<T> { public: enum Access { Random = 0, SortedAccess }; typedef ORecordList<T> List; typedef OPimAccessBackend<T> BackEnd; typedef OPimCache<T> Cache; /** * c'tor BackEnd * enum Access a small hint on how to handle the backend */ OPimAccessTemplate( BackEnd* end); virtual ~OPimAccessTemplate(); /** * load from the backend */ bool load(); /** Reload database. * You should execute this function if the external database * was changed. * This function will load the external database and afterwards * rejoin the local changes. Therefore the local database will be set consistent. */ virtual bool reload(); /** Save contacts database. * Save is more a "commit". After calling this function, all changes are public available. * @return true if successful */ bool save(); /** * if the resource was changed externally * You should use the signal handling instead of polling possible changes ! * zecke: Do you implement a signal for otodoaccess ? */ bool wasChangedExternally()const; /** * return a List of records * you can iterate over them */ virtual List allRecords()const; /** * return a List of records * that match the regex */ virtual List matchRegexp( const QRegExp &r ) const; /** * queryByExample. * @see otodoaccess, ocontactaccess */ virtual List queryByExample( const T& t, int querySettings, const QDateTime& d = QDateTime() ); /** * find the OPimRecord uid */ virtual T find( int uid )const; /** * read ahead cache find method ;) */ virtual T find( int uid, const QArray<int>&, uint current, typename OTemplateBase<T>::CacheDirection dir = OTemplateBase<T>::Forward )const; /* invalidate cache here */ /** * clears the backend and invalidates the backend */ void clear() ; /** * add T to the backend * @param t The item to add. * @return <i>true</i> if added successfully. */ virtual bool add( const T& t ) ; bool add( const OPimRecord& ); /* only the uid matters */ /** * remove T from the backend * @param t The item to remove * @return <i>true</i> if successful. */ virtual bool remove( const T& t ); /** * remove the OPimRecord with uid * @param uid The ID of the item to remove * @return <i>true</i> if successful. */ bool remove( int uid ); bool remove( const OPimRecord& ); /** * replace T from backend * @param t The item to replace * @return <i>true</i> if successful. */ virtual bool replace( const T& t) ; void setReadAhead( uint count ); /** * @internal */ void cache( const T& )const; void setSaneCacheSize( int ); QArray<int> records()const; protected: /** * invalidate the cache */ void invalidateCache(); void setBackEnd( BackEnd* end ); /** * returns the backend */ BackEnd* backEnd(); BackEnd* m_backEnd; Cache m_cache; +private: + OPimAccessTemplatePrivate *d; + }; template <class T> OPimAccessTemplate<T>::OPimAccessTemplate( BackEnd* end ) : OTemplateBase<T>(), m_backEnd( end ) { if (end ) end->setFrontend( this ); } template <class T> OPimAccessTemplate<T>::~OPimAccessTemplate() { qWarning("~OPimAccessTemplate<T>"); delete m_backEnd; } template <class T> bool OPimAccessTemplate<T>::load() { invalidateCache(); return m_backEnd->load(); } template <class T> bool OPimAccessTemplate<T>::reload() { invalidateCache(); // zecke: I think this should be added (se) return m_backEnd->reload(); } template <class T> bool OPimAccessTemplate<T>::save() { return m_backEnd->save(); } template <class T> typename OPimAccessTemplate<T>::List OPimAccessTemplate<T>::allRecords()const { QArray<int> ints = m_backEnd->allRecords(); List lis(ints, this ); return lis; } template <class T> typename OPimAccessTemplate<T>::List OPimAccessTemplate<T>::matchRegexp( const QRegExp &r )const { QArray<int> ints = m_backEnd->matchRegexp( r ); List lis(ints, this ); return lis; } template <class T> QArray<int> OPimAccessTemplate<T>::records()const { return m_backEnd->allRecords(); } template <class T> typename OPimAccessTemplate<T>::List OPimAccessTemplate<T>::queryByExample( const T& t, int settings, const QDateTime& d ) { QArray<int> ints = m_backEnd->queryByExample( t, settings, d ); List lis(ints, this ); return lis; } template <class T> T OPimAccessTemplate<T>::find( int uid ) const{ T t = m_backEnd->find( uid ); cache( t ); return t; } template <class T> T OPimAccessTemplate<T>::find( int uid, const QArray<int>& ar, uint current, typename OTemplateBase<T>::CacheDirection dir )const { /* * better do T.isEmpty() * after a find this way we would * avoid two finds in QCache... */ // qWarning("find it now %d", uid ); if (m_cache.contains( uid ) ) { return m_cache.find( uid ); } T t = m_backEnd->find( uid, ar, current, dir ); cache( t ); return t; } template <class T> void OPimAccessTemplate<T>::clear() { invalidateCache(); m_backEnd->clear(); } template <class T> bool OPimAccessTemplate<T>::add( const T& t ) { cache( t ); return m_backEnd->add( t ); } template <class T> bool OPimAccessTemplate<T>::add( const OPimRecord& rec) { /* same type */ if ( rec.rtti() == T::rtti() ) { const T &t = static_cast<const T&>(rec); return add(t); } return false; } template <class T> bool OPimAccessTemplate<T>::remove( const T& t ) { return remove( t.uid() ); } template <class T> bool OPimAccessTemplate<T>::remove( int uid ) { m_cache.remove( uid ); return m_backEnd->remove( uid ); } template <class T> bool OPimAccessTemplate<T>::remove( const OPimRecord& rec) { return remove( rec.uid() ); } template <class T> bool OPimAccessTemplate<T>::replace( const T& t ) { m_cache.replace( t ); return m_backEnd->replace( t ); } template <class T> void OPimAccessTemplate<T>::invalidateCache() { m_cache.invalidate(); } template <class T> typename OPimAccessTemplate<T>::BackEnd* OPimAccessTemplate<T>::backEnd() { return m_backEnd; } template <class T> bool OPimAccessTemplate<T>::wasChangedExternally()const { return false; } template <class T> void OPimAccessTemplate<T>::setBackEnd( BackEnd* end ) { m_backEnd = end; if (m_backEnd ) m_backEnd->setFrontend( this ); } template <class T> void OPimAccessTemplate<T>::cache( const T& t ) const{ /* hacky we need to work around the const*/ ((OPimAccessTemplate<T>*)this)->m_cache.add( t ); } template <class T> void OPimAccessTemplate<T>::setSaneCacheSize( int size ) { m_cache.setSize( size ); } template <class T> void OPimAccessTemplate<T>::setReadAhead( uint count ) { m_backEnd->setReadAhead( count ); } #endif diff --git a/libopie/pim/opimcache.h b/libopie/pim/opimcache.h index 73414e5..7f7cff5 100644 --- a/libopie/pim/opimcache.h +++ b/libopie/pim/opimcache.h @@ -1,125 +1,131 @@ #ifndef OPIE_PIM_CACHE_H #define OPIE_PIM_CACHE_H #include <qintcache.h> #include "opimrecord.h" +class OPimCacheItemPrivate; + template <class T = OPimRecord> class OPimCacheItem { public: OPimCacheItem( const T& t = T() ); OPimCacheItem( const OPimCacheItem& ); ~OPimCacheItem(); OPimCacheItem &operator=( const OPimCacheItem& ); T record()const; void setRecord( const T& ); private: T m_t; + OPimCacheItemPrivate *d; }; + +class OPimCachePrivate; /** * OPimCache for caching the items * We support adding, removing * and finding */ template <class T = OPimRecord> class OPimCache { public: typedef OPimCacheItem<T> Item; OPimCache(); OPimCache( const OPimCache& ); ~OPimCache(); OPimCache &operator=( const OPimCache& ); bool contains(int uid)const; void invalidate(); void setSize( int size ); T find(int uid )const; void add( const T& ); void remove( int uid ); void replace( const T& ); private: QIntCache<Item> m_cache; + OPimCachePrivate* d; }; // Implementation template <class T> OPimCacheItem<T>::OPimCacheItem( const T& t ) : m_t(t) { } template <class T> OPimCacheItem<T>::~OPimCacheItem() { } template <class T> T OPimCacheItem<T>::record()const { return m_t; } template <class T> void OPimCacheItem<T>::setRecord( const T& t ) { m_t = t; } // Cache template <class T> OPimCache<T>::OPimCache() : m_cache(100, 53 ) { m_cache.setAutoDelete( TRUE ); } template <class T> OPimCache<T>::~OPimCache() { } template <class T> bool OPimCache<T>::contains(int uid )const { Item* it = m_cache.find( uid, FALSE ); if (!it) return false; return true; } template <class T> void OPimCache<T>::invalidate() { m_cache.clear(); } template <class T> void OPimCache<T>::setSize( int size ) { m_cache.setMaxCost( size ); } template <class T> T OPimCache<T>::find(int uid )const { Item *it = m_cache.find( uid ); if (it) return it->record(); return T(); } template <class T> void OPimCache<T>::add( const T& t ) { Item* it = 0l; it = m_cache.find(t.uid(), FALSE ); if (it ) it->setRecord( t ); it = new Item( t ); if (!m_cache.insert( t.uid(), it ) ) delete it; } template <class T> void OPimCache<T>::remove( int uid ) { m_cache.remove( uid ); } template <class T> void OPimCache<T>::replace( const T& t) { Item *it = m_cache.find( t.uid() ); if ( it ) { it->setRecord( t ); } } #endif diff --git a/libopie/pim/opimmainwindow.cpp b/libopie/pim/opimmainwindow.cpp index 4044bc1..2739e26 100644 --- a/libopie/pim/opimmainwindow.cpp +++ b/libopie/pim/opimmainwindow.cpp @@ -1,138 +1,150 @@ #include <qapplication.h> #include <qdatetime.h> #include <qcopchannel_qws.h> #include <qpe/sound.h> #include <qpe/qcopenvelope_qws.h> +#include <qpe/qpeapplication.h> #include "opimresolver.h" #include "opimmainwindow.h" OPimMainWindow::OPimMainWindow( const QString& service, QWidget* parent, const char* name, WFlags flag ) : QMainWindow( parent, name, flag ), m_rtti(-1), m_service( service ), m_fallBack(0l) { /* * let's generate our QCopChannel */ m_str = QString("QPE/"+m_service).local8Bit(); m_channel= new QCopChannel(m_str, this ); connect(m_channel, SIGNAL(received(const QCString&, const QByteArray& ) ), this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); connect(qApp, SIGNAL(appMessage(const QCString&, const QByteArray& ) ), this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); /* connect flush and reload */ connect(qApp, SIGNAL(flush() ), this, SLOT(flush() ) ); connect(qApp, SIGNAL(reload() ), this, SLOT(reload() ) ); } OPimMainWindow::~OPimMainWindow() { delete m_channel; } QCopChannel* OPimMainWindow::channel() { return m_channel; } void OPimMainWindow::doSetDocument( const QString& ) { } void OPimMainWindow::appMessage( const QCString& cmd, const QByteArray& array ) { + bool needShow = false; /* * create demands to create * a new record... */ QDataStream stream(array, IO_ReadOnly); if ( cmd == "create()" ) { + raise(); int uid = create(); QCopEnvelope e(m_str, "created(int)" ); e << uid; + needShow = true; }else if ( cmd == "remove(int)" ) { int uid; stream >> uid; bool rem = remove( uid ); QCopEnvelope e(m_str, "removed(bool)" ); e << rem; + needShow = true; }else if ( cmd == "beam(int)" ) { int uid; stream >> uid; beam( uid); }else if ( cmd == "show(int)" ) { + raise(); int uid; stream >> uid; show( uid ); + needShow = true; }else if ( cmd == "edit(int)" ) { + raise(); int uid; stream >> uid; edit( uid ); }else if ( cmd == "add(int,QByteArray)" ) { int rtti; QByteArray array; stream >> rtti; stream >> array; m_fallBack = record(rtti, array ); if (!m_fallBack) return; add( *m_fallBack ); delete m_fallBack; }else if ( cmd == "alarm(QDateTime,int)" ) { + raise(); QDateTime dt; int uid; stream >> dt; stream >> uid; qWarning(" Date: %s Uid: %d", dt.toString().latin1(), uid ); QDateTime current = QDateTime::currentDateTime(); if ( current.time().hour() != dt.time().hour() && current.time().minute() != dt.time().minute() ) return; doAlarm( dt, uid ); - + needShow = true; } + + if (needShow ) + QPEApplication::setKeepRunning(); } /* implement the url scripting here */ void OPimMainWindow::setDocument( const QString& str) { doSetDocument( str ); } /* * we now try to get the array demarshalled * check if the rtti matches this one */ OPimRecord* OPimMainWindow::record( int rtti, const QByteArray& array ) { if ( service() != rtti ) return 0l; OPimRecord* record = OPimResolver::self()->record( rtti ); QDataStream str(array, IO_ReadOnly ); if ( !record || !record->loadFromStream(str) ) { delete record; record = 0l; } return record; } /* * get the rtti for the service */ int OPimMainWindow::service() { if ( m_rtti == -1 ) m_rtti = OPimResolver::self()->serviceId( m_service ); return m_rtti; } void OPimMainWindow::doAlarm( const QDateTime&, int ) { } void OPimMainWindow::startAlarm(int count ) { m_alarmCount = count; m_playedCount = 0; Sound::soundAlarm(); m_timerId = startTimer( 5000 ); } void OPimMainWindow::killAlarm() { killTimer( m_timerId ); } void OPimMainWindow::timerEvent( QTimerEvent* e) { if ( m_playedCount <m_alarmCount ) { m_playedCount++; Sound::soundAlarm(); }else { killTimer( e->timerId() ); } } diff --git a/libopie/pim/opimxrefmanager.h b/libopie/pim/opimxrefmanager.h index 39e5eef..c485e98 100644 --- a/libopie/pim/opimxrefmanager.h +++ b/libopie/pim/opimxrefmanager.h @@ -1,41 +1,43 @@ #ifndef OPIM_XREF_MANAGER_H #define OPIM_XREF_MANAGER_H #include <qstringlist.h> #include <opie/opimxref.h> /** * This is a simple manager for * OPimXRefs. * It allows addition, removing, replacing * clearing and 'querying' the XRef... */ class OPimXRefManager { public: OPimXRefManager(); OPimXRefManager( const OPimXRefManager& ); ~OPimXRefManager(); OPimXRefManager& operator=( const OPimXRefManager& ); bool operator==( const OPimXRefManager& ); void add( const OPimXRef& ); void remove( const OPimXRef& ); void replace( const OPimXRef& ); void clear(); /** * apps participating */ QStringList apps()const; OPimXRef::ValueList list()const; OPimXRef::ValueList list( const QString& service )const; OPimXRef::ValueList list( int uid )const; private: OPimXRef::ValueList m_list; + class Private; + Private *d; }; #endif diff --git a/libopie/pim/orecordlist.h b/libopie/pim/orecordlist.h index edcd729..5211f57 100644 --- a/libopie/pim/orecordlist.h +++ b/libopie/pim/orecordlist.h @@ -1,300 +1,306 @@ #ifndef OPIE_RECORD_LIST_H #define OPIE_RECORD_LIST_H #include <qarray.h> #include "otemplatebase.h" #include "opimrecord.h" +class ORecordListIteratorPrivate; /** * Our List Iterator * it behaves like STL or Qt * * for(it = list.begin(); it != list.end(); ++it ) * doSomeCoolStuff( (*it) ); */ template <class T> class ORecordList; template <class T = OPimRecord> class ORecordListIterator { friend class ORecordList<T>; public: typedef OTemplateBase<T> Base; /** * The c'tor used internally from * ORecordList */ ORecordListIterator( const QArray<int>, const Base* ); /** * The standard c'tor */ ORecordListIterator(); ~ORecordListIterator(); ORecordListIterator( const ORecordListIterator& ); ORecordListIterator &operator=(const ORecordListIterator& ); /** * a * operator ;) * use it like this T = (*it); */ T operator*(); ORecordListIterator &operator++(); ORecordListIterator &operator--(); bool operator==( const ORecordListIterator& it ); bool operator!=( const ORecordListIterator& it ); /** * the current item */ uint current()const; /** * the number of items */ uint count()const; /** * sets the current item */ void setCurrent( uint cur ); private: QArray<int> m_uids; uint m_current; const Base* m_temp; bool m_end : 1; T m_record; bool m_direction :1; /* d pointer for future versions */ - class IteratorPrivate; - IteratorPrivate *d; + ORecordListIteratorPrivate *d; }; + +class ORecordListPrivate; /** * The recordlist used as a return type * from OPimAccessTemplate */ template <class T = OPimRecord > class ORecordList { public: typedef OTemplateBase<T> Base; typedef ORecordListIterator<T> Iterator; /** * c'tor */ ORecordList () { } ORecordList( const QArray<int>& ids, const Base* ); ~ORecordList(); /** * the first iterator */ Iterator begin(); /** * the end */ Iterator end(); /** * the number of items in the list */ uint count()const; T operator[]( uint i ); int uidAt(uint i ); - /** + /** * Remove the contact with given uid */ bool remove( int uid ); /* ConstIterator begin()const; ConstIterator end()const; */ private: QArray<int> m_ids; const Base* m_acc; + ORecordListPrivate *d; }; /* ok now implement it */ template <class T> ORecordListIterator<T>::ORecordListIterator() { m_current = 0; m_temp = 0l; m_end = true; m_record = T(); /* forward */ m_direction = TRUE; } template <class T> ORecordListIterator<T>::~ORecordListIterator() { /* nothing to delete */ } template <class T> ORecordListIterator<T>::ORecordListIterator( const ORecordListIterator<T>& it) { // qWarning("ORecordListIterator copy c'tor"); m_uids = it.m_uids; m_current = it.m_current; m_temp = it.m_temp; m_end = it.m_end; m_record = it.m_record; m_direction = it.m_direction; } template <class T> ORecordListIterator<T> &ORecordListIterator<T>::operator=( const ORecordListIterator<T>& it) { m_uids = it.m_uids; m_current = it.m_current; m_temp = it.m_temp; m_end = it.m_end; m_record = it.m_record; return *this; } template <class T> T ORecordListIterator<T>::operator*() { //qWarning("operator* %d %d", m_current, m_uids[m_current] ); if (!m_end ) m_record = m_temp->find( m_uids[m_current], m_uids, m_current, m_direction ? Base::Forward : Base::Reverse ); else m_record = T(); return m_record; } template <class T> ORecordListIterator<T> &ORecordListIterator<T>::operator++() { m_direction = true; if (m_current < m_uids.count() ) { m_end = false; ++m_current; }else m_end = true; return *this; } template <class T> ORecordListIterator<T> &ORecordListIterator<T>::operator--() { m_direction = false; if ( m_current > 0 ) { --m_current; m_end = false; } else m_end = true; return *this; } template <class T> bool ORecordListIterator<T>::operator==( const ORecordListIterator<T>& it ) { /* if both are at we're the same.... */ if ( m_end == it.m_end ) return true; if ( m_uids != it.m_uids ) return false; if ( m_current != it.m_current ) return false; if ( m_temp != it.m_temp ) return false; return true; } template <class T> bool ORecordListIterator<T>::operator!=( const ORecordListIterator<T>& it ) { return !(*this == it ); } template <class T> ORecordListIterator<T>::ORecordListIterator( const QArray<int> uids, const Base* t ) : m_uids( uids ), m_current( 0 ), m_temp( t ), m_end( false ), m_direction( false ) { + /* if the list is empty we're already at the end of the list */ + if (uids.count() == 0 ) + m_end = true; } template <class T> uint ORecordListIterator<T>::current()const { return m_current; } template <class T> void ORecordListIterator<T>::setCurrent( uint cur ) { if( cur < m_uids.count() ) { m_end = false; m_current= cur; } } template <class T> uint ORecordListIterator<T>::count()const { return m_uids.count(); } template <class T> ORecordList<T>::ORecordList( const QArray<int>& ids, const Base* acc ) : m_ids( ids ), m_acc( acc ) { } template <class T> ORecordList<T>::~ORecordList() { /* nothing to do here */ } template <class T> typename ORecordList<T>::Iterator ORecordList<T>::begin() { Iterator it( m_ids, m_acc ); return it; } template <class T> typename ORecordList<T>::Iterator ORecordList<T>::end() { Iterator it( m_ids, m_acc ); it.m_end = true; it.m_current = m_ids.count(); return it; } template <class T> uint ORecordList<T>::count()const { return m_ids.count(); } template <class T> T ORecordList<T>::operator[]( uint i ) { if ( i >= m_ids.count() ) return T(); /* forward */ return m_acc->find( m_ids[i], m_ids, i ); } template <class T> int ORecordList<T>::uidAt( uint i ) { return m_ids[i]; } template <class T> bool ORecordList<T>::remove( int uid ) { QArray<int> copy( m_ids.count() ); int counter = 0; bool ret_val = false; for (uint i = 0; i < m_ids.count(); i++){ if ( m_ids[i] != uid ){ copy[counter++] = m_ids[i]; }else ret_val = true; } copy.resize( counter ); m_ids = copy; return ret_val; } #endif diff --git a/libopie/pim/otemplatebase.h b/libopie/pim/otemplatebase.h index 29fb6ec..cadac74 100644 --- a/libopie/pim/otemplatebase.h +++ b/libopie/pim/otemplatebase.h @@ -1,91 +1,98 @@ #ifndef OPIE_TEMPLATE_BASE_H #define OPIE_TEMPLATE_BASE_H #include <qarray.h> #include <opie/opimrecord.h> /** * Templates do not have a base class, This is why * we've this class * this is here to give us the possibility * to have a common base class * You may not want to use that interface internaly * POOR mans interface */ +class OPimBasePrivate; struct OPimBase { /** * return the rtti */ virtual int rtti()= 0; virtual OPimRecord* record()const = 0; virtual OPimRecord* record(int uid)const = 0; virtual bool add( const OPimRecord& ) = 0; virtual bool remove( int uid ) = 0; virtual bool remove( const OPimRecord& ) = 0; virtual void clear() = 0; virtual bool load() = 0; virtual bool save() = 0; virtual QArray<int> records()const = 0; /* * ADD editing here? * -zecke */ +private: + OPimBasePrivate* d; }; /** * internal template base * T needs to implement the copy c'tor!!! */ +class OTemplateBasePrivate; template <class T = OPimRecord> class OTemplateBase : public OPimBase { public: enum CacheDirection { Forward=0, Reverse }; OTemplateBase() { }; virtual ~OTemplateBase() { } virtual T find( int uid )const = 0; /** * read ahead find */ virtual T find( int uid, const QArray<int>& items, uint current, CacheDirection dir = Forward )const = 0; virtual void cache( const T& )const = 0; virtual void setSaneCacheSize( int ) = 0; /* reimplement of OPimBase */ int rtti(); OPimRecord* record()const; OPimRecord* record(int uid )const; static T* rec(); + +private: + OTemplateBasePrivate *d; }; /* * implementation */ template <class T> int OTemplateBase<T>::rtti() { return T::rtti(); } template <class T> OPimRecord* OTemplateBase<T>::record()const { T* t = new T; return t; } template <class T> OPimRecord* OTemplateBase<T>::record(int uid )const { T t2 = find(uid ); T* t1 = new T(t2); return t1; }; template <class T> T* OTemplateBase<T>::rec() { return new T; } #endif diff --git a/libopie/pim/otodo.cpp b/libopie/pim/otodo.cpp index 38b93f7..5a18c37 100644 --- a/libopie/pim/otodo.cpp +++ b/libopie/pim/otodo.cpp @@ -1,516 +1,520 @@ #include <qobject.h> #include <qshared.h> #include <qpe/palmtopuidgen.h> #include <qpe/stringutil.h> #include <qpe/palmtoprecord.h> #include <qpe/stringutil.h> #include <qpe/categories.h> #include <qpe/categoryselect.h> #include "opimstate.h" #include "orecur.h" #include "opimmaintainer.h" #include "opimnotifymanager.h" #include "opimresolver.h" #include "otodo.h" struct OTodo::OTodoData : public QShared { OTodoData() : QShared() { recur = 0; state = 0; maintainer = 0; notifiers = 0; }; + ~OTodoData() { + delete recur; + delete maintainer; + delete notifiers; + } QDate date; bool isCompleted:1; bool hasDate:1; int priority; QString desc; QString sum; QMap<QString, QString> extra; ushort prog; OPimState *state; ORecur *recur; OPimMaintainer *maintainer; QDate start; QDate completed; OPimNotifyManager *notifiers; }; OTodo::OTodo(const OTodo &event ) : OPimRecord( event ), data( event.data ) { data->ref(); // qWarning("ref up"); } OTodo::~OTodo() { // qWarning("~OTodo " ); if ( data->deref() ) { // qWarning("OTodo::dereffing"); delete data; data = 0l; } } OTodo::OTodo(bool completed, int priority, const QArray<int> &category, const QString& summary, const QString &description, ushort progress, bool hasDate, QDate date, int uid ) : OPimRecord( uid ) { // qWarning("OTodoData " + summary); setCategories( category ); data = new OTodoData; data->date = date; data->isCompleted = completed; data->hasDate = hasDate; data->priority = priority; data->sum = summary; data->prog = progress; data->desc = Qtopia::simplifyMultiLineSpace(description ); } OTodo::OTodo(bool completed, int priority, const QStringList &category, const QString& summary, const QString &description, ushort progress, bool hasDate, QDate date, int uid ) : OPimRecord( uid ) { // qWarning("OTodoData" + summary); setCategories( idsFromString( category.join(";") ) ); data = new OTodoData; data->date = date; data->isCompleted = completed; data->hasDate = hasDate; data->priority = priority; data->sum = summary; data->prog = progress; data->desc = Qtopia::simplifyMultiLineSpace(description ); } bool OTodo::match( const QRegExp ®Exp )const { if( QString::number( data->priority ).find( regExp ) != -1 ){ setLastHitField( Priority ); return true; }else if( data->hasDate && data->date.toString().find( regExp) != -1 ){ setLastHitField( HasDate ); return true; }else if(data->desc.find( regExp ) != -1 ){ setLastHitField( Description ); return true; }else if(data->sum.find( regExp ) != -1 ) { setLastHitField( Summary ); return true; } return false; } bool OTodo::isCompleted() const { return data->isCompleted; } bool OTodo::hasDueDate() const { return data->hasDate; } bool OTodo::hasStartDate()const { return data->start.isValid(); } bool OTodo::hasCompletedDate()const { return data->completed.isValid(); } int OTodo::priority()const { return data->priority; } QString OTodo::summary() const { return data->sum; } ushort OTodo::progress() const { return data->prog; } QDate OTodo::dueDate()const { return data->date; } QDate OTodo::startDate()const { return data->start; } QDate OTodo::completedDate()const { return data->completed; } QString OTodo::description()const { return data->desc; } bool OTodo::hasState() const{ if (!data->state ) return false; return ( data->state->state() != OPimState::Undefined ); } OPimState OTodo::state()const { if (!data->state ) { OPimState state; return state; } return (*data->state); } bool OTodo::hasRecurrence()const { if (!data->recur) return false; return data->recur->doesRecur(); } ORecur OTodo::recurrence()const { if (!data->recur) return ORecur(); return (*data->recur); } bool OTodo::hasMaintainer()const { if (!data->maintainer) return false; return (data->maintainer->mode() != OPimMaintainer::Undefined ); } OPimMaintainer OTodo::maintainer()const { if (!data->maintainer) return OPimMaintainer(); return (*data->maintainer); } void OTodo::setCompleted( bool completed ) { changeOrModify(); data->isCompleted = completed; } void OTodo::setHasDueDate( bool hasDate ) { changeOrModify(); data->hasDate = hasDate; } void OTodo::setDescription(const QString &desc ) { // qWarning( "desc " + desc ); changeOrModify(); data->desc = Qtopia::simplifyMultiLineSpace(desc ); } void OTodo::setSummary( const QString& sum ) { changeOrModify(); data->sum = sum; } void OTodo::setPriority(int prio ) { changeOrModify(); data->priority = prio; } void OTodo::setDueDate( const QDate& date ) { changeOrModify(); data->date = date; } void OTodo::setStartDate( const QDate& date ) { changeOrModify(); data->start = date; } void OTodo::setCompletedDate( const QDate& date ) { changeOrModify(); data->completed = date; } void OTodo::setState( const OPimState& state ) { changeOrModify(); if (data->state ) (*data->state) = state; else data->state = new OPimState( state ); } void OTodo::setRecurrence( const ORecur& rec) { changeOrModify(); if (data->recur ) (*data->recur) = rec; else data->recur = new ORecur( rec ); } void OTodo::setMaintainer( const OPimMaintainer& pim ) { changeOrModify(); if (data->maintainer ) (*data->maintainer) = pim; else data->maintainer = new OPimMaintainer( pim ); } bool OTodo::isOverdue( ) { if( data->hasDate && !data->isCompleted) return QDate::currentDate() > data->date; return false; } void OTodo::setProgress(ushort progress ) { changeOrModify(); data->prog = progress; } QString OTodo::toShortText() const { return summary(); } /*! Returns a richt text string */ QString OTodo::toRichText() const { QString text; QStringList catlist; // summary - text += "<b><h3><img src=\"todo/TodoList\">"; + text += "<b><h3><img src=\"todo/TodoList\"> "; if ( !summary().isEmpty() ) { text += Qtopia::escapeString(summary() ).replace(QRegExp( "[\n]"), "" ); } text += "</h3></b><br><hr><br>"; // description if( !description().isEmpty() ){ - text += "<b>" + QObject::tr( "Description:" ) + "</b><br>"; - text += Qtopia::escapeString(description() ).replace(QRegExp( "[\n]"), "<br>" ) ; + text += "<b>" + QObject::tr( "Notes:" ) + "</b><br>"; + text += Qtopia::escapeString(description() ).replace(QRegExp( "[\n]"), "<br>" ) + "<br>"; } // priority int priorityval = priority(); text += "<b>" + QObject::tr( "Priority:") +" </b><img src=\"todo/priority" + - QString::number( priorityval ) + "\">"; -// text += "<b>" + QObject::tr( "Priority:") +"</b><img src=\"todo/priority" + -// QString::number( priority() ) + "\"><br>"; + QString::number( priorityval ) + "\"> "; + switch ( priorityval ) { case 1 : text += QObject::tr( "Very high" ); break; case 2 : text += QObject::tr( "High" ); break; case 3 : text += QObject::tr( "Normal" ); break; case 4 : text += QObject::tr( "Low" ); break; case 5 : text += QObject::tr( "Very low" ); break; }; text += "<br>"; // progress text += "<b>" + QObject::tr( "Progress:") + " </b>" + QString::number( progress() ) + " %<br>"; // due date if (hasDueDate() ){ QDate dd = dueDate(); int off = QDate::currentDate().daysTo( dd ); text += "<b>" + QObject::tr( "Deadline:" ) + " </b><font color=\""; if ( off < 0 ) text += "#FF0000"; else if ( off == 0 ) text += "#FFFF00"; else if ( off > 0 ) text += "#00FF00"; text += "\">" + dd.toString() + "</font><br>"; } // categories text += "<b>" + QObject::tr( "Category:") + "</b> "; text += categoryNames( "Todo List" ).join(", "); text += "<br>"; return text; } bool OTodo::hasNotifiers()const { if (!data->notifiers) return false; return !data->notifiers->isEmpty(); } OPimNotifyManager& OTodo::notifiers() { if (!data->notifiers ) data->notifiers = new OPimNotifyManager; return (*data->notifiers); } const OPimNotifyManager& OTodo::notifiers()const{ if (!data->notifiers ) data->notifiers = new OPimNotifyManager; return (*data->notifiers); } bool OTodo::operator<( const OTodo &toDoEvent )const{ if( !hasDueDate() && !toDoEvent.hasDueDate() ) return true; if( !hasDueDate() && toDoEvent.hasDueDate() ) return false; if( hasDueDate() && toDoEvent.hasDueDate() ){ if( dueDate() == toDoEvent.dueDate() ){ // let's the priority decide return priority() < toDoEvent.priority(); }else{ return dueDate() < toDoEvent.dueDate(); } } return false; } bool OTodo::operator<=(const OTodo &toDoEvent )const { if( !hasDueDate() && !toDoEvent.hasDueDate() ) return true; if( !hasDueDate() && toDoEvent.hasDueDate() ) return true; if( hasDueDate() && toDoEvent.hasDueDate() ){ if( dueDate() == toDoEvent.dueDate() ){ // let's the priority decide return priority() <= toDoEvent.priority(); }else{ return dueDate() <= toDoEvent.dueDate(); } } return true; } bool OTodo::operator>(const OTodo &toDoEvent )const { if( !hasDueDate() && !toDoEvent.hasDueDate() ) return false; if( !hasDueDate() && toDoEvent.hasDueDate() ) return false; if( hasDueDate() && toDoEvent.hasDueDate() ){ if( dueDate() == toDoEvent.dueDate() ){ // let's the priority decide return priority() > toDoEvent.priority(); }else{ return dueDate() > toDoEvent.dueDate(); } } return false; } bool OTodo::operator>=(const OTodo &toDoEvent )const { if( !hasDueDate() && !toDoEvent.hasDueDate() ) return true; if( !hasDueDate() && toDoEvent.hasDueDate() ) return false; if( hasDueDate() && toDoEvent.hasDueDate() ){ if( dueDate() == toDoEvent.dueDate() ){ // let's the priority decide return priority() > toDoEvent.priority(); }else{ return dueDate() > toDoEvent.dueDate(); } } return true; } bool OTodo::operator==(const OTodo &toDoEvent )const { if ( data->priority != toDoEvent.data->priority ) return false; if ( data->priority != toDoEvent.data->prog ) return false; if ( data->isCompleted != toDoEvent.data->isCompleted ) return false; if ( data->hasDate != toDoEvent.data->hasDate ) return false; if ( data->date != toDoEvent.data->date ) return false; if ( data->sum != toDoEvent.data->sum ) return false; if ( data->desc != toDoEvent.data->desc ) return false; if ( data->maintainer != toDoEvent.data->maintainer ) return false; return OPimRecord::operator==( toDoEvent ); } void OTodo::deref() { // qWarning("deref in ToDoEvent"); if ( data->deref() ) { // qWarning("deleting"); delete data; data= 0; } } OTodo &OTodo::operator=(const OTodo &item ) { if ( this == &item ) return *this; OPimRecord::operator=( item ); //qWarning("operator= ref "); item.data->ref(); deref(); data = item.data; return *this; } QMap<int, QString> OTodo::toMap() const { QMap<int, QString> map; map.insert( Uid, QString::number( uid() ) ); map.insert( Category, idsToString( categories() ) ); map.insert( HasDate, QString::number( data->hasDate ) ); map.insert( Completed, QString::number( data->isCompleted ) ); map.insert( Description, data->desc ); map.insert( Summary, data->sum ); map.insert( Priority, QString::number( data->priority ) ); map.insert( DateDay, QString::number( data->date.day() ) ); map.insert( DateMonth, QString::number( data->date.month() ) ); map.insert( DateYear, QString::number( data->date.year() ) ); map.insert( Progress, QString::number( data->prog ) ); // map.insert( CrossReference, crossToString() ); /* FIXME!!! map.insert( State, ); map.insert( Recurrence, ); map.insert( Reminders, ); map. */ return map; } /** * change or modify looks at the ref count and either * creates a new QShared Object or it can modify it * right in place */ void OTodo::changeOrModify() { if ( data->count != 1 ) { qWarning("changeOrModify"); data->deref(); OTodoData* d2 = new OTodoData(); copy(data, d2 ); data = d2; } } // WATCHOUT /* * if you add something to the Data struct * be sure to copy it here */ void OTodo::copy( OTodoData* src, OTodoData* dest ) { dest->date = src->date; dest->isCompleted = src->isCompleted; dest->hasDate = src->hasDate; dest->priority = src->priority; dest->desc = src->desc; dest->sum = src->sum; dest->extra = src->extra; dest->prog = src->prog; if (src->state ) dest->state = new OPimState( *src->state ); if (src->recur ) dest->recur = new ORecur( *src->recur ); if (src->maintainer ) dest->maintainer = new OPimMaintainer( *src->maintainer ) ; dest->start = src->start; dest->completed = src->completed; if (src->notifiers ) dest->notifiers = new OPimNotifyManager( *src->notifiers ); } QString OTodo::type() const { return QString::fromLatin1("OTodo"); } QString OTodo::recordField(int /*id*/ )const { return QString::null; } int OTodo::rtti(){ return OPimResolver::TodoList; } diff --git a/libopie/pim/otodo.h b/libopie/pim/otodo.h index f9a345a..6df98b9 100644 --- a/libopie/pim/otodo.h +++ b/libopie/pim/otodo.h @@ -1,294 +1,285 @@ #ifndef OPIE_TODO_EVENT_H #define OPIE_TODO_EVENT_H #include <qarray.h> #include <qmap.h> #include <qregexp.h> #include <qstringlist.h> #include <qdatetime.h> #include <qvaluelist.h> #include <qpe/recordfields.h> #include <qpe/palmtopuidgen.h> #include <opie/opimrecord.h> class OPimState; class ORecur; class OPimMaintainer; class OPimNotifyManager; class OTodo : public OPimRecord { public: typedef QValueList<OTodo> ValueList; enum RecordFields { Uid = Qtopia::UID_ID, Category = Qtopia::CATEGORY_ID, HasDate, Completed, Description, Summary, Priority, DateDay, DateMonth, DateYear, Progress, CrossReference, State, Recurrence, Alarms, Reminders, Notifiers, Maintainer, StartDate, CompletedDate }; public: // priorities from Very low to very high enum TaskPriority { VeryHigh=1, High, Normal, Low, VeryLow }; /* Constructs a new ToDoEvent @param completed Is the TodoEvent completed @param priority What is the priority of this ToDoEvent @param category Which category does it belong( uid ) @param summary A small summary of the todo @param description What is this ToDoEvent about @param hasDate Does this Event got a deadline @param date what is the deadline? @param uid what is the UUID of this Event **/ OTodo( bool completed = false, int priority = Normal, const QStringList &category = QStringList(), const QString &summary = QString::null , const QString &description = QString::null, ushort progress = 0, bool hasDate = false, QDate date = QDate::currentDate(), int uid = 0 /*empty*/ ); OTodo( bool completed, int priority, const QArray<int>& category, const QString& summary = QString::null, const QString& description = QString::null, ushort progress = 0, bool hasDate = false, QDate date = QDate::currentDate(), int uid = 0 /* empty */ ); /** Copy c'tor * */ OTodo(const OTodo & ); /** *destructor */ ~OTodo(); /** * Is this event completed? */ bool isCompleted() const; /** * Does this Event have a deadline */ bool hasDueDate() const; bool hasStartDate()const; bool hasCompletedDate()const; /** - * Does this Event has an alarm time ? - */ - bool hasAlarmDateTime() const; - - /** * What is the priority? */ int priority()const ; /** * progress as ushort 0, 20, 40, 60, 80 or 100% */ ushort progress() const; /** * The due Date */ QDate dueDate()const; /** * When did it start? */ QDate startDate()const; /** * When was it completed? */ QDate completedDate()const; /** * does it have a state? */ bool hasState()const; /** * What is the state of this OTodo? */ OPimState state()const; /** * has recurrence? */ bool hasRecurrence()const; /** * the recurrance of this */ ORecur recurrence()const; /** * does this OTodo have a maintainer? */ bool hasMaintainer()const; /** * the Maintainer of this OTodo */ OPimMaintainer maintainer()const; /** * The description of the todo */ QString description()const; /** * A small summary of the todo */ QString summary() const; /** * @reimplemented * Return this todoevent in a RichText formatted QString */ QString toRichText() const; bool hasNotifiers()const; /* * FIXME check if the sharing is still fine!! -zecke * ### CHECK If API is fine */ /** * return a reference to our notifiers... */ OPimNotifyManager ¬ifiers(); /** * */ const OPimNotifyManager ¬ifiers()const; /** * reimplementations */ QString type()const; QString toShortText()const; QString recordField(int id )const; /** * toMap puts all data into the map. int relates * to ToDoEvent RecordFields enum */ QMap<int, QString> toMap()const; /** * Set if this Todo is completed */ void setCompleted(bool completed ); /** * set if this todo got an end data */ void setHasDueDate( bool hasDate ); // FIXME we do not have these for start, completed // cause we'll use the isNull() of QDate for figuring // out if it's has a date... // decide what to do here? -zecke /** * Set the priority of the Todo */ void setPriority(int priority ); /** * Set the progress. */ void setProgress( ushort progress ); /** * set the end date */ void setDueDate( const QDate& date ); /** * set the start date */ void setStartDate( const QDate& date ); /** * set the completed date */ void setCompletedDate( const QDate& date ); void setRecurrence( const ORecur& ); - /** - * set the alarm time - */ - void setAlarmDateTime ( const QDateTime& alarm ); void setDescription(const QString& ); void setSummary(const QString& ); /** * set the state of a Todo * @param state State what the todo should take */ void setState( const OPimState& state); /** * set the Maintainer Mode */ void setMaintainer( const OPimMaintainer& ); bool isOverdue(); virtual bool match( const QRegExp &r )const; bool operator<(const OTodo &toDoEvent )const; bool operator<=(const OTodo &toDoEvent )const; bool operator!=(const OTodo &toDoEvent )const; bool operator>(const OTodo &toDoEvent )const; bool operator>=(const OTodo &toDoEvent)const; bool operator==(const OTodo &toDoEvent )const; OTodo &operator=(const OTodo &toDoEvent ); static int rtti(); private: class OTodoPrivate; struct OTodoData; void deref(); inline void changeOrModify(); void copy( OTodoData* src, OTodoData* dest ); OTodoPrivate *d; OTodoData *data; }; inline bool OTodo::operator!=(const OTodo &toDoEvent )const { return !(*this == toDoEvent); } #endif diff --git a/libopie/pim/otodoaccessbackend.h b/libopie/pim/otodoaccessbackend.h index 05e8ca9..6be95bc 100644 --- a/libopie/pim/otodoaccessbackend.h +++ b/libopie/pim/otodoaccessbackend.h @@ -1,24 +1,28 @@ #ifndef OPIE_TODO_ACCESS_BACKEND_H #define OPIE_TODO_ACCESS_BACKEND_H #include <qbitarray.h> #include "otodo.h" #include "opimaccessbackend.h" class OTodoAccessBackend : public OPimAccessBackend<OTodo> { public: OTodoAccessBackend(); ~OTodoAccessBackend(); virtual QArray<int> effectiveToDos( const QDate& start, const QDate& end, bool includeNoDates ) = 0; virtual QArray<int> overDue() = 0; virtual QArray<int> sorted( bool asc, int sortOrder, int sortFilter, int cat ) = 0; virtual void removeAllCompleted() = 0; virtual QBitArray supports()const = 0; + +private: + class Private; + Private *d; }; #endif diff --git a/libopie/pim/otodoaccessvcal.cpp b/libopie/pim/otodoaccessvcal.cpp index 3577e14..6415952 100644 --- a/libopie/pim/otodoaccessvcal.cpp +++ b/libopie/pim/otodoaccessvcal.cpp @@ -1,225 +1,249 @@ #include <qfile.h> #include <qtopia/private/vobject_p.h> #include <qtopia/timeconversion.h> #include <qtopia/private/qfiledirect_p.h> #include "otodoaccessvcal.h" namespace { static OTodo eventByVObj( VObject *obj ){ OTodo event; VObject *ob; QCString name; // no uid, attendees, ... and no fun // description if( ( ob = isAPropertyOf( obj, VCDescriptionProp )) != 0 ){ name = vObjectStringZValue( ob ); +#if 0 event.setDescription( name ); +#else + event.setSummary( name ); +#endif } // summary if ( ( ob = isAPropertyOf( obj, VCSummaryProp ) ) != 0 ) { name = vObjectStringZValue( ob ); +#if 0 event.setSummary( name ); +#else + event.setDescription( name ); +#endif } // completed if( ( ob = isAPropertyOf( obj, VCStatusProp )) != 0 ){ name = vObjectStringZValue( ob ); if( name == "COMPLETED" ){ event.setCompleted( true ); }else{ event.setCompleted( false ); } }else event.setCompleted( false ); // priority if ((ob = isAPropertyOf(obj, VCPriorityProp))) { name = vObjectStringZValue( ob ); bool ok; event.setPriority(name.toInt(&ok) ); } //due date if((ob = isAPropertyOf(obj, VCDueProp)) ){ event.setHasDueDate( true ); name = vObjectStringZValue( ob ); event.setDueDate( TimeConversion::fromISO8601( name).date() ); } // categories if((ob = isAPropertyOf( obj, VCCategoriesProp )) != 0 ){ name = vObjectStringZValue( ob ); qWarning("Categories:%s", name.data() ); } event.setUid( 1 ); return event; }; static VObject *vobjByEvent( const OTodo &event ) { VObject *task = newVObject( VCTodoProp ); if( task == 0 ) return 0l; if( event.hasDueDate() ) { QTime time(0, 0, 0); QDateTime date(event.dueDate(), time ); addPropValue( task, VCDueProp, TimeConversion::toISO8601( date ) ); } if( event.isCompleted() ) addPropValue( task, VCStatusProp, "COMPLETED"); QString string = QString::number(event.priority() ); addPropValue( task, VCPriorityProp, string.local8Bit() ); addPropValue( task, VCCategoriesProp, event.idsToString( event.categories() ).local8Bit() ); +#if 0 + + // There seems a misrepresentation between summary in otodoevent + // and summary in vcard. + // The same with description.. + // Description is summary and vice versa.. Argh.. (eilers) + + addPropValue( task, VCDescriptionProp, event.description().local8Bit() ); addPropValue( task, VCSummaryProp, event.summary().local8Bit() ); + +#else + addPropValue( task, VCDescriptionProp, + event.summary().local8Bit() ); + + addPropValue( task, VCSummaryProp, + event.description().local8Bit() ); +#endif return task; }; } OTodoAccessVCal::OTodoAccessVCal( const QString& path ) : m_dirty(false), m_file( path ) { } OTodoAccessVCal::~OTodoAccessVCal() { } bool OTodoAccessVCal::load() { m_map.clear(); m_dirty = false; VObject* vcal = 0l; vcal = Parse_MIME_FromFileName( QFile::encodeName(m_file).data() ); if (!vcal ) return false; // Iterate over the list VObjectIterator it; VObject* vobj; initPropIterator(&it, vcal); while( moreIteration( &it ) ) { vobj = ::nextVObject( &it ); QCString name = ::vObjectName( vobj ); if( name == VCTodoProp ){ OTodo to = eventByVObj( vobj ); m_map.insert( to.uid(), to ); } } // Should I do a delete vcal? return true; } bool OTodoAccessVCal::reload() { return load(); } bool OTodoAccessVCal::save() { if (!m_dirty ) return true; QFileDirect file( m_file ); if (!file.open(IO_WriteOnly ) ) return false; VObject *obj; obj = newVObject( VCCalProp ); addPropValue( obj, VCVersionProp, "1.0" ); VObject *vo; for(QMap<int, OTodo>::ConstIterator it=m_map.begin(); it !=m_map.end(); ++it ){ vo = vobjByEvent( it.data() ); addVObjectProp(obj, vo ); } writeVObject( file.directHandle(), obj ); cleanVObject( obj ); cleanStrTbl(); m_dirty = false; return true; } void OTodoAccessVCal::clear() { m_map.clear(); m_dirty = true; } bool OTodoAccessVCal::add( const OTodo& to ) { m_map.insert( to.uid(), to ); m_dirty = true; return true; } bool OTodoAccessVCal::remove( int uid ) { m_map.remove( uid ); m_dirty = true; return true; } void OTodoAccessVCal::removeAllCompleted() { for ( QMap<int, OTodo>::Iterator it = m_map.begin(); it != m_map.end(); ++it ) { if ( (*it).isCompleted() ) m_map.remove( it ); } } bool OTodoAccessVCal::replace( const OTodo& to ) { m_map.replace( to.uid(), to ); m_dirty = true; return true; } OTodo OTodoAccessVCal::find(int uid )const { return m_map[uid]; } QArray<int> OTodoAccessVCal::sorted( bool, int, int, int ) { QArray<int> ar(0); return ar; } QArray<int> OTodoAccessVCal::allRecords()const { QArray<int> ar( m_map.count() ); QMap<int, OTodo>::ConstIterator it; int i = 0; for ( it = m_map.begin(); it != m_map.end(); ++it ) { ar[i] = it.key(); i++; } return ar; } -QArray<int> OTodoAccessVCal::matchRegexp(const QRegExp &r)const { +QArray<int> OTodoAccessVCal::matchRegexp(const QRegExp& /* r */)const { QArray<int> ar(0); return ar; } QArray<int> OTodoAccessVCal::queryByExample( const OTodo&, int, const QDateTime& ) { QArray<int> ar(0); return ar; } QArray<int> OTodoAccessVCal::effectiveToDos( const QDate& , const QDate& , bool ) { QArray<int> ar(0); return ar; } QArray<int> OTodoAccessVCal::overDue() { QArray<int> ar(0); return ar; } QBitArray OTodoAccessVCal::supports()const { static QBitArray ar = sup(); return ar; } QBitArray OTodoAccessVCal::sup() { QBitArray ar ( OTodo::CompletedDate +1 ); ar.fill( true ); ar[OTodo::CrossReference] = false; ar[OTodo::State ] = false; ar[OTodo::Reminders] = false; ar[OTodo::Notifiers] = false; ar[OTodo::Maintainer] = false; ar[OTodo::Progress] = false; ar[OTodo::Alarms ] = false; ar[OTodo::Recurrence] = false; return ar; } diff --git a/libopie/pim/otodoaccessxml.cpp b/libopie/pim/otodoaccessxml.cpp index 3d15354..f688735 100644 --- a/libopie/pim/otodoaccessxml.cpp +++ b/libopie/pim/otodoaccessxml.cpp @@ -1,874 +1,876 @@ #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <qfile.h> #include <qvector.h> #include <qpe/global.h> #include <qpe/stringutil.h> #include <qpe/timeconversion.h> #include "oconversion.h" #include "opimstate.h" #include "otimezone.h" #include "opimnotifymanager.h" #include "orecur.h" #include "otodoaccessxml.h" namespace { time_t rp_end; ORecur* rec; ORecur *recur() { if (!rec ) rec = new ORecur; return rec; } int snd; enum MoreAttributes { FRType = OTodo::CompletedDate + 2, FRWeekdays, FRPosition, FRFreq, FRHasEndDate, FREndDate, FRStart, FREnd }; // FROM TT again char *strstrlen(const char *haystack, int hLen, const char* needle, int nLen) { char needleChar; char haystackChar; if (!needle || !haystack || !hLen || !nLen) return 0; const char* hsearch = haystack; if ((needleChar = *needle++) != 0) { nLen--; //(to make up for needle++) do { do { if ((haystackChar = *hsearch++) == 0) return (0); if (hsearch >= haystack + hLen) return (0); } while (haystackChar != needleChar); } while (strncmp(hsearch, needle, QMIN(hLen - (hsearch - haystack), nLen)) != 0); hsearch--; } return ((char *)hsearch); } } OTodoAccessXML::OTodoAccessXML( const QString& appName, const QString& fileName ) : OTodoAccessBackend(), m_app( appName ), m_opened( false ), m_changed( false ) { if (!fileName.isEmpty() ) m_file = fileName; else m_file = Global::applicationFileName( "todolist", "todolist.xml" ); } OTodoAccessXML::~OTodoAccessXML() { } bool OTodoAccessXML::load() { rec = 0; m_opened = true; m_changed = false; /* initialize dict */ /* * UPDATE dict if you change anything!!! */ - QAsciiDict<int> dict(21); + QAsciiDict<int> dict(26); dict.setAutoDelete( TRUE ); dict.insert("Categories" , new int(OTodo::Category) ); dict.insert("Uid" , new int(OTodo::Uid) ); dict.insert("HasDate" , new int(OTodo::HasDate) ); dict.insert("Completed" , new int(OTodo::Completed) ); dict.insert("Description" , new int(OTodo::Description) ); dict.insert("Summary" , new int(OTodo::Summary) ); dict.insert("Priority" , new int(OTodo::Priority) ); dict.insert("DateDay" , new int(OTodo::DateDay) ); dict.insert("DateMonth" , new int(OTodo::DateMonth) ); dict.insert("DateYear" , new int(OTodo::DateYear) ); dict.insert("Progress" , new int(OTodo::Progress) ); dict.insert("CompletedDate", new int(OTodo::CompletedDate) ); dict.insert("StartDate", new int(OTodo::StartDate) ); dict.insert("CrossReference", new int(OTodo::CrossReference) ); dict.insert("State", new int(OTodo::State) ); dict.insert("Alarms", new int(OTodo::Alarms) ); dict.insert("Reminders", new int(OTodo::Reminders) ); dict.insert("Notifiers", new int(OTodo::Notifiers) ); dict.insert("Maintainer", new int(OTodo::Maintainer) ); dict.insert("rtype", new int(FRType) ); dict.insert("rweekdays", new int(FRWeekdays) ); dict.insert("rposition", new int(FRPosition) ); dict.insert("rfreq", new int(FRFreq) ); dict.insert("start", new int(FRStart) ); dict.insert("rhasenddate", new int(FRHasEndDate) ); dict.insert("enddt", new int(FREndDate) ); // here the custom XML parser from TT it's GPL // but we want to push OpiePIM... to TT..... // mmap part from zecke :) int fd = ::open( QFile::encodeName(m_file).data(), O_RDONLY ); struct stat attribut; if ( fd < 0 ) return false; if ( fstat(fd, &attribut ) == -1 ) { ::close( fd ); return false; } void* map_addr = ::mmap(NULL, attribut.st_size, PROT_READ, MAP_SHARED, fd, 0 ); if ( map_addr == ( (caddr_t)-1) ) { ::close(fd ); return false; } /* advise the kernel who we want to read it */ ::madvise( map_addr, attribut.st_size, MADV_SEQUENTIAL ); /* we do not the file any more */ ::close( fd ); char* dt = (char*)map_addr; int len = attribut.st_size; int i = 0; char *point; const char* collectionString = "<Task "; int strLen = strlen(collectionString); while ( ( point = strstrlen( dt+i, len -i, collectionString, strLen ) ) != 0l ) { i = point -dt; i+= strLen; qWarning("Found a start at %d %d", i, (point-dt) ); OTodo ev; m_year = m_month = m_day = 0; while ( TRUE ) { while ( i < len && (dt[i] == ' ' || dt[i] == '\n' || dt[i] == '\r') ) ++i; if ( i >= len-2 || (dt[i] == '/' && dt[i+1] == '>') ) break; // we have another attribute, read it. int j = i; while ( j < len && dt[j] != '=' ) ++j; QCString attr( dt+i, j-i+1); i = ++j; // skip = // find the start of quotes while ( i < len && dt[i] != '"' ) ++i; j = ++i; bool haveUtf = FALSE; bool haveEnt = FALSE; while ( j < len && dt[j] != '"' ) { if ( ((unsigned char)dt[j]) > 0x7f ) haveUtf = TRUE; if ( dt[j] == '&' ) haveEnt = TRUE; ++j; } if ( i == j ) { // empty value i = j + 1; continue; } QCString value( dt+i, j-i+1 ); i = j + 1; QString str = (haveUtf ? QString::fromUtf8( value ) : QString::fromLatin1( value ) ); if ( haveEnt ) str = Qtopia::plainString( str ); /* * add key + value */ todo( &dict, ev, attr, str ); } /* * now add it */ qWarning("End at %d", i ); if (m_events.contains( ev.uid() ) || ev.uid() == 0) { ev.setUid( 1 ); m_changed = true; } if ( ev.hasDueDate() ) { ev.setDueDate( QDate(m_year, m_month, m_day) ); } if ( rec && rec->doesRecur() ) { OTimeZone utc = OTimeZone::utc(); ORecur recu( *rec ); // call copy c'tor recu.setEndDate( utc.fromUTCDateTime( rp_end ).date() ); recu.setStart( ev.dueDate() ); ev.setRecurrence( recu ); } m_events.insert(ev.uid(), ev ); m_year = m_month = m_day = -1; delete rec; rec = 0; } munmap(map_addr, attribut.st_size ); qWarning("counts %d records loaded!", m_events.count() ); return true; } bool OTodoAccessXML::reload() { m_events.clear(); return load(); } bool OTodoAccessXML::save() { // qWarning("saving"); if (!m_opened || !m_changed ) { // qWarning("not saving"); return true; } QString strNewFile = m_file + ".new"; QFile f( strNewFile ); if (!f.open( IO_WriteOnly|IO_Raw ) ) return false; int written; QString out; out = "<!DOCTYPE Tasks>\n<Tasks>\n"; // for all todos QMap<int, OTodo>::Iterator it; for (it = m_events.begin(); it != m_events.end(); ++it ) { out+= "<Task " + toString( (*it) ) + " />\n"; QCString cstr = out.utf8(); written = f.writeBlock( cstr.data(), cstr.length() ); /* less written then we wanted */ if ( written != (int)cstr.length() ) { f.close(); QFile::remove( strNewFile ); return false; } out = QString::null; } out += "</Tasks>"; QCString cstr = out.utf8(); written = f.writeBlock( cstr.data(), cstr.length() ); if ( written != (int)cstr.length() ) { f.close(); QFile::remove( strNewFile ); return false; } /* flush before renaming */ f.close(); if( ::rename( strNewFile.latin1(), m_file.latin1() ) < 0 ) { // qWarning("error renaming"); QFile::remove( strNewFile ); } m_changed = false; return true; } QArray<int> OTodoAccessXML::allRecords()const { QArray<int> ids( m_events.count() ); QMap<int, OTodo>::ConstIterator it; int i = 0; for ( it = m_events.begin(); it != m_events.end(); ++it ) { ids[i] = it.key(); i++; } return ids; } QArray<int> OTodoAccessXML::queryByExample( const OTodo&, int, const QDateTime& ) { QArray<int> ids(0); return ids; } OTodo OTodoAccessXML::find( int uid )const { OTodo todo; todo.setUid( 0 ); // isEmpty() QMap<int, OTodo>::ConstIterator it = m_events.find( uid ); if ( it != m_events.end() ) todo = it.data(); return todo; } void OTodoAccessXML::clear() { if (m_opened ) m_changed = true; m_events.clear(); } bool OTodoAccessXML::add( const OTodo& todo ) { // qWarning("add"); m_changed = true; m_events.insert( todo.uid(), todo ); return true; } bool OTodoAccessXML::remove( int uid ) { m_changed = true; m_events.remove( uid ); return true; } bool OTodoAccessXML::replace( const OTodo& todo) { m_changed = true; m_events.replace( todo.uid(), todo ); return true; } QArray<int> OTodoAccessXML::effectiveToDos( const QDate& start, const QDate& end, bool includeNoDates ) { QArray<int> ids( m_events.count() ); QMap<int, OTodo>::Iterator it; int i = 0; for ( it = m_events.begin(); it != m_events.end(); ++it ) { if ( !it.data().hasDueDate() ) { if ( includeNoDates ) { ids[i] = it.key(); i++; } }else if ( it.data().dueDate() >= start && it.data().dueDate() <= end ) { ids[i] = it.key(); i++; } } ids.resize( i ); return ids; } QArray<int> OTodoAccessXML::overDue() { QArray<int> ids( m_events.count() ); int i = 0; QMap<int, OTodo>::Iterator it; for ( it = m_events.begin(); it != m_events.end(); ++it ) { if ( it.data().isOverdue() ) { ids[i] = it.key(); i++; } } ids.resize( i ); return ids; } /* private */ void OTodoAccessXML::todo( QAsciiDict<int>* dict, OTodo& ev, const QCString& attr, const QString& val) { // qWarning("parse to do from XMLElement" ); int *find=0; find = (*dict)[ attr.data() ]; if (!find ) { // qWarning("Unknown option" + it.key() ); ev.setCustomField( attr, val ); return; } switch( *find ) { case OTodo::Uid: ev.setUid( val.toInt() ); break; case OTodo::Category: ev.setCategories( ev.idsFromString( val ) ); break; case OTodo::HasDate: ev.setHasDueDate( val.toInt() ); break; case OTodo::Completed: ev.setCompleted( val.toInt() ); break; case OTodo::Description: ev.setDescription( val ); break; case OTodo::Summary: ev.setSummary( val ); break; case OTodo::Priority: ev.setPriority( val.toInt() ); break; case OTodo::DateDay: m_day = val.toInt(); break; case OTodo::DateMonth: m_month = val.toInt(); break; case OTodo::DateYear: m_year = val.toInt(); break; case OTodo::Progress: ev.setProgress( val.toInt() ); break; case OTodo::CompletedDate: ev.setCompletedDate( OConversion::dateFromString( val ) ); break; case OTodo::StartDate: ev.setStartDate( OConversion::dateFromString( val ) ); break; case OTodo::State: ev.setState( val.toInt() ); break; case OTodo::Alarms:{ OPimNotifyManager &manager = ev.notifiers(); QStringList als = QStringList::split(";", val ); for (QStringList::Iterator it = als.begin(); it != als.end(); ++it ) { QStringList alarm = QStringList::split(":", (*it), TRUE ); // allow empty qWarning("alarm: %s", alarm.join("___").latin1() ); qWarning("alarm[0]: %s %s", alarm[0].latin1(), OConversion::dateTimeFromString( alarm[0] ).toString().latin1() ); OPimAlarm al( alarm[2].toInt(), OConversion::dateTimeFromString( alarm[0] ), alarm[1].toInt() ); manager.add( al ); } } break; case OTodo::Reminders:{ OPimNotifyManager &manager = ev.notifiers(); QStringList rems = QStringList::split(";", val ); for (QStringList::Iterator it = rems.begin(); it != rems.end(); ++it ) { OPimReminder rem( (*it).toInt() ); manager.add( rem ); } } break; case OTodo::CrossReference: { /* * A cross refernce looks like * appname,id;appname,id * we need to split it up */ QStringList refs = QStringList::split(';', val ); QStringList::Iterator strIt; for (strIt = refs.begin(); strIt != refs.end(); ++strIt ) { int pos = (*strIt).find(','); if ( pos > -1 ) ; // ev.addRelation( (*strIt).left(pos), (*strIt).mid(pos+1).toInt() ); } break; } /* Recurrence stuff below + post processing later */ case FRType: if ( val == "Daily" ) recur()->setType( ORecur::Daily ); else if ( val == "Weekly" ) recur()->setType( ORecur::Weekly); else if ( val == "MonthlyDay" ) recur()->setType( ORecur::MonthlyDay ); else if ( val == "MonthlyDate" ) recur()->setType( ORecur::MonthlyDate ); else if ( val == "Yearly" ) recur()->setType( ORecur::Yearly ); else recur()->setType( ORecur::NoRepeat ); break; case FRWeekdays: recur()->setDays( val.toInt() ); break; case FRPosition: recur()->setPosition( val.toInt() ); break; case FRFreq: recur()->setFrequency( val.toInt() ); break; case FRHasEndDate: recur()->setHasEndDate( val.toInt() ); break; case FREndDate: { rp_end = (time_t) val.toLong(); break; } default: ev.setCustomField( attr, val ); break; } } // from PalmtopRecord... GPL ### FIXME namespace { QString customToXml(const QMap<QString, QString>& customMap ) { //qWarning(QString("writing custom %1").arg(customMap.count())); QString buf(" "); for ( QMap<QString, QString>::ConstIterator cit = customMap.begin(); cit != customMap.end(); ++cit) { // qWarning(".ITEM."); buf += cit.key(); buf += "=\""; buf += Qtopia::escapeString(cit.data()); buf += "\" "; } return buf; } } QString OTodoAccessXML::toString( const OTodo& ev )const { QString str; str += "Completed=\"" + QString::number( ev.isCompleted() ) + "\" "; str += "HasDate=\"" + QString::number( ev.hasDueDate() ) + "\" "; str += "Priority=\"" + QString::number( ev.priority() ) + "\" "; str += "Progress=\"" + QString::number(ev.progress() ) + "\" "; str += "Categories=\"" + toString( ev.categories() ) + "\" "; str += "Description=\"" + Qtopia::escapeString( ev.description() ) + "\" "; str += "Summary=\"" + Qtopia::escapeString( ev.summary() ) + "\" "; if ( ev.hasDueDate() ) { str += "DateYear=\"" + QString::number( ev.dueDate().year() ) + "\" "; str += "DateMonth=\"" + QString::number( ev.dueDate().month() ) + "\" "; str += "DateDay=\"" + QString::number( ev.dueDate().day() ) + "\" "; } // qWarning( "Uid %d", ev.uid() ); str += "Uid=\"" + QString::number( ev.uid() ) + "\" "; // append the extra options /* FIXME Qtopia::Record this is currently not * possible you can set custom fields * but don' iterate over the list * I may do #define private protected * for this case - cough --zecke */ /* QMap<QString, QString> extras = ev.extras(); QMap<QString, QString>::Iterator extIt; for (extIt = extras.begin(); extIt != extras.end(); ++extIt ) str += extIt.key() + "=\"" + extIt.data() + "\" "; */ // cross refernce if ( ev.hasRecurrence() ) { str += ev.recurrence().toString(); } if ( ev.hasStartDate() ) str += "StartDate=\""+ OConversion::dateToString( ev.startDate() ) +"\" "; if ( ev.hasCompletedDate() ) str += "CompletedDate=\""+ OConversion::dateToString( ev.completedDate() ) +"\" "; if ( ev.hasState() ) str += "State=\""+QString::number( ev.state().state() )+"\" "; /* * save reminders and notifiers! * DATE_TIME:DURATION:SOUND:NOT_USED_YET;OTHER_DATE_TIME:OTHER:DURATION:SOUND:.... */ if ( ev.hasNotifiers() ) { OPimNotifyManager manager = ev.notifiers(); OPimNotifyManager::Alarms alarms = manager.alarms(); if (!alarms.isEmpty() ) { QStringList als; OPimNotifyManager::Alarms::Iterator it = alarms.begin(); for ( ; it != alarms.end(); ++it ) { /* only if time is valid */ if ( (*it).dateTime().isValid() ) { als << OConversion::dateTimeToString( (*it).dateTime() ) + ":" + QString::number( (*it).duration() ) + ":" + QString::number( (*it).sound() ) + ":"; } } // now write the list qWarning("als: %s", als.join("____________").latin1() ); str += "Alarms=\""+als.join(";") +"\" "; } /* * now the same for reminders but more easy. We just save the uid of the OEvent. */ OPimNotifyManager::Reminders reminders = manager.reminders(); if (!reminders.isEmpty() ) { OPimNotifyManager::Reminders::Iterator it = reminders.begin(); QStringList records; for ( ; it != reminders.end(); ++it ) { records << QString::number( (*it).recordUid() ); } str += "Reminders=\""+ records.join(";") +"\" "; } } str += customToXml( ev.toExtraMap() ); return str; } QString OTodoAccessXML::toString( const QArray<int>& ints ) const { return Qtopia::Record::idsToString( ints ); } /* internal class for sorting * * Inspired by todoxmlio.cpp from TT */ struct OTodoXMLContainer { OTodo todo; }; namespace { inline QString string( const OTodo& todo) { return todo.summary().isEmpty() ? todo.description().left(20 ) : todo.summary(); } inline int completed( const OTodo& todo1, const OTodo& todo2) { int ret = 0; if ( todo1.isCompleted() ) ret++; if ( todo2.isCompleted() ) ret--; return ret; } inline int priority( const OTodo& t1, const OTodo& t2) { return ( t1.priority() - t2.priority() ); } inline int description( const OTodo& t1, const OTodo& t2) { return QString::compare( string(t1), string(t2) ); } inline int deadline( const OTodo& t1, const OTodo& t2) { int ret = 0; if ( t1.hasDueDate() && t2.hasDueDate() ) ret = t2.dueDate().daysTo( t1.dueDate() ); else if ( t1.hasDueDate() ) ret = -1; else if ( t2.hasDueDate() ) ret = 1; else ret = 0; return ret; } }; /* * Returns: * 0 if item1 == item2 * * non-zero if item1 != item2 * * This function returns int rather than bool so that reimplementations * can return one of three values and use it to sort by: * * 0 if item1 == item2 * * > 0 (positive integer) if item1 > item2 * * < 0 (negative integer) if item1 < item2 * */ class OTodoXMLVector : public QVector<OTodoXMLContainer> { public: OTodoXMLVector(int size, bool asc, int sort) : QVector<OTodoXMLContainer>( size ) { setAutoDelete( true ); m_asc = asc; m_sort = sort; } /* return the summary/description */ QString string( const OTodo& todo) { return todo.summary().isEmpty() ? todo.description().left(20 ) : todo.summary(); } /** * we take the sortorder( switch on it ) * */ int compareItems( Item d1, Item d2 ) { bool seComp, sePrio, seDesc, seDeadline; seComp = sePrio = seDeadline = seDesc = false; int ret =0; OTodoXMLContainer* con1 = (OTodoXMLContainer*)d1; OTodoXMLContainer* con2 = (OTodoXMLContainer*)d2; /* same item */ if ( con1->todo.uid() == con2->todo.uid() ) return 0; switch ( m_sort ) { /* completed */ case 0: { ret = completed( con1->todo, con2->todo ); seComp = TRUE; break; } /* priority */ case 1: { ret = priority( con1->todo, con2->todo ); sePrio = TRUE; break; } /* description */ case 2: { ret = description( con1->todo, con2->todo ); seDesc = TRUE; break; } /* deadline */ case 3: { ret = deadline( con1->todo, con2->todo ); seDeadline = TRUE; break; } default: ret = 0; break; }; /* * FIXME do better sorting if the first sort criteria * ret equals 0 start with complete and so on... */ /* twist it we're not ascending*/ if (!m_asc) ret = ret * -1; if ( ret ) return ret; // default did not gave difference let's try it other way around /* * General try if already checked if not test * and return * 1.Completed * 2.Priority * 3.Description * 4.DueDate */ if (!seComp ) { if ( (ret = completed( con1->todo, con2->todo ) ) ) { if (!m_asc ) ret *= -1; return ret; } } if (!sePrio ) { if ( (ret = priority( con1->todo, con2->todo ) ) ) { if (!m_asc ) ret *= -1; return ret; } } if (!seDesc ) { if ( (ret = description(con1->todo, con2->todo ) ) ) { if (!m_asc) ret *= -1; return ret; } } if (!seDeadline) { if ( (ret = deadline( con1->todo, con2->todo ) ) ) { if (!m_asc) ret *= -1; return ret; } } return 0; } private: bool m_asc; int m_sort; }; QArray<int> OTodoAccessXML::sorted( bool asc, int sortOrder, int sortFilter, int cat ) { OTodoXMLVector vector(m_events.count(), asc,sortOrder ); QMap<int, OTodo>::Iterator it; int item = 0; bool bCat = sortFilter & 1 ? true : false; bool bOnly = sortFilter & 2 ? true : false; bool comp = sortFilter & 4 ? true : false; for ( it = m_events.begin(); it != m_events.end(); ++it ) { /* show category */ /* -1 == unfiled */ if ( bCat && cat == -1 ) { if(!(*it).categories().isEmpty() ) continue; }else if ( bCat && cat != 0) if (!(*it).categories().contains( cat ) ) { continue; } /* isOverdue but we should not show overdue - why?*/ /* if ( (*it).isOverdue() && !bOnly ) { qWarning("item is overdue but !bOnly"); continue; } */ if ( !(*it).isOverdue() && bOnly ) { continue; } if ((*it).isCompleted() && comp ) { continue; } OTodoXMLContainer* con = new OTodoXMLContainer(); con->todo = (*it); vector.insert(item, con ); item++; } vector.resize( item ); /* sort it now */ vector.sort(); /* now get the uids */ QArray<int> array( vector.count() ); for (uint i= 0; i < vector.count(); i++ ) { array[i] = ( vector.at(i) )->todo.uid(); } return array; }; void OTodoAccessXML::removeAllCompleted() { + QMap<int, OTodo> events = m_events; for ( QMap<int, OTodo>::Iterator it = m_events.begin(); it != m_events.end(); ++it ) { if ( (*it).isCompleted() ) - m_events.remove( it ); + events.remove( it.key() ); } + m_events = events; } QBitArray OTodoAccessXML::supports()const { static QBitArray ar = sup(); return ar; } QBitArray OTodoAccessXML::sup() { QBitArray ar( OTodo::CompletedDate +1 ); ar.fill( true ); ar[OTodo::CrossReference] = false; ar[OTodo::State ] = false; ar[OTodo::Reminders] = false; ar[OTodo::Notifiers] = false; ar[OTodo::Maintainer] = false; return ar; } QArray<int> OTodoAccessXML::matchRegexp( const QRegExp &r ) const { QArray<int> m_currentQuery( m_events.count() ); uint arraycounter = 0; QMap<int, OTodo>::ConstIterator it; for (it = m_events.begin(); it != m_events.end(); ++it ) { if ( it.data().match( r ) ) m_currentQuery[arraycounter++] = it.data().uid(); } // Shrink to fit.. m_currentQuery.resize(arraycounter); return m_currentQuery; } |