kabc Library API Documentation

addresslineedit.cpp

00001 /*
00002     This file is part of libkabc.
00003     Copyright (c) 2002 Helge Deller <deller@gmx.de>
00004                   2002 Lubos Lunak <llunak@suse.cz>
00005                   2001,2003 Carsten Pfeiffer <pfeiffer@kde.org>
00006                   2001 Waldo Bastian <bastian@kde.org>
00007 
00008     This library is free software; you can redistribute it and/or
00009     modify it under the terms of the GNU Library General Public
00010     License as published by the Free Software Foundation; either
00011     version 2 of the License, or (at your option) any later version.
00012 
00013     This library is distributed in the hope that it will be useful,
00014     but WITHOUT ANY WARRANTY; without even the implied warranty of
00015     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016     Library General Public License for more details.
00017 
00018     You should have received a copy of the GNU Library General Public License
00019     along with this library; see the file COPYING.LIB.  If not, write to
00020     the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00021     Boston, MA 02111-1307, USA.
00022 */
00023 
00024 // $Id: addresslineedit.cpp,v 1.18 2003/12/11 10:28:35 waba Exp $
00025 
00026 #include "addresslineedit.h"
00027 
00028 #include <qapplication.h>
00029 #include <qobject.h>
00030 #include <qptrlist.h>
00031 #include <qregexp.h>
00032 #include <qevent.h>
00033 #include <qdragobject.h>
00034 
00035 #include <kcompletionbox.h>
00036 #include <kconfig.h>
00037 #include <kcursor.h>
00038 #include <kstandarddirs.h>
00039 #include <kstaticdeleter.h>
00040 #include <kstdaccel.h>
00041 #include <kurldrag.h>
00042 
00043 #include <kabc/stdaddressbook.h>
00044 #include <kabc/distributionlist.h>
00045 #include "ldapclient.h"
00046 
00047 #include <kdebug.h>
00048 
00049 //=============================================================================
00050 //
00051 //   Class  AddressLineEdit
00052 //
00053 //=============================================================================
00054 
00055 
00056 using namespace KABC;
00057 
00058 KCompletion * AddressLineEdit::s_completion = 0L;
00059 bool AddressLineEdit::s_addressesDirty = false;
00060 QTimer* AddressLineEdit::s_LDAPTimer = 0L;
00061 LdapSearch* AddressLineEdit::s_LDAPSearch = 0L;
00062 QString* AddressLineEdit::s_LDAPText = 0L;
00063 AddressLineEdit* AddressLineEdit::s_LDAPLineEdit = 0L;
00064 KConfig *AddressLineEdit::s_config = 0L;
00065 
00066 static KStaticDeleter<KCompletion> completionDeleter;
00067 static KStaticDeleter<QTimer> ldapTimerDeleter;
00068 static KStaticDeleter<LdapSearch> ldapSearchDeleter;
00069 static KStaticDeleter<QString> ldapTextDeleter;
00070 static KStaticDeleter<KConfig> configDeleter;
00071 
00072 AddressLineEdit::AddressLineEdit(QWidget* parent,
00073         bool useCompletion,
00074         const char *name)
00075     : KLineEdit(parent,name)
00076 {
00077   m_useCompletion = useCompletion;
00078   m_completionInitialized = false;
00079   m_smartPaste = false;
00080 
00081   init();
00082 
00083   // Whenever a new AddressLineEdit is created (== a new composer is created),
00084   // we set a dirty flag to reload the addresses upon the first completion.
00085   // The address completions are shared between all AddressLineEdits.
00086   // Is there a signal that tells us about addressbook updates?
00087   if (m_useCompletion)
00088     s_addressesDirty = true;
00089 }
00090 
00091 
00092 //-----------------------------------------------------------------------------
00093 void AddressLineEdit::init()
00094 {
00095   if ( !s_completion ) {
00096       completionDeleter.setObject( s_completion, new KCompletion() );
00097       s_completion->setOrder( KCompletion::Sorted );
00098       s_completion->setIgnoreCase( true );
00099   }
00100 
00101   if( m_useCompletion ) {
00102       if( !s_LDAPTimer ) {
00103         ldapTimerDeleter.setObject( s_LDAPTimer, new QTimer );
00104         ldapSearchDeleter.setObject( s_LDAPSearch, new LdapSearch );
00105         ldapTextDeleter.setObject( s_LDAPText, new QString );
00106       }
00107       connect( s_LDAPTimer, SIGNAL( timeout()), SLOT( slotStartLDAPLookup()));
00108       connect( s_LDAPSearch, SIGNAL( searchData( const QStringList& )),
00109         SLOT( slotLDAPSearchData( const QStringList& )));
00110   }
00111 
00112   if ( m_useCompletion && !m_completionInitialized )
00113   {
00114       setCompletionObject( s_completion, false ); // we handle it ourself
00115       connect( this, SIGNAL( completion(const QString&)),
00116                this, SLOT(slotCompletion() ));
00117 
00118       KCompletionBox *box = completionBox();
00119       connect( box, SIGNAL( highlighted( const QString& )),
00120                this, SLOT( slotPopupCompletion( const QString& ) ));
00121       connect( box, SIGNAL( userCancelled( const QString& )),
00122                SLOT( slotSetTextAsEdited( const QString& )));
00123 
00124       m_completionInitialized = true; // don't connect muliple times. That's
00125                                       // ugly, tho, better have completionBox()
00126                                       // virtual in KDE 4
00127       // Why? This is only called once. Why should this be called more
00128       // than once? And why was this protected?
00129   }
00130 }
00131 
00132 //-----------------------------------------------------------------------------
00133 AddressLineEdit::~AddressLineEdit()
00134 {
00135 }
00136 
00137 //-----------------------------------------------------------------------------
00138 
00139 KConfig* AddressLineEdit::config()
00140 {
00141   if ( !s_config )
00142     configDeleter.setObject( s_config, new KConfig( locateLocal( "config",
00143                              "kabldaprc" ) ) );
00144 
00145   return s_config;
00146 }
00147 
00148 void AddressLineEdit::setFont( const QFont& font )
00149 {
00150     KLineEdit::setFont( font );
00151     if ( m_useCompletion )
00152         completionBox()->setFont( font );
00153 }
00154 
00155 //-----------------------------------------------------------------------------
00156 void AddressLineEdit::keyPressEvent(QKeyEvent *e)
00157 {
00158     bool accept = false;
00159 
00160     if (KStdAccel::shortcut(KStdAccel::SubstringCompletion).contains(KKey(e)))
00161     {
00162       doCompletion(true);
00163       accept = true;
00164     }
00165     else if (e->state()==ControlButton && e->key() == Key_Right)
00166     {
00167       if ((int)text().length() == cursorPosition()) // at End?
00168       {
00169         doCompletion(true);
00170     accept = true;
00171       }
00172     }
00173     else if (e->state()==ControlButton && e->key() == Key_V)
00174     {
00175       if (m_useCompletion)
00176          m_smartPaste = true;
00177       paste();
00178       m_smartPaste = false;
00179       accept = true;
00180     }
00181 
00182     if( !accept )
00183         KLineEdit::keyPressEvent( e );
00184 
00185     if( e->isAccepted())
00186     {
00187         if( m_useCompletion && s_LDAPTimer != NULL )
00188     {
00189             if( *s_LDAPText != text())
00190                 stopLDAPLookup();
00191         *s_LDAPText = text();
00192         s_LDAPLineEdit = this;
00193         s_LDAPTimer->start( 500, true );
00194     }
00195     }
00196 }
00197 
00198 void AddressLineEdit::mouseReleaseEvent( QMouseEvent * e )
00199 {
00200    if (m_useCompletion && (e->button() == MidButton))
00201    {
00202       m_smartPaste = true;
00203       KLineEdit::mouseReleaseEvent(e);
00204       m_smartPaste = false;
00205       return;
00206    }
00207    KLineEdit::mouseReleaseEvent(e);
00208 }
00209 
00210 void AddressLineEdit::insert(const QString &t)
00211 {
00212     if (!m_smartPaste)
00213     {
00214        KLineEdit::insert(t);
00215        return;
00216     }
00217     QString newText = t.stripWhiteSpace();
00218     if (newText.isEmpty())
00219        return;
00220 
00221     // remove newlines in the to-be-pasted string as well as an eventual
00222     // mailto: protocol
00223     newText.replace( QRegExp("\r?\n"), ", " );
00224     if ( newText.startsWith( "mailto:" ) )
00225     {
00226       KURL u(newText);
00227       newText = u.path();
00228     }
00229     else if (newText.find(" at ") != -1)
00230     {
00231        // Anti-spam stuff
00232        newText.replace( " at ", "@" );
       newText.replace( " dot ", "." );
00233     }
00234     else if (newText.find("(at)") != -1)
00235     {
00236       newText.replace( QRegExp("\\s*\\(at\\)\\s*"), "@" );
    }

    QString contents = text();
    int start_sel = 0;
    int end_sel = 0;
    int pos = cursorPosition();
    if (getSelection(&start_sel, &end_sel))
    {
       // Cut away the selection.
       if (pos > end_sel)
          pos -= (end_sel - start_sel);
       else if (pos > start_sel)
          pos = start_sel;
       contents = contents.left(start_sel) + contents.right(end_sel+1);
    }

    int eot = contents.length();
    while ((eot > 0) && contents[eot-1].isSpace()) eot--;
    if (eot == 0)
    {
       contents = QString::null;
    }
    else if (pos >= eot)
    {
       if (contents[eot-1] == ',')
          eot--;
       contents.truncate(eot);
       contents += ", ";
00237        pos = eot+2;
00238     }
00239 
00240     contents = contents.left(pos)+newText+contents.mid(pos);
00241     slotSetTextAsEdited(contents);
00242     setCursorPosition(pos+newText.length());
00243 }
00244 
00245 void AddressLineEdit::paste()
00246 {
00247     if (m_useCompletion)
00248        m_smartPaste = true;
00249     KLineEdit::paste();
00250     m_smartPaste = false;
00251 }
00252 
00253 //-----------------------------------------------------------------------------
00254 void AddressLineEdit::cursorAtEnd()
00255 {
00256     setCursorPosition( text().length() );
00257 }
00258 
00259 //-----------------------------------------------------------------------------
00260 void AddressLineEdit::enableCompletion(bool enable)
00261 {
00262   m_useCompletion = enable;
00263 }
00264 
00265 //-----------------------------------------------------------------------------
00266 void AddressLineEdit::doCompletion(bool ctrlT)
00267 {
00268     if ( !m_useCompletion )
00269         return;
00270 
00271     QString s(text());
00272     QString prevAddr;
00273     int n = s.findRev(',');
00274     if (n>= 0)
00275     {
00276         prevAddr = s.left(n+1) + ' ';
00277         s = s.mid(n+1,255).stripWhiteSpace();
00278     }
00279 
00280     KCompletionBox *box = completionBox();
00281 
00282     if ( s.isEmpty() )
00283     {
00284         box->hide();
00285         return;
00286     }
00287 
00288     KGlobalSettings::Completion  mode = completionMode();
00289 
00290     if ( s_addressesDirty )
00291         loadAddresses();
00292 
00293     if ( ctrlT )
00294     {
00295         QStringList completions = s_completion->substringCompletion( s );
00296         if (completions.count() > 1) {
00297             m_previousAddresses = prevAddr;
00298             box->setItems( completions );
00299             box->setCancelledText( text() );
00300             box->popup();
00301         }
00302         else if (completions.count() == 1)
00303             slotSetTextAsEdited(prevAddr + completions.first());
00304         else
00305             box->hide();
00306 
00307         cursorAtEnd();
00308         return;
00309     }
00310 
00311     switch ( mode )
00312     {
00313         case KGlobalSettings::CompletionPopup:
00314         {
00315             m_previousAddresses = prevAddr;
00316             QStringList items = s_completion->allMatches( s );
00317             items += s_completion->allMatches( "\"" + s );
00318             items += s_completion->substringCompletion( '<' + s );
00319             uint beforeDollarCompletionCount = items.count();
00320 
00321             if( s.find( ' ' ) == -1 ) // one word, possibly given name
00322                 items += s_completion->allMatches( "$$" + s );
00323 
00324             if ( items.isEmpty() )
00325                 box->hide();
00326             else
00327             {
00328                 if ( items.count() > beforeDollarCompletionCount )
00329                 {
00330                     // remove the '$$whatever$' part                    
00331                     for( QStringList::Iterator it = items.begin();
00332                          it != items.end();
00333                          ++it )
00334                     { 
00335                         int pos = (*it).find( '$', 2 );
00336                         if( pos < 0 ) // ???
00337                             continue;
00338                         (*it)=(*it).mid( pos + 1 );
00339                     }
00340                 }
00341 
00342                 items = removeMailDupes( items );
00343                 box->setItems( items );
00344                 box->setCancelledText( text() );
00345                 box->popup();
00346             }
00347 
00348             break;
00349         }
00350 
00351         case KGlobalSettings::CompletionShell:
00352         {
00353             QString match = s_completion->makeCompletion( s );
00354             if ( !match.isNull() && match != s )
00355             {
00356                 slotSetTextAsEdited( prevAddr + match );
00357                 cursorAtEnd();
00358             }
00359             break;
00360         }
00361 
00362         case KGlobalSettings::CompletionMan: // Short-Auto in fact
00363         case KGlobalSettings::CompletionAuto:
00364         {
00365             QString match = s_completion->makeCompletion( s );
00366             if ( !match.isNull() && match != s )
00367             {
00368                 QString adds = prevAddr + match;
00369                 int curPos = cursorPosition();
00370                 validateAndSet( adds, curPos, curPos, adds.length() );
00371             }
00372             break;
00373         }
00374 
00375         default: // fall through
00376         case KGlobalSettings::CompletionNone:
00377             break;
00378     }
00379 }
00380 
00381 //-----------------------------------------------------------------------------
00382 void AddressLineEdit::slotPopupCompletion( const QString& completion )
00383 {
00384     slotSetTextAsEdited( m_previousAddresses + completion );
00385     cursorAtEnd();
00386 }
00387 
00388 //-----------------------------------------------------------------------------
00389 void AddressLineEdit::loadAddresses()
00390 {
00391     s_completion->clear();
00392     s_addressesDirty = false;
00393 
00394     QStringList adrs = addresses();
00395     for( QStringList::ConstIterator it = adrs.begin();
00396      it != adrs.end();
00397      ++it)
00398         addAddress( *it );
00399 }
00400 
00401 void AddressLineEdit::addAddress( const QString& adr )
00402 {
00403     s_completion->addItem( adr );
00404     int pos = adr.find( '<' );
00405     if( pos >= 0 )
00406     {
00407         ++pos;
00408         int pos2 = adr.find( pos, '>' );
00409         if( pos2 >= 0 )
00410             s_completion->addItem( adr.mid( pos, pos2 - pos ));
00411     }
00412 }
00413 
00414 void AddressLineEdit::slotStartLDAPLookup()
00415 {
00416     if( !s_LDAPSearch->isAvailable() || s_LDAPLineEdit != this )
00417     return;
00418     startLoadingLDAPEntries();
00419 }
00420 
00421 void AddressLineEdit::stopLDAPLookup()
00422 {
00423     s_LDAPSearch->cancelSearch();
00424     s_LDAPLineEdit = NULL;
00425 }
00426 
00427 void AddressLineEdit::startLoadingLDAPEntries()
00428 {
00429     QString s( *s_LDAPText );
00430     // TODO cache last?
00431     QString prevAddr;
00432     int n = s.findRev(',');
00433     if (n>= 0)
00434     {
00435         prevAddr = s.left(n+1) + ' ';
00436         s = s.mid(n+1,255).stripWhiteSpace();
00437     }
00438     if( s.length() == 0 )
00439     return;
00440     loadAddresses(); // TODO reuse these?
00441     s_LDAPSearch->startSearch( s );
00442 }
00443 
00444 void AddressLineEdit::slotLDAPSearchData( const QStringList& adrs )
00445 {
00446     if( s_LDAPLineEdit != this )
00447         return;
00448     for( QStringList::ConstIterator it = adrs.begin();
00449      it != adrs.end();
00450      ++it ) {
00451     QString name(*it);
00452     int pos = name.find( " <" );
00453     int pos_comma = name.find( ',' );
00454     // put name in quotes, if we have a comma in the name
00455     if (pos>0 && pos_comma>0 && pos_comma<pos) {
00456         name.insert(pos, '\"');
00457         name.prepend('\"');
00458     }
00459     addAddress( name );
00460     }
00461     if( hasFocus() || completionBox()->hasFocus())
00462     {
00463         if( completionMode() != KGlobalSettings::CompletionNone )
00464         {
00465             doCompletion( false );
00466         }
00467     }
00468 }
00469 
00470 void AddressLineEdit::slotSetTextAsEdited( const QString& text )
00471 {
00472     setText( text );
00473     setEdited( true );
00474 }
00475 
00476 QStringList AddressLineEdit::removeMailDupes( const QStringList& adrs )
00477 {
00478     QStringList src = adrs;
00479     qHeapSort( src );
00480     QString last;
00481     for( QStringList::Iterator it = src.begin();
00482      it != src.end();
00483      )
00484     {
00485     if( *it == last )
00486     {
00487         it = src.remove( it );
00488         continue; // dupe
00489     }
00490     last = *it;
00491     ++it;
00492     }
00493     return src;
00494 }
00495 
00496 //-----------------------------------------------------------------------------
00497 void AddressLineEdit::dropEvent(QDropEvent *e)
00498 {
00499   KURL::List uriList;
00500   if(KURLDrag::canDecode(e) && KURLDrag::decode( e, uriList ))
00501   {
00502     QString ct = text();
00503     KURL::List::Iterator it = uriList.begin();
00504     for (; it != uriList.end(); ++it)
00505     {
00506       if (!ct.isEmpty()) ct.append(", ");
00507       KURL u(*it);
00508       if ((*it).protocol() == "mailto")
00509           ct.append( (*it).path() );
00510       else
00511           ct.append( (*it).url() );
00512     }
00513     setText(ct);
00514     setEdited( true );
00515   }
00516   else {
00517     if (m_useCompletion)
00518        m_smartPaste = true;
00519     QLineEdit::dropEvent(e);
00520     m_smartPaste = false;
00521   }
00522 }
00523 
00524 
00525 QStringList AddressLineEdit::addresses()
00526 {
00527   QApplication::setOverrideCursor( KCursor::waitCursor() ); // loading might take a while
00528 
00529   QStringList result;
00530   QString space(" ");
00531   QRegExp needQuotes("[^ 0-9A-Za-z\\x0080-\\xFFFF]");
00532   QString endQuote("\" ");
00533   QString addr, email;
00534 
00535   KABC::AddressBook *addressBook = KABC::StdAddressBook::self();
00536   KABC::AddressBook::Iterator it;
00537   for( it = addressBook->begin(); it != addressBook->end(); ++it ) {
00538     QStringList emails = (*it).emails();
00539     QString n = (*it).prefix() + space +
00540         (*it).givenName() + space +
00541         (*it).additionalName() + space +
00542         (*it).familyName() + space +
00543         (*it).suffix();
00544     n = n.simplifyWhiteSpace();
00545 
00546     QStringList::ConstIterator mit;
00547 
00548     for ( mit = emails.begin(); mit != emails.end(); ++mit ) {
00549       email = *mit;
00550       if (!email.isEmpty()) {
00551     if (n.isEmpty() || (email.find( '<' ) != -1))
00552       addr = QString::null;
00553     else { /* do we really need quotes around this name ? */
00554           if (n.find(needQuotes) != -1)
00555         addr = '"' + n + endQuote;
00556       else
00557         addr = n + space;
00558     }
00559 
00560     if (!addr.isEmpty() && (email.find( '<' ) == -1)
00561         && (email.find( '>' ) == -1)
00562         && (email.find( ',' ) == -1))
00563       addr += '<' + email + '>';
00564     else
00565       addr += email;
00566     addr = addr.stripWhiteSpace();
00567     result.append( addr );
00568       }
00569     }
00570   }
00571   KABC::DistributionListManager manager( addressBook );
00572   manager.load();
00573   result += manager.listNames();
00574 
00575   QApplication::restoreOverrideCursor();
00576 
00577   return result;
00578 }
00579 
00580 #include "addresslineedit.moc"
00581 
KDE Logo
This file is part of the documentation for kabc Library Version 3.2.2.
Documentation copyright © 1996-2004 the KDE developers.
Generated on Wed May 5 07:17:59 2004 by doxygen 1.3.6 written by Dimitri van Heesch, © 1997-2003