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;
}
Пример #2
0
void PublishDialog::openAddressbook()
{
#ifndef KORG_NOKABC
  KABC::Addressee::List addressList;
  addressList = KABC::AddresseeDialog::getAddressees( this );
  //KABC::Addressee a = KABC::AddresseeDialog::getAddressee(this);
  KABC::Addressee a = addressList.first();
  if ( !a.isEmpty() ) {
    uint i;
    for ( i=0; i<addressList.size(); i++ ) {
      a = addressList[i];
      mWidget->mNameLineEdit->setEnabled( true );
      mWidget->mEmailLineEdit->setEnabled( true );
      QListViewItem *item = new QListViewItem( mWidget->mAddressListView );
      mWidget->mAddressListView->setSelected( item, true );
      mWidget->mNameLineEdit->setText( a.realName() );
      mWidget->mEmailLineEdit->setText( a.preferredEmail() );
      mWidget->mAddressListView->insertItem( item );
    }
  }
#endif
}
Пример #3
0
void KAddressBookView::updateView()
{
    const QStringList uidList = selectedUids();

    refresh(); // This relists and deselects everything, in all views

    if(!uidList.isEmpty())
    {
        // Keep previous selection
        QStringList::ConstIterator it, uidListEnd(uidList.end());
        for(it = uidList.begin(); it != uidListEnd; ++it)
            setSelected(*it, true);

    }
    else
    {
        const KABC::Addressee::List contacts = mCore->searchManager()->contacts();
        if(!contacts.isEmpty())
            setFirstSelected(true);
        else
            emit selected(QString::null);
    }
}
void KMail::ACLEntryDialog::slotSelectAddresses()
{
  AutoQPointer<KPIM::AddressesDialog> dlg( new KPIM::AddressesDialog( this ) );
  dlg->setShowCC( false );
  dlg->setShowBCC( false );
  if ( mUserIdFormat == FullEmail ) // otherwise we have no way to go back from userid to email
    dlg->setSelectedTo( userIds() );
  if ( dlg->exec() != QDialog::Accepted || !dlg ) {
    return;
  }

  const QStringList distrLists = dlg->toDistributionLists();
  QString txt = distrLists.join( ", " );
  const KABC::Addressee::List lst = dlg->toAddresses();
  if ( !lst.isEmpty() ) {
    for( QList<KABC::Addressee>::ConstIterator it = lst.constBegin(); it != lst.constEnd(); ++it ) {
      if ( !txt.isEmpty() )
        txt += ", ";
      txt += addresseeToUserId( *it, mUserIdFormat );
    }
  }
  mUserIdLineEdit->setText( txt );
}
Пример #5
0
void KMFilterActionWithAddressWidget::slotAddrBook()
{
  KABC::Addressee::List lst = KABC::AddresseeDialog::getAddressees( this );

  if ( lst.empty() )
    return;

  QStringList addrList;

  for( KABC::Addressee::List::const_iterator it = lst.begin(); it != lst.end(); ++it )
    addrList << (*it).fullEmail();

  QString txt = mLineEdit->text().stripWhiteSpace();

  if ( !txt.isEmpty() ) {
    if ( !txt.endsWith( "," ) )
      txt += ", ";
    else
      txt += ' ';
  }

  mLineEdit->setText( txt + addrList.join(",") );
}
Пример #6
0
void PublishDialog::openAddressbook()
{
  KABC::Addressee::List addressList = KABC::AddresseeDialog::getAddressees( this );
  if( addressList.isEmpty() ) {
     return;
  }

  KABC::Addressee a = addressList.first();
  if ( !a.isEmpty() ) {
    int i;
    for ( i=0; i<addressList.size(); i++ ) {
      a = addressList[i];
      mUI.mNameLineEdit->setEnabled( true );
      mUI.mEmailLineEdit->setEnabled( true );
      QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
      mUI.mListWidget->setItemSelected( item, true );
      mUI.mNameLineEdit->setText( a.realName() );
      mUI.mEmailLineEdit->setText( a.preferredEmail() );
      mUI.mListWidget->addItem( item );
    }
    mUI.mRemove->setEnabled( true );
  }
}
Пример #7
0
    bool AddressbookHandler::updateAddressees( KABC::Addressee::List& p_addresseeList )
    {
        bool ret = true;
        KABC::Addressee::List::Iterator it = p_addresseeList.begin();
        KABC::VCardConverter vCardConv;
        QString vCard;

        if ( p_addresseeList.begin() == p_addresseeList.end() ) {
            goto finish;
        }

        setStatus("Writing changed Contacts");

        for ( ; it != p_addresseeList.end(); ++it ) {
            incrementSteps();

            QString kUid = mUidHelper->konnectorId("SynCEAddressbook", (*it).uid(), "---");

            if (kUid != "---") {
                kdDebug(2120) << "Updating Contact on Device: " << "ID-Pair: KDEID: " <<
                    (*it).uid() << " DeviceId: " << kUid << endl;
                vCard = vCardConv.createVCard ( ( *it ) );
                uint32_t retId = m_rra->putVCard ( vCard, mTypeId, getOriginalId( kUid ) );
                if (retId == 0) {
                    addErrorEntry((*it).realName());
                    ret = false;
                }

                m_rra->markIdUnchanged( mTypeId, getOriginalId( kUid ) );
            }

            KApplication::kApplication()->processEvents();
        }

finish:
        return ret;
    }
