コード例 #1
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" );
}
コード例 #2
0
void HtmlExport::formatAttendees( QTextStream *ts, Incidence *event )
{
    Attendee::List attendees = event->attendees();
    if (attendees.count()) {
        *ts << "<em>";
#ifndef KORG_NOKABC
        KABC::AddressBook *add_book = KABC::StdAddressBook::self( true );
        KABC::Addressee::List addressList;
        addressList = add_book->findByEmail(event->organizer().email());
        KABC::Addressee o = addressList.first();
        if (!o.isEmpty() && addressList.size()<2) {
            *ts << "<a href=\"mailto:" << event->organizer().email() << "\">";
            *ts << cleanChars(o.formattedName()) << "</a>\n";
        }
        else *ts << event->organizer().fullName();
#else
        *ts << event->organizer().fullName();
#endif
        *ts << "</em><br />";
        Attendee::List::ConstIterator it;
        for( it = attendees.begin(); it != attendees.end(); ++it ) {
            Attendee *a = *it;
            if (!a->email().isEmpty()) {
                *ts << "<a href=\"mailto:" << a->email();
                *ts << "\">" << cleanChars(a->name()) << "</a>";
            }
            else {
                *ts << "    " << cleanChars(a->name());
            }
            *ts << "<br />" << "\n";
        }
    } else {
        *ts << "    &nbsp;\n";
    }
}
コード例 #3
0
QString KAddressBookView::selectedEmails()
{
    bool first = true;
    QString emailAddrs;
    const QStringList uidList = selectedUids();
    KABC::Addressee addr;
    QString email;

    QStringList::ConstIterator it;
    for(it = uidList.begin(); it != uidList.end(); ++it)
    {
        addr = mCore->addressBook()->findByUid(*it);

        if(!addr.isEmpty())
        {
            QString m = QString::null;

            if(addr.emails().count() > 1)
                m = KABC::EmailSelector::getEmail(addr.emails(), addr.preferredEmail(), this);

            email = addr.fullEmail(m);

            if(!first)
                emailAddrs += ", ";
            else
                first = false;

            emailAddrs += email;
        }
    }

    return emailAddrs;
}
コード例 #4
0
void ResourceGroupwise::slotReadJobData( KIO::Job *job , const QByteArray &data )
{
  kdDebug() << "ResourceGroupwise::slotReadJobData()" << endl;
  Q_UNUSED( job );

  mJobData.append( data.data() );

  KABC::VCardConverter conv;
  QTime profile;
  profile.start();
  Addressee::List addressees = conv.parseVCards( mJobData );
 // kdDebug() << "  parsed " << addressees.count() << " contacts in "  << profile.elapsed() << "ms, now adding to resource..." << endl;

  Addressee::List::ConstIterator it;
  for( it = addressees.begin(); it != addressees.end(); ++it ) {
    KABC::Addressee addr = *it;
    if ( !addr.isEmpty() ) {
      addr.setResource( this );

      QString remote = addr.custom( "GWRESOURCE", "UID" );
      QString local = idMapper().localId( remote );
      if ( local.isEmpty() ) {
        idMapper().setRemoteId( addr.uid(), remote );
      } else {
        addr.setUid( local );
      }

      insertAddressee( addr );
      clearChange( addr );
    }
  }
  mJobData = QString::null;
}
コード例 #5
0
void KOAttendeeEditor::openAddressBook()
{
#ifndef KORG_NOKABC
  KPIM::AddressesDialog *dia = new KPIM::AddressesDialog( this, "adddialog" );
  dia->setShowCC( false );
  dia->setShowBCC( false );
  if ( dia->exec() ) {
    KABC::Addressee::List aList = dia->allToAddressesNoDuplicates();
    for ( KABC::Addressee::List::iterator itr = aList.begin();
          itr != aList.end(); ++itr ) {
      insertAttendeeFromAddressee( (*itr) );
    }
  }
  delete dia;
  return;
#if 0
    // old code
    KABC::Addressee a = KABC::AddresseeDialog::getAddressee(this);
    if (!a.isEmpty()) {
        // If this is myself, I don't want to get a response but instead
        // assume I will be available
        bool myself = KOPrefs::instance()->thatIsMe( a.preferredEmail() );
        KCal::Attendee::PartStat partStat =
            myself ? KCal::Attendee::Accepted : KCal::Attendee::NeedsAction;
        insertAttendee( new Attendee( a.realName(), a.preferredEmail(),
                                      !myself, partStat,
                                      KCal::Attendee::ReqParticipant, a.uid() ) );
    }
#endif
#endif
}
コード例 #6
0
/**
 * Send the file to the contact
 * @param uid the KABC uid you are sending to.
 * @param sourceURL a KURL to send.
 * @param altFileName an alternate filename describing the file
 * @param fileSize file size in bytes
 */
