void SymbianPluginPerfomance::createSimpleContacts() { // Create N contacts QList<QContact> contactsList; for(int i=0; i<NO_OF_CONTACTS; i++) { QString c = QString::number(i); QString first("Alice"); QContact alice; // Contact details QContactName aliceName; aliceName.setFirstName(first.append(c)); alice.saveDetail(&aliceName); contactsList.append(alice); } // Save the contacts mTime.start(); mCntMng->saveContacts(&contactsList, 0); int elapsed = mTime.elapsed(); qDebug() << "Created " << contactsList.count() << " simple contacts in" << elapsed / 1000 << "s" << elapsed % 1000 << "ms"; }
void SeasidePerson::setTitle(const QString &name) { QContactName nameDetail = mContact.detail<QContactName>(); nameDetail.setPrefix(name); mContact.saveDetail(&nameDetail); emit titleChanged(); }
void SeasideCache::setFirstName(FilterType filterType, int index, const QString &firstName) { #ifdef USING_QTPIM CacheItem &cacheItem = m_cache[m_cacheIndices[m_contacts[filterType].at(index)]]; #else CacheItem &cacheItem = m_cache[m_contacts[filterType].at(index) - 1]; #endif QContactName name = cacheItem.contact.detail<QContactName>(); name.setFirstName(firstName); cacheItem.contact.saveDetail(&name); QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName(); cacheItem.nameGroup = determineNameGroup(&cacheItem); cacheItem.displayLabel = fullName; ItemListener *listener(cacheItem.listeners); while (listener) { listener->itemUpdated(&cacheItem); listener = listener->next; } if (m_models[filterType]) m_models[filterType]->sourceDataChanged(index, index); }
/*! * This function will be called before the first testfunction is executed. */ void Ut_NotificationManager::initTestCase() { nm = NotificationManager::instance(); nm->m_Notifications.clear(); nm->m_pMWIListener->disconnect(nm); // Create the contacts we need QContactOnlineAccount qcoa; qcoa.setValue(QContactOnlineAccount__FieldAccountPath, DUT_ACCOUNT_PATH); qcoa.setValue(QContactOnlineAccount::FieldAccountUri, CONTACT_1_REMOTE_ID); QVERIFY(contact1.saveDetail(&qcoa)); QContactName name; name.setPrefix(CONTACT_1_REMOTE_ID); QVERIFY(contact1.saveDetail(&name)); QVERIFY(nm->contactManager()->saveContact(&contact1)); qcoa = QContactOnlineAccount(); qcoa.setValue(QContactOnlineAccount__FieldAccountPath, DUT_ACCOUNT_PATH); qcoa.setValue(QContactOnlineAccount::FieldAccountUri, CONTACT_2_REMOTE_ID); QVERIFY(contact2.saveDetail(&qcoa)); name = QContactName(); name.setPrefix(CONTACT_2_REMOTE_ID); QVERIFY(contact2.saveDetail(&name)); QVERIFY(nm->contactManager()->saveContact(&contact2)); }
void tst_QVersitContactPlugins::testExporterPlugins() { QVersitContactExporter exporter("Test"); QContact contact; QContactName name; name.setFirstName("first name"); contact.saveDetail(&name); QVERIFY(exporter.exportContacts(QList<QContact>() << contact)); QCOMPARE(exporter.documents().size(), 1); QList<QVersitProperty> properties(exporter.documents().first().properties()); // The plugins have had their index set such that they should be executed in reverse order // Check that they are all loaded, and run in the correct order int n = 0; foreach (QVersitProperty property, properties) { if (property.name() == "TEST-PROPERTY") { switch (n) { case 0: QCOMPARE(property.value(), QLatin1String("5")); break; case 1: QCOMPARE(property.value(), QLatin1String("4")); break; case 2: QCOMPARE(property.value(), QLatin1String("3")); break; case 3: QCOMPARE(property.value(), QLatin1String("2")); break; case 4: QCOMPARE(property.value(), QLatin1String("1")); break; } n++; } } QCOMPARE(n, 5); }
void MT_CntVersitMyCardPlugin::exportOwnContact() { //create contact QContact phonecontact; QContactName contactName; contactName.setFirstName("Jo"); contactName.setLastName("Black"); phonecontact.saveDetail(&contactName); QContactPhoneNumber number; number.setContexts("Home"); number.setSubTypes("Mobile"); number.setNumber("+02644424429"); phonecontact.saveDetail(&number); //set MyCard detail QContactDetail myCard(MYCARD_DEFINTION_NAME); phonecontact.saveDetail(&myCard); //export QList<QContact> list; list.append(phonecontact); QVersitContactExporter exporter; QVERIFY(exporter.exportContacts(list, QVersitDocument::VCard21Type)); QList<QVersitDocument> documents = exporter.documents(); //X-SELF property is exported if MyCard QVersitDocument document = documents.first(); QVersitProperty property; property.setName(QLatin1String("X-SELF")); property.setValue("0"); bool propertyFound = document.properties().contains(property); QVERIFY(propertyFound); }
/* Synthesise the display label of a contact */ QString QContactWinCEEngine::synthesizedDisplayLabel(const QContact& contact, QContactManager::Error* error) const { Q_UNUSED(error) // The POOM API (well, lack thereof) makes this a bit strange. // It's basically just "Last, First" or "Company", if "FileAs" is not set. QContactName name = contact.detail<QContactName>(); QContactOrganization org = contact.detail<QContactOrganization>(); // Basically we ignore any existing labels for this contact, since we're being // asked what the synthesized label would be // XXX For greatest accuracy we might be better off converting this contact to // a real item (but don't save it), and then retrieve it... if (!name.customLabel().isEmpty()) { return name.customLabel(); } else if (!name.lastName().isEmpty()) { if (!name.firstName().isEmpty()) { return QString(QLatin1String("%1, %2")).arg(name.lastName()).arg(name.firstName()); } else { // Just last return name.lastName(); } } else if (!name.firstName().isEmpty()) { return name.firstName(); } else if (!org.name().isEmpty()) { return org.name(); } else { // XXX grargh. return QLatin1String("Unnamed"); } }
void SeasidePerson::setLastName(const QString &name) { QContactName nameDetail = mContact.detail<QContactName>(); nameDetail.setLastName(name); mContact.saveDetail(&nameDetail); emit lastNameChanged(); recalculateDisplayLabel(); }
bool CntSimStorePrivate::read(int index, int numSlots, QContactManager::Error *error) { if (IsActive()) { *error = QContactManager::LockedError; return false; } // ON store requires different read approach. // fetch ON contacts synchronously since there are usually only couple of them if (m_storeInfo.m_storeName == KParameterValueSimStoreNameOn) { TRequestStatus status; QList<QContact> fetchedContacts; for (int i = index; i <= numSlots; i++) { RMobileONStore::TMobileONEntryV1 onEntry; onEntry.iIndex = i; RMobileONStore::TMobileONEntryV1Pckg onEntryPkg(onEntry); m_etelOnStore.Read(status, onEntryPkg); User::WaitForRequest(status); if (status.Int() == KErrNone) { QContact c; c.setType(QContactType::TypeContact); QContactName name; name.setCustomLabel(QString::fromUtf16(onEntry.iText.Ptr(), onEntry.iText.Length())); c.saveDetail(&name); QContactPhoneNumber number; number.setNumber(QString::fromUtf16(onEntry.iNumber.iTelNumber.Ptr(), onEntry.iNumber.iTelNumber.Length())); c.saveDetail(&number); QScopedPointer<QContactId> contactId(new QContactId()); contactId->setLocalId(i); contactId->setManagerUri(m_managerUri); c.setId(*contactId); fetchedContacts.append(c); } } emit m_simStore.readComplete(fetchedContacts, QContactManager::NoError); *error = QContactManager::NoError; return true; } // start reading m_buffer.Zero(); m_buffer.ReAlloc(KOneSimContactBufferSize*numSlots); m_etelStore.Read(iStatus, index, numSlots, m_buffer); SetActive(); m_state = ReadState; *error = QContactManager::NoError; return true; }
QString SeasidePerson::displayLabel() { if (mDisplayLabel.isEmpty()) { QContactName name = mContact.detail<QContactName>(); mDisplayLabel = name.customLabel(); if (mDisplayLabel.isEmpty()) recalculateDisplayLabel(); } return mDisplayLabel; }
QString CntSymbianSimEngine::synthesizedDisplayLabel(const QContact& contact, QContactManager::Error* error) const { Q_UNUSED(error); QContactName name = contact.detail(QContactName::DefinitionName); if(!name.customLabel().isEmpty()) { return name.customLabel(); } else { return QString(""); } }
void SeasideCache::displayLabelOrderChanged() { #ifdef HAS_MLITE QVariant displayLabelOrder = m_displayLabelOrderConf.value(); if (displayLabelOrder.isValid() && displayLabelOrder.toInt() != m_displayLabelOrder) { m_displayLabelOrder = SeasideFilteredModel::DisplayLabelOrder(displayLabelOrder.toInt()); #ifdef SEASIDE_SPARQL_QUERIES m_contactIdRequest.setSortOnFirstName(true); #else QContactSortOrder firstNameOrder; firstNameOrder.setDetailDefinitionName( QContactName::DefinitionName, QContactName::FieldFirstName); firstNameOrder.setCaseSensitivity(Qt::CaseInsensitive); firstNameOrder.setDirection(Qt::AscendingOrder); firstNameOrder.setBlankPolicy(QContactSortOrder::BlanksFirst); QContactSortOrder secondNameOrder; secondNameOrder.setDetailDefinitionName( QContactName::DefinitionName, QContactName::FieldLastName); secondNameOrder.setCaseSensitivity(Qt::CaseInsensitive); secondNameOrder.setDirection(Qt::AscendingOrder); secondNameOrder.setBlankPolicy(QContactSortOrder::BlanksFirst); QList<QContactSortOrder> sorting = m_displayLabelOrder == SeasideFilteredModel::FirstNameFirst ? (QList<QContactSortOrder>() << firstNameOrder << secondNameOrder) : (QList<QContactSortOrder>() << secondNameOrder << firstNameOrder); m_fetchRequest.setSorting(sorting); m_contactIdRequest.setSorting(sorting); #endif typedef QHash<QContactLocalId, SeasideCacheItem>::iterator iterator; for (iterator it = m_people.begin(); it != m_people.begin(); ++it) { if (it->person) { it->person->recalculateDisplayLabel(SeasideProxyModel::DisplayLabelOrder(m_displayLabelOrder)); it->contact = it->person->contact(); } else { QContactName name = it->contact.detail<QContactName>(); name.setCustomLabel(SeasidePerson::generateDisplayLabel(it->contact)); it->contact.saveDetail(&name); } } for (int i = 0; i < SeasideFilteredModel::FilterTypesCount; ++i) { for (int j = 0; j < m_models[i].count(); ++j) m_models[i].at(j)->updateDisplayLabelOrder(); } m_refreshRequired = true; requestUpdate(); } #endif }
/*! Adds contacts in \a newContacts into \a manager, converting categories specified with tags into group membership relationships. Note that this implementation uses the synchronous API of QContactManager for clarity. It is recommended that the asynchronous API is used in practice. Relationships are added so that if a contact, A, has a tag "b", then a HasMember relationship is created between a group contact in the manager, B with display label "b", and contact A. If there does not exist a group contact with display label "b", one is created. */ void insertWithGroups(const QList<QContact>& newContacts, QContactManager* manager) { // Cache map from group names to QContactIds QMap<QString, QContactId> groupMap; foreach (QContact contact, newContacts) { if (!manager->saveContact(&contact)) continue; // In practice, better error handling may be required foreach (const QContactTag& tag, contact.details<QContactTag>()) { QString groupName = tag.tag(); QContactId groupId; if (groupMap.contains(groupName)) { // We've already seen a group with the right name groupId = groupMap.value(groupName); } else { QContactDetailFilter groupFilter; groupFilter.setDetailDefinitionName(QContactType::DefinitionName); groupFilter.setValue(QLatin1String(QContactType::TypeGroup)); groupFilter.setMatchFlags(QContactFilter::MatchExactly); // In practice, some detail other than the display label could be used QContactDetailFilter nameFilter = QContactDisplayLabel::match(groupName); QList<QContactLocalId> matchingGroups = manager->contactIds(groupFilter & nameFilter); if (!matchingGroups.isEmpty()) { // Found an existing group in the manager QContactId groupId; groupId.setManagerUri(manager->managerUri()); groupId.setLocalId(matchingGroups.first()); groupMap.insert(groupName, groupId); } else { // Make a new group QContact groupContact; QContactName name; name.setCustomLabel(groupName); // Beware that not all managers support custom label groupContact.saveDetail(&name); if (!manager->saveContact(&groupContact)) continue; // In practice, better error handling may be required groupId = groupContact.id(); groupMap.insert(groupName, groupId); } } // Add the relationship QContactRelationship rel; rel.setFirst(groupId); rel.setRelationshipType(QContactRelationship::HasMember); rel.setSecond(contact.id()); manager->saveRelationship(&rel); } } }
void TestBirthdayPlugin::testChangeName() { const QString contactID = QUuid::createUuid().toString(); const QDateTime contactBirthDate = QDateTime::currentDateTime(); // Add contact with birthday to tracker. QContactName contactName; contactName.setFirstName(contactID); QContactBirthday contactBirthday; contactBirthday.setDateTime(contactBirthDate); QContact contact; QVERIFY(contact.saveDetail(&contactName)); QVERIFY(contact.saveDetail(&contactBirthday)); QVERIFY2(mManager->saveContact(&contact), "Error saving contact to tracker"); // Wait until calendar event gets to calendar. loopWait(calendarTimeout); // Open calendar database. mKCal::ExtendedCalendar::Ptr calendar = mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(KDateTime::Spec::LocalZone())); mKCal::ExtendedStorage::Ptr storage = mKCal::ExtendedCalendar::defaultStorage(calendar); storage->open(); QVERIFY2(not storage->notebook(calNotebookId).isNull(), "No calendar database found"); // Check calendar database for contact. QVERIFY2(storage->loadNotebookIncidences(calNotebookId), "Unable to load events from notebook"); KCalCore::Event::List eventList = calendar->events(); QCOMPARE(countCalendarEvents(eventList, contact), 1); // Change the contact name and see if the calendar is updated. const QString newContactID = QUuid::createUuid().toString(); contactName.setFirstName(newContactID); QVERIFY(contact.saveDetail(&contactName)); // TODO: Should it be necessary to refetch the contact to get the synthesised displayLabel? contact = mManager->contact(apiId(contact)); QVERIFY2(mManager->saveContact(&contact), "Unable to update test contact in tracker"); // Wait until calendar event gets to calendar. loopWait(calendarTimeout); // Search for any events in the calendar. QVERIFY2(storage->loadNotebookIncidences(calNotebookId), "Unable to load events from notebook"); eventList = calendar->events(); QCOMPARE(countCalendarEvents(eventList, contact), 1); // Close the calendar. QVERIFY2(storage->close(), "Error closing the calendar"); }
void SeasidePerson::recalculateDisplayLabel(SeasideProxyModel::DisplayLabelOrder order) { QString oldDisplayLabel = mDisplayLabel; QString newDisplayLabel = generateDisplayLabel(mContact, order); if (oldDisplayLabel != newDisplayLabel) { // Save the display label as the custom label. QContactName name = mContact.detail<QContactName>(); name.setCustomLabel(newDisplayLabel); mContact.saveDetail(&name); mDisplayLabel = newDisplayLabel; emit displayLabelChanged(); } }
void TestBirthdayPlugin::testLeapYears() { const QString contactID = QUuid::createUuid().toString(); QFETCH(QDate, contactBirthDate); // Add contact with birthday to tracker. QContactName contactName; contactName.setFirstName(contactID); QContactBirthday contactBirthday; contactBirthday.setDate(contactBirthDate); QContact contact; QVERIFY(contact.saveDetail(&contactName)); QVERIFY(contact.saveDetail(&contactBirthday)); QVERIFY(saveContact(contact)); // Wait until calendar event gets to calendar. loopWait(calendarTimeout); // Open calendar database. mKCal::ExtendedCalendar::Ptr calendar = mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(KDateTime::Spec::LocalZone())); mKCal::ExtendedStorage::Ptr storage = mKCal::ExtendedCalendar::defaultStorage(calendar); QVERIFY(storage->open()); QVERIFY(not storage->notebook(calNotebookId).isNull()); // Check calendar database for contact. QVERIFY(storage->loadNotebookIncidences(calNotebookId)); const KCalCore::Event::List eventList = findCalendarEvents(calendar->events(), contact); QCOMPARE(eventList.count(), 1); const KCalCore::Event::Ptr event = eventList.first(); QCOMPARE(event->summary(), contactID); QCOMPARE(event->dtStart().date(), contactBirthDate); QCOMPARE(event->allDay(), true); // Check number of recurrences and their values. const KDateTime first(QDate(2000, 1, 1), QTime(), KDateTime::ClockTime); const KDateTime last(QDate(2020, 12, 31), QTime(), KDateTime::ClockTime); const KCalCore::DateTimeList instances = event->recurrence()->timesInInterval(first, last); QCOMPARE(instances.length(), 13); for(int i = 0; i < instances.length(); ++i) { QCOMPARE(instances.at(i).date(), contactBirthDate.addYears(i)); } }
QList<Contact> Contacts::getContactsFromPhone(){ QPointer<QContactManager> contactManager = new QContactManager(); // QStringList QContactManager::supportedContactTypes () QList<QContact> contactsPhone = contactManager->contacts(); QList<Contact> contacts; foreach (const QContact& contact, contactsPhone) { QContactPhoneNumber phoneNumber = contact.detail<QContactPhoneNumber>(); // QList<QContactPhoneNumber> phoneNumbers = contact.details<QContactPhoneNumber>(); if(!phoneNumber.isEmpty()){ QContactName name = contact.detail<QContactName>(); QString number = phoneNumber.number(); number = number.replace("+",""); QString nameFinal = name.firstName()+" "+name.lastName(); contacts.append(Contact(nameFinal.trimmed(),number)); } }
/*! * The leaving function that queries the SQL database * * \a aSqlQuery An SQL query * \return the list of matched contact ids */ QList<QContact> CntSymbianSrvConnection::searchContactNamesL(const TDesC& aSqlQuery) { readContactsToBufferL(aSqlQuery, CntSymbianSrvConnection::CntSearchResultList); RBufReadStream readStream; QList<QContact> contacts; TInt id; TBuf<256> firstName; TBuf<256> lastName; TBuf<256> company; readStream.Open(*m_buffer); while ((id = readStream.ReadInt32L()) != 0) { readStream >> firstName; readStream >> lastName; readStream >> company; QContact contact, tempContact; QContactName name; name.setFirstName(QString::fromUtf16(firstName.Ptr(), firstName.Length())); name.setLastName(QString::fromUtf16(lastName.Ptr(), lastName.Length())); tempContact.saveDetail(&name); QContactOrganization organization; organization.setName(QString::fromUtf16(company.Ptr(), company.Length())); tempContact.saveDetail(&organization); QContactManager::Error error(QContactManager::NoError); QString label = m_manager->synthesizedDisplayLabel(tempContact, &error); if (error != QContactManager::NoError) { continue; } tempContact.clearDetails(); m_manager->setContactDisplayLabel(&contact, label); QContactId contactId; contactId.setLocalId(id); contactId.setManagerUri(m_manager->managerUri()); contact.setId(contactId); contacts << contact; } return contacts; }
void SeasideCache::contactsAvailable() { if (m_fetchFilter == SeasideFilteredModel::FilterFavorites || m_fetchFilter == SeasideFilteredModel::FilterOnline || m_fetchFilter == SeasideFilteredModel::FilterAll) { // Part of an initial query. appendContacts(m_fetchRequest.contacts()); } else { // An update. const QList<QContact> contacts = m_fetchRequest.contacts(); for (int i = m_resultsRead; i < contacts.count(); ++i) { QContact contact = contacts.at(i); SeasideCacheItem &item = m_people[contact.localId()]; QContactName oldName = item.contact.detail<QContactName>(); QContactName newName = contact.detail<QContactName>(); if (newName.customLabel().isEmpty()) { newName.setCustomLabel(oldName.customLabel()); contact.saveDetail(&newName); } const bool roleDataChanged = newName != oldName || contact.detail<QContactAvatar>().imageUrl() != item.contact.detail<QContactAvatar>().imageUrl(); item.contact = contact; item.hasCompleteContact = true; if (item.person) { item.person->setContact(contact); item.person->setComplete(true); } QList<QContactPhoneNumber> phoneNumbers = contact.details<QContactPhoneNumber>(); for (int j = 0; j < phoneNumbers.count(); ++j) { m_phoneNumberIds[phoneNumbers.at(j).number()] = contact.localId(); } if (roleDataChanged) { instance->updateContactData(contact.localId(), SeasideFilteredModel::FilterFavorites); instance->updateContactData(contact.localId(), SeasideFilteredModel::FilterOnline); instance->updateContactData(contact.localId(), SeasideFilteredModel::FilterAll); } } m_resultsRead = contacts.count(); } }
void TestBirthdayPlugin::testAddAndRemoveBirthday() { const QString contactID = QUuid::createUuid().toString(); const QDateTime contactBirthDate = QDateTime::currentDateTime(); // Add contact with birthday to tracker. QContactName contactName; contactName.setFirstName(contactID); QContactBirthday contactBirthday; contactBirthday.setDateTime(contactBirthDate); QContact contact; QVERIFY(contact.saveDetail(&contactName)); QVERIFY(contact.saveDetail(&contactBirthday)); QVERIFY2(mManager->saveContact(&contact), "Error saving contact to tracker"); // Wait until calendar event gets to calendar. loopWait(calendarTimeout); // Open calendar database, which should have been created by the birthday plugin. mKCal::ExtendedCalendar::Ptr calendar = mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(KDateTime::Spec::LocalZone())); mKCal::ExtendedStorage::Ptr storage = mKCal::ExtendedCalendar::defaultStorage(calendar); storage->open(); QVERIFY2(not storage->notebook(calNotebookId).isNull(), "No calendar database found"); // Check calendar database for contact. QVERIFY2(storage->loadNotebookIncidences(calNotebookId), "Unable to load events from notebook"); KCalCore::Event::List eventList = calendar->events(); QCOMPARE(countCalendarEvents(eventList, contact), 1); // Delete the contact and see if the birthday is also deleted. QVERIFY2(mManager->removeContact(apiId(contact)), "Unable to delete test contact from tracker database"); // Wait until calendar event gets to calendar. loopWait(calendarTimeout); // Search for any events in the calendar. QVERIFY2(storage->loadNotebookIncidences(calNotebookId), "Unable to load events from notebook"); eventList = calendar->events(); QCOMPARE(countCalendarEvents(eventList, contact), 0); // Close the calendar. QVERIFY2(storage->close(), "Error closing the calendar"); }
void exportExample() { //! [Export example] QVersitContactExporter contactExporter; QContact contact; // Create a name QContactName name; name.setFirstName(QString::fromAscii("John")); contact.saveDetail(&name); if (!contactExporter.exportContacts(QList<QContact>() << contact, QVersitDocument::VCard30Type)) return; QList<QVersitDocument> versitDocuments = contactExporter.documents(); // detailHandler.mUnknownDetails now contains the list of unknown details //! [Export example] }
QString SeasideCache::determineNameGroup(const CacheItem *cacheItem) { if (!cacheItem) return QString(); const QContactName nameDetail = cacheItem->contact.detail<QContactName>(); const QString sort(sortProperty() == QString::fromLatin1("firstName") ? nameDetail.firstName() : nameDetail.lastName()); QString group; if (!sort.isEmpty()) { group = QString(sort[0].toUpper()); } else if (!cacheItem->displayLabel.isEmpty()) { group = QString(cacheItem->displayLabel[0].toUpper()); } if (group.isNull() || !allContactNameGroups.contains(group)) { group = QString::fromLatin1("#"); // 'other' group } return group; }
// small helper to avoid inconvenience static QString generateDisplayLabel(QContact mContact) { //REVISIT: Move this or parts of this to localeutils.cpp QString displayLabel; QContactName name = mContact.detail<QContactName>(); QString nameStr1 = name.firstName(); QString nameStr2 = name.lastName(); if (!nameStr1.isNull()) displayLabel.append(nameStr1); if (!nameStr2.isNull()) { if (!displayLabel.isEmpty()) displayLabel.append(" "); displayLabel.append(nameStr2); } if (!displayLabel.isEmpty()) return displayLabel; foreach (const QContactOnlineAccount& account, mContact.details<QContactOnlineAccount>()) { if (!account.accountUri().isNull()) return account.accountUri(); } foreach (const QContactEmailAddress& email, mContact.details<QContactEmailAddress>()) { if (!email.emailAddress().isNull()) return email.emailAddress(); } QContactOrganization company = mContact.detail<QContactOrganization>(); if (!company.name().isNull()) return company.name(); foreach (const QContactPhoneNumber& phone, mContact.details<QContactPhoneNumber>()) { if (!phone.number().isNull()) return phone.number(); } return "(unnamed)"; // TODO: localisation }
// small helper to avoid inconvenience QString SeasidePerson::generateDisplayLabel(const QContact &mContact, SeasideProxyModel::DisplayLabelOrder order) { //REVISIT: Move this or parts of this to localeutils.cpp QString displayLabel; QContactName name = mContact.detail<QContactName>(); QString nameStr1; QString nameStr2; if (order == SeasideProxyModel::LastNameFirst) { nameStr1 = name.lastName(); nameStr2 = name.firstName(); } else { nameStr1 = name.firstName(); nameStr2 = name.lastName(); } if (!nameStr1.isNull()) displayLabel.append(nameStr1); if (!nameStr2.isNull()) { if (!displayLabel.isEmpty()) displayLabel.append(" "); displayLabel.append(nameStr2); } if (!displayLabel.isEmpty()) return displayLabel; foreach (const QContactOnlineAccount& account, mContact.details<QContactOnlineAccount>()) { if (!account.accountUri().isNull()) return account.accountUri(); } foreach (const QContactEmailAddress& email, mContact.details<QContactEmailAddress>()) { if (!email.emailAddress().isNull()) return email.emailAddress(); } QContactOrganization company = mContact.detail<QContactOrganization>(); if (!company.name().isNull()) return company.name(); foreach (const QContactPhoneNumber& phone, mContact.details<QContactPhoneNumber>()) { if (!phone.number().isNull()) return phone.number(); } // This is last because the custom label is often source from this function, so we want to // overwrite that value in many cases. if (!name.customLabel().isNull()) return name.customLabel(); return "(Unnamed)"; // TODO: localisation }
void MainWindow::updateContact() { const QString& name = m_nameEdit->text(); const QString& phone = m_phoneEdit->text(); const QString& email = m_emailEdit->text(); if (!name.isEmpty()) { QContactName detail = m_contact.detail<QContactName>(); detail.setFirstName(name); m_contact.saveDetail(&detail); } if (!phone.isEmpty()) { QContactPhoneNumber detail = m_contact.detail<QContactPhoneNumber>(); detail.setNumber(phone); m_contact.saveDetail(&detail); } if (!email.isEmpty()) { QContactEmailAddress detail = m_contact.detail<QContactEmailAddress>(); detail.setEmailAddress(email); m_contact.saveDetail(&detail); } }
/* Synthesise the display label of a contact */ QString QContactMaemo5Engine::synthesizedDisplayLabel(const QContact& contact, QContactManager::Error* error) const { QString label; // Try to get the display name from the OSSO-ABook Contact label = d->m_abook->getDisplayName(contact); // Synthesise the display label for not saved contacts // A. FirstName + LastName if (label.isEmpty()){ QContactName name = contact.detail(QContactName::DefinitionName); QStringList nameList; nameList << name.firstName(); if (name.lastName().count()){ nameList << name.lastName(); } label = nameList.join(QString(' ')); } // B. Email if (label.isEmpty()){ QContactEmailAddress email = contact.detail(QContactEmailAddress::DefinitionName); label = email.emailAddress(); } // if (label.isEmpty()){ *error = QContactManager::UnspecifiedError; return QString("No name"); } *error = QContactManager::NoError; return label; }
QContactDetail *CntTransformName::transformItemField(const CContactItemField& field, const QContact &contact) { QContactName *name = new QContactName(contact.detail<QContactName>()); CContactTextField* storage = field.TextStorage(); QString nameValue = QString::fromUtf16(storage->Text().Ptr(), storage->Text().Length()); for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) { //Prefix if (field.ContentType().FieldType(i) == KUidContactFieldPrefixName) { name->setPrefix(nameValue); } //First name else if (field.ContentType().FieldType(i) == KUidContactFieldGivenName) { name->setFirstName(nameValue); } //Middle name else if (field.ContentType().FieldType(i) == KUidContactFieldAdditionalName) { name->setMiddleName(nameValue); } //Last name else if (field.ContentType().FieldType(i) == KUidContactFieldFamilyName) { name->setLastName(nameValue); } //Suffix else if (field.ContentType().FieldType(i) == KUidContactFieldSuffixName) { name->setSuffix(nameValue); } // custom label else if (field.ContentType().FieldType(i) == KUidContactFieldTemplateLabel) { name->setCustomLabel(nameValue); } } return name; }
QString SeasidePerson::lastName() const { QContactName nameDetail = mContact.detail<QContactName>(); return nameDetail.lastName(); }
/*! Parses SIM contacts in TLV format. * * \param rawData SIM contacts in TLV format. * \return List of contacts. */ QList<QContact> CntSimStorePrivate::decodeSimContactsL(TDes8& rawData) const { PbkPrintToLog(_L("CntSymbianSimEngine::decodeSimContactsL() - IN")); QList<QContact> fetchedContacts; QContact currentContact; TBuf16<KDataClientBuf> buffer; TPtrC16 bufPtr(buffer); TUint8 tagValue(0); CPhoneBookBuffer::TPhBkTagType dataType; bool isAdditionalNumber = false; CPhoneBookBuffer* pbBuffer = new(ELeave) CPhoneBookBuffer(); CleanupStack::PushL(pbBuffer); pbBuffer->Set(&rawData); pbBuffer->StartRead(); while (pbBuffer->GetTagAndType(tagValue, dataType) == KErrNone) { switch (tagValue) { case RMobilePhoneBookStore::ETagPBAdnIndex: { //save contact's id (SIM card index) and manager's name TUint16 index; if (pbBuffer->GetValue(index) == KErrNone) { QScopedPointer<QContactId> contactId(new QContactId()); contactId->setLocalId(index); contactId->setManagerUri(m_managerUri); currentContact.setId(*contactId); } isAdditionalNumber = false; break; } case RMobilePhoneBookStore::ETagPBTonNpi: { // Note, that TON info can be incorporated into the phone number by Etel // implementation (TSY). E.g. this is the case with Nokia TSY. // Here general case is implemented. // Check number type, we are only interested if it's international or not. // We assume here that ETagPBTonNpi always comes after ETagPBNumber, not before. TUint8 tonNpi; if (pbBuffer->GetValue(tonNpi) == KErrNone) { TUint8 intFlag = (tonNpi & KEtsiTonPosition) >> 4; if (intFlag == 1) { //international number format, append "+" to the last //saved number QList<QContactDetail> phoneNumbers = currentContact.details( QContactPhoneNumber::DefinitionName); if (phoneNumbers.count() > 0) { QContactPhoneNumber lastNumber = static_cast<QContactPhoneNumber>( phoneNumbers.at(phoneNumbers.count() - 1)); QString number = lastNumber.number(); number.insert(0, "+"); lastNumber.setNumber(number); if (m_storeInfo.m_readOnlyAccess) m_engine.setReadOnlyAccessConstraint(&lastNumber); currentContact.saveDetail(&lastNumber); } } } // We have rearched to the end of the number, // invalidate additional number flag. isAdditionalNumber = false; break; } case RMobilePhoneBookStore::ETagPBText: { if (pbBuffer->GetValue(bufPtr) == KErrNone) { if (isAdditionalNumber) { // For additional number bufPtr contains number alpha string, // this is ignored currently } else { // Contact name otherwise QContactName name; QString nameString = QString::fromUtf16(bufPtr.Ptr(), bufPtr.Length()); name.setCustomLabel(nameString); if (m_storeInfo.m_readOnlyAccess) m_engine.setReadOnlyAccessConstraint(&name); currentContact.saveDetail(&name); QContactManager::Error error(QContactManager::NoError); m_engine.setContactDisplayLabel(¤tContact, m_engine.synthesizedDisplayLabel(currentContact, &error)); } } break; } case RMobilePhoneBookStore::ETagPBSecondName: { if (pbBuffer->GetValue(bufPtr) == KErrNone) { QContactNickname nickName; QString name = QString::fromUtf16(bufPtr.Ptr(), bufPtr.Length()); nickName.setNickname(name); if (m_storeInfo.m_readOnlyAccess) m_engine.setReadOnlyAccessConstraint(&nickName); currentContact.saveDetail(&nickName); } break; } case RMobilePhoneBookStore::ETagPBNumber: { if (pbBuffer->GetValue(bufPtr) == KErrNone) { QContactPhoneNumber phoneNumber; QString number = QString::fromUtf16(bufPtr.Ptr(), bufPtr.Length()); phoneNumber.setNumber(number); if (m_storeInfo.m_readOnlyAccess) m_engine.setReadOnlyAccessConstraint(&phoneNumber); currentContact.saveDetail(&phoneNumber); } break; } case RMobilePhoneBookStore::ETagPBAnrStart: { // This tag should precede every additional number entry isAdditionalNumber = true; break; } case RMobilePhoneBookStore::ETagPBEmailAddress: { if (pbBuffer->GetValue(bufPtr) == KErrNone) { QContactEmailAddress email; QString emailAddress = QString::fromUtf16(bufPtr.Ptr(), bufPtr.Length()); email.setEmailAddress(emailAddress); if (m_storeInfo.m_readOnlyAccess) m_engine.setReadOnlyAccessConstraint(&email); currentContact.saveDetail(&email); } break; } case RMobilePhoneBookStore::ETagPBNewEntry: { // This signals the end of the entry and is a special case // which will be handled below. break; } default: { // An unsupported field type - just skip this value pbBuffer->SkipValue(dataType); break; } } //switch // save contact to the array of contact to be returned if the whole entry was extracted if ((tagValue == RMobilePhoneBookStore::ETagPBNewEntry && currentContact.localId() > 0) || (pbBuffer->RemainingReadLength() == 0 && currentContact.localId() > 0)) { fetchedContacts.append(currentContact); //clear current contact currentContact.clearDetails(); QScopedPointer<QContactId> contactId(new QContactId()); contactId->setLocalId(0); contactId->setManagerUri(QString()); currentContact.setId(*contactId); } } //while
QContact generateContact(const QString &syncTarget = QString(QLatin1String("local")), bool possiblyAggregate = false) { static const QStringList firstNames(generateFirstNamesList()); static const QStringList middleNames(generateMiddleNamesList()); static const QStringList lastNames(generateLastNamesList()); static const QStringList nonOverlappingFirstNames(generateNonOverlappingFirstNamesList()); static const QStringList nonOverlappingLastNames(generateNonOverlappingLastNamesList()); static const QStringList phoneNumbers(generatePhoneNumbersList()); static const QStringList emailProviders(generateEmailProvidersList()); static const QStringList avatars(generateAvatarsList()); static const QStringList hobbies(generateHobbiesList()); // we randomly determine whether to generate various details // to ensure that we have heterogeneous contacts in the db. QContact retn; int random = qrand(); bool preventAggregate = (syncTarget != QLatin1String("local") && !possiblyAggregate); // We always have a sync target. QContactSyncTarget synctarget; synctarget.setSyncTarget(syncTarget); retn.saveDetail(&synctarget); // We always have a name. Select an overlapping name if the sync target // is something other than "local" and possiblyAggregate is true. QContactName name; name.setFirstName(preventAggregate ? nonOverlappingFirstNames.at(random % nonOverlappingFirstNames.size()) : firstNames.at(random % firstNames.size())); name.setLastName(preventAggregate ? nonOverlappingLastNames.at(random % nonOverlappingLastNames.size()) : lastNames.at(random % lastNames.size())); if ((random % 6) == 0) name.setMiddleName(middleNames.at(random % middleNames.size())); if ((random % 17) == 0) name.setPrefix(QLatin1String("Dr.")); retn.saveDetail(&name); // Favorite if ((random % 31) == 0) { QContactFavorite fav; fav.setFavorite(true); retn.saveDetail(&fav); } // Phone number if ((random % 3) == 0) { QContactPhoneNumber phn; QString randomPhn = phoneNumbers.at(random % phoneNumbers.size()); phn.setNumber(preventAggregate ? QString(QString::number(random % 500000) + randomPhn) : randomPhn); if ((random % 9) == 0) phn.setContexts(QContactDetail::ContextWork); retn.saveDetail(&phn); } // Email if ((random % 2) == 0) { QContactEmailAddress em; em.setEmailAddress(QString(QLatin1String("%1%2%3%4")) .arg(preventAggregate ? QString(QString::number(random % 500000) + syncTarget) : QString()) .arg(name.firstName()).arg(name.lastName()) .arg(emailProviders.at(random % emailProviders.size()))); if (random % 9) em.setContexts(QContactDetail::ContextWork); retn.saveDetail(&em); } // Avatar if ((random % 5) == 0) { QContactAvatar av; av.setImageUrl(name.firstName() + avatars.at(random % avatars.size())); retn.saveDetail(&av); } // Hobby if ((random % 21) == 0) { QContactHobby h1; h1.setHobby(hobbies.at(random % hobbies.size())); retn.saveDetail(&h1); int newRandom = qrand(); if ((newRandom % 2) == 0) { QContactHobby h2; h2.setHobby(hobbies.at(newRandom % hobbies.size())); retn.saveDetail(&h2); } } return retn; }