Пример #8
0
    void AddressbookHandler::fakeAddresseeListFromDevice( KABC::Addressee::List &mAddresseeList, QValueList<uint32_t> &idList )
    {
        for ( QValueList<uint32_t>::const_iterator it = idList.begin(); it != idList.end(); ++it ) {
            KABC::Addressee addr;

            QString konId = "RRA-ID-" + QString::number( *it, 16 ).rightJustify( 8, '0' );
            QString kdeId;

            if ((kdeId = mUidHelper->kdeId("SynCEAddressbook", konId, "---")) != "---") {
                addr.setUid(kdeId);
                mUidHelper->removeId("SynCEAddressbook", addr.uid());
                mAddresseeList.push_back( addr );
            }
            kdDebug(2120) << "Contact: " << konId << "  --  " << kdeId << endl;
        }
    }
void XXPortManager::slotImport( const QString &identifier )
{
  const XXPort *xxport = mFactory.createXXPort( identifier, mParentWidget );
  if( !xxport ) {
    return;
  }

  const KABC::Addressee::List contacts = xxport->importContacts();

  delete xxport;

  if ( contacts.isEmpty() ) { // nothing to import
    return;
  }

  const QStringList mimeTypes( KABC::Addressee::mimeType() );

  QPointer<Akonadi::CollectionDialog> dlg = new Akonadi::CollectionDialog( mParentWidget );
  dlg->setMimeTypeFilter( mimeTypes );
  dlg->setAccessRightsFilter( Akonadi::Collection::CanCreateItem );
  dlg->setCaption( i18n( "Select Address Book" ) );
  dlg->setDescription(
    i18n( "Select the address book the imported contact(s) shall be saved in:" ) );
  dlg->setDefaultCollection( mDefaultAddressBook );

  if ( !dlg->exec() || !dlg ) {
    delete dlg;
    return;
  }

  const Akonadi::Collection collection = dlg->selectedCollection();
  delete dlg;

  if ( !mImportProgressDialog ) {
    mImportProgressDialog = new KProgressDialog( mParentWidget, i18n( "Import Contacts" ) );
    mImportProgressDialog->setLabelText(
      i18np( "Importing one contact to %2", "Importing %1 contacts to %2",
             contacts.count(), collection.name() ) );
    mImportProgressDialog->setAllowCancel( false );
    mImportProgressDialog->setAutoClose( true );
    mImportProgressDialog->progressBar()->setRange( 1, contacts.count() );
  }

  mImportProgressDialog->show();

  for ( int i = 0; i < contacts.count(); ++i ) {
    Akonadi::Item item;
    item.setPayload<KABC::Addressee>( contacts.at( i ) );
    item.setMimeType( KABC::Addressee::mimeType() );

    Akonadi::ItemCreateJob *job = new Akonadi::ItemCreateJob( item, collection );
    connect( job, SIGNAL(result(KJob*)), SLOT(slotImportJobDone(KJob*)) );
  }
}
Пример #10
0
bool ResourceGroupwareBase::asyncSave( Ticket* )
{
  if ( mUploadJob ) {
    // FIXME: If the user cancels, need to reset the mUploadJob variable to 0.
    kdWarning() << "Upload still in progress." << endl;
    return false;
  }

  mUploadJob = createUploadJob( mAdaptor );
  connect( mUploadJob, SIGNAL( result( KPIM::GroupwareJob * ) ),
    SLOT( slotUploadJobResult( KPIM::GroupwareJob * ) ) );

  KABC::Addressee::List addr;
  KABC::Addressee::List::Iterator it;
  KPIM::GroupwareUploadItem::List addedItems, changedItems, deletedItems;

  addr = addedAddressees();
  for( it = addr.begin(); it != addr.end(); ++it ) {
    addedItems.append( adaptor()->newUploadItem( *it,
                                           KPIM::GroupwareUploadItem::Added ) );
  }
  // TODO: Check if the item has changed on the server...
  // In particular, check if the version we based our change on is still current
  // on the server
  addr = changedAddressees();
  for( it = addr.begin(); it != addr.end(); ++it ) {
    changedItems.append( adaptor()->newUploadItem( *it,
                                         KPIM::GroupwareUploadItem::Changed ) );
  }
  addr = deletedAddressees();
  for( it = addr.begin(); it != addr.end(); ++it ) {
    deletedItems.append( adaptor()->newUploadItem( *it,
                                         KPIM::GroupwareUploadItem::Deleted ) );
  }

  mUploadJob->setAddedItems( addedItems );
  mUploadJob->setChangedItems( changedItems );
  mUploadJob->setDeletedItems( deletedItems );

  return true;
}
Пример #11
0
    bool AddressbookHandler::retrieveAddresseeListFromDevice( KABC::Addressee::List &mAddresseeList, QValueList<uint32_t> &idList )
    {
        KABC::VCardConverter vCardConv;
        bool ret = true;

        for ( QValueList<uint32_t>::const_iterator it = idList.begin(); it != idList.end(); ++it ) {
            incrementSteps();

            kdDebug(2120) << "Retrieving Contact from device: " << "RRA-ID-" +
                    QString::number ( *it, 16 ).rightJustify( 8, '0' ) << endl;

            QString vCard = m_rra->getVCard( mTypeId, *it );
            if (vCard.isEmpty()) {
                addErrorEntry("RRA-ID-" + QString::number ( *it, 16 ).rightJustify( 8, '0' ));
                ret = false;
            }

            KABC::Addressee addr = vCardConv.parseVCard ( vCard );
            addr.setFormattedName(addr.formattedName().replace("\\,", ","));

            QString kdeId;

            if ((kdeId = mUidHelper->kdeId("SynCEAddressbook", addr.uid(), "---")) != "---") {
                addr.setUid(kdeId);
            } else {
                mUidHelper->addId("SynCEAddressbook", addr.uid(), addr.uid());
            }

            kdDebug(2120) << "    ID-Pair: KDEID: " << addr.uid() << " DeviceID: " <<
                "RRA-ID-" + QString::number ( *it, 16 ).rightJustify( 8, '0' ) << endl;

            mAddresseeList.push_back( addr );

            KApplication::kApplication()->processEvents();
        }

        return ret;
    }