void Addressbook::sendFile(const QString &uid, const KURL &sourceURL, const QString &altFileName, uint fileSize)
{
    if(uid.isEmpty())
    {
        focusAndShowErrorMessage(i18n("Another KDE application tried to use Konversation to send a file to a contact, but did not specify any contact to send the file to.  This is probably a bug in the other application."));
        return;
    }
    KABC::Addressee addressee = addressBook->findByUid(uid);
    if(addressee.isEmpty())
    {
        focusAndShowErrorMessage(i18n("Another KDE application tried to use Konversation to send a file to a contact, but Konversation could not find the specified contact in the KDE address book."));
        return;
    }
    NickInfoPtr nickInfo = getNickInfo(addressee);
    if(!nickInfo)
    {
        QString user = addressee.fullEmail();
        if(!user.isEmpty()) user = "******" + user + ')';
        focusAndShowErrorMessage(i18n("Another KDE application tried to use Konversation to send a file to a contact, but the requested user%1 is not currently online.").arg(user));
        return;
    }
    nickInfo->getServer()->addDccSend(nickInfo->getNickname(), sourceURL, altFileName, fileSize);
    QWidget *widget = nickInfo->getServer()->getViewContainer()->getWindow();
    KWin::demandAttention(widget->winId());       //If activeWindow request is denied, at least demand attention!
    KWin::activateWindow(widget->winId());        //May or may not work, depending on focus stealing prevention.

}
コード例 #7
0
void AddresseeEditorDialog::widgetModified()
{
  const KABC::Addressee addressee = mEditorWidget->addressee();
  if ( !addressee.isEmpty() )
    setTitle( addressee );

  enableButton( KDialogBase::Apply, true );
}
コード例 #8
0
ファイル: documentmodel.cpp プロジェクト: KDE/kraft
void DocumentModel::slotAddresseeFound( const QString& uid, const KABC::Addressee & addressee )
{
  if( addressee.isEmpty() ) {
    kDebug() << "No address found for uid " << uid;
    mAddresses[uid] = KABC::Addressee();
  } else {
    mAddresses[uid] = addressee;
  }
}
コード例 #9
0
ファイル: kraftview.cpp プロジェクト: salt4pommes/kraft-4.2
void KraftView::slotAddresseeFound( const QString& uid, const KABC::Addressee& contact )
{
    if( !contact.isEmpty() ) {
        kDebug() << "Addressee Found with uid " << uid;
        slotNewAddress( contact, false );
        kDebug() << "The loaded Contact has this realname: " << contact.realName() << endl;
    } else {
        kDebug() << "No contact found for uid " << uid;
    }
}
コード例 #10
0
KABC::AddresseeList XXPortSelectDialog::contacts()
{
  const QStringList selection = mCore->selectedUIDs();

  KABC::AddresseeList list;
  if ( mUseSelection->isChecked() ) {
    QStringList::ConstIterator it;
    for ( it = selection.constBegin(); it != selection.constEnd(); ++it ) {
      KABC::Addressee addr = mCore->addressBook()->findByUid( *it );
      if ( !addr.isEmpty() )
        list.append( addr );
    }
  } else if ( mUseFilters->isChecked() ) {
    // find contacts that can pass selected filter
    Filter::List::ConstIterator filterIt;
    for ( filterIt = mFilters.constBegin(); filterIt != mFilters.constEnd(); ++filterIt )
      if ( (*filterIt).name() == mFiltersCombo->currentText() )
        break;

    KABC::AddressBook::Iterator it;
    for ( it = mCore->addressBook()->begin(); it != mCore->addressBook()->end(); ++it ) {
      if ( (*filterIt).filterAddressee( *it ) )
        list.append( *it );
    }
  } else if ( mUseCategories->isChecked() ) {
    const QStringList categorieList = categories();

    KABC::AddressBook::ConstIterator it;
    KABC::AddressBook::ConstIterator addressBookEnd( mCore->addressBook()->constEnd() );
    for ( it = mCore->addressBook()->constBegin(); it != addressBookEnd; ++it ) {
      const QStringList tmp( (*it).categories() );
      QStringList::ConstIterator tmpIt;
      for ( tmpIt = tmp.constBegin(); tmpIt != tmp.constEnd(); ++tmpIt )
        if ( categorieList.contains( *tmpIt ) ) {
          list.append( *it );
          break;
        }
    }
  } else {
    // create a string list of all entries:
    KABC::AddressBook::ConstIterator it;
    for ( it = mCore->addressBook()->constBegin(); it != mCore->addressBook()->constEnd(); ++it )
      list.append( *it );
  }

  if ( mUseSorting ) {
    list.setReverseSorting( mSortTypeCombo->currentIndex() == 1 );
    int pos = mFieldCombo->currentIndex();
    if ( pos < mFields.count() )
      list.sortByField( mFields[ pos ] );
  }

  return list;
}
コード例 #11
0
void KoDocumentInfoDlg::slotLoadFromKABC()
{
#ifdef KDEPIMLIBS_FOUND
    KABC::StdAddressBook *ab = static_cast<KABC::StdAddressBook*>
                               (KABC::StdAddressBook::self());
    if (!ab)
        return;

    KABC::Addressee addr = ab->whoAmI();
    if (addr.isEmpty()) {
        KMessageBox::sorry(0, i18n("No personal contact data set, please use the option \
                                    \"Set as Personal Contact Data\" from the \"Edit\"     menu in KAddressbook to set one."));
        return;
    }
コード例 #12
0
void ResourceGroupwise::slotUpdateJobData( KIO::Job *job, const QByteArray &data )
{
  kdDebug() << "ResourceGroupwise::slotUpdateJobData()" << endl;
  kdDebug() << "  Job address: " << job << endl;
  KABC::VCardConverter conv;
  mJobData.append( data.data() );

  Addressee::List addressees = conv.parseVCards( mJobData );
  Addressee::List::ConstIterator it;

  for( it = addressees.begin(); it != addressees.end(); ++it ) {
    KABC::Addressee addr = *it;
    if ( !addr.isEmpty() ) {
      // if added or changed
      QString syncType = addr.custom( "GWRESOURCE", "SYNC" );
      QString remote = addr.custom( "GWRESOURCE", "UID" );
      QString local = idMapper().localId( remote );

      if ( syncType == "ADD" || syncType == "UPD" )
      {
        addr.setResource( this );
          if ( local.isEmpty() ) {
          idMapper().setRemoteId( addr.uid(), remote );
        } else {
          addr.setUid( local );
        }

        insertAddressee( addr );
        clearChange( addr );
      }
      else if ( syncType == "DEL" )
      {
        // if deleted
        if ( !remote.isEmpty() )
        {
          if ( !local.isEmpty() )
          {
            idMapper().removeRemoteId( remote );
            KABC::Addressee addrToDelete = findByUid( local );
            removeAddressee( addrToDelete );
          }
        }
        else
          kdError() << "Addressee to delete did not have a remote UID, unable to find the corresponding local contact" << endl;
      }
    }
  }
  mJobData = QString::null;
}
コード例 #13
0
void KCalResourceSlox::parseMembersAttribute( const QDomElement &e,
                                              Incidence *incidence )
{
  incidence->clearAttendees();

  QDomNode n;
  for( n = e.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    QDomElement memberElement = n.toElement();
    if ( memberElement.tagName() == fieldName( Participant ) ) {
      QString member = memberElement.text();
      KABC::Addressee account;
      if ( mAccounts ) account = mAccounts->lookupUser( member );
      else kError() << "KCalResourceSlox: no accounts set";
      QString name;
      QString email;
      Attendee *a = incidence->attendeeByUid( member );
      if ( account.isEmpty() ) {
        if ( a ) continue;

        name = member;
        email = member + '@' + KUrl( mPrefs->url() ).host();
      } else {
        name = account.realName();
        email = account.preferredEmail();
      }
      if ( a ) {
        a->setName( name );
        a->setEmail( email );
      } else {
        a = new Attendee( name, email );
        a->setUid( member );
        incidence->addAttendee( a );
      }
      QString status = memberElement.attribute( "confirm" );
      if ( !status.isEmpty() ) {
        if ( status == "accept" ) {
          a->setStatus( Attendee::Accepted );
        } else if ( status == "decline" ) {
          a->setStatus( Attendee::Declined );
        } else {
          a->setStatus( Attendee::NeedsAction );
        }
      }
    } else {
      kDebug() << "Unknown tag in members attribute:"
               << memberElement.tagName();
    }
  }
}
コード例 #14
0
ファイル: viewmanager.cpp プロジェクト: serghei/kde3-kdepim
KABC::Addressee::List ViewManager::selectedAddressees() const
{
    KABC::Addressee::List list;

    const QStringList uids = selectedUids();
    QStringList::ConstIterator it;
    for(it = uids.begin(); it != uids.end(); ++it)
    {
        KABC::Addressee addr = mCore->addressBook()->findByUid(*it);
        if(!addr.isEmpty())
            list.append(addr);
    }

    return list;
}
コード例 #15
0
void ReportGenerator::contactToTemplate( TextTemplate *tmpl, const QString& prefix, const KABC::Addressee& contact )
{
  if( contact.isEmpty() ) return;

  tmpl->setValue( ADDRESS_TAG( prefix, "NAME" ),  escapeTrml2pdfXML( contact.realName() ) );
  QString co = contact.organization();
  if( co.isEmpty() ) {
    co = contact.realName();
  }
  tmpl->setValue( ADDRESS_TAG( prefix, "ORGANISATION" ), escapeTrml2pdfXML( co ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "URL" ),   escapeTrml2pdfXML( contact.url().prettyUrl() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "EMAIL" ), escapeTrml2pdfXML( contact.preferredEmail() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "PHONE" ), escapeTrml2pdfXML( contact.phoneNumber( KABC::PhoneNumber::Work ).number() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "FAX" ),   escapeTrml2pdfXML( contact.phoneNumber( KABC::PhoneNumber::Fax ).number() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "CELL" ),  escapeTrml2pdfXML( contact.phoneNumber( KABC::PhoneNumber::Cell ).number() ) );

  KABC::Address address;
  address = contact.address( KABC::Address::Pref );
  if( address.isEmpty() )
    address = contact.address(KABC::Address::Work );
  if( address.isEmpty() )
    address = contact.address(KABC::Address::Home );
  if( address.isEmpty() )
    address = contact.address(KABC::Address::Postal );

  tmpl->setValue( ADDRESS_TAG( prefix, "POSTBOX" ),
                  escapeTrml2pdfXML( address.postOfficeBox() ) );

  tmpl->setValue( ADDRESS_TAG( prefix, "EXTENDED" ),
                  escapeTrml2pdfXML( address.extended() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "STREET" ),
                  escapeTrml2pdfXML( address.street() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "LOCALITY" ),
                  escapeTrml2pdfXML( address.locality() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "REGION" ),
                  escapeTrml2pdfXML( address.region() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "POSTCODE" ),
                  escapeTrml2pdfXML( address.postalCode() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "COUNTRY" ),
                  escapeTrml2pdfXML( address.country() ) );
  tmpl->setValue( ADDRESS_TAG( prefix, "REGION" ),
                  escapeTrml2pdfXML( address.region() ) );
  tmpl->setValue( ADDRESS_TAG( prefix,"LABEL" ),
                  escapeTrml2pdfXML( address.label() ) );


}
コード例 #16
0
ファイル: viewmanager.cpp プロジェクト: serghei/kde3-kdepim
void ViewManager::dropped(QDropEvent *e)
{
    kdDebug(5720) << "ViewManager::dropped: got a drop event" << endl;

    // don't allow drops from our own drags
    if(e->source() == this)
        return;

    QString clipText, vcards;
    KURL::List urls;

    if(KURLDrag::decode(e, urls))
    {
        KURL::List::ConstIterator it = urls.begin();
        int c = urls.count();
        if(c > 1)
        {
            QString questionString = i18n("Import one contact into your addressbook?", "Import %n contacts into your addressbook?", c);
            if(KMessageBox::questionYesNo(this, questionString, i18n("Import Contacts?"), i18n("Import"), i18n("Do Not Import")) == KMessageBox::Yes)
            {
                for(; it != urls.end(); ++it)
                    emit urlDropped(*it);
            }
        }
        else if(c == 1)
            emit urlDropped(*it);
    }
    else if(KVCardDrag::decode(e, vcards))
    {
        KABC::VCardConverter converter;

        const KABC::Addressee::List list = converter.parseVCards(vcards);
        KABC::Addressee::List::ConstIterator it;
        for(it = list.begin(); it != list.end(); ++it)
        {
            KABC::Addressee a = mCore->addressBook()->findByUid((*it).uid());
            if(a.isEmpty())      // not yet in address book
            {
                mCore->addressBook()->insertAddressee(*it);
                emit modified();
            }
        }

        mActiveView->refresh();
    }
}
コード例 #17
0
/**
 * Refreshes the information for the given item in the list.
 * @param item               Pointer to listview item.
 */
void NicksOnline::refreshItem(QListViewItem* item)
{
    if (!item) return;
    QString serverName;
    QString nickname;
    if (getItemServerAndNick(item, serverName, nickname))
    {
        Server *server = KonversationApplication::instance()->getConnectionManager()->getServerByName(serverName);
        if (server)
        {
            NickInfoPtr nickInfo = server->getNickInfo(nickname);
            KABC::Addressee addressee;
            if (nickInfo)
                addressee = nickInfo->getAddressee();
            else
                addressee = server->getOfflineNickAddressee(nickname);
            int nickState = 2;
            if (addressee.isEmpty()) nickState = 1;
            switch (nickState)
            {
            case nsNotANick:
                break;
            case nsNoAddress:
            {
                item->setPixmap(nlvcKabc, m_kabcIconSet.pixmap(
                                    QIconSet::Small, QIconSet::Disabled, QIconSet::Off));
                break;
            }
            case nsHasAddress:
            {
                item->setPixmap(nlvcKabc, m_kabcIconSet.pixmap(
                                    QIconSet::Small, QIconSet::Normal, QIconSet::On));
                break;
            }
            }
            QString nickAdditionalInfo;
            bool needWhois = false;
            if (nickInfo) nickAdditionalInfo = getNickAdditionalInfo(nickInfo, addressee,
                                                   needWhois);
            item->setText(nlvcAdditionalInfo, nickAdditionalInfo);
            if (item == m_nickListView->selectedItem()) setupAddressbookButtons(nickState);
        }
    }
}
コード例 #18
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
}
コード例 #19
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 );
  }
}
コード例 #20
0
/**
 * Return a string containing formatted additional information about a nick.
 * @param nickInfo          A pointer to NickInfo structure for the nick.  May be Null.
 * @param addressee         Addressbook entry for the nick.  May be empty.
 * @return                  A string formatted for display containing the information
 *                          about the nick.
 * @return needWhois        True if a WHOIS needs to be performed on the nick
 *                          to get additional information.
 */
