Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Messages: back to the list, search, copy codes and texts, and more

Bee3417b67d3568
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index 0c2c643..61a3780 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -377,6 +377,8 @@ fn sample_texts() {
"Your parcel will arrive tomorrow between 9:00 and 13:00.",
now - 26 * 60 * min,
),
+ (2, "+15550123", "", true, "Track it at https://example.com/track?id=42.", now - 26 * 60 * min + min),
+ (4, "JD-BANK", "", true, "243928 is your one time password (OTP). Do not share it.", now - 5 * min),
(3, "+15550188", "Alex", false, "Can you send me the photos from Saturday?", now - 3 * 24 * 60 * min),
(3, "+15550188", "Alex", true, "Sure, uploading them now", now - 3 * 24 * 60 * min + 5 * min),
];
diff --git a/desktop/app/qml/components/Avatar.qml b/desktop/app/qml/components/Avatar.qml
index 6a84067..2aea7fc 100644
--- a/desktop/app/qml/components/Avatar.qml
+++ b/desktop/app/qml/components/Avatar.qml
@@ -8,16 +8,22 @@ Rectangle {
property string name
property string iconPath
property bool emphasized: false
+ // A color of its own (a contact's), in Bloom; Graphite stays ink on paper.
+ property real hue: -1
+ readonly property bool tinted: hue >= 0 && !Theme.graphite
implicitWidth: 36
implicitHeight: 36
radius: Theme.graphite ? Theme.radiusSm : width / 2
- color: Theme.graphite ? "transparent" : (emphasized ? Theme.primaryContainer : Theme.surfaceContainerHighest)
+ color: Theme.graphite ? "transparent"
+ : tinted ? Qt.hsla(hue, 0.42, Theme.dark ? 0.28 : 0.86, 1)
+ : (emphasized ? Theme.primaryContainer : Theme.surfaceContainerHighest)
border.width: Theme.graphite ? 1 : 0
border.color: Theme.outlineVariant
readonly property color ink: Theme.graphite ? Theme.surfaceContent
- : (emphasized ? Theme.primaryContainerContent : Theme.surfaceContentVariant)
+ : tinted ? Qt.hsla(hue, 0.55, Theme.dark ? 0.85 : 0.25, 1)
+ : (emphasized ? Theme.primaryContainerContent : Theme.surfaceContentVariant)
Icon {
visible: avatar.iconPath.length > 0
anchors.centerIn: parent
diff --git a/desktop/app/qml/pages/MessagesPage.qml b/desktop/app/qml/pages/MessagesPage.qml
index 3b85256..0c2c0e0 100644
--- a/desktop/app/qml/pages/MessagesPage.qml
+++ b/desktop/app/qml/pages/MessagesPage.qml
@@ -17,6 +17,50 @@ Item {
readonly property var messages: { try { return JSON.parse(Messages.messages) } catch (e) { return [] } }
readonly property var openThread: threads.find(t => t.id === Messages.thread) || null
readonly property bool ready: Messages.status === "ready"
+ // Conversations matching the search box.
+ readonly property string query: search.text.trim().toLocaleLowerCase()
+ readonly property var shownThreads: query.length === 0 ? threads
+ : threads.filter(t => (t.title + " " + t.addresses + " " + t.snippet).toLocaleLowerCase().indexOf(query) >= 0)
+
+ // Back to the list: nothing open.
+ function closeChat() {
+ Messages.closeThread()
+ composing = false
+ toField.text = ""
+ }
+
+ // A stable color for a contact (in Bloom).
+ function hueOf(name) {
+ let h = 0
+ for (let i = 0; i < name.length; i++)
+ h = (h * 31 + name.charCodeAt(i)) % 360
+ return h / 360
+ }
+
+ // "Today", "Yesterday", or the date, for separators.
+ function dayLabel(ms) {
+ const date = new Date(ms)
+ const today = new Date()
+ const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1)
+ if (date.toDateString() === today.toDateString()) return qsTr("Today")
+ if (date.toDateString() === yesterday.toDateString()) return qsTr("Yesterday")
+ return date.toLocaleDateString(Qt.locale(), date.getFullYear() === today.getFullYear() ? "dddd, d MMMM" : Locale.LongFormat)
+ }
+
+ // Text as HTML with its web links clickable.
+ function linkified(text) {
+ const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<br>")
+ return escaped.replace(/\b(https?:\/\/[^\s<]+[^\s<.,;:!?)\]'"])/g, '<a href="$1">$1</a>')
+ }
+
+ // How many texts a message takes (GSM letters: 160 in one, 153 each
+ // when split; anything else: 70 and 67).
+ function smsCount(text) {
+ const gsm = /^[\x0A\x0D\x20-\x7E£¥èéùìòÇØøÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉÄÖÑܧ¿äöñüà€]*$/.test(text)
+ const one = gsm ? 160 : 70
+ const each = gsm ? 153 : 67
+ return text.length <= one ? 1 : Math.ceil(text.length / each)
+ }
opacity: active ? 1 : 0
visible: opacity > 0
@@ -30,7 +74,29 @@ Item {
if (active && deviceId.length > 0)
Messages.open(deviceId)
}
- onActiveChanged: load()
+ // Leaving the page closes the open conversation.
+ onActiveChanged: active ? load() : closeChat()
+
+ Shortcut {
+ sequence: "Esc"
+ enabled: page.active && (!!page.openThread || page.composing)
+ onActivated: page.closeChat()
+ }
+ Shortcut {
+ sequence: StandardKey.Find
+ enabled: page.active && page.ready
+ onActivated: search.forceActiveFocus()
+ }
+ Shortcut {
+ sequence: StandardKey.New
+ enabled: page.active && page.ready
+ onActivated: page.startNew()
+ }
+ function startNew() {
+ Messages.closeThread()
+ composing = true
+ toField.forceActiveFocus()
+ }
onDeviceIdChanged: { composing = false; load() }
// "14:05", "Tue", or a date.
@@ -112,39 +178,105 @@ Item {
role: "title"
}
IconButton {
+ id: newButton
anchors.right: parent.right
anchors.rightMargin: 10
anchors.verticalCenter: parent.verticalCenter
iconPath: Icons.plus
- label: qsTr("New message")
+ label: qsTr("New message (Ctrl+N)")
tonal: page.composing
enabled: page.ready
- onClicked: {
- Messages.closeThread()
- page.composing = true
- toField.forceActiveFocus()
+ onClicked: page.startNew()
+ }
+ IconButton {
+ anchors.right: newButton.left
+ anchors.verticalCenter: parent.verticalCenter
+ iconPath: Icons.refresh
+ label: qsTr("Refresh")
+ enabled: Messages.status !== "loading"
+ onClicked: Messages.refresh()
+ }
+ }
+
+ // Search: by name, number or the latest text.
+ Rectangle {
+ id: searchBox
+ anchors.top: listHeader.bottom
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.leftMargin: 16
+ anchors.rightMargin: 16
+ height: 38
+ radius: Theme.graphite ? Theme.radiusSm : height / 2
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest
+ border.width: search.activeFocus ? 2 : (Theme.graphite ? 1 : 0)
+ border.color: search.activeFocus ? Theme.primary : Theme.outlineVariant
+ Icon {
+ id: searchIcon
+ anchors.left: parent.left
+ anchors.leftMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ width: 16; height: 16
+ path: Icons.search
+ color: Theme.surfaceContentVariant
+ }
+ TextInput {
+ id: search
+ anchors.left: searchIcon.right
+ anchors.leftMargin: 8
+ anchors.right: clearSearch.left
+ anchors.verticalCenter: parent.verticalCenter
+ font.family: Theme.fontUi
+ font.pixelSize: 14
+ color: Theme.surfaceContent
+ selectionColor: Theme.primaryContainer
+ selectedTextColor: Theme.primaryContainerContent
+ clip: true
+ Accessible.name: qsTr("Search conversations")
+ Keys.onEscapePressed: (event) => {
+ event.accepted = text.length > 0
+ text = ""
+ }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: search.text.length === 0
+ role: "body"
+ muted: true
+ text: qsTr("Search")
}
}
+ IconButton {
+ id: clearSearch
+ anchors.right: parent.right
+ anchors.rightMargin: 2
+ anchors.verticalCenter: parent.verticalCenter
+ width: 32; height: 32
+ visible: search.text.length > 0
+ iconPath: Icons.close
+ label: qsTr("Clear search")
+ onClicked: search.text = ""
+ }
}
ListView {
id: threadList
- anchors.top: listHeader.bottom
+ anchors.top: searchBox.bottom
+ anchors.topMargin: 8
anchors.bottom: parent.bottom
width: parent.width
clip: true
boundsBehavior: Flickable.StopAtBounds
- model: page.threads
+ model: page.shownThreads
delegate: ThreadRow {
width: threadList.width
thread: modelData
}
Txt {
anchors.centerIn: parent
- visible: page.ready && page.threads.length === 0
+ visible: page.ready && page.shownThreads.length === 0
role: "body"
muted: true
- text: qsTr("No conversations yet.")
+ text: page.query.length > 0 ? qsTr("No conversations match.") : qsTr("No conversations yet.")
}
}
Divider { anchors.right: parent.right; width: 1; height: parent.height }
@@ -171,9 +303,18 @@ Item {
visible: !!page.openThread || page.composing
width: parent.width
height: 64
- Column {
+ IconButton {
+ id: backButton
anchors.left: parent.left
- anchors.leftMargin: 24
+ anchors.leftMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ iconPath: Icons.back
+ label: qsTr("Back to conversations (Esc)")
+ onClicked: page.closeChat()
+ }
+ Column {
+ anchors.left: backButton.right
+ anchors.leftMargin: 8
anchors.right: parent.right
anchors.rightMargin: 24
anchors.verticalCenter: parent.verticalCenter
@@ -196,8 +337,8 @@ Item {
}
// New message: who to.
Row {
- anchors.left: parent.left
- anchors.leftMargin: 24
+ anchors.left: backButton.right
+ anchors.leftMargin: 8
anchors.right: parent.right
anchors.rightMargin: 24
anchors.verticalCenter: parent.verticalCenter
@@ -260,6 +401,7 @@ Item {
delegate: Bubble {
width: messageList.width
message: modelData
+ previous: index > 0 ? page.messages[index - 1] : null
}
Txt {
anchors.centerIn: parent
@@ -364,6 +506,17 @@ Item {
anchors.centerIn: sendButton
visible: Messages.sending
}
+ // Long texts: how many SMS they take.
+ Txt {
+ anchors.right: parent.right
+ anchors.rightMargin: 16
+ anchors.bottom: parent.top
+ anchors.bottomMargin: 4
+ visible: input.text.length > 120
+ role: "bodySmall"
+ muted: true
+ text: qsTr("%1 characters · %n text(s)", "", page.smsCount(input.text)).arg(input.text.length)
+ }
}
}
@@ -411,6 +564,7 @@ Item {
readonly property bool named: !/^[\d+(#*]/.test(row.thread.title)
name: row.thread.group || !named ? "" : row.thread.title
iconPath: row.thread.group ? Icons.messages : named ? "" : Icons.person
+ hue: named && !row.thread.group ? page.hueOf(row.thread.title) : -1
emphasized: row.thread.unread > 0
}
}
@@ -485,12 +639,42 @@ Item {
component Bubble: Item {
id: bubble
property var message
+ property var previous: null
readonly property bool mine: message.outgoing
readonly property real maxWidth: Math.min(width * 0.72, 520)
- height: content.height + meta.height + 4
+ readonly property bool newDay: !previous || new Date(previous.date).toDateString() !== new Date(message.date).toDateString()
+ readonly property bool showSender: !!message.sender && (!previous || previous.sender !== message.sender || newDay)
+ height: day.height + sender.height + content.height + meta.height + codeRow.height + 4
+
+ HoverHandler { id: bubbleHover }
+
+ // The day, above its first message.
+ Txt {
+ id: day
+ width: parent.width
+ height: bubble.newDay ? implicitHeight + 20 : 0
+ visible: bubble.newDay
+ topPadding: 8
+ horizontalAlignment: Text.AlignHCenter
+ role: "label"
+ muted: true
+ text: page.dayLabel(bubble.message.date)
+ }
+ // Who wrote it, in a group.
+ Txt {
+ id: sender
+ anchors.top: day.bottom
+ x: 30
+ height: bubble.showSender ? implicitHeight + 2 : 0
+ visible: bubble.showSender
+ role: "bodySmall"
+ muted: true
+ text: bubble.message.sender || ""
+ }
Rectangle {
id: content
+ anchors.top: sender.bottom
anchors.right: bubble.mine ? parent.right : undefined
anchors.left: bubble.mine ? undefined : parent.left
anchors.leftMargin: 24
@@ -533,12 +717,14 @@ Item {
x: 14
width: Math.min(implicitWidth, bubble.maxWidth - 28)
visible: bubble.message.body.length > 0 || bubble.message.attachments > 0
- text: bubble.message.body.length > 0 ? bubble.message.body
+ text: bubble.message.body.length > 0 ? page.linkified(bubble.message.body)
: qsTr("Attachment (open it on the phone)")
readOnly: true
selectByMouse: true
wrapMode: TextEdit.Wrap
- textFormat: TextEdit.PlainText
+ textFormat: bubble.message.body.length > 0 ? TextEdit.RichText : TextEdit.PlainText
+ onLinkActivated: (link) => Qt.openUrlExternally(link)
+ HoverHandler { cursorShape: text.hoveredLink.length > 0 ? Qt.PointingHandCursor : Qt.IBeamCursor }
font.family: Theme.fontUi
font.pixelSize: 14
font.italic: bubble.message.body.length === 0
@@ -560,7 +746,46 @@ Item {
color: bubble.message.status === "failed" ? Theme.error : Theme.surfaceContentVariant
text: bubble.message.status === "failed" ? qsTr("Not sent")
: bubble.message.status === "pending" ? qsTr("Sending…")
- : page.shortTime(bubble.message.date)
+ // The day is in the separator above.
+ : new Date(bubble.message.date).toLocaleTimeString(Qt.locale(), Locale.ShortFormat)
+ }
+ // Copy the text (shown while hovered).
+ IconButton {
+ anchors.verticalCenter: content.verticalCenter
+ anchors.left: bubble.mine ? undefined : content.right
+ anchors.right: bubble.mine ? content.left : undefined
+ anchors.margins: 4
+ width: 32; height: 32
+ visible: bubble.message.body.length > 0
+ opacity: bubbleHover.hovered || activeFocus ? 1 : 0
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }
+ iconPath: Icons.copy
+ label: qsTr("Copy text")
+ onClicked: Messages.copy(bubble.message.body)
+ }
+ // A one-time code, one click from the clipboard.
+ Item {
+ id: codeRow
+ anchors.top: meta.bottom
+ width: parent.width
+ height: bubble.message.code ? codeButton.height + 6 : 0
+ visible: !!bubble.message.code
+ Button {
+ id: codeButton
+ x: 24
+ y: 4
+ variant: "tonal"
+ size: "sm"
+ iconPath: copied ? Icons.check : Icons.copy
+ property bool copied: false
+ text: copied ? qsTr("Copied") : qsTr("Copy code %1").arg(bubble.message.code || "")
+ onClicked: {
+ Messages.copy(bubble.message.code)
+ copied = true
+ copiedTimer.restart()
+ }
+ Timer { id: copiedTimer; interval: 2000; onTriggered: codeButton.copied = false }
+ }
}
}
}
diff --git a/desktop/app/src/bridge/messages.rs b/desktop/app/src/bridge/messages.rs
index 8660a59..a88e9dc 100644
--- a/desktop/app/src/bridge/messages.rs
+++ b/desktop/app/src/bridge/messages.rs
@@ -60,6 +60,12 @@ pub mod qobject {
#[qinvokable]
#[cxx_name = "sendTo"]
fn send_to(self: &Messages, to: &QString, body: &QString);
+ /// Reads the conversations (and the open one) again.
+ #[qinvokable]
+ fn refresh(self: &Messages);
+ /// Puts text on this PC's clipboard (it isn't sent back to the phone).
+ #[qinvokable]
+ fn copy(self: &Messages, text: &QString);
}
}
@@ -82,13 +88,13 @@ impl cxx_qt::Initialize for qobject::Messages {
self.as_mut().set_status(QString::from("idle"));
self.as_mut().set_threads(QString::from("[]"));
self.as_mut().set_messages(QString::from("[]"));
- super::subscribe(self.qt_thread(), Changes::MESSAGES, Self::refresh);
- self.refresh();
+ super::subscribe(self.qt_thread(), Changes::MESSAGES, Self::update_view);
+ self.update_view();
}
}
impl qobject::Messages {
- fn refresh(mut self: Pin<&mut Self>) {
+ fn update_view(mut self: Pin<&mut Self>) {
let view = messages::view();
if self.rust().last.as_ref() == Some(&view) {
return;
@@ -135,6 +141,16 @@ impl qobject::Messages {
}
}
+ pub fn refresh(&self) {
+ messages::reload();
+ }
+
+ pub fn copy(&self, text: &QString) {
+ if let Err(reason) = crate::win::clipboard::write(&String::from(text)) {
+ tracing::warn!(reason, "can't copy");
+ }
+ }
+
pub fn send_to(&self, to: &QString, body: &QString) {
let (to, body) = (String::from(to), String::from(body));
let to: Vec<String> =
diff --git a/desktop/app/src/messages.rs b/desktop/app/src/messages.rs
index f8b67a9..e7e68b0 100644
--- a/desktop/app/src/messages.rs
+++ b/desktop/app/src/messages.rs
@@ -110,7 +110,18 @@ pub fn view() -> View {
status: s.status,
threads: Value::Array(s.threads.iter().map(|t| thread_json(t, s.photos.get(&t.id))).collect()),
thread: s.thread.clone(),
- messages: Value::Array(s.messages.iter().rev().map(|m| message_json(m, &s.pictures)).collect()),
+ messages: {
+ // In a group, who sent each message (by contact name when known).
+ let thread = s.thread.as_ref().and_then(|id| s.threads.iter().find(|t| &t.id == id));
+ let group = thread.filter(|t| t.addresses.len() > 1);
+ Value::Array(
+ s.messages
+ .iter()
+ .rev()
+ .map(|m| message_json(m, &s.pictures, group.map(|t| sender_of(t, &m.address))))
+ .collect(),
+ )
+ },
more: s.more,
loading_older: s.loading_older,
sending: s.sending,
@@ -141,7 +152,60 @@ fn thread_json(t: &SmsThread, photo: Option<&PathBuf>) -> Value {
})
}
-fn message_json(m: &SmsMessage, pictures: &HashMap<String, PathBuf>) -> Value {
+fn now_ms() -> i64 {
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64)
+}
+
+/// A group member's name, or their number.
+fn sender_of(thread: &SmsThread, address: &str) -> String {
+ let wanted = digits(address);
+ thread
+ .addresses
+ .iter()
+ .position(|a| digits(a) == wanted)
+ .and_then(|i| thread.names.get(i))
+ .filter(|n| !n.trim().is_empty())
+ .cloned()
+ .unwrap_or_else(|| address.to_owned())
+}
+
+/// A one-time code in a text ("243928 is your OTP"): 4 to 8 digits on
+/// their own, in a text that says it's a code.
+pub fn one_time_code(body: &str) -> Option<String> {
+ let lower = body.to_lowercase();
+ const WORDS: [&str; 7] = ["otp", "code", "password", "passcode", "verification", "pin", "one time"];
+ if !WORDS.iter().any(|w| lower.contains(w)) {
+ return None;
+ }
+ let chars: Vec<char> = body.chars().collect();
+ let mut i = 0;
+ while i < chars.len() {
+ if !chars[i].is_ascii_digit() {
+ i += 1;
+ continue;
+ }
+ let start = i;
+ while i < chars.len() && chars[i].is_ascii_digit() {
+ i += 1;
+ }
+ // On its own: not part of a word ("XX3465"), an amount ("Rs.500",
+ // "1,000") or a longer number.
+ let before = start.checked_sub(1).map(|b| chars[b]);
+ let after = chars.get(i).copied();
+ let alone = before
+ .is_none_or(|c| !c.is_alphanumeric() && !matches!(c, '.' | ',' | '₹' | '$' | '€' | '£'))
+ && after.is_none_or(|c| {
+ !c.is_alphanumeric()
+ && !(matches!(c, '.' | ',') && chars.get(i + 1).is_some_and(char::is_ascii_digit))
+ });
+ if alone && (4..=8).contains(&(i - start)) {
+ return Some(chars[start..i].iter().collect());
+ }
+ }
+ None
+}
+
+fn message_json(m: &SmsMessage, pictures: &HashMap<String, PathBuf>, sender: Option<String>) -> Value {
let images: Vec<Value> = m
.parts
.iter()
@@ -157,6 +221,8 @@ fn message_json(m: &SmsMessage, pictures: &HashMap<String, PathBuf>) -> Value {
"status": m.status.clone().unwrap_or_default(),
"images": images,
"attachments": others,
+ "sender": if m.outgoing { None } else { sender },
+ "code": if m.outgoing { None } else { one_time_code(&m.body) },
})
}
@@ -376,6 +442,23 @@ pub fn send(body: String) {
pub fn send_to(to: Vec<String>, body: String) {
let Some(device) = state(|s| {
s.sending = true;
+ // Shown at once as "Sending…"; the phone's copy replaces it.
+ if let Some(thread) = s.thread.clone() {
+ let now = now_ms();
+ s.messages.insert(
+ 0,
+ SmsMessage {
+ id: format!("local:{now}"),
+ thread,
+ address: to.join(", "),
+ body: body.clone(),
+ date: now,
+ outgoing: true,
+ status: Some("pending".into()),
+ parts: Vec::new(),
+ },
+ );
+ }
s.device
}) else {
return;
@@ -384,7 +467,15 @@ pub fn send_to(to: Vec<String>, body: String) {
let Some(node) = core_host::node() else { return };
core_host::spawn(async move {
let result = node.sms_send(device, to.clone(), body).await;
- state(|s| s.sending = false);
+ state(|s| {
+ s.sending = false;
+ if result.is_err() {
+ // Not sent: say so on it.
+ for m in s.messages.iter_mut().filter(|m| m.id.starts_with("local:")) {
+ m.status = Some("failed".into());
+ }
+ }
+ });
changed();
match result {
Ok(()) => {
@@ -419,6 +510,14 @@ fn digits(number: &str) -> String {
all[all.len().saturating_sub(9)..].to_owned()
}
+/// Reads the conversations and the open one again.
+pub fn reload() {
+ load_threads();
+ if state(|s| s.thread.is_some()) {
+ load_messages(None);
+ }
+}
+
/// Closes the open conversation (for writing a new one).
pub fn close_thread() {
state(|s| {
@@ -492,6 +591,28 @@ mod tests {
assert_eq!(title_of(&thread(&["+1555"], &[])), "+1555");
}
+ #[test]
+ fn one_time_codes_are_found() {
+ let found = |body: &str| one_time_code(body);
+ assert_eq!(
+ found(
+ "Dear Customer,
+243928 is your one time password (OTP)."
+ ),
+ Some("243928".into())
+ );
+ assert_eq!(found("840941 is your OTP to create JioID"), Some("840941".into()));
+ assert_eq!(found("740421 is OTP for Aadhaar (XX3465) valid for 10 mins"), Some("740421".into()));
+ // Google's "G-482193" is typed without the "G-".
+ assert_eq!(found("G-482193 is your Google verification code."), Some("482193".into()));
+ assert_eq!(found("Your code is AB4821CD"), None, "letters stuck to it");
+ assert_eq!(found("Use code 1234-5678"), Some("1234".into()));
+ assert_eq!(found("Payment received for Rs. 2000 - thanks"), None, "no code words");
+ assert_eq!(found("Your code is ready. Pay Rs.5000 at the counter"), None, "an amount");
+ assert_eq!(found("OTP 12"), None, "too short");
+ assert_eq!(found("PIN 1,234 used"), None, "a formatted number");
+ }
+
#[test]
fn numbers_match_however_they_are_written() {
assert_eq!(digits("+1 (555) 010-0100"), digits("5550100100"));
diff --git a/desktop/app/src/win/h264.rs b/desktop/app/src/win/h264.rs
index 32b896c..cbabeae 100644
--- a/desktop/app/src/win/h264.rs
+++ b/desktop/app/src/win/h264.rs
@@ -10,11 +10,11 @@ use windows::{
Media::MediaFoundation::{
CLSID_MSH264DecoderMFT, IMF2DBuffer, IMFMediaType, IMFSample, IMFTransform, MF_E_NOTACCEPTING,
MF_E_TRANSFORM_NEED_MORE_INPUT, MF_E_TRANSFORM_STREAM_CHANGE, MF_LOW_LATENCY, MF_MT_FRAME_SIZE,
- MF_MT_MAJOR_TYPE, MF_MT_SUBTYPE, MF_MT_VIDEO_NOMINAL_RANGE, MF_MT_YUV_MATRIX, MFNominalRange_0_255,
- MFVideoTransferMatrix_BT601, MF_VERSION, MFCreateMediaType, MFCreateMemoryBuffer,
- MFCreateSample, MFMediaType_Video, MFSTARTUP_NOSOCKET, MFStartup, MFT_MESSAGE_COMMAND_FLUSH,
- MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM, MFT_OUTPUT_DATA_BUFFER,
- MFT_OUTPUT_STREAM_PROVIDES_SAMPLES, MFVideoFormat_H264, MFVideoFormat_NV12,
+ MF_MT_MAJOR_TYPE, MF_MT_SUBTYPE, MF_MT_VIDEO_NOMINAL_RANGE, MF_MT_YUV_MATRIX, MF_VERSION,
+ MFCreateMediaType, MFCreateMemoryBuffer, MFCreateSample, MFMediaType_Video, MFNominalRange_0_255,
+ MFSTARTUP_NOSOCKET, MFStartup, MFT_MESSAGE_COMMAND_FLUSH, MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,
+ MFT_MESSAGE_NOTIFY_START_OF_STREAM, MFT_OUTPUT_DATA_BUFFER, MFT_OUTPUT_STREAM_PROVIDES_SAMPLES,
+ MFVideoFormat_H264, MFVideoFormat_NV12, MFVideoTransferMatrix_BT601,
},
System::Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx},
},
@@ -88,8 +88,13 @@ impl Decoder {
input.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;
input.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_H264)?;
transform.SetInputType(0, &input, 0)?;
- let mut decoder =
- Decoder { transform, coded: (0, 0), provides_samples: false, output_size: 0, colors: Colors::default() };
+ let mut decoder = Decoder {
+ transform,
+ coded: (0, 0),
+ provides_samples: false,
+ output_size: 0,
+ colors: Colors::default(),
+ };
decoder.choose_output()?;
decoder.transform.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)?;
decoder.transform.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)?;
@@ -114,7 +119,9 @@ impl Decoder {
self.coded = ((size >> 32) as u32, size as u32);
// Unknown until the stream says (then the type changes again).
self.colors = Colors {
- bt601: chosen.GetUINT32(&MF_MT_YUV_MATRIX).is_ok_and(|m| m == MFVideoTransferMatrix_BT601.0 as u32),
+ bt601: chosen
+ .GetUINT32(&MF_MT_YUV_MATRIX)
+ .is_ok_and(|m| m == MFVideoTransferMatrix_BT601.0 as u32),
full_range: chosen
.GetUINT32(&MF_MT_VIDEO_NOMINAL_RANGE)
.is_ok_and(|r| r == MFNominalRange_0_255.0 as u32),
@@ -302,7 +309,8 @@ mod tests {
// Chroma for pixel pairs (0,1) and (2,3): neutral; then red's... the
// second pair holds red's chroma (u=102, v=240).
nv12[8..12].copy_from_slice(&[128, 128, 102, 240]);
- let picture = Picture { width: 4, height: 2, stride: 4, plane_rows: 2, nv12, colors: Colors::default() };
+ let picture =
+ Picture { width: 4, height: 2, stride: 4, plane_rows: 2, nv12, colors: Colors::default() };
let out = to_bgrx(&picture, 4, 2);
assert_eq!(&out[..4], &[0, 0, 0, 255], "black");
assert_eq!(&out[4..8], &[255, 255, 255, 255], "white");
@@ -312,8 +320,14 @@ mod tests {
#[test]
fn odd_sizes_are_cropped_safely() {
- let picture =
- Picture { width: 6, height: 4, stride: 8, plane_rows: 4, nv12: vec![128; 8 * 6], colors: Colors::default() };
+ let picture = Picture {
+ width: 6,
+ height: 4,
+ stride: 8,
+ plane_rows: 4,
+ nv12: vec![128; 8 * 6],
+ colors: Colors::default(),
+ };
assert_eq!(to_bgrx(&picture, 5, 3).len(), 5 * 3 * 4);
assert_eq!(to_bgrx(&picture, 10, 10).len(), 6 * 4 * 4, "never larger than the picture");
}