Ejemplo n.º 1
0
void
AddressesDialog::updateAvailableAddressees()
{
  d->ui->mAvailableView->clear();
  d->groupDict.clear();

  static const QString &personalGroup = KGlobal::staticQString( i18n( "Other Addresses" ) );
  d->personal = new AddresseeViewItem( d->ui->mAvailableView, personalGroup );
  d->personal->setHidden( true );
  d->groupDict.insert( personalGroup, d->personal );

  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
  for( KABC::AddressBook::Iterator it = addressBook->begin();
       it != addressBook->end(); ++it ) {
    addAddresseeToAvailable( *it, d->personal );
  }

  d->recent = 0;
  updateRecentAddresses();

  addDistributionLists();
  if ( d->personal->childCount() > 0 ) {
    d->personal->setHidden( false );
  }

  checkForSingleAvailableGroup();
}
Ejemplo n.º 2
0
bool KAddrBookExternal::addVCard(const KABC::Addressee &addressee, QWidget *parent)
{
    KABC::AddressBook *ab = KABC::StdAddressBook::self(true);
    bool inserted = false;

    ab->setErrorHandler(new KABC::GuiErrorHandler(parent));

    KABC::Addressee::List addressees =
        ab->findByEmail(addressee.preferredEmail());

    if(addressees.isEmpty())
    {
        if(KAddrBookExternal::addAddressee(addressee))
        {
            QString text = i18n("The VCard was added to your addressbook; "
                                "you can add more information to this "
                                "entry by opening the addressbook.");
            KMessageBox::information(parent, text, QString::null, "addedtokabc");
            inserted = true;
        }
    }
    else
    {
        QString text = i18n("The VCard's primary email address is already in "
                            "your addressbook; however, you may save the VCard "
                            "into a file and import it into the addressbook "
                            "manually.");
        KMessageBox::information(parent, text);
        inserted = true;
    }

    ab->setErrorHandler(0);
    return inserted;
}
Ejemplo n.º 3
0
void TestDistrList::setup()
{
    // We need a std addressbook
    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    KABC::StdAddressBook::setAutomaticSave( false );

    // and two contacts
    KABC::Addressee addr1;
    addr1.setName( "addr1" );
    addr1.setFormattedName( "addr1" );
    addr1.insertEmail( "*****@*****.**", true );
    addr1.insertEmail( "*****@*****.**" );
    ab->insertAddressee( addr1 );
    assert( addr1.emails().count() == 2 );

    KABC::Addressee addr2;
    addr2.setName( "addr2" );
    addr2.insertEmail( "*****@*****.**", true );
    addr2.insertEmail( "*****@*****.**" );
    ab->insertAddressee( addr2 );
    assert( addr2.emails().count() == 2 );

    assert( !ab->findByName( "addr1" ).isEmpty() );
    assert( !ab->findByName( "addr2" ).isEmpty() );
}
Ejemplo n.º 4
0
void TestDistrList::testNewList()
{
    kDebug() ;
    DistributionList dl;
    dl.setName( "foo" );
    assert( !dl.isEmpty() );
    check( "name set", dl.formattedName(), "foo" );
    assert( DistributionList::isDistributionList( dl ) );

    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    ab->insertAddressee( dl );
#if 0 // can't do that until we have KABC::AddressBook::findByFormattedName, or we use setName()
    KABC::Addressee::List addrList = ab->findByName( "foo" );
    assert( addrList.count() == 1 );
    KABC::Addressee addr = addrList.first();
    assert( !addr.isEmpty() );
    check( "correct name", addr.name(), "foo" );
    assert( DistributionList::isDistributionList( addr ) );
#else
    KABC::Addressee addr = dl;
#endif

    DistributionList dl2 = DistributionList::findByName( ab, "foo" );
    assert( !dl2.isEmpty() );
    check( "correct name", dl2.formattedName(), "foo" );
    assert( DistributionList::isDistributionList( dl2 ) );

    // Test the ctor that takes an addressee
    DistributionList dl3( addr );
    assert( !dl3.isEmpty() );
    assert( DistributionList::isDistributionList( dl3 ) );
    check( "correct name", dl3.formattedName(), "foo" );
}
Ejemplo n.º 5
0
void TestDistrList::testDuplicate()
{
    kDebug() ;
    // This is a special test for the case where we have a contact and a distr list with the same name
    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    KABC::Addressee addr;
    addr.setName( "foo" );
    addr.insertEmail( "*****@*****.**", true );
    ab->insertAddressee( addr );

#if 0 // we need a findByFormattedName
    KABC::Addressee::List addrList = ab->findByName( "foo" );
    assert( addrList.count() == 2 );

    bool a = DistributionList::isDistributionList( addrList.first() );
    bool b = DistributionList::isDistributionList( addrList.last() );
    // one is a distr list, but not both
    assert( a || b );
    //
    assert( ! ( a && b ) );
#endif

    DistributionList dl = DistributionList::findByName( ab, "foo" );
    assert( !dl.isEmpty() );
    assert( DistributionList::isDistributionList( dl ) );
    assert( dl.formattedName() == "foo" );
}
Ejemplo n.º 6
0
//-----------------------------------------------------------------------------
void KAddrBookExternal::openEmail(const QString &addr, QWidget *parent)
{
    QString email;
    QString name;

    KABC::Addressee::parseEmailAddress(addr, name, email);

    KABC::AddressBook *ab = KABC::StdAddressBook::self(true);

    // force a reload of the address book file so that changes that were made
    // by other programs are loaded
    ab->asyncLoad();

    // if we have to reload the address book then we should also wait until
    // it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
    // This ugly hack will be removed in 4.0
    while(!ab->loadingHasFinished())
    {
        QApplication::eventLoop()->processEvents(QEventLoop::ExcludeUserInput);

        // use sleep here to reduce cpu usage
        usleep(100);
    }
#endif

    KABC::Addressee::List addressees = ab->findByEmail(email);

    if(addressees.count() > 0)
    {
        if(kapp->dcopClient()->isApplicationRegistered("kaddressbook"))
        {
            //make sure kaddressbook is loaded, otherwise showContactEditor
            //won't work as desired, see bug #87233
            DCOPRef call("kaddressbook", "kaddressbook");
            call.send("newInstance()");
        }
        else
        {
            kapp->startServiceByDesktopName("kaddressbook");
        }

        DCOPRef call("kaddressbook", "KAddressBookIface");
        call.send("showContactEditor(QString)", addressees.first().uid());
    }
    else
    {
        //TODO: Enable the better message at the next string unfreeze
#if 0
        QString text = i18n("<qt>The email address <b>%1</b> cannot be "
                            "found in your addressbook.</qt>").arg(email);
#else
        QString text = email + " " + i18n("is not in address book");
#endif
        KMessageBox::information(parent, text, QString::null, "notInAddressBook");
    }
}
Ejemplo n.º 7
0
void TestDistrList::testDeleteList()
{
    kDebug() ;

    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    DistributionList dl = DistributionList::findByName( ab, "foo" );
    assert( !dl.isEmpty() );
    ab->removeAddressee( dl );
    dl = DistributionList::findByName( ab, "foo" );
    assert( dl.isEmpty() );
}
Ejemplo n.º 8
0
void TestDistrList::cleanup()
{
    kDebug() ;
    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    ab->clear();
    KABC::StdAddressBook::close();

    QString kdehome = QFile::decodeName( getenv("KDEHOME") );
    KUrl urlkdehome;
    urlkdehome.setPath( kdehome );
    KIO::NetAccess::del( urlkdehome, 0 );
}
Ejemplo n.º 9
0
/** Select a mail address, using the KabApi */
void TagMailDlg::slotSelectAddress()
{
//Based on KMail
  QString addr, email, emailString;
  QStringList result;
  KABC::AddressBook *addressBook = KABC::StdAddressBook::self();
  KABC::AddressBook::Iterator it;
  for( it = addressBook->begin(); it != addressBook->end(); ++it ) {
    QStringList emails = (*it).emails();
    QString n = (*it).prefix() + " " +
    (*it).givenName() + " " +
    (*it).additionalName() + " " +
          (*it).familyName() + " " +
    (*it).suffix();
    n = n.simplifyWhiteSpace();
    for( unsigned int i = 0; i < emails.count(); ++i ) {
      if (!emails[i].isEmpty()) {
  if (n.isEmpty() || (emails[i].find( "<" ) != -1))
    addr = "";
  else { /* do we really need quotes around this name ? */
    if (n.find(QRegExp("[^ 0-9A-Za-z\\x0080-\\xFFFF]")) != -1)
      addr = qConfig.attrValueQuotation + n + qConfig.attrValueQuotation + " ";
    else
      addr = n + " ";
  }
  email = emails[i];
  if (!addr.isEmpty() && (email.find( "<" ) == -1)
      && (email.find( ">" ) == -1)
      && (email.find( "," ) == -1))
    addr += "<" + email + ">";
  else
    addr += email;
  addr.stripWhiteSpace();
  result.append( addr );
      }
    }
  }
 result.sort();

 if ( result.count() > 0 )
 {
   ListDlg listDlg(result);
   listDlg.setCaption(i18n("Select Address"));
   if (!listDlg.exec()) return;
   emailString = listDlg.getEntry();
   lineEmail->setText(emailString);
 } else
 {
//Actually this may mean also other erros, but the result is the same for us: cannot get the
//e-mail address
   KMessageBox::error(this,i18n("No addresses found."));
  }
}
Ejemplo n.º 10
0
KAB::Book::Book (Ekiga::ContactCore &_core): core(_core)
{
    KABC::AddressBook *kab = KABC::StdAddressBook::self ();

    kab->load (); // FIXME: turn async!

    for (KABC::AddressBook::Iterator iter = kab->begin ();
            iter != kab->end ();
            iter++) {

        add_contact (ContactPtr (new Contact (core, &(*iter))));
    }
}
Ejemplo n.º 11
0
void KabcBridge::addresses(QStringList& result) // includes lists
{
  KCursorSaver busy(KBusyPtr::busy()); // loading might take a while

  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
  KABC::AddressBook::ConstIterator it;
  for( it = addressBook->constBegin(); it != addressBook->constEnd(); ++it ) {
    const QStringList emails = (*it).emails();
    QString n = (*it).prefix() + ' ' +
                (*it).givenName() + ' ' +
                (*it).additionalName() + ' ' +
                (*it).familyName() + ' ' +
                (*it).suffix();
    n = n.simplified();

    QRegExp needQuotes("[^ 0-9A-Za-z\\x0080-\\xFFFF]");
    QString endQuote = "\" ";
    QStringList::ConstIterator mit;
    QString addr, email;

    for ( mit = emails.begin(); mit != emails.end(); ++mit ) {
      email = *mit;
      if (!email.isEmpty()) {
        if (n.isEmpty() || (email.contains( '<' ) ))
          addr.clear();
        else { // do we really need quotes around this name ?
          if (n.contains(needQuotes) )
            addr = '"' + n + endQuote;
          else
            addr = n + ' ';
        }

        if (!addr.isEmpty() && !(email.contains( '<' ) )
            && !(email.contains( '>' ) )
            && !(email.contains( ',' ) ))
          addr += '<' + email + '>';
        else
          addr += email;
        addr = addr.trimmed();
        result.append( addr );
      }
    }
  }

  result += addressBook->allDistributionListNames();

  result.sort();
}
Ejemplo n.º 12
0
void KoRdfFoaF::saveToKABC()
{
    Q_D (KoRdfFoaF);
    kDebug(30015) << "saving name:" << d->m_name;
#ifdef KDEPIMLIBS_FOUND
    KABC::StdAddressBook *ab = static_cast<KABC::StdAddressBook*>
                               (KABC::StdAddressBook::self());
    if (!ab) {
        return;
    }
    KABC::Ticket *ticket = ab->requestSaveTicket();
    KABC::Addressee addr = d->toKABC();
    ab->insertAddressee(addr);
    KABC::AddressBook* pab = ab;
    pab->save(ticket);
#endif
}
Ejemplo n.º 13
0
void TestDistrList::testInsertEntry()
{
    kDebug() ;
    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    DistributionList dl = DistributionList::findByName( ab, "foo" );
    assert( !dl.isEmpty() );

#if 0 // the usual method
    KABC::Addressee addr1 = ab->findByName( "addr1" ).first();
    assert( !addr1.isEmpty() );
    dl.insertEntry( addr1 );
#else // the kolab-resource method
    dl.insertEntry( "addr1" );
#endif

    KABC::Addressee addr2 = ab->findByName( "addr2" ).first();
    assert( !addr2.isEmpty() );
    dl.insertEntry( addr2, "*****@*****.**" );

    // Try inserting it again, should do nothing
    dl.insertEntry( addr2, "*****@*****.**" );

    // And insert it with another email address
    dl.insertEntry( addr2, "*****@*****.**" );

    // Test entries()
    DistributionList::Entry::List entries = dl.entries( ab );
    check( "entries count", QString::number( entries.count() ), "3" );
    check( "first entry", entries[0].addressee.name(), "addr1" );
    check( "first entry", entries[0].email, QString() );
    check( "second entry", entries[1].addressee.name(), "addr2" );
    check( "second entry", entries[1].email, "*****@*****.**" );
    check( "third entry", entries[2].addressee.name(), "addr2" );
    check( "third entry", entries[2].email, "*****@*****.**" );

    // Test emails()
    QStringList emails = dl.emails( ab );
    kDebug() << emails;
    assert( emails.count() == 3 );
    check( "first email", emails[0], "addr1 <*****@*****.**>" );
    check( "second email", emails[1], "addr2 <*****@*****.**>" );
    check( "third email", emails[2], "addr2 <*****@*****.**>" );

    // Commit changes to the addressbook !!
    ab->insertAddressee( dl );
}
Ejemplo n.º 14
0
QStringList KabcBridge::categories()
{
  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
  KABC::Addressee::List addresses = addressBook->allAddressees();
  QStringList allcategories, aux;

  for ( KABC::Addressee::List::Iterator it = addresses.begin();
        it != addresses.end(); ++it ) {
    aux = ( *it ).categories();
    for ( QStringList::ConstIterator itAux = aux.constBegin();
          itAux != aux.constEnd(); ++itAux ) {
      // don't have duplicates in allcategories
      if ( !allcategories.contains( *itAux )  )
        allcategories += *itAux;
    }
  }
  return allcategories;
}
Ejemplo n.º 15
0
void TestDistrList::testRemoveEntry()
{
    kDebug() ;
    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    DistributionList dl = DistributionList::findByName( ab, "foo" );
    assert( !dl.isEmpty() );
    DistributionList::Entry::List entries = dl.entries( ab );
    check( "entries count before removeEntry", QString::number( entries.count() ), "3" );

    // Removing an empty entry shouldn't do anything
    dl.removeEntry( KABC::Addressee() );
    check( "entries count after removing empty entry", QString::number( dl.entries(ab).count() ), "3" );

    KABC::Addressee addr1 = ab->findByName( "addr1" ).first();
    assert( !addr1.isEmpty() );
    // Removing an entry with the wrong email passed, shouldn't do anything
    dl.removeEntry( addr1, "*****@*****.**" );
    check( "entries count after removing entry with invalid email", QString::number( dl.entries(ab).count() ), "3" );

    // Now remove entry correctly
    dl.removeEntry( addr1 );
    check( "removeEntry(addr1) worked", QString::number( dl.entries(ab).count() ), "2" );
    QStringList emails = dl.emails( ab );
    assert( emails.count() == 2 );
    check( "first email", emails[0], "addr2 <*****@*****.**>" );

    // Now move on to addr2. First remove with no or a wrong email (nothing should happen)
    KABC::Addressee addr2 = ab->findByName( "addr2" ).first();
    assert( !addr2.isEmpty() );
    dl.removeEntry( addr2 );
    check( "entries count after removing entry with no email", QString::number( dl.entries(ab).count() ), "2" );

    // Now remove addr2 correctly
    dl.removeEntry( addr2, "*****@*****.**" );
    check( "entries count after removing addr2", QString::number( dl.entries(ab).count() ), "1" );
    dl.removeEntry( addr2, "*****@*****.**" );
    check( "entries count after removing alternate addr2", QString::number( dl.entries(ab).count() ), "0" );
    assert( dl.entries(ab).isEmpty() );
    assert( dl.emails(ab).isEmpty() );
    assert( DistributionList::isDistributionList( dl ) );

    ab->insertAddressee( dl );
}
Ejemplo n.º 16
0
KABC::Addressee::List
AddressesDialog::allToAddressesNoDuplicates()  const
{
  KABC::Addressee::List aList = allAddressee( d->toItem );
  const QStringList dList = toDistributionLists();
  KABC::AddressBook* abook = KABC::StdAddressBook::self( true );
  for ( QStringList::ConstIterator it = dList.constBegin(); it != dList.constEnd(); ++it ) {
    const KABC::DistributionList *list = abook->findDistributionListByName( *it );
    if ( !list )
      continue;
    const KABC::DistributionList::Entry::List eList = list->entries();
    KABC::DistributionList::Entry::List::ConstIterator eit;
    for( eit = eList.constBegin(); eit != eList.constEnd(); ++eit ) {
      KABC::Addressee a = (*eit).addressee();
      if ( !a.preferredEmail().isEmpty() && !aList.contains( a ) ) {
        aList.append( a ) ;
      }
    }
  }
  return aList;
}
Ejemplo n.º 17
0
bool KAddrBookExternal::addAddressee(const KABC::Addressee &addr)
{
    KABC::AddressBook *addressBook = KABC::StdAddressBook::self(true);

#if KDE_IS_VERSION(3,4,89)
    // This ugly hack will be removed in 4.0
    while(!addressBook->loadingHasFinished())
    {
        QApplication::eventLoop()->processEvents(QEventLoop::ExcludeUserInput);

        // use sleep here to reduce cpu usage
        usleep(100);
    }
#endif

    // Select a resource
    QPtrList<KABC::Resource> kabcResources = addressBook->resources();

    QPtrList<KRES::Resource> kresResources;
    QPtrListIterator<KABC::Resource> resIt(kabcResources);
    KABC::Resource *kabcResource;
    while((kabcResource = resIt.current()) != 0)
    {
        ++resIt;
        if(!kabcResource->readOnly())
        {
            KRES::Resource *res = static_cast<KRES::Resource *>(kabcResource);
            if(res)
                kresResources.append(res);
        }
    }

    kabcResource = static_cast<KABC::Resource *>(KRES::SelectDialog::getResource(kresResources, 0));

    KABC::Ticket *ticket = addressBook->requestSaveTicket(kabcResource);
    bool saved = false;
    if(ticket)
    {
        KABC::Addressee addressee(addr);
        addressee.setResource(kabcResource);
        addressBook->insertAddressee(addressee);
        saved = addressBook->save(ticket);
        if(!saved)
            addressBook->releaseSaveTicket(ticket);
    }

    addressBook->emitAddressBookChanged();

    return saved;
}
Ejemplo n.º 18
0
void KABCPersistence::slotWriteAddressBook()
{
	//kDebug(  14010 ) ;
	KABC::AddressBook* ab = addressBook();
	QListIterator<KABC::Resource *> it( d->pendingResources );
	while ( it.hasNext() )
	{
		//kDebug(  14010 )  << "Writing resource " << it.current()->resourceName();
		KABC::Ticket *ticket = ab->requestSaveTicket( it.next() );
		if ( !ticket )
			kWarning( 14010 ) << "WARNING: Resource is locked by other application!";
		else
		{
			if ( !ab->save( ticket ) )
			{
				kWarning( 14010 ) << "ERROR: Saving failed!";
				ab->releaseSaveTicket( ticket );
			}
		}
		//kDebug( 14010 ) << "Finished writing KABC";
	}
	d->pendingResources.clear();
	d->addrBookWritePending = false;
}
Ejemplo n.º 19
0
CompletionOrderEditor::CompletionOrderEditor(KPIM::LdapSearch *ldapSearch,
        QWidget *parent, const char *name)
    : KDialogBase(parent, name, true, i18n("Edit Completion Order"), Ok | Cancel, Ok, true),
      mConfig("kpimcompletionorder"), mDirty(false)
{
    mItems.setAutoDelete(true);
    // The first step is to gather all the data, creating CompletionItem objects
    QValueList< LdapClient * > ldapClients = ldapSearch->clients();
    for(QValueList<LdapClient *>::const_iterator it = ldapClients.begin(); it != ldapClients.end(); ++it)
    {
        //kdDebug(5300) << "LDAP: host " << (*it)->host() << " weight " << (*it)->completionWeight() << endl;
        mItems.append(new LDAPCompletionItem(*it));
    }
    KABC::AddressBook *addressBook = KABC::StdAddressBook::self(true);
    QPtrList<KABC::Resource> resources = addressBook->resources();
    for(QPtrListIterator<KABC::Resource> resit(resources); *resit; ++resit)
    {
        //kdDebug(5300) << "KABC Resource: " << (*resit)->className() << endl;
        ResourceABC *res = dynamic_cast<ResourceABC *>(*resit);
        if(res)      // IMAP KABC resource
        {
            const QStringList subresources = res->subresources();
            for(QStringList::const_iterator it = subresources.begin(); it != subresources.end(); ++it)
            {
                mItems.append(new KABCImapSubResCompletionItem(res, *it));
            }
        }
        else     // non-IMAP KABC resource
        {
            mItems.append(new SimpleCompletionItem(this, (*resit)->resourceName(),
                                                   (*resit)->identifier()));
        }
    }

#ifndef KDEPIM_NEW_DISTRLISTS // new distr lists are normal contact, so no separate item if using them
    // Add an item for distribution lists
    mItems.append(new SimpleCompletionItem(this, i18n("Distribution Lists"), "DistributionLists"));
#endif

    // Now sort the items, then create the GUI
    mItems.sort();

    QHBox *page = makeHBoxMainWidget();
    mListView = new KListView(page);
    mListView->setSorting(-1);
    mListView->addColumn(QString::null);
    mListView->header()->hide();

    for(QPtrListIterator<CompletionItem> compit(mItems); *compit; ++compit)
    {
        new CompletionViewItem(mListView, *compit);
        kdDebug(5300) << "  " << (*compit)->label() << " " << (*compit)->completionWeight() << endl;
    }

    QVBox *upDownBox = new QVBox(page);
    mUpButton = new KPushButton(upDownBox, "mUpButton");
    mUpButton->setIconSet(BarIconSet("up", KIcon::SizeSmall));
    mUpButton->setEnabled(false);   // b/c no item is selected yet
    mUpButton->setFocusPolicy(StrongFocus);

    mDownButton = new KPushButton(upDownBox, "mDownButton");
    mDownButton->setIconSet(BarIconSet("down", KIcon::SizeSmall));
    mDownButton->setEnabled(false);   // b/c no item is selected yet
    mDownButton->setFocusPolicy(StrongFocus);

    QWidget *spacer = new QWidget(upDownBox);
    upDownBox->setStretchFactor(spacer, 100);

    connect(mListView, SIGNAL(selectionChanged(QListViewItem *)),
            SLOT(slotSelectionChanged(QListViewItem *)));
    connect(mUpButton, SIGNAL(clicked()), this, SLOT(slotMoveUp()));
    connect(mDownButton, SIGNAL(clicked()), this, SLOT(slotMoveDown()));
}
void DistributionListDialog::slotUser1()
{
  bool isEmpty = true;

  KABC::AddressBook *ab = KABC::StdAddressBook::self( true );

  for (int i = 0; i < mRecipientsList->topLevelItemCount(); ++i) {
    DistributionListItem *item = static_cast<DistributionListItem *>(
        mRecipientsList->topLevelItem( i ));
    if ( item && item->checkState( 0 ) == Qt::Checked ) {
      isEmpty = false;
      break;
    }
  }

  if ( isEmpty ) {
    KMessageBox::information( this,
                              i18nc("@info", "There are no recipients in your list. "
                                   "First select some recipients, "
                                   "then try again.") );
    return;
  }

  QString name = mTitleEdit->text();

  if ( name.isEmpty() ) {
    bool ok = false;
    name = KInputDialog::getText( i18nc("@title:window","New Distribution List"),
      i18nc("@label:textbox","Please enter name:"), QString(), &ok, this );
    if ( !ok || name.isEmpty() )
      return;
  }

  if ( ab->findDistributionListByName( name ) ) {
    KMessageBox::information( this,
      i18nc( "@info", "<para>Distribution list with the given name <resource>%1</resource> "
        "already exists. Please select a different name.</para>", name ) );
    return;
  }

  KABC::DistributionList *dlist = ab->createDistributionList( name );

  for (int i = 0; i < mRecipientsList->topLevelItemCount(); ++i) {
    DistributionListItem *item = static_cast<DistributionListItem *>(
        mRecipientsList->topLevelItem( i ));
    if ( item && item->checkState( 0 ) == Qt::Checked ) {
      kDebug() << item->addressee().fullEmail() << item->addressee().uid();
      if ( item->isTransient() ) {
        ab->insertAddressee( item->addressee() );
      }
      if ( item->email() == item->addressee().preferredEmail() ) {
        dlist->insertEntry( item->addressee() );
      } else {
        dlist->insertEntry( item->addressee(), item->email() );
      }
    }
  }

  // let the resource know that the data has changed
  KABC::Resource *resource = dlist->resource();
  resource->insertDistributionList( dlist );

  // save the resource
  bool saveError = true;
  KABC::Ticket *ticket = ab->requestSaveTicket( resource );
  if ( ticket ) {
    if ( ab->save( ticket ) ) {
      saveError = false;
    }
    else
      ab->releaseSaveTicket( ticket );
  }

  if ( saveError ) {
    kWarning() << "Couldn't save new addresses in the distribution list just created to the address book";
  }

  close();
}
Ejemplo n.º 21
0
void JumpButtonBar::updateButtons()
{
  int currentButton = mGroupBox->selectedId();

  // the easiest way to remove all buttons ;)
  mButtons.setAutoDelete( true );
  mButtons.clear();
  mButtons.setAutoDelete( false );

  QStringList characters;

  // calculate how many buttons are possible
  QFontMetrics fm = fontMetrics();
  QPushButton *btn = new QPushButton( "", this );
  btn->hide();
  QSize buttonSize = style().sizeFromContents( QStyle::CT_PushButton, btn,
                     fm.size( ShowPrefix, "X - X") ).
                     expandedTo( QApplication::globalStrut() );
  delete btn;

  int buttonHeight = buttonSize.height() + 8;
  uint possibleButtons = (height() / buttonHeight) - 1;

  QString character;
  KABC::AddressBook *ab = mCore->addressBook();
  KABC::AddressBook::Iterator it;
  for ( it = ab->begin(); it != ab->end(); ++it ) {
    KABC::Field *field = 0;
    field = mCore->currentSortField();
    if ( field ) {
      setEnabled( true );
      if ( !field->value( *it ).isEmpty() )
        character = field->value( *it )[ 0 ].lower();
    } else {
      setEnabled( false );
      return;
    }

    if ( !character.isEmpty() && !characters.contains( character ) )
      characters.append( character );
  }

  sortListLocaleAware( characters );

  if ( characters.count() <= possibleButtons ) {
    // at first the easy case: all buttons fits in window
    for ( uint i = 0; i < characters.count(); ++i ) {
      JumpButton *button = new JumpButton( characters[ i ], QString::null,
                                           mGroupBox );
      connect( button, SIGNAL( clicked() ), this, SLOT( letterClicked() ) );
      mButtons.append( button );
      button->show();
    }
  } else {
    if ( possibleButtons == 0 ) // to avoid crashes on startup
      return;
    int offset = characters.count() / possibleButtons;
    int odd = characters.count() % possibleButtons;
    if ( odd )
      offset++;

    int current = 0;
    for ( uint i = 0; i < possibleButtons; ++i ) {
      if ( characters.count() - current == 0 )
        continue;
      if ( characters.count() - current <= possibleButtons - i ) {
        JumpButton *button = new JumpButton( characters[ current ],
                                             QString::null, mGroupBox );
        connect( button, SIGNAL( clicked() ), this, SLOT( letterClicked() ) );
        mButtons.append( button );
        button->show();
        current++;
      } else {
        int pos = ( current + offset >= (int)characters.count() ?
                    characters.count() - 1 : current + offset - 1 );
        QString range;
        for ( int j = current; j < pos + 1; ++j )
          range.append( characters[ j ] );
        JumpButton *button = new JumpButton( characters[ current ],
                                             characters[ pos ], mGroupBox );
        connect( button, SIGNAL( clicked() ), this, SLOT( letterClicked() ) );
        mButtons.append( button );
        button->show();
        current = ( i + 1 ) * offset;
      }
    }
  }

  if ( currentButton != -1 )
    mGroupBox->setButton( currentButton );
  else
    mGroupBox->setButton( 0 );

  int maxWidth = 0;
  QPushButton *button;
  for ( button = mButtons.first(); button; button = mButtons.next() )
    maxWidth = QMAX( maxWidth, button->sizeHint().width() );

  setFixedWidth( maxWidth );
}
Ejemplo n.º 22
0
bool KABCPersistence::syncWithKABC( MetaContact * mc )
{
	kDebug(14010) ;
	bool contactAdded = false;
	// check whether the dontShowAgain was checked
		KABC::AddressBook* ab = addressBook();
		KABC::Addressee addr  = ab->findByUid( mc->kabcId() );

		if ( !addr.isEmpty() ) // if we are associated with KABC
		{
// load the set of addresses from KABC
		const QStringList customs = addr.customs();

		QStringList::ConstIterator it;
		for ( it = customs.constBegin(); it != customs.constEnd(); ++it )
		{
			QString app, name, value;
			splitField( *it, app, name, value );
			kDebug( 14010 ) << "app=" << app << " name=" << name << " value=" << value;

			if ( app.startsWith( QLatin1String( "messaging/" ) ) )
			{
				if ( name == QLatin1String( "All" ) )
				{
					kDebug( 14010 ) << " syncing \"" << app << ":" << name << " with contact list ";
					// Get the protocol name from the custom field
					// by chopping the 'messaging/' prefix from the custom field app name
					QString protocolName = app.right( app.length() - 10 );
					// munge Jabber hack
					if ( protocolName == QLatin1String( "xmpp" ) )
						protocolName = QLatin1String( "jabber" );

					// Check Kopete supports it
					Protocol * proto = dynamic_cast<Protocol*>( PluginManager::self()->loadPlugin( QLatin1String( "kopete_" ) + protocolName ) );
					if ( !proto )
					{
						KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry,
																					 i18n( "<qt>\"%1\" is not supported by Kopete.</qt>", protocolName ),
																					 i18n( "Could Not Sync with KDE Address Book" )  );
						continue;
					}

					// See if we need to add each contact in this protocol
					QStringList addresses = value.split( QChar( 0xE000 ), QString::SkipEmptyParts );
					QStringList::iterator end = addresses.end();
					for ( QStringList::iterator it = addresses.begin(); it != end; ++it )
					{
						// check whether each one is present in Kopete
						// Is it in the contact list?
						// First discard anything after an 0xE120, this is used by IRC to separate nick and server group name, but
						// IRC doesn't support this properly yet, so the user will have to select an appropriate account manually
						int separatorPos = (*it).indexOf( QChar( 0xE120 ) );
						if ( separatorPos != -1 )
							*it = (*it).left( separatorPos );

						Kopete::MetaContact *otherMc = 0;
						foreach( Kopete::Account *act, Kopete::AccountManager::self()->accounts() )
						{
							if( act->protocol() != proto )
								continue;
							Kopete::Contact *c= act->contacts().value(*it);
							if(c)
							{
								otherMc=c->metaContact();
								break;
							}
						}

						if ( otherMc ) // Is it in another metacontact?
						{
							// Is it already in this metacontact? If so, we needn't do anything
							if ( otherMc == mc )
							{
								kDebug( 14010 ) << *it << " already a child of this metacontact.";
								continue;
							}
							kDebug( 14010 ) << *it << " already exists in OTHER metacontact, move here?";
							// find the Kopete::Contact and attempt to move it to this metacontact.
							otherMc->findContact( proto->pluginId(), QString(), *it )->setMetaContact( mc );
						}
						else
						{
							// if not, prompt to add it
							kDebug( 14010 ) << proto->pluginId() << "://" << *it << " was not found in the contact list.  Prompting to add...";
							if ( KMessageBox::Yes == KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),
									 i18n( "<qt>An address was added to this contact by another application.<br />Would you like to use it in Kopete?<br /><b>Protocol:</b> %1<br /><b>Address:</b> %2</qt>", proto->displayName(), *it ), i18n( "Import Address From Address Book" ), KGuiItem( i18n("Use") ), KGuiItem( i18n("Do Not Use") ), QLatin1String( "ImportFromKABC" ) ) )
							{
								// Check the accounts for this protocol are all connected
								// Most protocols do not allow you to add contacts while offline
								// Would be better to have a virtual bool Kopete::Account::readyToAddContact()
								int accountcount=0;
								bool allAccountsConnected = true;
								Kopete::Account *chosen = 0;
								foreach( Kopete::Account *act, Kopete::AccountManager::self()->accounts() )
								{
									if( act->protocol() == proto) 
									{
										accountcount++;
										if(!act->isConnected())
										{
											allAccountsConnected=false;
											break;
										}
										chosen=act;
									}
								}

								if ( !allAccountsConnected )
								{
									KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry,
											i18n( "<qt>One or more of your accounts using %1 are offline.  Most systems have to be connected to add contacts.  Please connect these accounts and try again.</qt>", protocolName ),
											i18n( "Not Connected" )  );
									continue;
								}

								// we have got a contact to add, our accounts are connected, so add it.
								// Do we need to choose an account
								if ( accountcount > 1 )
								{	// if we have >1 account in this protocol, prompt for the protocol.
									KDialog *chooser = new KDialog(0);
									chooser->setCaption( i18n("Choose Account") );
									chooser->setButtons( KDialog::Ok | KDialog::Cancel );

									AccountSelector *accSelector = new AccountSelector(proto, chooser);
									accSelector->setObjectName( QLatin1String("accSelector") );
									chooser->setMainWidget(accSelector);
									if ( chooser->exec() == QDialog::Rejected )
										continue;
									chosen = accSelector->selectedItem();

									delete chooser;
								}
								else if ( accountcount == 0 )
								{
									KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry,
											i18n( "<qt>You do not have an account configured for <b>%1</b> yet.  Please create an account, connect it, and try again.</qt>", protocolName ),
											i18n( "No Account Found" )  );
									continue;
								}

								// add the contact to the chosen account
								if ( chosen )
								{
									kDebug( 14010 ) << "Adding " << *it << " to " << chosen->accountId();
									if ( chosen->addContact( *it, mc ) )
										contactAdded = true;
									else
										KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry,
											i18n( "<qt>It was not possible to add the contact.</qt>" ),
											i18n( "Could Not Add Contact") ) ;
								}
							}
							else
								kDebug( 14010 ) << " user declined to add " << *it << " to contact list ";
						}
					}
					kDebug( 14010 ) << " all " << addresses.count() << " contacts in " << proto->pluginId() << " checked ";
				}
				else