QString NicksOnline::getNickAdditionalInfo(NickInfoPtr nickInfo, KABC::Addressee addressee,
        bool& needWhois)
{
    QString info;
    if (!addressee.isEmpty())
    {
        if (addressee.fullEmail().isEmpty())
            info += addressee.realName();
        else
            info += addressee.fullEmail();
    }
    QString niInfo;
    if (nickInfo)
    {
        if (nickInfo->isAway())
        {
            niInfo += i18n("Away");
            if (!nickInfo->getAwayMessage().isEmpty())
                niInfo += '(' + nickInfo->getAwayMessage() + ')';
        }
        if (!nickInfo->getHostmask().isEmpty())
            niInfo += ' ' + nickInfo->getHostmask();
        if (!nickInfo->getRealName().isEmpty())
            niInfo += " (" + nickInfo->getRealName() + ')';
        if (!nickInfo->getNetServer().isEmpty())
        {
            niInfo += i18n( " online via %1" ).arg( nickInfo->getNetServer() );
            if (!nickInfo->getNetServerInfo().isEmpty())
                niInfo += " (" + nickInfo->getNetServerInfo() + ')';
        }
        if (!nickInfo->getOnlineSince().isNull())
            niInfo += i18n( " since %1" ).arg( nickInfo->getPrettyOnlineSince() );
    }
    needWhois = niInfo.isEmpty();
    if (!info.isEmpty() && !needWhois) info += ' ';
    return info + niInfo;
}
コード例 #21
0
    /**
     * Send a single message to the specified addressee
     * Any response will be handled by the IM client as a normal
     * conversation.
     * @param uid the KABC uid you want to chat with.
     * @param message the message to send them.
     */
    void Addressbook::messageContact( const QString &uid, const QString& message )
    {
        if(uid.isEmpty())
        {
            focusAndShowErrorMessage(i18n("Another KDE application tried to use Konversation for instant messaging, but did not specify any contact to send the message to.  This is probably a bug in the other application."));
            return;
        }
        KABC::Addressee addressee = addressBook->findByUid(uid);
        if(addressee.isEmpty())
        {
            focusAndShowErrorMessage(i18n("Another KDE application tried to use Konversation for instant messaging, but Konversation could not find the specified contact in the KDE address book."));
            return;
        }
        NickInfoPtr nickInfo = getNickInfo(addressee);
        if(!nickInfo)
        {
            QString user = addressee.fullEmail();
            if(!user.isEmpty()) user = "******" + user + ')';
            focusAndShowErrorMessage(i18n("Another KDE application tried to use Konversation for instant messaging, but the requested user%1 is not online.").arg(user));
            return;
        }

        nickInfo->getServer()->dcopSay(nickInfo->getNickname(), message);
    }
