Add dedicated Add Contact page with manual public key entry

Replace the Contacts add-contact modal sheet and separate menu shortcuts with a unified Add Contact screen supporting manual type/name/public-key entry, clipboard import (meshcore:// URIs, share tokens, and bare 64-hex keys), discovered contacts, and QR scanning.
This commit is contained in:
zjs81 committed 2026-11-21 14:03:18 -07:00
1 parent 3a93481bdf
commit f45b511bcb
35 files changed
+2315 -188

No files matched your search

+10 -5
View File
@@ -89,8 +89,8 @@ Groups are stored per radio identity (scoped by public key).
The Contacts screen has a single **three-dot overflow menu** (`⋮`) in the app bar: The Contacts screen has a single **three-dot overflow menu** (`⋮`) in the app bar:
- Add Contact — opens the Add Contact page
- Discovered Contacts — opens the DiscoveryScreen - Discovered Contacts — opens the DiscoveryScreen
- Add Contact from Clipboard — reads a `meshcore://<hex>` URI from clipboard and imports it
- *(divider)* - *(divider)*
- Zero-Hop Advert — broadcasts your advertisement to immediately adjacent nodes - Zero-Hop Advert — broadcasts your advertisement to immediately adjacent nodes
- Flood Advert — broadcasts across the full mesh network - Flood Advert — broadcasts across the full mesh network
@@ -99,15 +99,20 @@ The Contacts screen has a single **three-dot overflow menu** (`⋮`) in the app
- Disconnect — disconnects from the device - Disconnect — disconnects from the device
- Settings — opens the Settings screen - Settings — opens the Settings screen
A **floating action button** (person-add icon) provides a shortcut sheet to "Add Contact from Clipboard" or "Discovered Contacts". A **floating action button** (person-add icon) also opens the Add Contact page.
## Adding Contacts ## Adding Contacts
### Automatic (Passive) ### Automatic (Passive)
When the radio hears an advertisement, the contact appears automatically if auto-add is enabled for that type (configurable in Settings → Contact Settings). When the radio hears an advertisement, the contact appears automatically if auto-add is enabled for that type (configurable in Settings → Contact Settings).
### Import from Clipboard ### Add Contact Page (Manual, Clipboard, Discovered, QR)
Overflow menu (or the FAB shortcut) → "Add Contact from Clipboard". Reads a `meshcore://<hex>` URI from clipboard and imports it to the device. Open **Add Contact** from the Contacts overflow menu or the person-add floating action button.
- **Manual entry**: Pick the **Contact Type** (Chat, Repeater, Room, or Sensor), enter a **Name**, paste or enter the 64-character hex **Public Key** (leading/trailing whitespace and an optional `0x` prefix are handled automatically), and tap the checkmark (`✓`) to save.
- **Add Contact from Clipboard**: Imports `meshcore://` contact URIs and `<PUBKEY:TYPE:NAME>` chat share tokens directly, or detects a bare 64-hex-char public key and fills the Public Key field so you can pick the type, enter a name, and save.
- **Add from Discovered Contacts**: Opens the Discovered Contacts screen.
- **Scan QR Code**: Opens the QR scanner.
### Import from Discovered Contacts ### Import from Discovered Contacts
Overflow menu → "Discovered Contacts". Shows nodes heard passively that haven't been added yet. Tap to immediately import (no confirmation dialog), or long-press for more options (Copy URI, Delete). The Discovery screen has its own search bar, type filters (Users, Repeaters, Rooms), and sort options (Last Seen, A-Z). Its overflow menu has **Export discovered contacts**, **Import discovered contacts**, and "Delete All". Overflow menu → "Discovered Contacts". Shows nodes heard passively that haven't been added yet. Tap to immediately import (no confirmation dialog), or long-press for more options (Copy URI, Delete). The Discovery screen has its own search bar, type filters (Users, Repeaters, Rooms), and sort options (Last Seen, A-Z). Its overflow menu has **Export discovered contacts**, **Import discovered contacts**, and "Delete All".
@@ -131,7 +136,7 @@ Use the Discovered Contacts overflow menu to move the list of heard-but-not-adde
### Import from a QR Code ### Import from a QR Code
Choose **Scan QR Code** from the Contacts overflow menu or the add-contact sheet. Allow camera access and scan a compatible contact QR code, or use **Scan QR from Gallery** on the scanner screen to import a QR code from a saved image. Contact QR import is separate from community QR scanning; use Channels for community codes. Choose **Scan QR Code** from the Add Contact page. Allow camera access and scan a compatible contact QR code, or use **Scan QR from Gallery** on the scanner screen to import a QR code from a saved image. Contact QR import is separate from community QR scanning; use Channels for community codes.
## Contact Sharing Format ## Contact Sharing Format
+1
View File
@@ -48,6 +48,7 @@ ContactsScreen (selected=0)
├─ [quick-switch 1] → pushReplacement → ChannelsScreen ├─ [quick-switch 1] → pushReplacement → ChannelsScreen
├─ [quick-switch 2] → pushReplacement → MapScreen ├─ [quick-switch 2] → pushReplacement → MapScreen
├─ [tap contact] → push → ChatScreen ├─ [tap contact] → push → ChatScreen
├─ [FAB / overflow > Add Contact] → push → AddContactScreen
├─ [overflow > Settings] → push → SettingsScreen ├─ [overflow > Settings] → push → SettingsScreen
└─ [overflow > Discovered] → push → DiscoveryScreen └─ [overflow > Discovered] → push → DiscoveryScreen
+57
View File
@@ -0,0 +1,57 @@
import '../helpers/contact_share_message.dart';
import '../utils/contact_qr.dart';
/// Kind of content found when parsing clipboard text for adding a contact.
enum ContactClipboardKind { empty, contact, publicKey, invalid }
/// Result of parsing clipboard text on the Add Contact screen.
class ContactClipboardParseResult {
final ContactClipboardKind kind;
final ScannedContact? contact;
final String? publicKeyHex;
const ContactClipboardParseResult._(
this.kind, {
this.contact,
this.publicKeyHex,
});
const ContactClipboardParseResult.empty()
: this._(ContactClipboardKind.empty);
const ContactClipboardParseResult.contact(ScannedContact contact)
: this._(ContactClipboardKind.contact, contact: contact);
const ContactClipboardParseResult.publicKey(String publicKeyHex)
: this._(ContactClipboardKind.publicKey, publicKeyHex: publicKeyHex);
const ContactClipboardParseResult.invalid()
: this._(ContactClipboardKind.invalid);
}
/// Parses clipboard text as a `meshcore://` contact URI/advert, an embedded
/// `<PUBKEY:TYPE:NAME>` contact share, or a bare 64-hex-char public key.
ContactClipboardParseResult parseContactClipboard(String? rawText) {
if (rawText == null) return const ContactClipboardParseResult.empty();
final trimmed = rawText.trim();
if (trimmed.isEmpty) return const ContactClipboardParseResult.empty();
if (trimmed.toLowerCase().startsWith('meshcore://')) {
final scanned = parseContactQr(trimmed);
return scanned != null
? ContactClipboardParseResult.contact(scanned)
: const ContactClipboardParseResult.invalid();
}
final share = findContactShare(trimmed);
if (share != null) {
return ContactClipboardParseResult.contact(share.toScannedContact());
}
final normalizedKey = normalizeContactPublicKeyHex(trimmed);
if (normalizedKey != null) {
return ContactClipboardParseResult.publicKey(normalizedKey);
}
return const ContactClipboardParseResult.invalid();
}
+12 -1
View File
@@ -4423,5 +4423,16 @@
"chatCompression_profile": "Cyr2Lat profile", "chatCompression_profile": "Cyr2Lat profile",
"chatCompression_noStorageId": "Can't change compression until this channel has synced from the radio.", "chatCompression_noStorageId": "Can't change compression until this channel has synced from the radio.",
"chatCompression_saveFailed": "Couldn't save the compression setting. Showing the saved setting.", "chatCompression_saveFailed": "Couldn't save the compression setting. Showing the saved setting.",
"messageMeta_smazCompressed": "SMAZ compressed" "messageMeta_smazCompressed": "SMAZ compressed",
"addContact_title": "Add Contact",
"addContact_infoBanner": "If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.",
"addContact_contactType": "Contact Type",
"addContact_name": "Name",
"addContact_nameRequired": "Please enter a name",
"addContact_publicKeyHex": "Public Key (hex)",
"addContact_publicKeyRequired": "Please enter a public key",
"addContact_publicKeyInvalid": "Public key must be 64 hex characters (32 bytes)",
"addContact_clipboardKeyLoaded": "Public key filled in. Choose a contact type, enter a name, and tap save.",
"addContact_fromDiscovered": "Add from Discovered Contacts",
"addContact_saveFailed": "Failed to add contact."
} }
+66
View File
@@ -12867,6 +12867,72 @@ abstract class AppLocalizations {
/// In en, this message translates to: /// In en, this message translates to:
/// **'SMAZ compressed'** /// **'SMAZ compressed'**
String get messageMeta_smazCompressed; String get messageMeta_smazCompressed;
/// No description provided for @addContact_title.
///
/// In en, this message translates to:
/// **'Add Contact'**
String get addContact_title;
/// No description provided for @addContact_infoBanner.
///
/// In en, this message translates to:
/// **'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.'**
String get addContact_infoBanner;
/// No description provided for @addContact_contactType.
///
/// In en, this message translates to:
/// **'Contact Type'**
String get addContact_contactType;
/// No description provided for @addContact_name.
///
/// In en, this message translates to:
/// **'Name'**
String get addContact_name;
/// No description provided for @addContact_nameRequired.
///
/// In en, this message translates to:
/// **'Please enter a name'**
String get addContact_nameRequired;
/// No description provided for @addContact_publicKeyHex.
///
/// In en, this message translates to:
/// **'Public Key (hex)'**
String get addContact_publicKeyHex;
/// No description provided for @addContact_publicKeyRequired.
///
/// In en, this message translates to:
/// **'Please enter a public key'**
String get addContact_publicKeyRequired;
/// No description provided for @addContact_publicKeyInvalid.
///
/// In en, this message translates to:
/// **'Public key must be 64 hex characters (32 bytes)'**
String get addContact_publicKeyInvalid;
/// No description provided for @addContact_clipboardKeyLoaded.
///
/// In en, this message translates to:
/// **'Public key filled in. Choose a contact type, enter a name, and tap save.'**
String get addContact_clipboardKeyLoaded;
/// No description provided for @addContact_fromDiscovered.
///
/// In en, this message translates to:
/// **'Add from Discovered Contacts'**
String get addContact_fromDiscovered;
/// No description provided for @addContact_saveFailed.
///
/// In en, this message translates to:
/// **'Failed to add contact.'**
String get addContact_saveFailed;
} }
class _AppLocalizationsDelegate class _AppLocalizationsDelegate
+36
View File
@@ -7726,4 +7726,40 @@ class AppLocalizationsBg extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7697,4 +7697,40 @@ class AppLocalizationsCs extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7740,4 +7740,40 @@ class AppLocalizationsDe extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7611,4 +7611,40 @@ class AppLocalizationsEn extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7718,4 +7718,40 @@ class AppLocalizationsEs extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7746,4 +7746,40 @@ class AppLocalizationsFr extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7709,4 +7709,40 @@ class AppLocalizationsHu extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7729,4 +7729,40 @@ class AppLocalizationsIt extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7371,4 +7371,40 @@ class AppLocalizationsJa extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7383,4 +7383,40 @@ class AppLocalizationsKo extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7685,4 +7685,40 @@ class AppLocalizationsNl extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7763,4 +7763,40 @@ class AppLocalizationsPl extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7707,6 +7707,42 @@ class AppLocalizationsPt extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
/// The translations for Portuguese, as used in Portugal (`pt_PT`). /// The translations for Portuguese, as used in Portugal (`pt_PT`).
+36
View File
@@ -7743,4 +7743,40 @@ class AppLocalizationsRu extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7708,4 +7708,40 @@ class AppLocalizationsSk extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7702,4 +7702,40 @@ class AppLocalizationsSl extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7662,4 +7662,40 @@ class AppLocalizationsSv extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7755,4 +7755,40 @@ class AppLocalizationsUk extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+36
View File
@@ -7213,4 +7213,40 @@ class AppLocalizationsZh extends AppLocalizations {
@override @override
String get messageMeta_smazCompressed => 'SMAZ compressed'; String get messageMeta_smazCompressed => 'SMAZ compressed';
@override
String get addContact_title => 'Add Contact';
@override
String get addContact_infoBanner =>
'If you know the public key of someone you want to contact, you can add them manually without waiting for them to advert.';
@override
String get addContact_contactType => 'Contact Type';
@override
String get addContact_name => 'Name';
@override
String get addContact_nameRequired => 'Please enter a name';
@override
String get addContact_publicKeyHex => 'Public Key (hex)';
@override
String get addContact_publicKeyRequired => 'Please enter a public key';
@override
String get addContact_publicKeyInvalid =>
'Public key must be 64 hex characters (32 bytes)';
@override
String get addContact_clipboardKeyLoaded =>
'Public key filled in. Choose a contact type, enter a name, and tap save.';
@override
String get addContact_fromDiscovered => 'Add from Discovered Contacts';
@override
String get addContact_saveFailed => 'Failed to add contact.';
} }
+4 -1
View File
@@ -84,6 +84,7 @@ class ReviewFrames {
required Uint8List publicKey, required Uint8List publicKey,
required int type, required int type,
required Uint8List path, required Uint8List path,
int? pathLen,
required String name, required String name,
required int lastAdvertSecs, required int lastAdvertSecs,
required int latitudeE6, required int latitudeE6,
@@ -96,7 +97,9 @@ class ReviewFrames {
writer.writeBytes(publicKey); writer.writeBytes(publicKey);
writer.writeByte(type); writer.writeByte(type);
writer.writeByte(flags); writer.writeByte(flags);
writer.writeByte(path.length); // one-byte hashes: hop count == byte count writer.writeByte(
pathLen ?? path.length,
); // one-byte hashes: hop count == byte count
writer.writeBytesPadded(path, maxPathSize); writer.writeBytesPadded(path, maxPathSize);
writer.writeCString(name, maxNameSize); writer.writeCString(name, maxNameSize);
writer.writeUInt32LE(lastAdvertSecs); writer.writeUInt32LE(lastAdvertSecs);
+62
View File
@@ -318,6 +318,9 @@ class ReviewRadio {
} }
_emit([ReviewFrames.ok()]); _emit([ReviewFrames.ok()]);
break; break;
case cmdAddUpdateContact:
_handleAddUpdateContact(frame);
break;
case cmdSendLogin: case cmdSendLogin:
_handleLogin(frame); _handleLogin(frame);
break; break;
@@ -365,13 +368,68 @@ class ReviewRadio {
publicKey: c.publicKey, publicKey: c.publicKey,
type: c.type, type: c.type,
path: c.path, path: c.path,
pathLen: c.pathLen,
name: c.name, name: c.name,
lastAdvertSecs: c.lastAdvertSecs, lastAdvertSecs: c.lastAdvertSecs,
latitudeE6: c.latitudeE6, latitudeE6: c.latitudeE6,
longitudeE6: c.longitudeE6, longitudeE6: c.longitudeE6,
lastModSecs: c.lastModSecs, lastModSecs: c.lastModSecs,
flags: c.flags,
); );
void _handleAddUpdateContact(Uint8List frame) {
// [cmd][pub_key x32][type][flags][path_len][path x64][name x32][last_advert? x4][lat? x4][lon? x4]
const minLen = 1 + pubKeySize + 3 + maxPathSize + maxNameSize;
if (frame.length < minLen) {
_emit([ReviewFrames.err()]);
return;
}
final publicKey = Uint8List.fromList(frame.sublist(1, 1 + pubKeySize));
final type = frame[33];
final flags = frame[34];
final pathLen = frame[35];
final Uint8List path;
if (pathLen == 0xFF) {
path = Uint8List(0);
} else {
final width = ((pathLen & 0xC0) >> 6) + 1;
final hops = pathLen & 0x3F;
final byteLen = (hops * width).clamp(0, maxPathSize);
path = Uint8List.fromList(frame.sublist(36, 36 + byteLen));
}
final name = _readCString(frame, 36 + maxPathSize, maxNameSize);
final lastAdvertSecs = frame.length >= minLen + 4
? readUint32LE(frame, minLen)
: 0;
final latE6 = frame.length >= minLen + 12
? readInt32LE(frame, minLen + 4)
: 0;
final lonE6 = frame.length >= minLen + 12
? readInt32LE(frame, minLen + 8)
: 0;
final contact = _Contact(
publicKey: publicKey,
type: type,
flags: flags,
path: path,
pathLen: pathLen,
name: name,
lastAdvertSecs: lastAdvertSecs,
latitudeE6: latE6,
longitudeE6: lonE6,
lastModSecs: _nowSecs,
);
final index = _contacts.indexWhere(
(c) => listEquals(c.publicKey, publicKey),
);
if (index >= 0) {
_contacts[index] = contact;
} else {
_contacts.add(contact);
}
_emit([ReviewFrames.ok()]);
}
void _handleGetContacts(Uint8List frame) { void _handleGetContacts(Uint8List frame) {
final since = frame.length >= 5 ? readUint32LE(frame, 1) : 0; final since = frame.length >= 5 ? readUint32LE(frame, 1) : 0;
final matching = _contacts.where((c) => c.lastModSecs > since).toList(); final matching = _contacts.where((c) => c.lastModSecs > since).toList();
@@ -659,7 +717,9 @@ class ReviewRadio {
class _Contact { class _Contact {
final Uint8List publicKey; final Uint8List publicKey;
final int type; final int type;
final int flags;
final Uint8List path; final Uint8List path;
final int? pathLen;
final String name; final String name;
final int lastAdvertSecs; final int lastAdvertSecs;
final int latitudeE6; final int latitudeE6;
@@ -669,7 +729,9 @@ class _Contact {
_Contact({ _Contact({
required this.publicKey, required this.publicKey,
required this.type, required this.type,
this.flags = 0,
required this.path, required this.path,
this.pathLen,
required this.name, required this.name,
required this.lastAdvertSecs, required this.lastAdvertSecs,
required this.latitudeE6, required this.latitudeE6,
+493
View File
@@ -0,0 +1,493 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/contact_clipboard.dart';
import '../helpers/snack_bar_builder.dart';
import '../helpers/utf8_length_limiter.dart';
import '../l10n/app_localizations.dart';
import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
import '../utils/app_logger.dart';
import '../utils/contact_qr.dart';
import '../utils/radio_guard.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../widgets/mesh_nav_tile.dart';
import '../widgets/mesh_ui.dart';
import 'contact_qr_scanner_screen.dart';
import 'discovery_screen.dart';
/// Unified page for adding a contact manually by public key, from clipboard,
/// from discovered contacts, or by scanning a QR code.
class AddContactScreen extends StatefulWidget {
const AddContactScreen({super.key});
@override
State<AddContactScreen> createState() => _AddContactScreenState();
}
class _AddContactScreenState extends State<AddContactScreen> {
final _formKey = GlobalKey<FormState>();
final _publicKeyFieldKey = GlobalKey<FormFieldState<String>>();
final _nameController = TextEditingController();
final _publicKeyController = TextEditingController();
final _nameFocusNode = FocusNode();
final _publicKeyFocusNode = FocusNode();
int _selectedType = advTypeChat;
bool _isSaving = false;
bool _isImporting = false;
bool get _isBusy => _isSaving || _isImporting;
static const List<int> _contactTypes = [
advTypeChat,
advTypeRepeater,
advTypeRoom,
advTypeSensor,
];
@override
void dispose() {
_nameController.dispose();
_publicKeyController.dispose();
_nameFocusNode.dispose();
_publicKeyFocusNode.dispose();
super.dispose();
}
String _typeLabel(AppLocalizations l10n, int type) {
switch (type) {
case advTypeChat:
return l10n.contact_typeChat;
case advTypeRepeater:
return l10n.contact_typeRepeater;
case advTypeRoom:
return l10n.contact_typeRoom;
case advTypeSensor:
return l10n.contact_typeSensor;
default:
return l10n.contact_typeUnknown;
}
}
Future<void> _pickContactType() async {
final chosen = await showMeshSheet<int>(
context,
builder: (sheetContext) {
final l10n = sheetContext.l10n;
return SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
BottomSheetHeader(title: l10n.addContact_contactType),
for (final type in _contactTypes)
MeshSheetOption(
label: _typeLabel(l10n, type),
selected: type == _selectedType,
onTap: () => Navigator.pop(sheetContext, type),
),
const SizedBox(height: 8),
],
),
),
);
},
);
if (!mounted || chosen == null) return;
setState(() => _selectedType = chosen);
}
Future<void> _saveContact() async {
if (_isBusy) return;
if (!(_formKey.currentState?.validate() ?? false)) return;
if (!ensureRadioConnected(context)) return;
final keyHex = normalizeContactPublicKeyHex(_publicKeyController.text);
final publicKeyBytes = decodeContactPublicKeyHex(_publicKeyController.text);
if (keyHex == null || publicKeyBytes == null) return;
final connector = context.read<MeshCoreConnector>();
if (connector.selfPublicKeyHex.isNotEmpty &&
keyHex == connector.selfPublicKeyHex.toLowerCase()) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contactShare_isYou),
);
return;
}
setState(() => _isSaving = true);
try {
await connector.addContactFromCard(
ScannedContact(
publicKey: publicKeyBytes,
name: _nameController.text.trim(),
type: _selectedType,
),
);
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.discoveredContacts_contactAdded),
);
Navigator.pop(context, true);
} catch (e) {
appLogger.warn('Manual contact add failed: $e', tag: 'AddContactScreen');
if (!mounted) return;
setState(() => _isSaving = false);
showDismissibleSnackBar(
context,
content: Text(context.l10n.addContact_saveFailed),
);
}
}
Future<void> _importFromClipboard() async {
if (_isBusy) return;
final clipboardData = await Clipboard.getData('text/plain');
if (!mounted) return;
final parsed = parseContactClipboard(clipboardData?.text);
switch (parsed.kind) {
case ContactClipboardKind.empty:
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_clipboardEmpty),
);
return;
case ContactClipboardKind.invalid:
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_invalidAdvertFormat),
);
return;
case ContactClipboardKind.publicKey:
_publicKeyController.text = parsed.publicKeyHex!;
if (_publicKeyFieldKey.currentState?.hasError == true) {
_publicKeyFieldKey.currentState?.validate();
}
_nameFocusNode.requestFocus();
showDismissibleSnackBar(
context,
content: Text(context.l10n.addContact_clipboardKeyLoaded),
);
return;
case ContactClipboardKind.contact:
if (!ensureRadioConnected(context)) return;
final scanned = parsed.contact!;
final connector = context.read<MeshCoreConnector>();
if (scanned.publicKey != null &&
connector.selfPublicKeyHex.isNotEmpty &&
pubKeyToHex(scanned.publicKey!).toLowerCase() ==
connector.selfPublicKeyHex.toLowerCase()) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contactShare_isYou),
);
return;
}
setState(() => _isImporting = true);
try {
await connector.addContactFromCard(scanned);
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_contactImported),
);
Navigator.pop(context, true);
} catch (e) {
appLogger.warn(
'Clipboard contact import failed: $e',
tag: 'AddContactScreen',
);
if (!mounted) return;
setState(() => _isImporting = false);
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_contactImportFailed),
);
}
return;
}
}
void _openDiscoveredContacts() {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => const DiscoveryScreen()),
);
}
Future<void> _scanQrCode() async {
if (!ensureRadioConnected(context)) return;
final imported = await Navigator.push<bool>(
context,
MaterialPageRoute(builder: (_) => const ContactQrScannerScreen()),
);
if (imported == true && mounted) {
Navigator.pop(context, true);
}
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return Scaffold(
appBar: AppBar(
title: AdaptiveAppBarTitle(l10n.addContact_title),
centerTitle: true,
actions: [
IconButton(
tooltip: l10n.common_save,
onPressed: _isBusy ? null : _saveContact,
icon: _isSaving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.check),
),
],
),
body: SafeArea(
top: false,
child: Form(
key: _formKey,
child: ListView(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 24),
children: [
MeshCard(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 14,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
Icons.info_outline,
size: 24,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 16),
Expanded(
child: Text(
l10n.addContact_infoBanner,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurface,
),
),
),
],
),
),
const SizedBox(height: 8),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
_buildContactTypeRow(context),
const Divider(height: 1, indent: 16),
_buildNameRow(context),
const Divider(height: 1, indent: 16),
_buildPublicKeyRow(context),
],
),
),
const SizedBox(height: 8),
MeshCard(
padding: EdgeInsets.zero,
child: MeshNavTile(
icon: Icons.content_paste,
title: l10n.contacts_addContactFromClipboard,
onTap: _isBusy ? null : _importFromClipboard,
),
),
MeshCard(
padding: EdgeInsets.zero,
child: MeshNavTile(
icon: Icons.person_add_rounded,
title: l10n.addContact_fromDiscovered,
onTap: _isBusy ? null : _openDiscoveredContacts,
),
),
MeshCard(
padding: EdgeInsets.zero,
child: MeshNavTile(
icon: Icons.qr_code_scanner,
title: l10n.contacts_scanQrCode,
onTap: _isBusy ? null : _scanQrCode,
),
),
],
),
),
),
);
}
Widget _buildContactTypeRow(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final label = _typeLabel(l10n, _selectedType);
return Semantics(
button: true,
enabled: !_isBusy,
label: '${l10n.addContact_contactType}: $label',
child: InkWell(
onTap: _isBusy ? null : _pickContactType,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 48),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(
Icons.info_outline,
size: 24,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
l10n.addContact_contactType,
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
const SizedBox(height: 2),
Text(label, style: theme.textTheme.bodyLarge),
],
),
),
const SizedBox(width: 8),
Icon(
Icons.arrow_drop_down,
size: 24,
color: scheme.onSurfaceVariant,
),
],
),
),
),
),
);
}
Widget _buildNameRow(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
Icon(Icons.person_outline, size: 24, color: scheme.onSurfaceVariant),
const SizedBox(width: 16),
Expanded(
child: TextFormField(
controller: _nameController,
focusNode: _nameFocusNode,
enabled: !_isBusy,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => _publicKeyFocusNode.requestFocus(),
inputFormatters: [
Utf8LengthLimitingTextInputFormatter(maxRadioNameBytes),
],
style: theme.textTheme.bodyLarge,
decoration: InputDecoration(
labelText: l10n.addContact_name,
filled: false,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
errorBorder: InputBorder.none,
focusedErrorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(vertical: 12),
errorMaxLines: 4,
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return l10n.addContact_nameRequired;
}
return null;
},
),
),
],
),
);
}
Widget _buildPublicKeyRow(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
Icon(
Icons.vpn_key_outlined,
size: 24,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 16),
Expanded(
child: TextFormField(
key: _publicKeyFieldKey,
controller: _publicKeyController,
focusNode: _publicKeyFocusNode,
enabled: !_isBusy,
autocorrect: false,
enableSuggestions: false,
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => _saveContact(),
minLines: 1,
maxLines: 3,
style: MeshTheme.mono(fontSize: 15, color: scheme.onSurface),
decoration: InputDecoration(
labelText: l10n.addContact_publicKeyHex,
filled: false,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
errorBorder: InputBorder.none,
focusedErrorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(vertical: 12),
errorMaxLines: 4,
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return l10n.addContact_publicKeyRequired;
}
if (decodeContactPublicKeyHex(value) == null) {
return l10n.addContact_publicKeyInvalid;
}
return null;
},
),
),
],
),
);
}
}
+1 -1
View File
@@ -190,7 +190,7 @@ class _ContactQrScannerScreenState extends State<ContactQrScannerScreen> {
); );
// Keep _isProcessing set: resetting it would restart the camera on a // Keep _isProcessing set: resetting it would restart the camera on a
// closing route and let a second detection import and pop again. // closing route and let a second detection import and pop again.
Navigator.pop(context); Navigator.pop(context, true);
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
setState(() { setState(() {
+15 -158
View File
@@ -34,11 +34,10 @@ import '../widgets/repeater_login_dialog.dart';
import '../widgets/room_login_dialog.dart'; import '../widgets/room_login_dialog.dart';
import '../widgets/sync_progress_overlay.dart'; import '../widgets/sync_progress_overlay.dart';
import '../widgets/unread_badge.dart'; import '../widgets/unread_badge.dart';
import '../helpers/contact_share_message.dart';
import '../helpers/snack_bar_builder.dart'; import '../helpers/snack_bar_builder.dart';
import 'add_contact_screen.dart';
import 'channels_screen.dart'; import 'channels_screen.dart';
import 'chat_screen.dart'; import 'chat_screen.dart';
import 'contact_qr_scanner_screen.dart';
import 'discovery_screen.dart'; import 'discovery_screen.dart';
import 'map_screen.dart'; import 'map_screen.dart';
import '../review_mode/review_mode_banner.dart'; import '../review_mode/review_mode_banner.dart';
@@ -48,7 +47,7 @@ import '../theme/theme_icons.dart';
enum RoomLoginDestination { chat, management } enum RoomLoginDestination { chat, management }
enum ContactOperationType { import, export, zeroHopShare } enum ContactOperationType { export, zeroHopShare }
/// An export/import/share awaiting its generic OK/ERR ack. The timer drops /// An export/import/share awaiting its generic OK/ERR ack. The timer drops
/// it if no ack arrives, so a stuck op can't consume a later unrelated ack. /// it if no ack arrives, so a stuck op can't consume a later unrelated ack.
@@ -159,10 +158,6 @@ class _ContactsScreenState extends State<ContactsScreen> {
final l10n = context.l10n; final l10n = context.l10n;
final String message; final String message;
switch (type) { switch (type) {
case ContactOperationType.import:
message = success
? l10n.contacts_contactImported
: l10n.contacts_contactImportFailed;
case ContactOperationType.zeroHopShare: case ContactOperationType.zeroHopShare:
message = success message = success
? l10n.contacts_zeroHopContactAdvertSent ? l10n.contacts_zeroHopContactAdvertSent
@@ -345,85 +340,10 @@ class _ContactsScreenState extends State<ContactsScreen> {
} }
} }
Future<void> _contactImport() async { void _openAddContact() {
final connector = Provider.of<MeshCoreConnector>(context, listen: false); Navigator.push(
final clipboardData = await Clipboard.getData('text/plain');
if (clipboardData == null || clipboardData.text == null) {
if (mounted) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_clipboardEmpty),
);
}
return;
}
final text = clipboardData.text!.trim();
// A contact shared in chat (`<PUBKEY:TYPE:NAME>`) copied from the bubble.
final share = findContactShare(text);
if (share != null && !text.startsWith('meshcore://')) {
await _importContactShare(connector, share);
return;
}
if (!text.startsWith('meshcore://')) {
if (mounted) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_invalidAdvertFormat),
);
}
return;
}
final hexString = text.substring('meshcore://'.length);
final Uint8List importContactFrame;
try {
final bytes = hex2Uint8List(hexString);
importContactFrame = buildImportContactFrame(bytes);
} catch (e) {
if (mounted) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_invalidAdvertFormat),
);
}
return;
}
_addPendingOperation(ContactOperationType.import);
try {
await connector.sendFrame(importContactFrame, expectsGenericAck: true);
} catch (e) {
_takePendingOperation(ContactOperationType.import);
if (mounted) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_contactImportFailed),
);
}
}
}
Future<void> _importContactShare(
MeshCoreConnector connector,
ContactShare share,
) async {
if (!mounted) return;
final l10n = context.l10n;
if (share.publicKeyHex == connector.selfPublicKeyHex) {
showDismissibleSnackBar(context, content: Text(l10n.contactShare_isYou));
return;
}
var ok = true;
try {
await connector.addContactFromCard(share.toScannedContact());
} catch (e) {
appLogger.warn('Contact share import failed: $e', tag: 'ContactsScreen');
ok = false;
}
if (!mounted) return;
showDismissibleSnackBar(
context, context,
content: Text( MaterialPageRoute(builder: (context) => const AddContactScreen()),
ok ? l10n.contacts_contactImported : l10n.contacts_contactImportFailed,
),
); );
} }
@@ -444,6 +364,14 @@ class _ContactsScreenState extends State<ContactsScreen> {
PopupMenuButton( PopupMenuButton(
tooltip: context.l10n.contacts_moreOptions, tooltip: context.l10n.contacts_moreOptions,
itemBuilder: (context) => <PopupMenuEntry<dynamic>>[ itemBuilder: (context) => <PopupMenuEntry<dynamic>>[
PopupMenuItem(
enabled: !readOnly,
onTap: _openAddContact,
child: MeshMenuItemRow(
icon: Icons.person_add,
label: context.l10n.addContact_title,
),
),
PopupMenuItem( PopupMenuItem(
child: MeshMenuItemRow( child: MeshMenuItemRow(
icon: Icons.person_add_rounded, icon: Icons.person_add_rounded,
@@ -456,27 +384,6 @@ class _ContactsScreenState extends State<ContactsScreen> {
), ),
), ),
), ),
PopupMenuItem(
enabled: !readOnly,
child: MeshMenuItemRow(
icon: Icons.paste,
label: context.l10n.contacts_addContactFromClipboard,
),
onTap: () => _contactImport(),
),
PopupMenuItem(
enabled: !readOnly,
child: MeshMenuItemRow(
icon: Icons.qr_code_scanner,
label: context.l10n.contacts_scanQrCode,
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ContactQrScannerScreen(),
),
),
),
const PopupMenuDivider(), const PopupMenuDivider(),
PopupMenuItem( PopupMenuItem(
enabled: !readOnly, enabled: !readOnly,
@@ -538,7 +445,8 @@ class _ContactsScreenState extends State<ContactsScreen> {
floatingActionButton: readOnly floatingActionButton: readOnly
? null ? null
: FloatingActionButton( : FloatingActionButton(
onPressed: () => _showAddContactSheet(context), tooltip: context.l10n.addContact_title,
onPressed: _openAddContact,
child: const Icon(Icons.person_add), child: const Icon(Icons.person_add),
), ),
bottomNavigationBar: SafeArea( bottomNavigationBar: SafeArea(
@@ -555,57 +463,6 @@ class _ContactsScreenState extends State<ContactsScreen> {
); );
} }
void _showAddContactSheet(BuildContext context) {
showMeshSheet(
context,
builder: (sheetContext) => SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
BottomSheetHeader(title: context.l10n.contacts_title),
ListTile(
leading: const Icon(Icons.paste),
title: Text(context.l10n.contacts_addContactFromClipboard),
onTap: () {
Navigator.pop(sheetContext);
_contactImport();
},
),
ListTile(
leading: const Icon(Icons.qr_code_scanner),
title: Text(context.l10n.contacts_scanQrCode),
onTap: () {
Navigator.pop(sheetContext);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ContactQrScannerScreen(),
),
);
},
),
ListTile(
leading: const Icon(Icons.person_add_rounded),
title: Text(context.l10n.discoveredContacts_Title),
onTap: () {
Navigator.pop(sheetContext);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const DiscoveryScreen(),
),
);
},
),
const SizedBox(height: 8),
],
),
),
),
);
}
ContactGroup? _selectedGroupForName(String selectedGroupName) { ContactGroup? _selectedGroupForName(String selectedGroupName) {
if (selectedGroupName == contactsAllGroupsValue) return null; if (selectedGroupName == contactsAllGroupsValue) return null;
for (final group in _groups) { for (final group in _groups) {
+22
View File
@@ -78,6 +78,28 @@ ScannedContact? _parseContactCard(Uri uri) {
return ScannedContact(publicKey: publicKey, name: name, type: type); return ScannedContact(publicKey: publicKey, name: name, type: type);
} }
/// Normalizes a 64-character hex public key, trimming surrounding whitespace
/// and stripping an optional `0x` prefix. Returns lowercase hex or null when
/// [input] is not a valid 32-byte hex key.
String? normalizeContactPublicKeyHex(String input) {
var trimmed = input.trim();
if (trimmed.length >= 2 &&
(trimmed.startsWith('0x') || trimmed.startsWith('0X'))) {
trimmed = trimmed.substring(2);
}
if (trimmed.length != _contactCardKeyBytes * 2) return null;
if (_tryHexDecode(trimmed) == null) return null;
return trimmed.toLowerCase();
}
/// Decodes a 64-character hex public key (allowing surrounding whitespace,
/// optional `0x` prefix, and mixed case) into 32 bytes, or returns null.
Uint8List? decodeContactPublicKeyHex(String input) {
final normalized = normalizeContactPublicKeyHex(input);
if (normalized == null) return null;
return _tryHexDecode(normalized);
}
/// Local hex decoder: keeps this util pure-Dart. `hex2Uint8List` in /// Local hex decoder: keeps this util pure-Dart. `hex2Uint8List` in
/// `connector/meshcore_protocol.dart` throws on invalid input and that file /// `connector/meshcore_protocol.dart` throws on invalid input and that file
/// pulls in `package:flutter/widgets.dart` and `package:crypto`, which this /// pulls in `package:flutter/widgets.dart` and `package:crypto`, which this
+546
View File
@@ -0,0 +1,546 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/l10n/app_localizations_en.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/add_contact_screen.dart';
import 'package:meshcore_open/screens/contacts_screen.dart';
import 'package:meshcore_open/screens/discovery_screen.dart';
import 'package:meshcore_open/services/app_debug_log_service.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/ble_debug_log_service.dart';
import 'package:meshcore_open/services/chat_text_scale_service.dart';
import 'package:meshcore_open/services/image_codec_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/network_map/network_map_upload_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/services/translation_service.dart';
import 'package:meshcore_open/services/ui_view_state_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
final _l10n = AppLocalizationsEn();
MeshCoreConnector? _sharedConnector;
Future<MeshCoreConnector> _connectedConnector(WidgetTester tester) async {
if (_sharedConnector != null) {
return _sharedConnector!;
}
final storage = StorageService();
final connector = MeshCoreConnector();
final retry = MessageRetryService();
final settings = AppSettingsService();
final translation = TranslationService(settings);
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: retry,
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while (!connector.hasLoadedContacts && DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
_sharedConnector = connector;
return connector;
}
Widget _wrapApp({
required MeshCoreConnector connector,
required Widget home,
ThemeData? theme,
Locale locale = const Locale('en'),
double textScale = 1.0,
}) {
final storage = StorageService();
final settings = AppSettingsService();
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider(create: (_) => MessageRetryService()),
ChangeNotifierProvider(create: (_) => PathHistoryService(storage)),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider(create: (_) => BleDebugLogService()),
ChangeNotifierProvider(create: (_) => AppDebugLogService()),
ChangeNotifierProvider(create: (_) => ChatTextScaleService()),
ChangeNotifierProvider(create: (_) => TranslationService(settings)),
ChangeNotifierProvider(create: (_) => UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider(
create: (_) => MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider(create: (_) => TimeoutPredictionService(storage)),
ChangeNotifierProvider(create: (_) => ImageCodecService(settings)),
ChangeNotifierProvider(create: (_) => ReceivedImageStore()),
ChangeNotifierProvider(
create: (_) =>
NetworkMapUploadService(connector: connector, settings: settings),
),
],
child: MaterialApp(
theme: theme ?? MeshTheme.dark(),
locale: locale,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: home,
),
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('add_contact_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
tearDownAll(() {
_sharedConnector?.dispose();
_sharedConnector = null;
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
});
testWidgets('validates empty fields and invalid public key', (tester) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
expect(find.text(_l10n.addContact_title), findsOneWidget);
expect(find.text(_l10n.addContact_infoBanner), findsOneWidget);
expect(find.text(_l10n.contacts_addContactFromClipboard), findsOneWidget);
expect(find.text(_l10n.addContact_fromDiscovered), findsOneWidget);
expect(find.text(_l10n.contacts_scanQrCode), findsOneWidget);
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.addContact_nameRequired), findsOneWidget);
expect(find.text(_l10n.addContact_publicKeyRequired), findsOneWidget);
await tester.enterText(find.byType(TextFormField).first, 'Repeater One');
await tester.enterText(find.byType(TextFormField).last, 'abcd');
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.addContact_publicKeyInvalid), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('selects contact type and submits manual contact', (
tester,
) async {
final connector = await _connectedConnector(tester);
final keyHex = List.generate(
32,
(i) => (i + 1).toRadixString(16).padLeft(2, '0'),
).join();
await tester.pumpWidget(
_wrapApp(
connector: connector,
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: FilledButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const AddContactScreen()),
),
child: const Text('Open'),
),
),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
// Change Contact Type from Chat to Repeater.
expect(find.text(_l10n.contact_typeChat), findsOneWidget);
await tester.tap(find.text(_l10n.contact_typeChat));
await tester.pumpAndSettle();
expect(find.text(_l10n.contact_typeRepeater), findsOneWidget);
expect(find.text(_l10n.contact_typeRoom), findsOneWidget);
expect(find.text(_l10n.contact_typeSensor), findsOneWidget);
await tester.tap(find.text(_l10n.contact_typeRepeater));
await tester.pumpAndSettle();
expect(find.text(_l10n.contact_typeRepeater), findsOneWidget);
await tester.enterText(find.byType(TextFormField).first, ' North Ridge ');
await tester.enterText(
find.byType(TextFormField).last,
' 0x${keyHex.toUpperCase()} ',
);
await tester.runAsync(() async {
await tester.tap(find.byIcon(Icons.check));
final end = DateTime.now().add(const Duration(seconds: 5));
while (!connector.contacts.any((c) => c.publicKeyHex == keyHex) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
await tester.pumpAndSettle();
final added = connector.contacts.firstWhere(
(c) => c.publicKeyHex == keyHex,
);
expect(added.name, 'North Ridge');
expect(added.type, advTypeRepeater);
expect(find.byType(AddContactScreen), findsNothing);
expect(find.text(_l10n.discoveredContacts_contactAdded), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('bare hex key in clipboard fills Public Key and focuses Name', (
tester,
) async {
final connector = await _connectedConnector(tester);
final keyHex = 'ab' * 32;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.getData') {
return <String, dynamic>{'text': ' 0x${keyHex.toUpperCase()} \n'};
}
return null;
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null),
);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
// Trigger empty validation error first, then ensure pasting a bare key clears it.
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.addContact_publicKeyRequired), findsOneWidget);
await tester.tap(find.text(_l10n.contacts_addContactFromClipboard));
await tester.pumpAndSettle();
final nameField = tester.widget<TextField>(find.byType(TextField).first);
final keyField = tester.widget<TextField>(find.byType(TextField).last);
expect(keyField.controller!.text, keyHex);
expect(nameField.focusNode!.hasFocus, isTrue);
expect(find.text(_l10n.addContact_publicKeyRequired), findsNothing);
expect(find.text(_l10n.addContact_clipboardKeyLoaded), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('empty and invalid clipboard show feedback snackbars', (
tester,
) async {
final connector = await _connectedConnector(tester);
String? clipboardText;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.getData') {
return clipboardText == null
? null
: <String, dynamic>{'text': clipboardText};
}
return null;
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null),
);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.contacts_addContactFromClipboard));
await tester.pumpAndSettle();
expect(find.text(_l10n.contacts_clipboardEmpty), findsOneWidget);
clipboardText = 'not-a-valid-key-or-uri';
await tester.tap(find.text(_l10n.contacts_addContactFromClipboard));
await tester.pumpAndSettle();
expect(find.text(_l10n.contacts_invalidAdvertFormat), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('rejects adding own public key manually', (tester) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextFormField).first, 'Self');
await tester.enterText(
find.byType(TextFormField).last,
connector.selfPublicKeyHex,
);
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.contactShare_isYou), findsOneWidget);
expect(find.byType(AddContactScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('meshcore:// contact URI in clipboard imports contact', (
tester,
) async {
final connector = await _connectedConnector(tester);
final keyHex = 'cd' * 32;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.getData') {
return <String, dynamic>{
'text': 'meshcore://contact/add?name=UriPeer&public_key=$keyHex',
};
}
return null;
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null),
);
await tester.pumpWidget(
_wrapApp(
connector: connector,
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: FilledButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const AddContactScreen()),
),
child: const Text('Open'),
),
),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
await tester.runAsync(() async {
await tester.tap(find.text(_l10n.contacts_addContactFromClipboard));
final end = DateTime.now().add(const Duration(seconds: 5));
while (!connector.contacts.any((c) => c.publicKeyHex == keyHex) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
await tester.pumpAndSettle();
expect(connector.contacts.any((c) => c.name == 'UriPeer'), isTrue);
expect(find.byType(AddContactScreen), findsNothing);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Contacts FAB and menu item both open AddContactScreen', (
tester,
) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const ContactsScreen()),
);
await tester.pumpAndSettle();
// Entry point 1: Contacts FAB.
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
expect(find.byType(AddContactScreen), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
expect(find.byType(AddContactScreen), findsNothing);
// Entry point 2: Overflow menu item.
await tester.tap(find.byIcon(Icons.more_vert));
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.addContact_title));
await tester.pumpAndSettle();
expect(find.byType(AddContactScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('navigates to Discovered Contacts and adds a discovered node', (
tester,
) async {
final connector = await _connectedConnector(tester);
final discoveredKey = Uint8List.fromList(List<int>.filled(32, 0x5E));
final discoveredKeyHex = pubKeyToHex(discoveredKey);
const name = 'Discovered Node';
final frameData = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12);
final frame = frameData.buffer.asUint8List();
frame[0] = pushCodeNewAdvert;
frame.setRange(1, 33, discoveredKey);
frame[33] = advTypeChat;
frame[35] = 0xFF;
frame.setRange(100, 100 + name.length, name.codeUnits);
frameData.setUint32(132, 1700000000, Endian.little);
connector.handleFrameForTest(frame);
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.addContact_fromDiscovered));
await tester.pumpAndSettle();
expect(find.byType(DiscoveryScreen), findsOneWidget);
expect(find.text(name), findsOneWidget);
await tester.runAsync(() async {
await tester.tap(find.byIcon(Icons.person_add_alt_1));
final end = DateTime.now().add(const Duration(seconds: 5));
while (!connector.contacts.any(
(c) => c.publicKeyHex == discoveredKeyHex,
) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
await tester.pumpAndSettle();
expect(
connector.contacts.any((c) => c.publicKeyHex == discoveredKeyHex),
isTrue,
);
expect(find.text(_l10n.discoveredContacts_contactAdded), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('disconnected manual submit shows offline error snackbar', (
tester,
) async {
final connector = MeshCoreConnector();
addTearDown(connector.dispose);
final keyHex = 'ef' * 32;
await tester.pumpWidget(
_wrapApp(connector: connector, home: const AddContactScreen()),
);
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextFormField).first, 'Offline Node');
await tester.enterText(find.byType(TextFormField).last, keyHex);
await tester.tap(find.byIcon(Icons.check));
await tester.pumpAndSettle();
expect(find.text(_l10n.settings_notConnectedError), findsOneWidget);
expect(find.byType(AddContactScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
for (final (label, theme, locale) in [
('light en', MeshTheme.light(), const Locale('en')),
('dark en', MeshTheme.dark(), const Locale('en')),
('dark de', MeshTheme.dark(), const Locale('de')),
]) {
for (final scale in [1.3, 2.0]) {
testWidgets('fits 320dp width at ${scale}x in $label', (tester) async {
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
final connector = await _connectedConnector(tester);
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
final text = details.exceptionAsString();
if (text.contains('overflowed')) {
overflows.add(text.split('\n').first);
} else {
previous?.call(details);
}
};
addTearDown(() => FlutterError.onError = previous);
await tester.pumpWidget(
_wrapApp(
connector: connector,
home: const AddContactScreen(),
theme: theme,
locale: locale,
textScale: scale,
),
);
await tester.pumpAndSettle();
FlutterError.onError = previous;
expect(overflows, isEmpty, reason: overflows.join('\n'));
await tester.pumpWidget(const SizedBox());
});
}
}
}
+1 -1
View File
@@ -251,7 +251,7 @@ void main() {
await _settle(tester); await _settle(tester);
expect(_menuItem(_l10n.contacts_floodAdvert).enabled, isFalse); expect(_menuItem(_l10n.contacts_floodAdvert).enabled, isFalse);
expect(_menuItem(_l10n.contacts_zeroHopAdvert).enabled, isFalse); expect(_menuItem(_l10n.contacts_zeroHopAdvert).enabled, isFalse);
expect(_menuItem(_l10n.contacts_addContactFromClipboard).enabled, isFalse); expect(_menuItem(_l10n.addContact_title).enabled, isFalse);
expect(_menuItem(_l10n.common_connect).enabled, isTrue); expect(_menuItem(_l10n.common_connect).enabled, isTrue);
await tester.pumpWidget(const SizedBox()); await tester.pumpWidget(const SizedBox());
}); });
+4 -2
View File
@@ -15,6 +15,7 @@ import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart'; import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart'; import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/review_mode/review_radio.dart'; import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/add_contact_screen.dart';
import 'package:meshcore_open/screens/app_debug_log_screen.dart'; import 'package:meshcore_open/screens/app_debug_log_screen.dart';
import 'package:meshcore_open/screens/app_settings_screen.dart'; import 'package:meshcore_open/screens/app_settings_screen.dart';
import 'package:meshcore_open/screens/ble_debug_log_screen.dart'; import 'package:meshcore_open/screens/ble_debug_log_screen.dart';
@@ -145,7 +146,7 @@ _interactions = {
.first, .first,
); );
}, },
'Contacts add sheet': (t, _) async { 'Contacts add page': (t, _) async {
await t.tap(find.byType(FloatingActionButton)); await t.tap(find.byType(FloatingActionButton));
}, },
// Four routing modes (Auto, Flood, Direct, Manual) share one row. // Four routing modes (Auto, Flood, Direct, Manual) share one row.
@@ -161,7 +162,8 @@ _interactions = {
final Map<String, _ScreenBuilder> _screens = { final Map<String, _ScreenBuilder> _screens = {
'Contacts options sheet': (_) => const ContactsScreen(), 'Contacts options sheet': (_) => const ContactsScreen(),
'Contacts add sheet': (_) => const ContactsScreen(), 'Contacts add page': (_) => const ContactsScreen(),
'AddContact': (_) => const AddContactScreen(),
'Routing sheet': (c) => ChatScreen(contact: _contactOfType(c, advTypeChat)), 'Routing sheet': (c) => ChatScreen(contact: _contactOfType(c, advTypeChat)),
'Scanner': (_) => const ScannerScreen(), 'Scanner': (_) => const ScannerScreen(),
'Tcp': (_) => const TcpScreen(), 'Tcp': (_) => const TcpScreen(),
+109
View File
@@ -0,0 +1,109 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/contact_clipboard.dart';
import 'package:meshcore_open/utils/contact_qr.dart';
void main() {
final validLowerHex = List.generate(
32,
(i) => i.toRadixString(16).padLeft(2, '0'),
).join();
final validUpperHex = validLowerHex.toUpperCase();
group('normalizeContactPublicKeyHex & decodeContactPublicKeyHex', () {
test('accepts lowercase 64-char hex', () {
expect(normalizeContactPublicKeyHex(validLowerHex), validLowerHex);
final bytes = decodeContactPublicKeyHex(validLowerHex);
expect(bytes, isNotNull);
expect(bytes!.length, 32);
expect(bytes[0], 0x00);
expect(bytes[31], 0x1f);
});
test('trims whitespace, strips 0x/0X prefix, and normalizes case', () {
expect(
normalizeContactPublicKeyHex(' 0x$validUpperHex \n\t '),
validLowerHex,
);
expect(normalizeContactPublicKeyHex('0X$validUpperHex'), validLowerHex);
});
test(
'rejects invalid lengths, non-hex characters, and internal spaces',
() {
expect(normalizeContactPublicKeyHex(''), isNull);
expect(normalizeContactPublicKeyHex(' '), isNull);
expect(
normalizeContactPublicKeyHex(validLowerHex.substring(0, 63)),
isNull,
);
expect(normalizeContactPublicKeyHex('${validLowerHex}aa'), isNull);
expect(normalizeContactPublicKeyHex('0x $validLowerHex'), isNull);
expect(normalizeContactPublicKeyHex('zz' * 32), isNull);
expect(decodeContactPublicKeyHex('zz' * 32), isNull);
},
);
});
group('parseContactClipboard', () {
test('parses official meshcore://contact/add URI', () {
final result = parseContactClipboard(
' meshcore://contact/add?name=Alice&public_key=$validLowerHex&type=2 ',
);
expect(result.kind, ContactClipboardKind.contact);
expect(result.contact, isNotNull);
expect(result.contact!.name, 'Alice');
expect(result.contact!.type, 2);
expect(result.contact!.publicKey!.length, 32);
});
test('parses legacy meshcore://<advert> URI', () {
final advertHex = '0a' * 98;
final result = parseContactClipboard('meshcore://$advertHex');
expect(result.kind, ContactClipboardKind.contact);
expect(result.contact!.isAdvertPacket, isTrue);
expect(result.contact!.advertPacket!.length, 98);
});
test('parses contact share token', () {
final result = parseContactClipboard('Bob: <$validUpperHex:3:Bob Node>');
expect(result.kind, ContactClipboardKind.contact);
expect(result.contact!.name, 'Bob Node');
expect(result.contact!.type, 3);
expect(result.contact!.publicKey!.length, 32);
});
test('parses bare 64-char hex key with whitespace, 0x, and uppercase', () {
final result = parseContactClipboard('\n 0x$validUpperHex ');
expect(result.kind, ContactClipboardKind.publicKey);
expect(result.publicKeyHex, validLowerHex);
expect(result.contact, isNull);
});
test('returns empty for null or whitespace-only text', () {
expect(parseContactClipboard(null).kind, ContactClipboardKind.empty);
expect(parseContactClipboard('').kind, ContactClipboardKind.empty);
expect(parseContactClipboard(' \n\t ').kind, ContactClipboardKind.empty);
});
test('returns invalid for malformed URIs, short keys, and random text', () {
expect(
parseContactClipboard('meshcore://not-valid').kind,
ContactClipboardKind.invalid,
);
expect(
parseContactClipboard(
'meshcore://channel/add?name=Public&secret=abcd',
).kind,
ContactClipboardKind.invalid,
);
expect(
parseContactClipboard(validLowerHex.substring(0, 62)).kind,
ContactClipboardKind.invalid,
);
expect(
parseContactClipboard('hello world').kind,
ContactClipboardKind.invalid,
);
});
});
}
+228 -19
View File
@@ -36,7 +36,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"cs": [ "cs": [
@@ -76,7 +87,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"de": [ "de": [
@@ -116,7 +138,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"es": [ "es": [
@@ -156,7 +189,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"fr": [ "fr": [
@@ -196,7 +240,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"hu": [ "hu": [
@@ -236,7 +291,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"it": [ "it": [
@@ -276,7 +342,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"ja": [ "ja": [
@@ -316,7 +393,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"ko": [ "ko": [
@@ -356,7 +444,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"nl": [ "nl": [
@@ -396,7 +495,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"pl": [ "pl": [
@@ -436,7 +546,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"pt": [ "pt": [
@@ -476,7 +597,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"pt_PT": [ "pt_PT": [
@@ -516,7 +648,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"ru": [ "ru": [
@@ -556,7 +699,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"sk": [ "sk": [
@@ -596,7 +750,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"sl": [ "sl": [
@@ -636,7 +801,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"sv": [ "sv": [
@@ -676,7 +852,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"uk": [ "uk": [
@@ -716,7 +903,18 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
], ],
"zh": [ "zh": [
@@ -756,6 +954,17 @@
"chatCompression_profile", "chatCompression_profile",
"chatCompression_noStorageId", "chatCompression_noStorageId",
"chatCompression_saveFailed", "chatCompression_saveFailed",
"messageMeta_smazCompressed" "messageMeta_smazCompressed",
"addContact_title",
"addContact_infoBanner",
"addContact_contactType",
"addContact_name",
"addContact_nameRequired",
"addContact_publicKeyHex",
"addContact_publicKeyRequired",
"addContact_publicKeyInvalid",
"addContact_clipboardKeyLoaded",
"addContact_fromDiscovered",
"addContact_saveFailed"
] ]
} }