Ejemplo n.º 23
0
void DistributionListDialog::slotUser1()
{
  bool isEmpty = true;

  KABC::AddressBook *ab = KABC::StdAddressBook::self( true );

  QListViewItem *i = mRecipientsList->firstChild();
  while( i ) {
    DistributionListItem *item = static_cast<DistributionListItem *>( i );
    if ( item->isOn() ) {
      isEmpty = false;
      break;
    }
    i = i->nextSibling();
  }

  if ( isEmpty ) {
    KMessageBox::information( this,
                              i18n("There are no recipients in your list. "
                                   "First select some recipients, "
                                   "then try again.") );
    return;
  }

#ifndef KDEPIM_NEW_DISTRLISTS
  KABC::DistributionListManager manager( ab );
  manager.load();
#endif

  QString name = mTitleEdit->text();

  if ( name.isEmpty() ) {
    bool ok = false;
    name = KInputDialog::getText( i18n("New Distribution List"),
      i18n("Please enter name:"), QString::null, &ok, this );
    if ( !ok || name.isEmpty() )
      return;
  }

#ifdef KDEPIM_NEW_DISTRLISTS
  if ( !KPIM::DistributionList::findByName( ab, name ).isEmpty() ) {
#else
  if ( manager.list( name ) ) {
#endif
    KMessageBox::information( this,
      i18n( "<qt>Distribution list with the given name <b>%1</b> "
        "already exists. Please select a different name.</qt>" ).arg( name ) );
    return;
  }

#ifdef KDEPIM_NEW_DISTRLISTS
  KPIM::DistributionList dlist;
  dlist.setName( name );

  i = mRecipientsList->firstChild();
  while( i ) {
    DistributionListItem *item = static_cast<DistributionListItem *>( i );
    if ( item->isOn() ) {
      kdDebug() << "  " << item->addressee().fullEmail() << endl;
      if ( item->isTransient() ) {
        ab->insertAddressee( item->addressee() );
      }
      if ( item->email() == item->addressee().preferredEmail() ) {
        dlist.insertEntry( item->addressee() );
      } else {
        dlist.insertEntry( item->addressee(), item->email() );
      }
    }
    i = i->nextSibling();
  }

  ab->insertAddressee( dlist );
#else
  KABC::DistributionList *dlist = new KABC::DistributionList( &manager, name );
  i = mRecipientsList->firstChild();
  while( i ) {
    DistributionListItem *item = static_cast<DistributionListItem *>( i );
    if ( item->isOn() ) {
      kdDebug() << "  " << item->addressee().fullEmail() << endl;
      if ( item->isTransient() ) {
        ab->insertAddressee( item->addressee() );
      }
      if ( item->email() == item->addressee().preferredEmail() ) {
        dlist->insertEntry( item->addressee() );
      } else {
        dlist->insertEntry( item->addressee(), item->email() );
      }
    }
    i = i->nextSibling();
  }
#endif

  // FIXME: Ask the user which resource to save to instead of the default
  bool saveError = true;
  KABC::Ticket *ticket = ab->requestSaveTicket( 0 /*default resource */ );
  if ( ticket )
    if ( ab->save( ticket ) )
      saveError = false;
    else
      ab->releaseSaveTicket( ticket );

  if ( saveError )
    kdWarning(5006) << k_funcinfo << " Couldn't save new addresses in the distribution list just created to the address book" << endl;

#ifndef KDEPIM_NEW_DISTRLISTS
  manager.save();
#endif

  close();
}
Ejemplo n.º 24
0
//-----------------------------------------------------------------------------
void KAddrBookExternal::addEmail(const QString &addr, QWidget *parent)
{
    QString email;
    QString name;

    KABC::Addressee::parseEmailAddress(addr, name, email);

    KABC::AddressBook *ab = KABC::StdAddressBook::self(true);

    ab->setErrorHandler(new KABC::GuiErrorHandler(parent));

    // force a reload of the address book file so that changes that were made
    // by other programs are loaded
    ab->asyncLoad();

    // if we have to reload the address book then we should also wait until
    // it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
    // This ugly hack will be removed in 4.0
    while(!ab->loadingHasFinished())
    {
        QApplication::eventLoop()->processEvents(QEventLoop::ExcludeUserInput);

        // use sleep here to reduce cpu usage
        usleep(100);
    }
#endif

    KABC::Addressee::List addressees = ab->findByEmail(email);

    if(addressees.isEmpty())
    {
        KABC::Addressee a;
        a.setNameFromString(name);
        a.insertEmail(email, true);

        {
            KConfig config("kaddressbookrc");
            config.setGroup("General");
            int type = config.readNumEntry("FormattedNameType", 1);

            QString name;
            switch(type)
            {
                case 1:
                    name = a.givenName() + " " + a.familyName();
                    break;
                case 2:
                    name = a.assembledName();
                    break;
                case 3:
                    name = a.familyName() + ", " + a.givenName();
                    break;
                case 4:
                    name = a.familyName() + " " + a.givenName();
                    break;
                case 5:
                    name = a.organization();
                    break;
                default:
                    name = "";
                    break;
            }
            name.simplifyWhiteSpace();

            a.setFormattedName(name);
        }

        if(KAddrBookExternal::addAddressee(a))
        {
            QString text = i18n("<qt>The email address <b>%1</b> was added to your "
                                "addressbook; you can add more information to this "
                                "entry by opening the addressbook.</qt>").arg(addr);
            KMessageBox::information(parent, text, QString::null, "addedtokabc");
        }
    }
    else
    {
        QString text = i18n("<qt>The email address <b>%1</b> is already in your "
                            "addressbook.</qt>").arg(addr);
        KMessageBox::information(parent, text, QString::null,
                                 "alreadyInAddressBook");
    }
    ab->setErrorHandler(0);
}
Ejemplo n.º 25
0
void TestDistrList::testConverter()
{
    kDebug() ;

    KABC::AddressBook *ab = KABC::StdAddressBook::self();
    QList<KABC::Resource*> resources = ab->resources();
    assert( resources.count() == 1 );

    DistributionListConverter converter( resources[ 0 ] );

    DistributionList pimList;
    KABC::DistributionList *kabcList = converter.convertToKABC( pimList );

    assert( kabcList != 0 );
    assert( kabcList->entries().isEmpty() && kabcList->emails().isEmpty() );
    assert( kabcList->identifier().isEmpty() && kabcList->name().isEmpty() );

    DistributionList pimList2 = converter.convertFromKABC( kabcList );
    assert( pimList2 == pimList );

    delete kabcList;

    pimList.setName( "pimlist-name" );
    pimList.setUid( "pimlist-id" );

    kabcList = converter.convertToKABC( pimList );
    assert( kabcList != 0 );
    assert( kabcList->entries().isEmpty() && kabcList->emails().isEmpty() );
    assert( kabcList->identifier() == "pimlist-id" &&
            kabcList->name() == "pimlist-name" );

    pimList2 = converter.convertFromKABC( kabcList );
    assert( pimList2 == pimList );

    delete kabcList;

    KABC::Addressee addr1 = ab->findByName( "addr1" ).first();
    assert( !addr1.isEmpty() );

    pimList.insertEntry( addr1 );

    kabcList = converter.convertToKABC( pimList );
    assert( kabcList != 0 );
    assert( kabcList->identifier() == "pimlist-id" &&
            kabcList->name() == "pimlist-name" );
    assert( kabcList->entries().count() == 1 && kabcList->emails().count() == 1 );
    assert( kabcList->entries()[ 0 ].addressee() == addr1 );

    pimList2 = converter.convertFromKABC( kabcList );
    assert( pimList2 == pimList );

    delete kabcList;

    KABC::Addressee addr2 = ab->findByName( "addr2" ).first();
    assert( !addr2.isEmpty() );

    pimList.insertEntry( addr2 );

    kabcList = converter.convertToKABC( pimList );
    assert( kabcList != 0 );
    assert( kabcList->identifier() == "pimlist-id" &&
            kabcList->name() == "pimlist-name" );
    assert( kabcList->entries().count() == 2 && kabcList->emails().count() == 2 );
    assert( kabcList->entries()[ 0 ].addressee() == addr1 );
    assert( kabcList->entries()[ 2 ].addressee() == addr2 );

    pimList2 = converter.convertFromKABC( kabcList );
    assert( pimList2 == pimList );

    delete kabcList;
}