コード例 #22
0
ファイル: formatter.cpp プロジェクト: pvuorela/kcalcore
QString KTnef::msTNEFToVPart( const QByteArray &tnef )
{
  bool bOk = false;

  KTNEFParser parser;
  QByteArray b( tnef );
  QBuffer buf( &b );
  MemoryCalendar::Ptr cal( new MemoryCalendar( KDateTime::UTC ) );
  KABC::Addressee addressee;
  ICalFormat calFormat;
  Event::Ptr event( new Event() );

  if ( parser.openDevice( &buf ) ) {
    KTNEFMessage *tnefMsg = parser.message();
    //QMap<int,KTNEFProperty*> props = parser.message()->properties();

    // Everything depends from property PR_MESSAGE_CLASS
    // (this is added by KTNEFParser):
    QString msgClass = tnefMsg->findProp( 0x001A, QString(), true ).toUpper();
    if ( !msgClass.isEmpty() ) {
      // Match the old class names that might be used by Outlook for
      // compatibility with Microsoft Mail for Windows for Workgroups 3.1.
      bool bCompatClassAppointment = false;
      bool bCompatMethodRequest = false;
      bool bCompatMethodCancled = false;
      bool bCompatMethodAccepted = false;
      bool bCompatMethodAcceptedCond = false;
      bool bCompatMethodDeclined = false;
      if ( msgClass.startsWith( QLatin1String( "IPM.MICROSOFT SCHEDULE." ) ) ) {
        bCompatClassAppointment = true;
        if ( msgClass.endsWith( QLatin1String( ".MTGREQ" ) ) ) {
          bCompatMethodRequest = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGCNCL" ) ) ) {
          bCompatMethodCancled = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPP" ) ) ) {
          bCompatMethodAccepted = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPA" ) ) ) {
          bCompatMethodAcceptedCond = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPN" ) ) ) {
          bCompatMethodDeclined = true;
        }
      }
      bool bCompatClassNote = ( msgClass == "IPM.MICROSOFT MAIL.NOTE" );

      if ( bCompatClassAppointment || "IPM.APPOINTMENT" == msgClass ) {
        // Compose a vCal
        bool bIsReply = false;
        QString prodID = "-//Microsoft Corporation//Outlook ";
        prodID += tnefMsg->findNamedProp( "0x8554", "9.0" );
        prodID += "MIMEDIR/EN\n";
        prodID += "VERSION:2.0\n";
        calFormat.setApplication( "Outlook", prodID );

        iTIPMethod method;
        if ( bCompatMethodRequest ) {
          method = iTIPRequest;
        } else if ( bCompatMethodCancled ) {
          method = iTIPCancel;
        } else if ( bCompatMethodAccepted || bCompatMethodAcceptedCond ||
                 bCompatMethodDeclined ) {
          method = iTIPReply;
          bIsReply = true;
        } else {
          // pending(khz): verify whether "0x0c17" is the right tag ???
          //
          // at the moment we think there are REQUESTS and UPDATES
          //
          // but WHAT ABOUT REPLIES ???
          //
          //

          if ( tnefMsg->findProp(0x0c17) == "1" ) {
            bIsReply = true;
          }
          method = iTIPRequest;
        }

        /// ###  FIXME Need to get this attribute written
        ScheduleMessage schedMsg( event, method, ScheduleMessage::Unknown );

        QString sSenderSearchKeyEmail( tnefMsg->findProp( 0x0C1D ) );

        if ( !sSenderSearchKeyEmail.isEmpty() ) {
          int colon = sSenderSearchKeyEmail.indexOf( ':' );
          // May be e.g. "SMTP:[email protected]"
          if ( sSenderSearchKeyEmail.indexOf( ':' ) == -1 ) {
            sSenderSearchKeyEmail.remove( 0, colon+1 );
          }
        }

        QString s( tnefMsg->findProp( 0x8189 ) );
        const QStringList attendees = s.split( ';' );
        if ( attendees.count() ) {
          for ( QStringList::const_iterator it = attendees.begin();
               it != attendees.end(); ++it ) {
            // Skip all entries that have no '@' since these are
            // no mail addresses
            if ( (*it).indexOf( '@' ) == -1 ) {
              s = (*it).trimmed();

              Attendee::Ptr attendee( new Attendee( s, s, true ) );
              if ( bIsReply ) {
                if ( bCompatMethodAccepted ) {
                  attendee->setStatus( Attendee::Accepted );
                }
                if ( bCompatMethodDeclined ) {
                  attendee->setStatus( Attendee::Declined );
                }
                if ( bCompatMethodAcceptedCond ) {
                  attendee->setStatus( Attendee::Tentative );
                }
              } else {
                attendee->setStatus( Attendee::NeedsAction );
                attendee->setRole( Attendee::ReqParticipant );
              }
              event->addAttendee( attendee );
            }
          }
        } else {
          // Oops, no attendees?
          // This must be old style, let us use the PR_SENDER_SEARCH_KEY.
          s = sSenderSearchKeyEmail;
          if ( !s.isEmpty() ) {
            Attendee::Ptr attendee( new Attendee( QString(), QString(), true ) );
            if ( bIsReply ) {
              if ( bCompatMethodAccepted ) {
                attendee->setStatus( Attendee::Accepted );
              }
              if ( bCompatMethodAcceptedCond ) {
                attendee->setStatus( Attendee::Declined );
              }
              if ( bCompatMethodDeclined ) {
                attendee->setStatus( Attendee::Tentative );
              }
            } else {
              attendee->setStatus( Attendee::NeedsAction );
              attendee->setRole( Attendee::ReqParticipant );
            }
            event->addAttendee( attendee );
          }
        }
        s = tnefMsg->findProp( 0x3ff8 ); // look for organizer property
        if ( s.isEmpty() && !bIsReply ) {
          s = sSenderSearchKeyEmail;
        }
        // TODO: Use the common name?
        if ( !s.isEmpty() ) {
          event->setOrganizer( s );
        }

        s = tnefMsg->findProp( 0x819b ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        event->setDtStart( KDateTime::fromString( s ) ); // ## Format??

        s = tnefMsg->findProp( 0x819c ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        event->setDtEnd( KDateTime::fromString( s ) );

        s = tnefMsg->findProp( 0x810d );
        event->setLocation( s );
        // is it OK to set this to OPAQUE always ??
        //vPart += "TRANSP:OPAQUE\n"; ###FIXME, portme!
        //vPart += "SEQUENCE:0\n";

        // is "0x0023" OK  -  or should we look for "0x0003" ??
        s = tnefMsg->findProp( 0x0023 );
        event->setUid( s );

        // PENDING(khz): is this value in local timezone? Must it be
        // adjusted? Most likely this is a bug in the server or in
        // Outlook - we ignore it for now.
        s = tnefMsg->findProp( 0x8202 ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        // ### kcal always uses currentDateTime()
        // event->setDtStamp( QDateTime::fromString( s ) );

        s = tnefMsg->findNamedProp( "Keywords" );
        event->setCategories( s );

        s = tnefMsg->findProp( 0x1000 );
        event->setDescription( s );

        s = tnefMsg->findProp( 0x0070 );
        event->setSummary( s );

        s = tnefMsg->findProp( 0x0026 );
        event->setPriority( s.toInt() );
        // is reminder flag set ?
        if ( !tnefMsg->findProp( 0x8503 ).isEmpty() ) {
          Alarm::Ptr alarm( new Alarm( event.data() ) ); // TODO: fix when KCalCore::Alarm is fixed
          KDateTime highNoonTime =
            pureISOToLocalQDateTime( tnefMsg->findProp( 0x8502 ).
                                     remove( QChar( '-' ) ).remove( QChar( ':' ) ) );
          KDateTime wakeMeUpTime =
            pureISOToLocalQDateTime( tnefMsg->findProp( 0x8560, "" ).
                                     remove( QChar( '-' ) ).remove( QChar( ':' ) ) );
          alarm->setTime( wakeMeUpTime );

          if ( highNoonTime.isValid() && wakeMeUpTime.isValid() ) {
            alarm->setStartOffset( Duration( highNoonTime, wakeMeUpTime ) );
          } else {
            // default: wake them up 15 minutes before the appointment
            alarm->setStartOffset( Duration( 15 * 60 ) );
          }
          alarm->setDisplayAlarm( i18n( "Reminder" ) );

          // Sorry: the different action types are not known (yet)
          //        so we always set 'DISPLAY' (no sounds, no images...)
          event->addAlarm( alarm );
        }
        //ensure we have a uid for this event
        if ( event->uid().isEmpty() ) {
          event->setUid( CalFormat::createUniqueId() );
        }
        cal->addEvent( event );
        bOk = true;
        // we finished composing a vCal
      } else if ( bCompatClassNote || "IPM.CONTACT" == msgClass ) {
        addressee.setUid( stringProp( tnefMsg, attMSGID ) );
        addressee.setFormattedName( stringProp( tnefMsg, MAPI_TAG_PR_DISPLAY_NAME ) );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL1EMAILADDRESS ), true );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL2EMAILADDRESS ), false );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL3EMAILADDRESS ), false );
        addressee.insertCustom( "KADDRESSBOOK", "X-IMAddress",
                                sNamedProp( tnefMsg, MAPI_TAG_CONTACT_IMADDRESS ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-SpousesName",
                                stringProp( tnefMsg, MAPI_TAG_PR_SPOUSE_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-ManagersName",
                                stringProp( tnefMsg, MAPI_TAG_PR_MANAGER_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-AssistantsName",
                                stringProp( tnefMsg, MAPI_TAG_PR_ASSISTANT ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Department",
                                stringProp( tnefMsg, MAPI_TAG_PR_DEPARTMENT_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Office",
                                stringProp( tnefMsg, MAPI_TAG_PR_OFFICE_LOCATION ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Profession",
                                stringProp( tnefMsg, MAPI_TAG_PR_PROFESSION ) );

        QString s = tnefMsg->findProp( MAPI_TAG_PR_WEDDING_ANNIVERSARY ).
                    remove( QChar( '-' ) ).remove( QChar( ':' ) );
        if ( !s.isEmpty() ) {
          addressee.insertCustom( "KADDRESSBOOK", "X-Anniversary", s );
        }

        addressee.setUrl( KUrl( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_WEBPAGE ) ) );

        // collect parts of Name entry
        addressee.setFamilyName( stringProp( tnefMsg, MAPI_TAG_PR_SURNAME ) );
        addressee.setGivenName( stringProp( tnefMsg, MAPI_TAG_PR_GIVEN_NAME ) );
        addressee.setAdditionalName( stringProp( tnefMsg, MAPI_TAG_PR_MIDDLE_NAME ) );
        addressee.setPrefix( stringProp( tnefMsg, MAPI_TAG_PR_DISPLAY_NAME_PREFIX ) );
        addressee.setSuffix( stringProp( tnefMsg, MAPI_TAG_PR_GENERATION ) );

        addressee.setNickName( stringProp( tnefMsg, MAPI_TAG_PR_NICKNAME ) );
        addressee.setRole( stringProp( tnefMsg, MAPI_TAG_PR_TITLE ) );
        addressee.setOrganization( stringProp( tnefMsg, MAPI_TAG_PR_COMPANY_NAME ) );
        /*
        the MAPI property ID of this (multiline) )field is unknown:
        vPart += stringProp(tnefMsg, "\n","NOTE", ... , "" );
        */

        KABC::Address adr;
        adr.setPostOfficeBox( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_PO_BOX ) );
        adr.setStreet( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_STREET ) );
        adr.setLocality( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_CITY ) );
        adr.setRegion( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_STATE_OR_PROVINCE ) );
        adr.setPostalCode( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_POSTAL_CODE ) );
        adr.setCountry( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_COUNTRY ) );
        adr.setType( KABC::Address::Home );
        addressee.insertAddress( adr );

        adr.setPostOfficeBox( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSPOBOX ) );
        adr.setStreet( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSSTREET ) );
        adr.setLocality( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSCITY ) );
        adr.setRegion( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSSTATE ) );
        adr.setPostalCode( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSPOSTALCODE ) );
        adr.setCountry( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSCOUNTRY ) );
        adr.setType( KABC::Address::Work );
        addressee.insertAddress( adr );

        adr.setPostOfficeBox( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_PO_BOX ) );
        adr.setStreet( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_STREET ) );
        adr.setLocality( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_CITY ) );
        adr.setRegion( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_STATE_OR_PROVINCE ) );
        adr.setPostalCode( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_POSTAL_CODE ) );
        adr.setCountry( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_COUNTRY ) );
        adr.setType( KABC::Address::Dom );
        addressee.insertAddress( adr );

        // problem: the 'other' address was stored by KOrganizer in
        //          a line looking like the following one:
        // vPart += "\nADR;TYPE=dom;TYPE=intl;TYPE=parcel;TYPE=postal;TYPE=work;"
        //          "TYPE=home:other_pobox;;other_str1\nother_str2;other_loc;other_region;"
        //          "other_pocode;other_country"

        QString nr;
        nr = stringProp( tnefMsg, MAPI_TAG_PR_HOME_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Home ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_BUSINESS_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Work ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_MOBILE_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Cell ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_HOME_FAX_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Fax | KABC::PhoneNumber::Home ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_BUSINESS_FAX_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Fax | KABC::PhoneNumber::Work ) );

        s = tnefMsg->findProp( MAPI_TAG_PR_BIRTHDAY ).
            remove( QChar( '-' ) ).remove( QChar( ':' ) );
        if ( !s.isEmpty() ) {
          addressee.setBirthday( QDateTime::fromString( s ) );
        }

        bOk = ( !addressee.isEmpty() );
      } else if ( "IPM.NOTE" == msgClass ) {

      } // else if ... and so on ...
    }
  }

  // Compose return string
  // KDAB_TODO: Interesting, without the explicit QString the toString call is
  //            reported to be ambigious with toString( const Incidence::Ptr & ).
  const QString iCal = calFormat.toString( cal, QString() );
  if ( !iCal.isEmpty() ) {
    // This was an iCal
    return iCal;
  }

  // Not an iCal - try a vCard
  KABC::VCardConverter converter;
  return QString::fromUtf8( converter.createVCard( addressee ) );
}
コード例 #23
0
bool TemplateInterface::expandMacros( QMap<QString, QString> &map, QWidget *parentWindow )
{
  KABC::StdAddressBook *addrBook = 0;
  KABC::Addressee userAddress;
  QDateTime datetime = QDateTime::currentDateTime();
  QDate date = datetime.date();
  QTime time = datetime.time();

  QMap<QString,QString>::Iterator it;
  for ( it = map.begin(); it != map.end(); ++it )
  {
    QString placeholder = it.key();
    if ( map[ placeholder ].isEmpty() )
    {
      if ( placeholder == "index" ) map[ placeholder ] = "i";
      else if ( placeholder == "loginname" )
      {}
      else if ( placeholder == "firstname" )
      {
        INITKABC;
        if ( !userAddress.isEmpty() )
          map[ placeholder ] = userAddress.givenName();
      }
      else if ( placeholder == "lastname" )
      {
        INITKABC;
        if ( !userAddress.isEmpty() )
          map[ placeholder ] = userAddress.familyName();
      }
      else if ( placeholder == "fullname" )
      {
        INITKABC;
        if ( !userAddress.isEmpty() )
          map[ placeholder ] = userAddress.assembledName();
      }
      else if ( placeholder == "email" )
      {
        INITKABC;
        if ( !userAddress.isEmpty() )
          map[ placeholder ] = userAddress.preferredEmail();
      }
      else if ( placeholder == "date" )
      {
        map[ placeholder ] = KGlobal::locale() ->formatDate( date, true );
      }
      else if ( placeholder == "time" )
      {
        map[ placeholder ] = KGlobal::locale() ->formatTime( time, true, false );
      }
      else if ( placeholder == "year" )
      {
        map[ placeholder ] = KGlobal::locale() ->calendar() ->yearString( date, false );
      }
      else if ( placeholder == "month" )
      {
        map[ placeholder ] = QString::number( KGlobal::locale() ->calendar() ->month( date ) );
      }
      else if ( placeholder == "day" )
      {
        map[ placeholder ] = QString::number( KGlobal::locale() ->calendar() ->day( date ) );
      }
      else if ( placeholder == "hostname" )
      {
        char hostname[ 256 ];
        hostname[ 0 ] = 0;
        gethostname( hostname, 255 );
        hostname[ 255 ] = 0;
        map[ placeholder ] = QString::fromLocal8Bit( hostname );
      }
      else if ( placeholder == "cursor" )
      {
        map[ placeholder ] = "|";
      }
      else map[ placeholder ] = placeholder;
    }
  }
  return true;
}
コード例 #24
0
bool ContactListView::event( QEvent *e )
{

  if( e->type() != QEvent::ToolTip )
    return K3ListView::event( e );
  if ( !tooltips() )
    return true;
  QHelpEvent * he = static_cast< QHelpEvent * >( e );
  QPoint pnt = viewport()->mapFromGlobal( mapToGlobal( he->pos() ) );
  Q3ListViewItem * item = itemAt ( pnt );
  if ( item )
  {
    ContactListViewItem *plvi = static_cast<ContactListViewItem *>( item );
    QString s;

    //kDebug(5720) <<"Tip rec:" << r.x() <<"," << r.y() <<"," << r.width()
    //          << "," << r.height();

    KABC::Addressee a = plvi->addressee();
    if (a.isEmpty())
      return true;

    s += i18nc("label: value", "%1: %2", a.formattedNameLabel(),
               a.formattedName());

    s += '\n';
    s += i18nc("label: value", "%1: %2", a.organizationLabel(),
               a.organization());

    QString notes = a.note().trimmed();
    if ( !notes.isEmpty() ) {
      notes += '\n';
      s += '\n' + i18nc("label: value", "%1: \n", a.noteLabel());
      QFontMetrics fm( font() );

      // Begin word wrap code based on QMultiLineEdit code
      int i = 0;
      bool doBreak = false;
      int linew = 0;
      int lastSpace = -1;
      int a = 0;
      int lastw = 0;

      while ( i < int(notes.length()) ) {
        doBreak = false;
        if ( notes[i] != '\n' )
          linew += fm.width( notes[i] );

        if ( lastSpace >= a && notes[i] != '\n' )
          if  (linew >= parentWidget()->width()) {
            doBreak = true;
            if ( lastSpace > a ) {
              i = lastSpace;
              linew = lastw;
            }
            else
              i = qMax( a, i-1 );
          }

        if ( notes[i] == '\n' || doBreak ) {
          s += notes.mid( a, i - a + (doBreak?1:0) ) +'\n';

          a = i + 1;
          lastSpace = a;
          linew = 0;
        }

        if ( notes[i].isSpace() ) {
          lastSpace = i;
          lastw = linew;
        }

        if ( lastSpace <= a ) {
          lastw = linew;
        }

        ++i;
      }
    }
    if ( s.isEmpty() )
      QToolTip::hideText();
    else
      QToolTip::showText( he->globalPos(), s );
  }
  return true;
}
コード例 #25
0
ファイル: kodemain.cpp プロジェクト: serghei/kde3-kdepim
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;
}
コード例 #26
0
ファイル: opera_xxport.cpp プロジェクト: serghei/kde3-kdepim
KABC::AddresseeList OperaXXPort::importContacts(const QString &) const
{
    KABC::AddresseeList addrList;

    QString fileName = KFileDialog::getOpenFileName(QDir::homeDirPath() + QString::fromLatin1("/.opera/contacts.adr"));
    if(fileName.isEmpty())
        return addrList;

    QFile file(fileName);
    if(!file.open(IO_ReadOnly))
    {
        QString msg = i18n("<qt>Unable to open <b>%1</b> for reading.</qt>");
        KMessageBox::error(parentWidget(), msg.arg(fileName));
        return addrList;
    }

    QTextStream stream(&file);
    stream.setEncoding(QTextStream::UnicodeUTF8);
    QString line, key, value;
    bool parseContact = false;
    KABC::Addressee addr;

    QRegExp separator("\x02\x02");

    while(!stream.atEnd())
    {
        line = stream.readLine();
        line = line.stripWhiteSpace();
        if(line == QString::fromLatin1("#CONTACT"))
        {
            parseContact = true;
            addr = KABC::Addressee();
            continue;
        }
        else if(line.isEmpty())
        {
            parseContact = false;
            if(!addr.isEmpty())
            {
                addrList.append(addr);
                addr = KABC::Addressee();
            }
            continue;
        }

        if(parseContact == true)
        {
            int sep = line.find('=');
            key = line.left(sep).lower();
            value = line.mid(sep + 1);
            if(key == QString::fromLatin1("name"))
                addr.setNameFromString(value);
            else if(key == QString::fromLatin1("mail"))
            {
                QStringList emails = QStringList::split(separator, value);

                QStringList::Iterator it = emails.begin();
                bool preferred = true;
                for(; it != emails.end(); ++it)
                {
                    addr.insertEmail(*it, preferred);
                    preferred = false;
                }
            }
            else if(key == QString::fromLatin1("phone"))
                addr.insertPhoneNumber(KABC::PhoneNumber(value));
            else if(key == QString::fromLatin1("fax"))
                addr.insertPhoneNumber(KABC::PhoneNumber(value,
                                       KABC::PhoneNumber::Fax | KABC::PhoneNumber::Home));
            else if(key == QString::fromLatin1("postaladdress"))
            {
                KABC::Address address(KABC::Address::Home);
                address.setLabel(value.replace(separator, "\n"));
                addr.insertAddress(address);
            }
            else if(key == QString::fromLatin1("description"))
                addr.setNote(value.replace(separator, "\n"));
            else if(key == QString::fromLatin1("url"))
                addr.setUrl(KURL(value));
            else if(key == QString::fromLatin1("pictureurl"))
            {
                KABC::Picture pic(value);
                addr.setPhoto(pic);
            }
        }
    }

    file.close();

    return addrList;
}
コード例 #27
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
コード例 #28
0
QString CSVTemplate::fieldText(int column, const KABC::Addressee& addressee) const
{
    if (column < 0 || addressee.isEmpty()) return QString();
    if (m_columnToField.isEmpty()) return QString();

    QMap<int, int>::const_iterator it = m_columnToField.find(column);
    if (it == m_columnToField.end()) return QString();

    QString text;
    switch (it.value())
    {
        case  0: // "Formatted Name"
            text = addressee.formattedName();
            break;
        case  1: // "Family Name"
            text = addressee.familyName();
            break;
        case  2: // "Given Name"
            text = addressee.givenName();
            break;
        case  3: // "Additional Names"
            text = addressee.additionalName();
            break;
        case  4: // "Honorific Prefixes"
            text = addressee.prefix();
            break;
        case  5: // "Honorific Suffixes"
            text = addressee.suffix();
            break;
        case  6: // "Nick Name"
            text = addressee.nickName();
            break;
        case  7: // "Birthday"
            text = formatDate(addressee.birthday());
            break;
        case  8: // "Home Address Street"
            text = addressee.address(Address::Home).street();
            break;
        case  9: // "Home Address Locality"
            text = addressee.address(Address::Home).locality();
            break;
        case 10: // "Home Address Region"
            text = addressee.address(Address::Home).region();
            break;
        case 11: // "Home Address Postal Code"
            text = addressee.address(Address::Home).postalCode();
            break;
        case 12: // "Home Address Country"
            text = addressee.address(Address::Home).country();
            break;
        case 13: // "Home Address Label"
            text = addressee.address(Address::Home).label();
            break;
        case 14: // "Business Address Street"
            text = addressee.address(Address::Work).street();
            break;
        case 15: // "Business Address Locality"
            text = addressee.address(Address::Work).locality();
            break;
        case 16: // "Business Address Region"
            text = addressee.address(Address::Work).region();
            break;
        case 17: // "Business Address Postal Code"
            text = addressee.address(Address::Work).postalCode();
            break;
        case 18: // "Business Address Country"
            text = addressee.address(Address::Work).country();
            break;
        case 19: // "Business Address Label"
            text = addressee.address(Address::Work).label();
            break;
        case 20: // "Home Phone"
            text = addressee.phoneNumber(PhoneNumber::Home).number();
            break;
        case 21: // "Business Phone"
            text = addressee.phoneNumber(PhoneNumber::Work).number();
            break;
        case 22: // "Mobile Phone"
            text = addressee.phoneNumber(PhoneNumber::Cell).number();
            break;
        case 23: // "Home Fax"
            text = addressee.phoneNumber(PhoneNumber::Fax | PhoneNumber::Home).number();
            break;
        case 24: // "Business Fax"
            text = addressee.phoneNumber(PhoneNumber::Fax | PhoneNumber::Work).number();
            break;
        case 25: // "Car Phone"
            text = addressee.phoneNumber(PhoneNumber::Car).number();
            break;
        case 26: // "Isdn"
            text = addressee.phoneNumber(PhoneNumber::Isdn).number();
            break;
        case 27: // "Pager"
            text = addressee.phoneNumber(PhoneNumber::Pager).number();
            break;
        case 28: // "Email Address"
            text = addressee.preferredEmail();
            break;
        case 29: // "Mail Client"
            text = addressee.mailer();
            break;
        case 30: // "Title"
            text = addressee.title();
            break;
        case 31: // "Role"
            text = addressee.role();
            break;
        case 32: // "Organization"
            text = addressee.organization();
            break;
        case 33: // "Note"
            text = addressee.note();
            break;
        case 34: // "URL"
            text = addressee.url().prettyUrl();
            break;
        case 35: // "Department"
            break;
        case 36: // "Profession"
            break;
        case 37: // "Assistant's Name"
            break;
        case 38: // "Manager's Name"
            break;
        case 39: // "Spouse's Name"
            break;
        case 40: // "Office"
            break;
        case 41: // "IM Address"
            break;
        case 42: // "Anniversary"
            break;

        default:
            break;
    }

    return text;
}
コード例 #29
0
/**
 * Perform an addressbook command (edit contact, create new contact,
 * change/delete association.)
 * @param id                The command id.  @ref CommandIDs.
 *
 * The operation is performed on the nickname at the currently-selected item in
 * the nicklistview.
 *
 * Also refreshes the nicklistview display to reflect the new addressbook state
 * for the nick.
 */