Пример #12
0
void VCardViewerDialog::slotCancel()
{
  mContacts.clear();
  QDialog::accept();
}
Пример #13
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);
}
Пример #14
0
int main( int argc, char **argv )
{
  KAboutData aboutData( "soapdebug", 0, ki18n("Groupwise Soap Debug"), "0.1" );
  aboutData.addAuthor( ki18n("Cornelius Schumacher"), KLocalizedString(), "*****@*****.**" );

  KCmdLineArgs::init( argc, argv, &aboutData );

  KCmdLineOptions options;
  options.add("s");
  options.add("server <hostname>", ki18n("Server"));
  options.add("u");
  options.add("user <string>", ki18n("User"));
  options.add("p");
  options.add("password <string>", ki18n("Password"));
  options.add("f");
  options.add("freebusy-user <string>", ki18n("Free/Busy user name"));
  options.add("addressbook-id <string>", ki18n("Address book identifier"));
  KCmdLineArgs::addCmdLineOptions( options );

  KApplication app;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  QString user = args->getOption( "user" );
  QString pass = args->getOption( "password" );
  QString url = args->getOption( "server" );

#if 1
  if ( user.isEmpty() ) {
    kError() <<"Need user.";
    return 1; 
  }
  if ( pass.isEmpty() ) {
    kError() <<"Need password.";
    return 1; 
  }
  if ( url.isEmpty() ) {
    kError() <<"Need server.";
    return 1; 
  }
#endif
  KDateTime::Spec spec = KDateTime::Spec::LocalZone();
  GroupwiseServer server( url, user, pass, spec, 0 );

#if 1
  if ( !server.login() ) {
    kError() <<"Unable to login to server" << url;
    return 1;
  }
#endif

#if 0
  server.dumpData();
#endif

#if 0
  server.getCategoryList();
#endif

#if 0
  server.dumpFolderList();
#endif

#if 0
  QString fbUser = args->getOption( "freebusy-user" );
  if ( fbUser.isEmpty() ) {
    kError() <<"Need user for which the freebusy data should be retrieved.";
  } else {
    KCal::FreeBusy *fb = new KCal::FreeBusy;

    server.readFreeBusy( "user1",
      QDate( 2004, 9, 1 ), QDate( 2004, 10, 31 ), fb );
  }
#endif

#if 0
  KTemporaryFile temp;
  temp.setautoRemove(false);
  temp.open();
  KCal::ResourceLocal resource( temp.fileName() );
  resource.setActive( true );
  KCal::CalendarResources calendar;
  calendar.resourceManager()->add( &resource );
  kDebug() <<"Login";

  if ( !server.login() ) {
    kDebug() <<"Unable to login.";
  } else {
    kDebug() <<"Read calendar";
    if ( !server.readCalendarSynchronous( &resource ) ) {
      kDebug() <<"Unable to read calendar data.";
    }
    kDebug() <<"Logout";
    server.logout();
  }
  KCal::ICalFormat format;

  QString ical = format.toString( &calendar );

  kDebug() <<"ICALENDAR:" << ical;
#endif

#if 0
  QString id = args->getOption( "addressbook-id" );

  kDebug() <<"ADDRESSBOOK ID:" << id;

  QStringList ids;
  ids.append( id );

  KABC::ResourceMemory resource;

  kDebug() <<"Login";
  if ( !server.login() ) {
    kError() <<"Unable to login.";
  } else {
    kDebug() <<"Read Addressbook";
    if ( !server.readAddressBooksSynchronous( ids, &resource ) ) {
      kError() <<"Unable to read addressbook data.";
    }
    kDebug() <<"Logout";
    server.logout();
  }

  KABC::Addressee::List addressees;
  KABC::Resource::Iterator it2;
  for( it2 = resource.begin(); it2 != resource.end(); ++it2 ) {
    kDebug() <<"ADDRESSEE:" << (*it2).fullEmail();
    addressees.append( *it2 );
  }
#endif

#if 0    
  server.getDelta();
#endif

  server.logout();

  return 0;
}
bool VCard_LDIFCreator::readContents( const QString &path )
{
  // read file contents
  QFile file( path );
  if ( !file.open( QIODevice::ReadOnly ) )
    return false;

  QString info;
  text.truncate(0);

  // read the file
  QByteArray contents = file.readAll();
  file.close();

  // convert the file contents to a KABC::Addressee address
  KABC::Addressee::List addrList;
  KABC::Addressee addr;
  KABC::VCardConverter converter;

  addrList = converter.parseVCards( contents);
  if ( addrList.count() == 0 ) {
    KABC::AddresseeList l; // FIXME porting
    if ( !KABC::LDIFConverter::LDIFToAddressee( contents, l ) )
	return false;
    // FIXME porting
    KABC::AddresseeList::ConstIterator it( l.constBegin() );
    for ( ; it != l.constEnd(); ++ it ) {
        addrList.append( *it );
    }
  }
  if ( addrList.count()>1 ) {
    // create an overview (list of all names)
    name = i18np("One contact found:", "%1 contacts found:", addrList.count());
    int no, linenr;
    for (linenr=no=0; linenr<30 && no<addrList.count(); ++no) {
       addr = addrList[no];
       info = addr.formattedName().simplified();
       if (info.isEmpty())
          info = addr.givenName() + ' ' + addr.familyName();
       info = info.simplified();
       if (info.isEmpty())
         continue;
       text.append(info);
       text.append("\n");
       ++linenr;
    }
    return true;
  }

  // create card for _one_ contact
  addr = addrList[ 0 ];

  // prepare the text
  name = addr.formattedName().simplified();
  if ( name.isEmpty() )
    name = addr.givenName() + ' ' + addr.familyName();
  name = name.simplified();


  KABC::PhoneNumber::List pnList = addr.phoneNumbers();
  QStringList phoneNumbers;
  for (int no=0; no<pnList.count(); ++no) {
    QString pn = pnList[no].number().simplified();
    if (!pn.isEmpty() && !phoneNumbers.contains(pn))
      phoneNumbers.append(pn);
  }
  if ( !phoneNumbers.isEmpty() )
      text += phoneNumbers.join("\n") + '\n';

  info = addr.organization().simplified();
  if ( !info.isEmpty() )
    text += info + '\n';

  // get an address
  KABC::Address address = addr.address(KABC::Address::Work);
  if (address.isEmpty())
    address = addr.address(KABC::Address::Home);
  if (address.isEmpty())
    address = addr.address(KABC::Address::Pref);
  info = address.formattedAddress();
  if ( !info.isEmpty() )
    text += info + '\n';

  return true;
}
void KOEditorAttachments::handlePasteOrDrop( const QMimeData *mimeData )
{
  KUrl::List urls;
  bool probablyWeHaveUris = false;
  bool weCanCopy = true;
  QStringList labels;

  if ( KPIM::KVCardDrag::canDecode( mimeData ) ) {
    KABC::Addressee::List addressees;
    KPIM::KVCardDrag::fromMimeData( mimeData, addressees );
    for ( KABC::Addressee::List::ConstIterator it = addressees.constBegin();
          it != addressees.constEnd(); ++it ) {
      urls.append( KDEPIMPROTOCOL_CONTACT + ( *it ).uid() );
      // there is some weirdness about realName(), hence fromUtf8
      labels.append( QString::fromUtf8( ( *it ).realName().toLatin1() ) );
    }
    probablyWeHaveUris = true;
  } else if ( KUrl::List::canDecode( mimeData ) ) {
    QMap<QString,QString> metadata;

    urls = KUrl::List::fromMimeData( mimeData, &metadata );
    probablyWeHaveUris = true;
    labels = metadata["labels"].split( ':', QString::SkipEmptyParts );
    for ( QStringList::Iterator it = labels.begin(); it != labels.end(); ++it ) {
      *it = KUrl::fromPercentEncoding( (*it).toLatin1() );
    }
  } else if ( mimeData->hasText() ) {
    QString text = mimeData->text();
    QStringList lst = text.split( '\n', QString::SkipEmptyParts );
    for ( QStringList::ConstIterator it = lst.constBegin(); it != lst.constEnd(); ++it ) {
      urls.append( *it );
    }
    probablyWeHaveUris = true;
  }

  KMenu menu( this );
  QAction *linkAction = 0, *cancelAction;
  if ( probablyWeHaveUris ) {
    linkAction = menu.addAction( i18nc( "@action:inmenu", "&Link here" ) );
    // we need to check if we can reasonably expect to copy the objects
    for ( KUrl::List::ConstIterator it = urls.constBegin(); it != urls.constEnd(); ++it ) {
      if ( !( weCanCopy = KProtocolManager::supportsReading( *it ) ) ) {
        break; // either we can copy them all, or no copying at all
      }
    }
    if ( weCanCopy ) {
      menu.addAction( i18nc( "@action:inmenu", "&Copy here" ) );
    }
  } else {
    menu.addAction( i18nc( "@action:inmenu", "&Copy here" ) );
  }

  menu.addSeparator();
  cancelAction = menu.addAction( i18nc( "@action:inmenu", "C&ancel" ) );

  QByteArray data;
  QString mimeType;
  QString label;

  if(!mimeData->formats().isEmpty() && !probablyWeHaveUris) {
    data=mimeData->data( mimeData->formats().first() );
    mimeType = mimeData->formats().first();
    if( KMimeType::mimeType( mimeData->formats().first() ) )
      label = KMimeType::mimeType( mimeData->formats().first() )->name();
  }


  QAction *ret = menu.exec( QCursor::pos() );
  if ( linkAction == ret ) {
    QStringList::ConstIterator jt = labels.constBegin();
    for ( KUrl::List::ConstIterator it = urls.constBegin();
          it != urls.constEnd(); ++it ) {
      addUriAttachment( (*it).url(), QString(), ( jt == labels.constEnd() ?
                                                  QString() : *( jt++ ) ), true );
    }
  } else if ( cancelAction != ret ) {
    if ( probablyWeHaveUris ) {
      for ( KUrl::List::ConstIterator it = urls.constBegin();
            it != urls.constEnd(); ++it ) {
        KIO::Job *job = KIO::storedGet( *it );
        connect( job, SIGNAL(result(KJob *)), SLOT(downloadComplete(KJob *)) );
      }
    } else { // we take anything
      addDataAttachment( data,
                         mimeType,
                         label );
    }
  }
}
Пример #17
0
void readKMailEntry(const QString &kmailEntry, KABC::AddressBook *ab)
{
    kdDebug() << "KMAILENTRY: " << kmailEntry << endl;

    QString entry = kmailEntry.simplifyWhiteSpace();
    if(entry.isEmpty())
        return;

    QString email;
    QString name;
    QString comment;

    if(entry.at(entry.length() - 1) == ')')
    {
        int br = entry.findRev('(');
        if(br >= 0)
        {
            comment = entry.mid(br + 1, entry.length() - br - 2);
            entry.truncate(br);
            if(entry.at(entry.length() - 1).isSpace())
            {
                entry.truncate(br - 1);
            }
        }
    }

    int posSpace = entry.findRev(' ');
    if(posSpace < 0)
    {
        email = entry;
        if(!comment.isEmpty())
        {
            name = comment;
            comment = "";
        }
    }
    else
    {
        email = entry.mid(posSpace + 1);
        name = entry.left(posSpace);
    }

    if(email.at(0) == '<' && email.at(email.length() - 1) == '>')
    {
        email = email.mid(1, email.length() - 2);
    }
    if(name.at(0) == '"' && name.at(name.length() - 1) == '"')
    {
        name = name.mid(1, name.length() - 2);
    }
    if(name.at(0) == '\'' && name.at(name.length() - 1) == '\'')
    {
        name = name.mid(1, name.length() - 2);
    }

    if(name.at(name.length() - 1) == ')')
    {
        int br = name.findRev('(');
        if(br >= 0)
        {
            comment = name.mid(br + 1, name.length() - br - 2) + " " + comment;
            name.truncate(br);
            if(name.at(name.length() - 1).isSpace())
            {
                name.truncate(br - 1);
            }
        }
    }

    kdDebug() << "  EMAIL   : " << email << endl;
    kdDebug() << "  NAME    : " << name << endl;
    kdDebug() << "  COMMENT : " << comment << endl;

    KABC::Addressee::List al = ab->findByEmail(email);
    if(al.isEmpty())
    {
        KABC::Addressee a;
        a.setNameFromString(name);
        a.insertEmail(email);
        a.setNote(comment);

        ab->insertAddressee(a);

        kdDebug() << "--INSERTED: " << a.realName() << endl;
    }
}
Пример #18
0
void KNotesPlugin::processDropEvent( QDropEvent *event )
{
  const QMimeData *md = event->mimeData();

  if ( KVCardDrag::canDecode( md ) ) {
    KABC::Addressee::List contacts;

    KVCardDrag::fromMimeData( md, contacts );

    KABC::Addressee::List::ConstIterator it;

    QStringList attendees;
    for ( it = contacts.constBegin(); it != contacts.constEnd(); ++it ) {
      QString email = (*it).fullEmail();
      if ( email.isEmpty() ) {
        attendees.append( (*it).realName() + "<>" );
      } else {
        attendees.append( email );
      }
    }
    event->accept();
    static_cast<KNotesPart *>( part() )->newNote(
      i18nc( "@item", "Meeting" ), attendees.join( ", " ) );
    return;
  }

  if ( ICalDrag::canDecode( event->mimeData() ) ) {
    CalendarLocal cal( KSystemTimeZones::local() );
    if ( ICalDrag::fromMimeData( event->mimeData(), &cal ) ) {
      Journal::List journals = cal.journals();
      if ( !journals.isEmpty() ) {
        event->accept();
        Journal *j = journals.first();
        static_cast<KNotesPart *>( part() )->
          newNote( i18nc( "@item", "Note: %1", j->summary() ), j->description() );
        return;
      }
      // else fall through to text decoding
    }
  }

  if ( md->hasText() ) {
    static_cast<KNotesPart *>( part() )->newNote(
      i18nc( "@item", "New Note" ), md->text() );
    return;
  }

  if ( MailList::canDecode( md ) ) {
    MailList mails = MailList::fromMimeData( md );
    event->accept();
    if ( mails.count() != 1 ) {
      KMessageBox::sorry(
        core(),
        i18nc( "@info", "Dropping multiple mails is not supported." ) );
    } else {
      MailSummary mail = mails.first();
      QString txt = i18nc( "@item", "From: %1\nTo: %2\nSubject: %3",
                           mail.from(), mail.to(), mail.subject() );
      static_cast<KNotesPart *>( part() )->newNote(
        i18nc( "@item", "Mail: %1", mail.subject() ), txt );
    }
    return;
  }

  kWarning() << QString( "Cannot handle drop events of type '%1'." ).arg( event->format() );
}
void TodoPlugin::processDropEvent( QDropEvent *event )
{
  const QMimeData *md = event->mimeData();

  if ( KABC::VCardDrag::canDecode( md ) ) {
    KABC::Addressee::List contacts;

    KABC::VCardDrag::fromMimeData( md, contacts );

    KABC::Addressee::List::Iterator it;

    QStringList attendees;
    for ( it = contacts.begin(); it != contacts.end(); ++it ) {
      QString email = (*it).fullEmail();
      if ( email.isEmpty() ) {
        attendees.append( (*it).realName() + "<>" );
      } else {
        attendees.append( email );
      }
    }

    interface()->openTodoEditor( i18nc( "@item", "Meeting" ),
                                 QString(), QStringList(), attendees );
    return;
  }

  if ( KCalUtils::ICalDrag::canDecode( event->mimeData() ) ) {
    KCalCore::MemoryCalendar::Ptr cal( new KCalCore::MemoryCalendar( KSystemTimeZones::local() ) );
    if ( KCalUtils::ICalDrag::fromMimeData( event->mimeData(), cal ) ) {
      KCalCore::Incidence::List incidences = cal->incidences();
      Q_ASSERT( incidences.count() );
      if ( !incidences.isEmpty() ) {
        event->accept();
        KCalCore::Incidence::Ptr i = incidences.first();
        QString summary;
        if ( i->type() == KCalCore::Incidence::TypeJournal ) {
          summary = i18nc( "@item", "Note: %1", i->summary() );
        } else {
          summary = i->summary();
        }
        interface()->openTodoEditor( summary, i->description(), QStringList() );
        return;
      }
      // else fall through to text decoding
    }
  }

  if ( md->hasText() ) {
    QString text = md->text();
    interface()->openTodoEditor( text );
    return;
  }

  if ( KPIM::MailList::canDecode( md ) ) {
    KPIM::MailList mails = KPIM::MailList::fromMimeData( md );
    event->accept();
    if ( mails.count() != 1 ) {
      KMessageBox::sorry(
        core(),
        i18nc( "@info", "Dropping multiple mails is not supported." ) );
    } else {
      KPIM::MailSummary mail = mails.first();
      QString txt = i18nc( "@item", "From: %1\nTo: %2\nSubject: %3",
                           mail.from(), mail.to(), mail.subject() );
      QString uri = QLatin1String( "kmail:" ) +
                    QString::number( mail.serialNumber() ) + '/' +
                    mail.messageId();
      KTemporaryFile tf;
      tf.setAutoRemove( true );
      tf.write( event->encodedData( "message/rfc822" ) );
      interface()->openTodoEditor(
        i18nc( "@item", "Mail: %1", mail.subject() ),
        txt, uri, tf.fileName(), QStringList(), "message/rfc822" );
      tf.close();
    }
    return;
  }

  kWarning() << QString( "Cannot handle drop events of type '%1'." ).arg( event->format() );
}
Пример #20
0
int create(KCmdLineArgs *args)
{
    KODE::Printer p;
    if(args->isSet("warning")) p.setCreationWarning(true);

    bool createKioslave = args->isSet("create-kioslave");
    bool createMain = args->isSet("create-main");

    QString filename = args->getOption("filename");

    if(createMain)
    {
        if(filename.isEmpty())
        {
            kdError() << "Error: No file name given." << endl;
            return 1;
        }

        if(filename.endsWith(".cpp"))
        {
            filename = filename.left(filename.length() - 4);
        }
    }
    else
    {
        if(!args->isSet("classname"))
        {
            kdError() << "Error: No class name given." << endl;
            return 1;
        }
    }

    QString className = args->getOption("classname");

    QString protocol;

    if(createKioslave)
    {
        if(!args->isSet("protocol"))
        {
            protocol = className.lower();
            kdWarning() << "Warning: No protocol for kioslave given. Assuming '"
                        << protocol << "'" << endl;
        }
        else
        {
            protocol = args->getOption("protocol");
        }
    }

    KODE::File file;

    file.setProject(args->getOption("project"));

    QString authorEmail = args->getOption("author-email");
    QString authorName;
    KABC::Addressee a;
    if(authorEmail.isEmpty())
    {
        a = KABC::StdAddressBook::self()->whoAmI();
        authorEmail = a.preferredEmail();
    }
    else
    {
        KABC::Addressee::List as =
            KABC::StdAddressBook::self()->findByEmail(authorEmail);
        if(as.isEmpty())
        {
            kdDebug() << "Unable to find '" << authorEmail << "' in address book."
                      << endl;
        }
        else
        {
            a = as.first();
        }
    }
    if(!a.isEmpty())
    {
        authorName = a.realName();
    }
    if(!authorEmail.isEmpty())
    {
        file.addCopyright(QDate::currentDate().year(), authorName, authorEmail);
    }

    KODE::License l;
    if(args->isSet("gpl")) l = KODE::License(KODE::License::GPL);
    if(args->isSet("lgpl")) l = KODE::License(KODE::License::LGPL);
    l.setQtException(args->isSet("qt-exception"));
    file.setLicense(l);

    file.setNameSpace(args->getOption("namespace"));

    if(createMain)
    {
        file.addInclude("kaboutdata.h");
        file.addInclude("kapplication.h");
        file.addInclude("kdebug");
        file.addInclude("klocale");
        file.addInclude("kcmdlineargs");

        KODE::Code code;
        code += "static const KCmdLineOptions options[] =";
        code += "{";
        code += "  { \"verbose\", \"Verbose output\", 0 },";
        code += "  KCmdLineLastOption";
        code += "};";
        file.addFileCode(code);

        KODE::Function main("main", "int");
        main.addArgument("int argc");
        main.addArgument("char **argv");

        code.clear();
        code += "KAboutData aboutData(\"test\",\"Test\",\"0.1\");";
        code += "KCmdLineArgs::init(argc,argv,&aboutData);";
        code += "KCmdLineArgs::addCmdLineOptions( options );";
        code += "";
        code += "KApplication app;";
        code += "";
        code += "KCmdLineArgs *args = KCmdLineArgs::parsedArgs();";
        code += "";
        code += "Q_UNUSED( args );";
        main.setBody(code);

        file.addFileFunction(main);

        file.setFilename(filename);

        p.printImplementation(file, false);

        return 0;
    }

    KODE::Class c(className);

    if(args->isSet("create-dialog"))
    {
        c.addBaseClass(KODE::Class("KDialogBase"));
        c.addInclude("kdialogbase.h");
    }
    else if(createKioslave)
    {
        c.setDocs("This class implements a kioslave for ...");

        c.addBaseClass(KODE::Class("SlaveBase", "KIO"));
        c.addHeaderInclude("kio/slavebase.h");

        KODE::Function get("get", "void");
        get.addArgument("const KURL &url");

        KODE::Code code;

        code += "kdDebug(7000) << \"" + className + "::get()\" << endl;";
        code += "kdDebug(7000) << \" URL: \" << url.url() << endl;";
        code += "#if 1";
        code += "kdDebug(7000) << \" Path: \" << url.path() << endl;";
        code += "kdDebug(7000) << \" Query: \" << url.query() << endl;";
        code += "kdDebug(7000) << \" Protocol: \" << url.protocol() << endl;";
        code += "kdDebug(7000) << \" Filename: \" << url.filename() << endl;";
        code += "#endif";
        code.newLine();

        code += "mimeType( \"text/plain\" );";
        code.newLine();

        code += "QCString str( \"Hello!\" );";
        code += "data( str );";
        code.newLine();

        code += "finished();";
        code.newLine();

        code += "kdDebug(7000) << \"" + className + "CgiProtocol::get() done\" << endl;";

        get.setBody(code);

        c.addFunction(get);


        c.addInclude("kinstance.h");
        c.addInclude("kdebug.h");
        c.addInclude("sys/types.h");
        c.addInclude("unistd.h");
        c.addInclude("stdlib.h");

        KODE::Function main("kdemain", "int");
        main.addArgument("int argc");
        main.addArgument("char **argv");

        code.clear();

        code += "KInstance instance( \"kio_" + protocol + "\" );";
        code += "";
        code += "kdDebug(7000) << \"Starting kio_" + protocol + "(pid:  \" << getpid() << \")\" << endl;";
        code += "";
        code += "if (argc != 4) {";
        code.indent();
        code += "fprintf( stderr, \"Usage: kio_" + protocol + " protocol domain-socket1 domain-socket2\\n\");";
        code += "exit( -1 );";
        code.unindent();
        code += "}";
        code += "";
        code += className + " slave( argv[2], argv[3] );";
        code += "slave.dispatchLoop();";
        code += "";
        code += "return 0;";

        main.setBody(code);

        file.addFileFunction(main);

        file.addExternCDeclaration(p.functionSignature(main));
    }

    KODE::Function constructor(className);

    if(args->isSet("singleton"))
    {
        constructor.setAccess(KODE::Function::Private);

        KODE::Function self("self", className + " *");
        self.setStatic(true);

        KODE::Code code;
        code += "if ( !mSelf ) {";
        code += "  selfDeleter.setObject( mSelf, new " + className + "() );";
        code += "}";
        code += "return mSelf;";

        self.setBody(code);

        c.addFunction(self);

        KODE::MemberVariable selfVar("mSelf", className + " *", true);
        selfVar.setInitializer("0");

        c.addMemberVariable(selfVar);

        KODE::Variable staticDeleter("selfDeleter",
                                     "KStaticDeleter<" + className + ">",
                                     true);
        file.addFileVariable(staticDeleter);
        file.addInclude("kstaticdeleter.h");
    }

    if(createKioslave)
    {
        constructor.addArgument("const QCString &pool");
        constructor.addArgument("const QCString &app");

        constructor.addInitializer("SlaveBase( \"" + protocol + "\", pool, app )");
    }

    c.addFunction(constructor);

    file.insertClass(c);

    p.printHeader(file);
    p.printImplementation(file);

    if(createKioslave)
    {
        // Write automake Makefile
        KODE::AutoMakefile am;

        am.addEntry("INCLUDES", "$(all_includes)");
        am.newLine();
        am.addEntry("noinst_HEADERS", className.lower() + ".h");
        am.newLine();
        am.addEntry("METASOURCES", "AUTO");
        am.newLine();
        am.addEntry("kdelnkdir", "$(kde_servicesdir)");
        am.addEntry("kdelnk_DATA", protocol + ".protocol");

        KODE::AutoMakefile::Target t("kde_module_LTLIBRARIES",
                                     "kio_" + protocol + ".la");
        t.setSources(className.lower() + ".cpp");
        t.setLibAdd("$(LIB_KIO)");
        t.setLdFlags("$(all_libraries) -module $(KDE_PLUGIN)");

        am.addTarget(t);

        p.printAutoMakefile(am);


        // Write protocol file
        QString protocolFilename = protocol + ".protocol";

        QFileInfo fi(protocolFilename);
        protocolFilename = fi.absFilePath();

        KSaveFile::backupFile(protocolFilename, QString::null, ".backup");

        QFile::remove(protocolFilename);

        KSimpleConfig protocolFile(protocolFilename);

        protocolFile.setGroup("Protocol");
        protocolFile.writeEntry("exec", "kio_" + protocol);
        protocolFile.writeEntry("protocol", protocol);
        protocolFile.writeEntry("input", "none");
        protocolFile.writeEntry("output", "filesystem");
        protocolFile.writeEntry("reading", "true");
        protocolFile.writeEntry("DocPath", "kioslave/" + protocol + ".html");

        protocolFile.sync();
    }

    return 0;
}
Пример #21
0
void SearchManager::search(const QString &pattern, const KABC::Field::List &fields, Type type)
{
    mPattern = pattern;
    mFields = fields;
    mType = type;

    KABC::Addressee::List allContacts;
    mContacts.clear();

#if KDE_VERSION >= 319
    KABC::AddresseeList list(mAddressBook->allAddressees());
    if(!fields.isEmpty())
        list.sortByField(fields.first());

    allContacts = list;
#else
    KABC::AddressBook::ConstIterator abIt(mAddressBook->begin());
    const KABC::AddressBook::ConstIterator abEndIt(mAddressBook->end());
    for(; abIt != abEndIt; ++abIt)
        allContacts.append(*abIt);
#endif

#ifdef KDEPIM_NEW_DISTRLISTS
    // Extract distribution lists from allContacts
    mDistributionLists.clear();
    KABC::Addressee::List::Iterator rmIt(allContacts.begin());
    const KABC::Addressee::List::Iterator rmEndIt(allContacts.end());
    while(rmIt != rmEndIt)
    {
        if(KPIM::DistributionList::isDistributionList(*rmIt))
        {
            mDistributionLists.append(static_cast<KPIM::DistributionList>(*rmIt));
            rmIt = allContacts.remove(rmIt);
        }
        else
            ++rmIt;
    }

    typedef KPIM::DistributionList::Entry Entry;
    if(!mSelectedDistributionList.isNull())
    {
        const KPIM::DistributionList dl = KPIM::DistributionList::findByName(mAddressBook, mSelectedDistributionList);
        if(!dl.isEmpty())
        {
            allContacts.clear();
            const Entry::List entries = dl.entries(mAddressBook);
            const Entry::List::ConstIterator end = entries.end();
            for(Entry::List::ConstIterator it = entries.begin(); it != end; ++it)
            {
                allContacts.append((*it).addressee);
            }
        }
    }

#endif

    if(mPattern.isEmpty())      // no pattern, return all
    {
        mContacts = allContacts;

        emit contactsUpdated();

        return;
    }

    const KABC::Field::List fieldList = !mFields.isEmpty() ? mFields : KABC::Field::allFields();

    KABC::Addressee::List::ConstIterator it(allContacts.begin());
    const KABC::Addressee::List::ConstIterator endIt(allContacts.end());
    for(; it != endIt; ++it)
    {
#ifdef KDEPIM_NEW_DISTRLISTS
        if(KPIM::DistributionList::isDistributionList(*it))
            continue;
#endif

        bool found = false;
        // search over all fields
        KABC::Field::List::ConstIterator fieldIt(fieldList.begin());
        const KABC::Field::List::ConstIterator fieldEndIt(fieldList.end());
        for(; fieldIt != fieldEndIt; ++fieldIt)
        {

            if(type == StartsWith && (*fieldIt)->value(*it).startsWith(pattern, false))
            {
                mContacts.append(*it);
                found = true;
                break;
            }
            else if(type == EndsWith && (*fieldIt)->value(*it).endsWith(pattern, false))
            {
                mContacts.append(*it);
                found = true;
                break;
            }
            else if(type == Contains && (*fieldIt)->value(*it).find(pattern, 0, false) != -1)
            {
                mContacts.append(*it);
                found = true;
                break;
            }
            else if(type == Equals && (*fieldIt)->value(*it).localeAwareCompare(pattern) == 0)
            {
                mContacts.append(*it);
                found = true;
                break;
            }
        }

        if(!found)
        {
            // search over custom fields
            const QStringList customs = (*it).customs();

            QStringList::ConstIterator customIt(customs.begin());
            const QStringList::ConstIterator customEndIt(customs.end());
            for(; customIt != customEndIt; ++customIt)
            {
                int pos = (*customIt).find(':');
                if(pos != -1)
                {
                    const QString value = (*customIt).mid(pos + 1);
                    if(type == StartsWith && value.startsWith(pattern, false))
                    {
                        mContacts.append(*it);
                        break;
                    }
                    else if(type == EndsWith && value.endsWith(pattern, false))
                    {
                        mContacts.append(*it);
                        break;
                    }
                    else if(type == Contains && value.find(pattern, 0, false) != -1)
                    {
                        mContacts.append(*it);
                        break;
                    }
                    else if(type == Equals && value.localeAwareCompare(pattern) == 0)
                    {
                        mContacts.append(*it);
                        break;
                    }
                }
            }
        }
    }

    emit contactsUpdated();
}