Skip to content

Linux + iPhone Continuity / iMessage / SMS

feat: sort contacts by first or last name

Zack Bartela8e38523c4e7
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index 416f96f..0a8b67e 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -437,6 +437,12 @@ take MAP from another computer that holds it. Answered with a `bt_status` broadc
Persisted. While the session is locked or idle, MAP and PBAP are released so another
computer can take them. Reported as `yield_when_inactive` in `bt_status`.
+#### `bt_set_contacts_by_last_name` (Client -> Daemon, broadcast)
+**Payload**: `{"command": "bt_set_contacts_by_last_name", "enabled": true}`
+Persisted. `bt_contacts` lists favorites first, then by the family and given name from the
+vCard `N` field; a card with no family name sorts by whichever name it has. Reported as
+`contacts_by_last_name` in `bt_status`.
+
### AirPods
Battery does not come from BlueZ. It arrives over Apple's AAP protocol on an L2CAP
diff --git a/docs/man/man1/tether.1.in b/docs/man/man1/tether.1.in
index 8d8c5d0..d9b6b01 100644
--- a/docs/man/man1/tether.1.in
+++ b/docs/man/man1/tether.1.in
@@ -175,6 +175,10 @@ List iPhone contacts, or search them by name, number or email address. Prints ea
contact's name followed by its addresses, one per line, in the same
\fItel:\fR/\fIemail:\fR form \fB\-\-bt-send\fR takes as its conversation.
.TP
+\fB\-\-bt-contacts-sort\fR \fIfirst\fR|\fIlast\fR
+List contacts by first or last name, as entered on the iPhone. Contacts with
+only one name, and businesses, sort by the name they have. Favorites stay first.
+.TP
\fB\-\-bt-retention\fR \fIencrypted\fR|\fIplaintext\fR|\fInone\fR
How message history and the contact cache are kept on disk. \fIencrypted\fR, the
default, seals them with a key from the desktop keyring, falling back to a 0600
diff --git a/src/cli/main.cpp b/src/cli/main.cpp
index c983005..2500b79 100644
--- a/src/cli/main.cpp
+++ b/src/cli/main.cpp
@@ -209,6 +209,7 @@ static const Opt kOptions[] = {
{"--bt-messages <thread>", N_("Show messages in one conversation.")},
{"--bt-send <thread> <text>", N_("Reply in one conversation.")},
{"--bt-contacts [query]", N_("List iPhone contacts, or search them by name or number.")},
+ {"--bt-contacts-sort <first|last>", N_("List contacts by first or last name.")},
{"--bt-pair <addr> [--explicit-pair]", N_("Pair with an iPhone over Bluetooth.")},
{"--explicit-pair",
N_("Ask the iPhone to authenticate directly instead of connecting first. Tether falls back to this on "
@@ -1485,6 +1486,10 @@ int main(int argc, char* argv[]) {
action = "bt_call";
if (i + 1 < argc && argv[i + 1][0] != '-')
arg_val = argv[++i];
+ } else if (arg == "--bt-contacts-sort") {
+ action = "bt_contacts_sort";
+ if (i + 1 < argc && argv[i + 1][0] != '-')
+ arg_val = argv[++i];
} else if (arg == "--bt-calls-enable") {
action = "bt_calls_enable";
if (i + 1 < argc && argv[i + 1][0] != '-')
@@ -1735,6 +1740,21 @@ int main(int argc, char* argv[]) {
: arg_val == "audio_phone" ? _("Call audio stays on the iPhone.")
: _("Hanging up.");
return run_call_command(client, request, done);
+ } else if (action == "bt_contacts_sort") {
+ if (arg_val != "first" && arg_val != "last") {
+ debug::log(ERR, _("Expected first or last, e.g. --bt-contacts-sort last\n"));
+ return 1;
+ }
+ nlohmann::json request;
+ request["command"] = "bt_set_contacts_by_last_name";
+ request["enabled"] = arg_val == "last";
+ if (!client.send(request.dump() + "\n")) {
+ debug::log(ERR, _("Could not reach the daemon.\n"));
+ return 1;
+ }
+ fprintf(stdout,
+ "%s\n",
+ arg_val == "last" ? _("Contacts sorted by last name.") : _("Contacts sorted by first name."));
} else if (action == "bt_calls_enable") {
if (arg_val != "on" && arg_val != "off") {
debug::log(ERR, _("Expected on or off, e.g. --bt-calls-enable on\n"));
diff --git a/src/core/include/tether/bluetooth/config.hpp b/src/core/include/tether/bluetooth/config.hpp
index cd31018..86e24ea 100644
--- a/src/core/include/tether/bluetooth/config.hpp
+++ b/src/core/include/tether/bluetooth/config.hpp
@@ -71,6 +71,8 @@ namespace tether::bluetooth {
int yield_idle_seconds = YIELD_IDLE_SECONDS;
// What performs the lock. Empty uses logind.
std::string lock_command;
+ // Whether contacts list by last name rather than first.
+ bool contacts_by_last_name = false;
bool operator==(const Config&) const = default;
};
diff --git a/src/core/include/tether/bluetooth/contacts.hpp b/src/core/include/tether/bluetooth/contacts.hpp
index 645525b..354beb0 100644
--- a/src/core/include/tether/bluetooth/contacts.hpp
+++ b/src/core/include/tether/bluetooth/contacts.hpp
@@ -23,8 +23,8 @@ namespace tether::bluetooth {
std::vector<std::string> addresses_for_name(const std::string& name) const;
// Contacts whose name or any of their addresses contains `needle`, case- and accent-insensitively.
- // Favorites first, then by name.
- std::vector<VCard> search(const std::string& needle, size_t limit) const;
+ // Favorites first, then by name, or by family then given name when `by_last_name`.
+ std::vector<VCard> search(const std::string& needle, size_t limit, bool by_last_name = false) const;
size_t size() const { return contacts_.size(); }
size_t indexed() const { return by_key_.size(); }
diff --git a/src/core/include/tether/bluetooth/vcard.hpp b/src/core/include/tether/bluetooth/vcard.hpp
index 424d7cf..229ed27 100644
--- a/src/core/include/tether/bluetooth/vcard.hpp
+++ b/src/core/include/tether/bluetooth/vcard.hpp
@@ -10,6 +10,9 @@ namespace tether::bluetooth {
// Name is display data. The tel and email lists are the identity keys, and a contact routinely has several of each.
struct VCard {
std::string name;
+ // From N, for sorting by last name. Empty when the card has no N.
+ std::string family;
+ std::string given;
std::vector<std::string> tels;
std::vector<std::string> emails;
// Call history only (X-IRMC-CALL-DATETIME): MISSED, RECEIVED or DIALED,
@@ -33,7 +36,9 @@ namespace tether::bluetooth {
// Parameters after ';' are discarded; only the property name matters.
bool vcard_split_property(const std::string& line, std::string& name, std::string& value);
- // vCard N is structured "Family;Given;Middle;Prefix;Suffix".
+ // vCard N is structured "Family;Given;Middle;Prefix;Suffix". Takes the raw
+ // value: parts are split on unescaped ';' and then unescaped.
+ std::vector<std::string> vcard_n_parts(const std::string& value);
std::string vcard_name_from_n(const std::string& value);
// vCard 3.0 escapes \, \; \n and \\ in values.
diff --git a/src/core/src/bluetooth/config.cpp b/src/core/src/bluetooth/config.cpp
index dd22fed..bce4c97 100644
--- a/src/core/src/bluetooth/config.cpp
+++ b/src/core/src/bluetooth/config.cpp
@@ -73,6 +73,7 @@ namespace tether::bluetooth {
j["lock_command"] = config.lock_command;
j["yield_when_inactive"] = config.yield_when_inactive;
j["yield_idle_seconds"] = config.yield_idle_seconds;
+ j["contacts_by_last_name"] = config.contacts_by_last_name;
return j.dump(2);
}
@@ -105,6 +106,7 @@ namespace tether::bluetooth {
// A zero or negative grace would lock on the first flap.
config.lock_away_seconds = std::max(1, j.value("lock_away_seconds", AWAY_LOCK_GRACE_SECONDS));
config.lock_command = j.value("lock_command", "");
+ config.contacts_by_last_name = j.value("contacts_by_last_name", false);
} catch (const std::exception&) {
// A corrupt file must not stop the daemon; defaults are safe.
}
diff --git a/src/core/src/bluetooth/contacts.cpp b/src/core/src/bluetooth/contacts.cpp
index 40d7129..a508110 100644
--- a/src/core/src/bluetooth/contacts.cpp
+++ b/src/core/src/bluetooth/contacts.cpp
@@ -12,6 +12,7 @@
#include <fstream>
#include <glib.h>
#include <set>
+#include <tuple>
#include <unistd.h>
namespace tether::bluetooth {
@@ -100,7 +101,7 @@ namespace tether::bluetooth {
return out;
}
- std::vector<VCard> ContactStore::search(const std::string& needle, size_t limit) const {
+ std::vector<VCard> ContactStore::search(const std::string& needle, size_t limit, bool by_last_name) const {
const std::string wanted = fold(needle);
std::vector<VCard> out;
for (const auto& card : contacts_) {
@@ -117,10 +118,20 @@ namespace tether::bluetooth {
out.push_back(card);
}
// Sorted before the limit applies, so a favorite is never cut off.
- std::sort(out.begin(), out.end(), [](const VCard& a, const VCard& b) {
+ // A card without a family name (a single name, a business, FN only)
+ // sorts on whichever name it has.
+ auto key = [by_last_name](const VCard& card) {
+ if (!by_last_name)
+ return std::tuple{fold(card.name), std::string{}, std::string{}};
+ const std::string& primary = !card.family.empty() ? card.family
+ : !card.given.empty() ? card.given
+ : card.name;
+ return std::tuple{fold(primary), fold(card.given), fold(card.name)};
+ };
+ std::sort(out.begin(), out.end(), [&key](const VCard& a, const VCard& b) {
if (a.favorite != b.favorite)
return a.favorite;
- return fold(a.name) < fold(b.name);
+ return key(a) < key(b);
});
if (out.size() > limit)
out.resize(limit);
@@ -164,6 +175,8 @@ namespace tether::bluetooth {
for (const auto& card : store.contacts()) {
nlohmann::json c;
c["name"] = card.name;
+ c["family"] = card.family;
+ c["given"] = card.given;
c["tels"] = card.tels;
c["emails"] = card.emails;
c["favorite"] = card.favorite;
@@ -184,6 +197,8 @@ namespace tether::bluetooth {
for (const auto& c : j.value("contacts", nlohmann::json::array())) {
VCard card;
card.name = c.value("name", "");
+ card.family = c.value("family", "");
+ card.given = c.value("given", "");
card.tels = c.value("tels", std::vector<std::string>{});
card.emails = c.value("emails", std::vector<std::string>{});
card.favorite = c.value("favorite", false);
diff --git a/src/core/src/bluetooth/vcard.cpp b/src/core/src/bluetooth/vcard.cpp
index 007cc9b..cf3354a 100644
--- a/src/core/src/bluetooth/vcard.cpp
+++ b/src/core/src/bluetooth/vcard.cpp
@@ -57,18 +57,27 @@ namespace tether::bluetooth {
return !name.empty();
}
- std::string vcard_name_from_n(const std::string& value) {
- std::vector<std::string> parts;
- size_t start = 0;
- while (true) {
- size_t semi = value.find(';', start);
- parts.push_back(value.substr(start, semi == std::string::npos ? std::string::npos : semi - start));
- if (semi == std::string::npos)
- break;
- start = semi + 1;
+ std::vector<std::string> vcard_n_parts(const std::string& value) {
+ std::vector<std::string> parts(1);
+ for (size_t i = 0; i < value.size(); ++i) {
+ if (value[i] == '\\' && i + 1 < value.size()) {
+ parts.back() += value.substr(i, 2);
+ ++i;
+ } else if (value[i] == ';') {
+ parts.emplace_back();
+ } else {
+ parts.back() += value[i];
+ }
}
- std::string given = parts.size() > 1 ? trim(parts[1]) : std::string{};
- std::string family = parts.empty() ? std::string{} : trim(parts[0]);
+ for (auto& part : parts)
+ part = trim(vcard_unescape(part));
+ return parts;
+ }
+
+ std::string vcard_name_from_n(const std::string& value) {
+ const auto parts = vcard_n_parts(value);
+ const std::string& family = parts[0];
+ const std::string given = parts.size() > 1 ? parts[1] : std::string{};
if (!given.empty() && !family.empty())
return given + " " + family;
return given.empty() ? family : given;
@@ -156,9 +165,12 @@ namespace tether::bluetooth {
current.emails.push_back(vcard_unescape(value));
else if (name == "FN")
current.name = vcard_unescape(value);
- else if (name == "N")
- structured_name = vcard_name_from_n(vcard_unescape(value));
- else if (name == "X-IRMC-CALL-DATETIME") {
+ else if (name == "N") {
+ const auto parts = vcard_n_parts(value);
+ current.family = parts[0];
+ current.given = parts.size() > 1 ? parts[1] : std::string{};
+ structured_name = vcard_name_from_n(value);
+ } else if (name == "X-IRMC-CALL-DATETIME") {
// The call type is the parameter: ";MISSED:" (iOS) or ";TYPE=MISSED:".
const std::string head = token.substr(0, token.find(':'));
const size_t semi = head.find(';');
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index 8758d15..2e7a1cd 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -434,6 +434,7 @@ namespace tether {
status["lock_on_away"] = config.lock_on_away;
status["lock_away_seconds"] = config.lock_away_seconds;
status["yield_when_inactive"] = config.yield_when_inactive;
+ status["contacts_by_last_name"] = config.contacts_by_last_name;
status["version"] = TETHER_VERSION;
if (!bluetooth::g_bluez) {
status["capability"] = nullptr;
@@ -812,9 +813,10 @@ namespace tether {
result["command"] = "bt_contacts";
result["query"] = query;
nlohmann::json contacts = nlohmann::json::array();
+ const bool by_last_name = bluetooth::load_config().contacts_by_last_name;
{
std::lock_guard<std::mutex> lock(bluetooth::message_store_mutex());
- for (const auto& card : bluetooth::contact_store().search(query, limit)) {
+ for (const auto& card : bluetooth::contact_store().search(query, limit, by_last_name)) {
nlohmann::json entry;
entry["name"] = card.name;
entry["favorite"] = card.favorite;
@@ -1477,6 +1479,11 @@ namespace tether {
if (bluetooth::g_bt_connections)
bluetooth::g_bt_connections->set_yield_when_inactive(config.yield_when_inactive);
broadcast_local_event(build_bt_status().dump());
+ } else if (j.contains("command") && j["command"] == "bt_set_contacts_by_last_name") {
+ auto config = bluetooth::load_config();
+ config.contacts_by_last_name = j.value("enabled", false);
+ bluetooth::save_config(config);
+ broadcast_local_event(build_bt_status().dump());
} else if (j.contains("command") && j["command"] == "bt_hold" && j.contains("profile")) {
if (bluetooth::g_bt_connections &&
bluetooth::g_bt_connections->set_hold(j.value("profile", ""), j.value("held", true)))
diff --git a/src/gtk/contacts_view.cpp b/src/gtk/contacts_view.cpp
index dec3e88..3d6e7a1 100644
--- a/src/gtk/contacts_view.cpp
+++ b/src/gtk/contacts_view.cpp
@@ -19,6 +19,7 @@ namespace tether::ui {
std::string shown;
bool visible = false;
bool calls_available = false;
+ bool by_last_name = false;
void (*open_thread)(const std::string&) = nullptr;
void (*start_call)(const std::string&) = nullptr;
};
@@ -229,6 +230,14 @@ namespace tether::ui {
gtk_widget_grab_focus(g_contacts.search_entry);
}
+ void contacts_view_set_sort(bool by_last_name) {
+ if (by_last_name == g_contacts.by_last_name)
+ return;
+ g_contacts.by_last_name = by_last_name;
+ if (g_contacts.visible)
+ request_contacts();
+ }
+
bool contacts_view_handle_event(const nlohmann::json& event) {
const std::string command = event.value("command", "");
if (command == "bt_contacts")
diff --git a/src/gtk/contacts_view.hpp b/src/gtk/contacts_view.hpp
index d7bc19f..fad6925 100644
--- a/src/gtk/contacts_view.hpp
+++ b/src/gtk/contacts_view.hpp
@@ -16,4 +16,7 @@ namespace tether::ui {
// Contacts are only pulled while the view is on screen.
void contacts_view_set_visible(bool visible);
+ // Re-pulls the list on screen when the daemon's sort order changes.
+ void contacts_view_set_sort(bool by_last_name);
+
} // namespace tether::ui
diff --git a/src/gtk/main.cpp b/src/gtk/main.cpp
index f44b775..6c271b7 100644
--- a/src/gtk/main.cpp
+++ b/src/gtk/main.cpp
@@ -382,8 +382,10 @@ namespace {
daemon_client_start([](const nlohmann::json& event) {
contact_completion_update(event);
settings_handle_event(event);
- if (event.value("command", "") == "bt_status")
+ if (event.value("command", "") == "bt_status") {
set_calls_tab_visible(event.value("calls_enabled", false));
+ contacts_view_set_sort(event.value("contacts_by_last_name", false));
+ }
if (devices_view_handle_event(event))
return;
if (contacts_view_handle_event(event))
diff --git a/src/gtk/settings_view.cpp b/src/gtk/settings_view.cpp
index 1e355d7..ccb1aaf 100644
--- a/src/gtk/settings_view.cpp
+++ b/src/gtk/settings_view.cpp
@@ -34,6 +34,8 @@ namespace tether::ui {
GtkWidget* cmb_retention = nullptr;
GtkWidget* lbl_keyring = nullptr;
+ GtkWidget* sw_last_name = nullptr;
+
GtkWidget* row_calls = nullptr;
GtkWidget* sw_calls = nullptr;
@@ -139,6 +141,11 @@ namespace tether::ui {
daemon_send({{"command", "set_popup_previews"}, {"enabled", gtk_switch_get_active(widget) == TRUE}});
}
+ void on_last_name_toggled(GtkSwitch* widget, GParamSpec*, gpointer) {
+ daemon_send(
+ {{"command", "bt_set_contacts_by_last_name"}, {"enabled", gtk_switch_get_active(widget) == TRUE}});
+ }
+
void on_calls_toggled(GtkSwitch* widget, GParamSpec*, gpointer) {
daemon_send({{"command", "bt_set_calls"}, {"enabled", gtk_switch_get_active(widget) == TRUE}});
}
@@ -201,6 +208,10 @@ namespace tether::ui {
reinterpret_cast<gpointer>(on_lock_away_toggled),
status.value("lock_on_away", false));
+ set_switch(g_settings.sw_last_name,
+ reinterpret_cast<gpointer>(on_last_name_toggled),
+ status.value("contacts_by_last_name", false));
+
const std::string retention = status.value("retention", "encrypted");
set_combo(g_settings.cmb_retention, reinterpret_cast<gpointer>(on_retention_changed), retention);
@@ -347,6 +358,16 @@ namespace tether::ui {
gtk_widget_set_no_show_all(g_settings.lbl_keyring, TRUE);
gtk_box_pack_start(GTK_BOX(column), g_settings.lbl_keyring, FALSE, FALSE, 0);
+ // Contacts
+ GtkWidget* contacts = add_group(column, _("Contacts"), "");
+
+ g_settings.sw_last_name = new_switch();
+ g_signal_connect(g_settings.sw_last_name, "notify::active", G_CALLBACK(on_last_name_toggled), nullptr);
+ add_row(contacts,
+ _("Sort contacts by last name"),
+ _("Contacts with only one name, and businesses, sort by the name they have."),
+ g_settings.sw_last_name);
+
// Experimental
GtkWidget* experimental =
add_group(column, _("Experimental"), _("Unfinished features. These can stop working at any time."));
diff --git a/src/tui/settings.cpp b/src/tui/settings.cpp
index ccca91d..c1daa42 100644
--- a/src/tui/settings.cpp
+++ b/src/tui/settings.cpp
@@ -61,6 +61,13 @@ namespace tether::tui {
"bt_set_retention",
"retention",
false},
+ {"lastname",
+ N_("Contacts"),
+ N_("Sort contacts by last name"),
+ N_("Contacts with only one name, and businesses, sort by the name they have."),
+ "bt_set_contacts_by_last_name",
+ "contacts_by_last_name",
+ false},
{"calls",
N_("Experimental"),
N_("Call control over Bluetooth"),
diff --git a/test/test_vcard.cpp b/test/test_vcard.cpp
index 2756a5f..76e8ca8 100644
--- a/test/test_vcard.cpp
+++ b/test/test_vcard.cpp
@@ -460,3 +460,50 @@ TEST(ContactStore, FavoriteSurvivesJsonRoundTrip) {
ScopedStore scope("favorite-roundtrip");
ASSERT_TRUE(deserialize_contacts(serialize_contacts(store)).contacts().at(0).favorite);
}
+
+TEST(VCard, KeepsStructuredNameParts) {
+ auto cards = parse_vcards("BEGIN:VCARD\nN:van Beethoven;Ludwig;;;\nFN:Ludwig van Beethoven\nEND:VCARD\n");
+
+ ASSERT_EQ(cards.size(), 1u);
+ EXPECT_EQ(cards[0].family, "van Beethoven");
+ EXPECT_EQ(cards[0].given, "Ludwig");
+}
+
+// The ';' is the part separator, so an escaped one belongs to its part.
+TEST(VCard, SplitsStructuredNameBeforeUnescaping) {
+ auto cards = parse_vcards("BEGIN:VCARD\nN:Smith\\;Jones;Ann\\, Marie;;;\nEND:VCARD\n");
+
+ ASSERT_EQ(cards.size(), 1u);
+ EXPECT_EQ(cards[0].family, "Smith;Jones");
+ EXPECT_EQ(cards[0].given, "Ann, Marie");
+ EXPECT_EQ(cards[0].name, "Ann, Marie Smith;Jones");
+}
+
+TEST(ContactSearch, SortsByLastNameFallingBackToWhicheverNameACardHas) {
+ ContactStore store;
+ store.set(parse_vcards("BEGIN:VCARD\nN:Turing;Alan;;;\nFN:Alan Turing\nEND:VCARD\n"
+ "BEGIN:VCARD\nN:;Cher;;;\nFN:Cher\nEND:VCARD\n"
+ "BEGIN:VCARD\nN:;;;;\nFN:Acme Corp\nEND:VCARD\n"
+ "BEGIN:VCARD\nN:Smith-Jones;Mary Ann;;;\nFN:Mary Ann Smith-Jones\nEND:VCARD\n"
+ "BEGIN:VCARD\nFN:Bob\nEND:VCARD\n"
+ "BEGIN:VCARD\nN:Smith;Jane;;;\nFN:Jane Smith\nEND:VCARD\n"
+ "BEGIN:VCARD\nN:Smith;Adam;;;\nFN:Adam Smith\nEND:VCARD\n"));
+
+ EXPECT_EQ(names_of(store.search("", 10, true)),
+ (std::vector<std::string>{
+ "Acme Corp", "Bob", "Cher", "Adam Smith", "Jane Smith", "Mary Ann Smith-Jones", "Alan Turing"}));
+ EXPECT_EQ(names_of(store.search("", 10)),
+ (std::vector<std::string>{
+ "Acme Corp", "Adam Smith", "Alan Turing", "Bob", "Cher", "Jane Smith", "Mary Ann Smith-Jones"}));
+}
+
+TEST(ContactStore, StructuredNameSurvivesJsonRoundTrip) {
+ ContactStore store;
+ store.set(parse_vcards("BEGIN:VCARD\nN:Lovelace;Ada;;;\nTEL:+15551234567\nEND:VCARD\n"));
+
+ ScopedStore scope("structured-roundtrip");
+ const auto restored = deserialize_contacts(serialize_contacts(store)).contacts();
+ ASSERT_EQ(restored.size(), 1u);
+ EXPECT_EQ(restored[0].family, "Lovelace");
+ EXPECT_EQ(restored[0].given, "Ada");
+}