void NicksOnline::doCommand(int id)
{
    if(id < 0)
    {
        return;
    }

    QString serverName;
    QString nickname;
    QListViewItem* item = m_nickListView->selectedItem();

    if(!getItemServerAndNick(item, serverName, nickname))
    {
        return;
    }

    // Get the server object corresponding to the server name.
    Server* server = KonversationApplication::instance()->getConnectionManager()->getServerByName(serverName);

    if (!server) return;

    // Get NickInfo object corresponding to the nickname.
    NickInfoPtr nickInfo = server->getNickInfo(nickname);
    // Get addressbook entry for the nick.
    KABC::Addressee addressee;

    if(nickInfo)
    {
        addressee = nickInfo->getAddressee();
    }
    else
    {
        addressee = server->getOfflineNickAddressee(nickname);
    }

    switch(id)
    {
    case ciSendEmail:
        Konversation::Addressbook::self()->sendEmail(addressee);
        return;                               //no need to refresh item
    case ciAddressbookEdit:
        Konversation::Addressbook::self()->editAddressee(addressee.uid());
        return;                               //no need to refresh item - nickinfo changed will be called anyway.
    case ciAddressbookChange:
        if(nickInfo)
        {
            nickInfo->showLinkAddressbookUI();
        }
        else
        {
            LinkAddressbookUI *linkaddressbookui = new LinkAddressbookUI(server->getViewContainer()->getWindow(), NULL, nickname, server->getServerName(), server->getDisplayName(), addressee.realName());
            linkaddressbookui->show();
        }
        break;
    case ciAddressbookNew:
    case ciAddressbookDelete:
    {
        Konversation::Addressbook *addressbook = Konversation::Addressbook::self();

        if(addressbook && addressbook->getAndCheckTicket())
        {
            if(id == ciAddressbookDelete)
            {
                if (addressee.isEmpty())
                {
                    return;
                }

                addressbook->unassociateNick(addressee, nickname, server->getServerName(), server->getDisplayName());
            }
            else
            {
                addressee.setGivenName(nickname);
                addressee.setNickName(nickname);
                addressbook->associateNickAndUnassociateFromEveryoneElse(addressee, nickname, server->getServerName(), server->getDisplayName());
            }
            if(addressbook->saveTicket())
            {
                //saveTicket will refresh the addressees for us.
                if(id == ciAddressbookNew)
                {
                    Konversation::Addressbook::self()->editAddressee(addressee.uid());
                }
            }
        }
        break;
    }
    case ciJoinChannel:
    {
        // only join real channels
        if (static_cast<NicksOnlineItem*>(m_nickListView->selectedItem())->type() == NicksOnlineItem::ChannelItem)
        {
            QString contactChannel = m_nickListView->selectedItem()->text(nlvcChannel);
            server->queue( "JOIN "+contactChannel );
        }
        break;
    }
    case ciWhois:
        server->queue("WHOIS "+nickname);
        return;
    case ciOpenQuery:
        NickInfoPtr nickInfo = server->obtainNickInfo(nickname);
        class Query* query = server->addQuery(nickInfo, true /*we initiated*/);
        emit showView(query);
        return;
    }

    refreshItem(item);
}
コード例 #30
0
/**
 * Refresh the nicklistview for a single server.
 * @param server            The server to be refreshed.
 */
void NicksOnline::updateServerOnlineList(Server* servr)
{
    bool newNetworkRoot = false;
    QString serverName = servr->getServerName();
    QString networkName = servr->getDisplayName();
    QListViewItem* networkRoot = findNetworkRoot(networkName);
    // If network is not in our list, add it.
    if (!networkRoot)
    {
        networkRoot = new NicksOnlineItem(NicksOnlineItem::NetworkRootItem,m_nickListView,networkName);
        newNetworkRoot = true;
    }
    // Store server name in hidden column.
    // Note that there could be more than one server in the network connected,
    // but it doesn't matter because all the servers in a network have the same
    // watch list.
    networkRoot->setText(nlvcServerName, serverName);
    // Update list of servers in the network that are connected.
    QStringList serverList = QStringList::split(",", networkRoot->text(nlvcAdditionalInfo));
    if (!serverList.contains(serverName)) serverList.append(serverName);
    networkRoot->setText(nlvcAdditionalInfo, serverList.join(","));
    // Get item in nicklistview for the Offline branch.
    QListViewItem* offlineRoot = findItemType(networkRoot, NicksOnlineItem::OfflineItem);
    if (!offlineRoot)
    {
        offlineRoot = new NicksOnlineItem(NicksOnlineItem::OfflineItem,networkRoot,i18n("Offline"));
        offlineRoot->setText(nlvcServerName, serverName);
    }

    // Get watch list.
    QStringList watchList = servr->getWatchList();
    QStringList::iterator itEnd = watchList.end();
    QString nickname;

    for (QStringList::iterator it = watchList.begin(); it != itEnd; ++it)
    {
        nickname = (*it);
        NickInfoPtr nickInfo = getOnlineNickInfo(networkName, nickname);

        if (nickInfo && nickInfo->getPrintedOnline())
        {
            // Nick is online.
            // Which server did NickInfo come from?
            Server* server=nickInfo->getServer();
            // Get addressbook entry (if any) for the nick.
            KABC::Addressee addressee = nickInfo->getAddressee();
            // Construct additional information string for nick.
            bool needWhois = false;
            QString nickAdditionalInfo = getNickAdditionalInfo(nickInfo, addressee, needWhois);
            // Remove from offline branch if present.
            QListViewItem* item = findItemChild(offlineRoot, nickname, NicksOnlineItem::NicknameItem);
            if (item) delete item;
            // Add to network if not already added.
            QListViewItem* nickRoot = findItemChild(networkRoot, nickname, NicksOnlineItem::NicknameItem);
            if (!nickRoot) nickRoot = new NicksOnlineItem(NicksOnlineItem::NicknameItem,networkRoot, nickname, nickAdditionalInfo);
            nickRoot->setText(nlvcAdditionalInfo, nickAdditionalInfo);
            nickRoot->setText(nlvcServerName, serverName);
            // If no additional info available, request a WHOIS on the nick.
            if (!m_whoisRequested)
            {
                if (needWhois)
                {
                    requestWhois(networkName, nickname);
                    m_whoisRequested = true;
                }
            }
            // Set Kabc icon if the nick is associated with an addressbook entry.
            if (!addressee.isEmpty())
                nickRoot->setPixmap(nlvcKabc, m_kabcIconSet.pixmap(
                                        QIconSet::Small, QIconSet::Normal, QIconSet::On));
            else
                nickRoot->setPixmap(nlvcKabc, m_kabcIconSet.pixmap(
                                        QIconSet::Small, QIconSet::Disabled, QIconSet::Off));

            QStringList channelList = server->getNickChannels(nickname);
            QStringList::iterator itEnd2 = channelList.end();

            for (QStringList::iterator it2 = channelList.begin(); it2 != itEnd2; ++it2)
            {
                // Known channels where nickname is online and mode in each channel.
                // FIXME: If user connects to multiple servers in same network, the
                // channel info will differ between the servers, resulting in inaccurate
                // mode and led info displayed.

                QString channelName = (*it2);

                ChannelNickPtr channelNick = server->getChannelNick(channelName, nickname);
                QString nickMode;
                if (channelNick->hasVoice()) nickMode = nickMode + i18n(" Voice");
                if (channelNick->isHalfOp()) nickMode = nickMode + i18n(" HalfOp");
                if (channelNick->isOp()) nickMode = nickMode + i18n(" Operator");
                if (channelNick->isOwner()) nickMode = nickMode + i18n(" Owner");
                if (channelNick->isAdmin()) nickMode = nickMode + i18n(" Admin");
                QListViewItem* channelItem = findItemChild(nickRoot, channelName, NicksOnlineItem::ChannelItem);
                if (!channelItem) channelItem = new NicksOnlineItem(NicksOnlineItem::ChannelItem,nickRoot,
                            channelName, nickMode);
                channelItem->setText(nlvcAdditionalInfo, nickMode);

                // Icon for mode of nick in each channel.
                Images::NickPrivilege nickPrivilege = Images::Normal;
                if (channelNick->hasVoice()) nickPrivilege = Images::Voice;
                if (channelNick->isHalfOp()) nickPrivilege = Images::HalfOp;
                if (channelNick->isOp()) nickPrivilege = Images::Op;
                if (channelNick->isOwner()) nickPrivilege = Images::Owner;
                if (channelNick->isAdmin()) nickPrivilege = Images::Admin;
                if (server->getJoinedChannelMembers(channelName) != 0)
                    channelItem->setPixmap(nlvcChannel,
                                           KonversationApplication::instance()->images()->getNickIcon(nickPrivilege, false));
                else
                    channelItem->setPixmap(nlvcChannel,
                                           KonversationApplication::instance()->images()->getNickIcon(nickPrivilege, true));
            }
            // Remove channel if nick no longer in it.
            QListViewItem* child = nickRoot->firstChild();
            while (child)
            {
                QListViewItem* nextChild = child->nextSibling();
                if (channelList.find(child->text(nlvcNick)) == channelList.end())
                    delete child;
                child = nextChild;
            }
        }
        else
        {
            // Nick is offline.
            // Remove from online nicks, if present.
            QListViewItem* item = findItemChild(networkRoot, nickname, NicksOnlineItem::NicknameItem);
            if (item) delete item;
            // Add to offline list if not already listed.
            QListViewItem* nickRoot = findItemChild(offlineRoot, nickname, NicksOnlineItem::NicknameItem);
            if (!nickRoot) nickRoot = new NicksOnlineItem(NicksOnlineItem::NicknameItem,offlineRoot, nickname);
            nickRoot->setText(nlvcServerName, serverName);
            // Get addressbook entry for the nick.
            KABC::Addressee addressee = servr->getOfflineNickAddressee(nickname);
            // Format additional information for the nick.
            bool needWhois = false;
            QString nickAdditionalInfo = getNickAdditionalInfo(0, addressee, needWhois);
            nickRoot->setText(nlvcAdditionalInfo, nickAdditionalInfo);
            // Set Kabc icon if the nick is associated with an addressbook entry.
            if (!addressee.isEmpty())
                nickRoot->setPixmap(nlvcKabc, m_kabcIconSet.pixmap(
                                        QIconSet::Small, QIconSet::Normal, QIconSet::On));
            else
                nickRoot->setPixmap(nlvcKabc, m_kabcIconSet.pixmap(
                                        QIconSet::Small, QIconSet::Disabled, QIconSet::Off));
        }
    }
    // Erase nicks no longer being watched.
    QListViewItem* item = networkRoot->firstChild();
    while (item)
    {
        QListViewItem* nextItem = item->nextSibling();
        if (static_cast<NicksOnlineItem*>(item)->type() != NicksOnlineItem::OfflineItem)
        {
            QString nickname = item->text(nlvcNick);
            if ((watchList.find(nickname) == watchList.end()) &&
                    (serverName == item->text(nlvcServerName))) delete item;
        }
        item = nextItem;
    }
    item = offlineRoot->firstChild();

    if(item) {
        while (item)
        {
            QListViewItem* nextItem = item->nextSibling();
            QString nickname = item->text(nlvcNick);
            if ((watchList.find(nickname) == watchList.end()) &&
                    (serverName == item->text(nlvcServerName))) delete item;
            item = nextItem;
        }
    }
    else
    {
        delete offlineRoot;
    }
    // Expand server if newly added to list.
    if (newNetworkRoot)
    {
        networkRoot->setOpen(true);
        // Connect server NickInfo updates.
        connect (servr, SIGNAL(nickInfoChanged(Server*, const NickInfoPtr)),
                 this, SLOT(slotNickInfoChanged(Server*, const NickInfoPtr)));
    }
}