Merge pull request #676 from zjs81/fix/list-sorting-and-performance
Fix list ordering and long-list scrolling
This commit is contained in:
35 files changed
+1357
-43
No files matched your search
@@ -132,7 +132,7 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act
|
|||||||
| Radio offline on a remote-node screen | `RadioDisconnectedBanner` | Renders nothing while connected |
|
| Radio offline on a remote-node screen | `RadioDisconnectedBanner` | Renders nothing while connected |
|
||||||
| Sync progress | `SyncProgressAppBarBottom` as the app bar `bottom` | 3px bar |
|
| Sync progress | `SyncProgressAppBarBottom` as the app bar `bottom` | 3px bar |
|
||||||
| Toast message | `showDismissibleSnackBar(context, content: Text(...))` | Tap to dismiss, replaces the current snackbar, safe after an async gap |
|
| Toast message | `showDismissibleSnackBar(context, content: Text(...))` | Tap to dismiss, replaces the current snackbar, safe after an async gap |
|
||||||
| List item entrance | `ListEntrance(index:)` | Optional |
|
| List item entrance | `ListEntrance(index:)` | Optional. Plays only for rows built while the list is at rest at the top; rows scrolled into view appear at once |
|
||||||
|
|
||||||
**Buttons.** Theme shapes are all pill-shaped. In use:
|
**Buttons.** Theme shapes are all pill-shaped. In use:
|
||||||
|
|
||||||
|
|||||||
@@ -57,3 +57,39 @@ them into the selected radio's scope. Review-mode cleanup also covers the databa
|
|||||||
For a manual full application-data copy, keep the history database alongside the
|
For a manual full application-data copy, keep the history database alongside the
|
||||||
application's other support files; copying the preferences file alone no longer
|
application's other support files; copying the preferences file alone no longer
|
||||||
includes native message or route histories.
|
includes native message or route histories.
|
||||||
|
|
||||||
|
## Long contact and channel lists
|
||||||
|
|
||||||
|
`test/screens/list_scroll_perf_test.dart` builds the contacts list with 500
|
||||||
|
contacts and the channels list with 40 channels, flings each one with a
|
||||||
|
connector notify partway through, and prints build counts and how many visible
|
||||||
|
rows were blank or still fading in during the fling:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
flutter test test/screens/list_scroll_perf_test.dart
|
||||||
|
```
|
||||||
|
|
||||||
|
It fails if rows scrolled into view play the entrance fade, or if a connector
|
||||||
|
notify that changes nothing rebuilds contact rows. The counts are a widget-test
|
||||||
|
proxy; frame times still need a phone.
|
||||||
|
|
||||||
|
To check scrolling on a phone:
|
||||||
|
|
||||||
|
1. Connect a radio with several hundred contacts and a few dozen channels (or
|
||||||
|
use the same radio before and after a change), then run
|
||||||
|
`flutter run --profile` on the phone.
|
||||||
|
2. Open DevTools from the printed link and select the Performance page. Turn
|
||||||
|
on "Track widget builds" only for a separate run: it adds overhead to the
|
||||||
|
frame times.
|
||||||
|
3. Open Contacts, wait for sync to finish, and clear the timeline.
|
||||||
|
4. Fling the list hard to the bottom and back to the top five times, then drag
|
||||||
|
it up and down quickly for a few seconds. Repeat while messages and adverts
|
||||||
|
are arriving.
|
||||||
|
5. In the frame chart, note the share of frames over budget (16 ms at 60 Hz,
|
||||||
|
8 ms at 120 Hz) on the UI and raster threads, and the worst frames. Select a
|
||||||
|
slow frame to see whether build, layout, paint or raster dominates.
|
||||||
|
6. Watch the screen: rows must be fully drawn as they enter, with no blank
|
||||||
|
rows trailing the finger.
|
||||||
|
7. Repeat steps 3 to 6 on Channels.
|
||||||
|
8. Record the device, build mode, contact and channel counts and the numbers
|
||||||
|
from step 5 for the before and after builds.
|
||||||
@@ -62,6 +62,7 @@ import '../storage/channel_settings_store.dart';
|
|||||||
import '../storage/channel_region_store.dart';
|
import '../storage/channel_region_store.dart';
|
||||||
import '../storage/channel_storage_migration.dart';
|
import '../storage/channel_storage_migration.dart';
|
||||||
import '../storage/channel_store.dart';
|
import '../storage/channel_store.dart';
|
||||||
|
import '../storage/contact_added_at_store.dart';
|
||||||
import '../storage/contact_discovery_store.dart';
|
import '../storage/contact_discovery_store.dart';
|
||||||
import '../storage/contact_settings_store.dart';
|
import '../storage/contact_settings_store.dart';
|
||||||
import '../storage/contact_store.dart';
|
import '../storage/contact_store.dart';
|
||||||
@@ -526,6 +527,8 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
final ChannelRegionStore _channelRegionStore = ChannelRegionStore();
|
final ChannelRegionStore _channelRegionStore = ChannelRegionStore();
|
||||||
final ContactSettingsStore _contactSettingsStore = ContactSettingsStore();
|
final ContactSettingsStore _contactSettingsStore = ContactSettingsStore();
|
||||||
final ContactStore _contactStore = ContactStore();
|
final ContactStore _contactStore = ContactStore();
|
||||||
|
final ContactAddedAtStore _contactAddedAtStore = ContactAddedAtStore();
|
||||||
|
final Map<String, DateTime> _contactAddedAt = {};
|
||||||
final ContactDiscoveryStore _discoveryContactStore = ContactDiscoveryStore();
|
final ContactDiscoveryStore _discoveryContactStore = ContactDiscoveryStore();
|
||||||
final ChannelStore _channelStore = ChannelStore();
|
final ChannelStore _channelStore = ChannelStore();
|
||||||
final UnreadStore _unreadStore = UnreadStore();
|
final UnreadStore _unreadStore = UnreadStore();
|
||||||
@@ -649,6 +652,11 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
return radio.bleDisplayName;
|
return radio.bleDisplayName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Phone time a contact was first added from a card; the list orders by it
|
||||||
|
/// while the radio has no advert time for the contact.
|
||||||
|
DateTime? contactAddedAt(String contactPubKeyHex) =>
|
||||||
|
_contactAddedAt[contactPubKeyHex];
|
||||||
|
|
||||||
Contact? getContactByPubKeyHex(String contactPubKeyHex) {
|
Contact? getContactByPubKeyHex(String contactPubKeyHex) {
|
||||||
return _contacts.cast<Contact?>().firstWhere(
|
return _contacts.cast<Contact?>().firstWhere(
|
||||||
(c) => c?.publicKeyHex == contactPubKeyHex,
|
(c) => c?.publicKeyHex == contactPubKeyHex,
|
||||||
@@ -2466,6 +2474,9 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
_contacts
|
_contacts
|
||||||
..clear()
|
..clear()
|
||||||
..addAll(cached);
|
..addAll(cached);
|
||||||
|
_contactAddedAt
|
||||||
|
..clear()
|
||||||
|
..addAll(_contactAddedAtStore.load());
|
||||||
for (final contact in cached) {
|
for (final contact in cached) {
|
||||||
_ensureContactSmazSettingLoaded(contact.publicKeyHex);
|
_ensureContactSmazSettingLoaded(contact.publicKeyHex);
|
||||||
_ensureContactCyr2LatSettingLoaded(contact.publicKeyHex);
|
_ensureContactCyr2LatSettingLoaded(contact.publicKeyHex);
|
||||||
@@ -5128,6 +5139,13 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
pathHashByteWidth: pathHashByteWidth,
|
pathHashByteWidth: pathHashByteWidth,
|
||||||
);
|
);
|
||||||
await sendFrame(frame, waitForGenericAck: true);
|
await sendFrame(frame, waitForGenericAck: true);
|
||||||
|
if (publicKey != null) {
|
||||||
|
final keyHex = pubKeyToHex(publicKey);
|
||||||
|
if (!_contactAddedAt.containsKey(keyHex)) {
|
||||||
|
_contactAddedAt[keyHex] = DateTime.now();
|
||||||
|
await _contactAddedAtStore.save(_contactAddedAt);
|
||||||
|
}
|
||||||
|
}
|
||||||
await refreshContacts();
|
await refreshContacts();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6123,6 +6141,9 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
_contactsStorageFull = false;
|
_contactsStorageFull = false;
|
||||||
_contacts.removeWhere((c) => c.publicKeyHex == contact.publicKeyHex);
|
_contacts.removeWhere((c) => c.publicKeyHex == contact.publicKeyHex);
|
||||||
_knownContactKeys.remove(contact.publicKeyHex);
|
_knownContactKeys.remove(contact.publicKeyHex);
|
||||||
|
if (_contactAddedAt.remove(contact.publicKeyHex) != null) {
|
||||||
|
unawaited(_contactAddedAtStore.save(_contactAddedAt));
|
||||||
|
}
|
||||||
unawaited(updateKnownDiscovered());
|
unawaited(updateKnownDiscovered());
|
||||||
unawaited(_persistContacts());
|
unawaited(_persistContacts());
|
||||||
_conversations.remove(contact.publicKeyHex);
|
_conversations.remove(contact.publicKeyHex);
|
||||||
@@ -7811,6 +7832,9 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
_contacts.removeWhere((c) => c.publicKeyHex == keyHex);
|
_contacts.removeWhere((c) => c.publicKeyHex == keyHex);
|
||||||
_knownContactKeys.remove(keyHex);
|
_knownContactKeys.remove(keyHex);
|
||||||
|
if (_contactAddedAt.remove(keyHex) != null) {
|
||||||
|
unawaited(_contactAddedAtStore.save(_contactAddedAt));
|
||||||
|
}
|
||||||
_contactsStorageFull = false;
|
_contactsStorageFull = false;
|
||||||
unawaited(updateKnownDiscovered());
|
unawaited(updateKnownDiscovered());
|
||||||
unawaited(_persistContacts());
|
unawaited(_persistContacts());
|
||||||
@@ -9895,6 +9919,7 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
_channelRegionStore.setPublicKeyHex = keyHex;
|
_channelRegionStore.setPublicKeyHex = keyHex;
|
||||||
_contactSettingsStore.setPublicKeyHex = keyHex;
|
_contactSettingsStore.setPublicKeyHex = keyHex;
|
||||||
_contactStore.setPublicKeyHex = keyHex;
|
_contactStore.setPublicKeyHex = keyHex;
|
||||||
|
_contactAddedAtStore.setPublicKeyHex = keyHex;
|
||||||
_channelStore.setPublicKeyHex = keyHex;
|
_channelStore.setPublicKeyHex = keyHex;
|
||||||
_unreadStore.setPublicKeyHex = keyHex;
|
_unreadStore.setPublicKeyHex = keyHex;
|
||||||
_discoveryContactStore.setPublicKeyHex = keyHex;
|
_discoveryContactStore.setPublicKeyHex = keyHex;
|
||||||
|
|||||||
@@ -844,6 +844,7 @@
|
|||||||
"contacts_noContactsMatchFilter": "No contacts match your filter",
|
"contacts_noContactsMatchFilter": "No contacts match your filter",
|
||||||
"contacts_noMembers": "No members",
|
"contacts_noMembers": "No members",
|
||||||
"contacts_lastSeenNow": "recently",
|
"contacts_lastSeenNow": "recently",
|
||||||
|
"contacts_lastSeenNever": "not heard yet",
|
||||||
"contacts_lastSeenMinsAgo": "~ {minutes} min.",
|
"contacts_lastSeenMinsAgo": "~ {minutes} min.",
|
||||||
"@contacts_lastSeenMinsAgo": {
|
"@contacts_lastSeenMinsAgo": {
|
||||||
"placeholders": {
|
"placeholders": {
|
||||||
|
|||||||
@@ -3295,6 +3295,12 @@ abstract class AppLocalizations {
|
|||||||
/// **'recently'**
|
/// **'recently'**
|
||||||
String get contacts_lastSeenNow;
|
String get contacts_lastSeenNow;
|
||||||
|
|
||||||
|
/// No description provided for @contacts_lastSeenNever.
|
||||||
|
///
|
||||||
|
/// In en, this message translates to:
|
||||||
|
/// **'not heard yet'**
|
||||||
|
String get contacts_lastSeenNever;
|
||||||
|
|
||||||
/// No description provided for @contacts_lastSeenMinsAgo.
|
/// No description provided for @contacts_lastSeenMinsAgo.
|
||||||
///
|
///
|
||||||
/// In en, this message translates to:
|
/// In en, this message translates to:
|
||||||
|
|||||||
@@ -1838,6 +1838,9 @@ class AppLocalizationsBg extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'наскоро';
|
String get contacts_lastSeenNow => 'наскоро';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes мин.';
|
return '~ $minutes мин.';
|
||||||
|
|||||||
@@ -1825,6 +1825,9 @@ class AppLocalizationsCs extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'nedávno';
|
String get contacts_lastSeenNow => 'nedávno';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min.';
|
return '~ $minutes min.';
|
||||||
|
|||||||
@@ -1838,6 +1838,9 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'gerade eben';
|
String get contacts_lastSeenNow => 'gerade eben';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes Min.';
|
return '~ $minutes Min.';
|
||||||
|
|||||||
@@ -1805,6 +1805,9 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'recently';
|
String get contacts_lastSeenNow => 'recently';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min.';
|
return '~ $minutes min.';
|
||||||
|
|||||||
@@ -1830,6 +1830,9 @@ class AppLocalizationsEs extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'Reciente';
|
String get contacts_lastSeenNow => 'Reciente';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min';
|
return '~ $minutes min';
|
||||||
|
|||||||
@@ -1835,6 +1835,9 @@ class AppLocalizationsFr extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'À l\'instant';
|
String get contacts_lastSeenNow => 'À l\'instant';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min';
|
return '~ $minutes min';
|
||||||
|
|||||||
@@ -1828,6 +1828,9 @@ class AppLocalizationsHu extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'nemrég';
|
String get contacts_lastSeenNow => 'nemrég';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min.';
|
return '~ $minutes min.';
|
||||||
|
|||||||
@@ -1832,6 +1832,9 @@ class AppLocalizationsIt extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'Poco fa';
|
String get contacts_lastSeenNow => 'Poco fa';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min';
|
return '~ $minutes min';
|
||||||
|
|||||||
@@ -1741,6 +1741,9 @@ class AppLocalizationsJa extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => '最近';
|
String get contacts_lastSeenNow => '最近';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '約 $minutes 分前';
|
return '約 $minutes 分前';
|
||||||
|
|||||||
@@ -1745,6 +1745,9 @@ class AppLocalizationsKo extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => '최근';
|
String get contacts_lastSeenNow => '최근';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes분';
|
return '~ $minutes분';
|
||||||
|
|||||||
@@ -1824,6 +1824,9 @@ class AppLocalizationsNl extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'recent';
|
String get contacts_lastSeenNow => 'recent';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min.';
|
return '~ $minutes min.';
|
||||||
|
|||||||
@@ -1846,6 +1846,9 @@ class AppLocalizationsPl extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'niedawno';
|
String get contacts_lastSeenNow => 'niedawno';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min';
|
return '~ $minutes min';
|
||||||
|
|||||||
@@ -1831,6 +1831,9 @@ class AppLocalizationsPt extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'Recente';
|
String get contacts_lastSeenNow => 'Recente';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min';
|
return '~ $minutes min';
|
||||||
|
|||||||
@@ -1830,6 +1830,9 @@ class AppLocalizationsRu extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'недавно';
|
String get contacts_lastSeenNow => 'недавно';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes мин.';
|
return '~ $minutes мин.';
|
||||||
|
|||||||
@@ -1824,6 +1824,9 @@ class AppLocalizationsSk extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'nedávno';
|
String get contacts_lastSeenNow => 'nedávno';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min.';
|
return '~ $minutes min.';
|
||||||
|
|||||||
@@ -1822,6 +1822,9 @@ class AppLocalizationsSl extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'pravkar';
|
String get contacts_lastSeenNow => 'pravkar';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min';
|
return '~ $minutes min';
|
||||||
|
|||||||
@@ -1812,6 +1812,9 @@ class AppLocalizationsSv extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'nyss';
|
String get contacts_lastSeenNow => 'nyss';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes min';
|
return '~ $minutes min';
|
||||||
|
|||||||
@@ -1826,6 +1826,9 @@ class AppLocalizationsUk extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => 'нещодавно';
|
String get contacts_lastSeenNow => 'нещодавно';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '~ $minutes хв.';
|
return '~ $minutes хв.';
|
||||||
|
|||||||
@@ -1715,6 +1715,9 @@ class AppLocalizationsZh extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get contacts_lastSeenNow => '刚刚';
|
String get contacts_lastSeenNow => '刚刚';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String get contacts_lastSeenNever => 'not heard yet';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String contacts_lastSeenMinsAgo(int minutes) {
|
String contacts_lastSeenMinsAgo(int minutes) {
|
||||||
return '约 $minutes 分钟';
|
return '约 $minutes 分钟';
|
||||||
|
|||||||
@@ -783,13 +783,14 @@ class _ChannelsScreenState extends State<ChannelsScreen> {
|
|||||||
break;
|
break;
|
||||||
case ChannelSortOption.latestMessages:
|
case ChannelSortOption.latestMessages:
|
||||||
// Filtered messages don't bump a channel, matching the preview.
|
// Filtered messages don't bump a channel, matching the preview.
|
||||||
|
// Ordered by local arrival time: sender clocks can be far off.
|
||||||
// Looked up once per channel: the lookup can scan back through
|
// Looked up once per channel: the lookup can scan back through
|
||||||
// filtered messages, and the comparator runs O(n log n) times.
|
// filtered messages, and the comparator runs O(n log n) times.
|
||||||
final epoch = DateTime(1970);
|
final epoch = DateTime(1970);
|
||||||
final latest = <Channel, DateTime>{
|
final latest = <Channel, DateTime>{
|
||||||
for (final channel in filtered)
|
for (final channel in filtered)
|
||||||
channel:
|
channel:
|
||||||
connector.latestVisibleChannelMessage(channel)?.timestamp ??
|
connector.latestVisibleChannelMessage(channel)?.receivedAt ??
|
||||||
epoch,
|
epoch,
|
||||||
};
|
};
|
||||||
filtered.sort((a, b) {
|
filtered.sort((a, b) {
|
||||||
|
|||||||
@@ -80,6 +80,8 @@ class _ContactsScreenState extends State<ContactsScreen> {
|
|||||||
|
|
||||||
final List<_PendingContactOperation> _pendingOperations = [];
|
final List<_PendingContactOperation> _pendingOperations = [];
|
||||||
final DerivedListCache<Contact> _filteredCache = DerivedListCache<Contact>();
|
final DerivedListCache<Contact> _filteredCache = DerivedListCache<Contact>();
|
||||||
|
final Map<String, _ContactTileEntrance> _rowCache = {};
|
||||||
|
MeshCoreConnector? _rowCacheConnector;
|
||||||
|
|
||||||
StreamSubscription<Uint8List>? _frameSubscription;
|
StreamSubscription<Uint8List>? _frameSubscription;
|
||||||
|
|
||||||
@@ -1098,21 +1100,12 @@ class _ContactsScreenState extends State<ContactsScreen> {
|
|||||||
itemBuilder: (context, row) {
|
itemBuilder: (context, row) {
|
||||||
if (row == 0) return discoveredTile;
|
if (row == 0) return discoveredTile;
|
||||||
final index = row - 1;
|
final index = row - 1;
|
||||||
final contact = filteredAndSorted[index];
|
return _contactRow(
|
||||||
final unreadCount = connector.getUnreadCountForContact(
|
context,
|
||||||
contact,
|
connector,
|
||||||
);
|
filteredAndSorted[index],
|
||||||
return _ContactTileEntrance(
|
index,
|
||||||
index: index,
|
filteredAndSorted.length,
|
||||||
contact: contact,
|
|
||||||
pathHashByteWidth: connector.pathHashByteWidth,
|
|
||||||
lastSeen: resolveContactLastSeen(contact),
|
|
||||||
unreadCount: unreadCount,
|
|
||||||
isFavorite: contact.isFavorite,
|
|
||||||
onTap: () => _openChat(context, contact),
|
|
||||||
onLongPress: () =>
|
|
||||||
_showContactOptions(context, connector, contact),
|
|
||||||
onManage: _manageAction(context, contact),
|
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
@@ -1122,6 +1115,54 @@ class _ContactsScreenState extends State<ContactsScreen> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the row built last time for [contact] when nothing it shows has
|
||||||
|
/// changed. The connector notifies up to 20 times a second on a busy mesh
|
||||||
|
/// and each notify rebuilds this screen; handing the list the same widget
|
||||||
|
/// instance lets Flutter skip rebuilding those rows.
|
||||||
|
_ContactTileEntrance _contactRow(
|
||||||
|
BuildContext context,
|
||||||
|
MeshCoreConnector connector,
|
||||||
|
Contact contact,
|
||||||
|
int index,
|
||||||
|
int rowCount,
|
||||||
|
) {
|
||||||
|
if (!identical(_rowCacheConnector, connector)) {
|
||||||
|
_rowCache.clear();
|
||||||
|
_rowCacheConnector = connector;
|
||||||
|
}
|
||||||
|
final unreadCount = connector.getUnreadCountForContact(contact);
|
||||||
|
final pathHashByteWidth = connector.pathHashByteWidth;
|
||||||
|
// Relative ("5 mins ago"), so it can change while the contact does not.
|
||||||
|
final lastSeenLabel = formatContactLastSeen(
|
||||||
|
context.l10n,
|
||||||
|
resolveContactLastSeen(contact),
|
||||||
|
);
|
||||||
|
final cached = _rowCache[contact.publicKeyHex];
|
||||||
|
if (cached != null &&
|
||||||
|
identical(cached.contact, contact) &&
|
||||||
|
cached.index == index &&
|
||||||
|
cached.unreadCount == unreadCount &&
|
||||||
|
cached.pathHashByteWidth == pathHashByteWidth &&
|
||||||
|
cached.lastSeenLabel == lastSeenLabel) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
// Drop rows of contacts that left the list now and then.
|
||||||
|
if (_rowCache.length > rowCount + 100) _rowCache.clear();
|
||||||
|
return _rowCache[contact.publicKeyHex] = _ContactTileEntrance(
|
||||||
|
index: index,
|
||||||
|
contact: contact,
|
||||||
|
pathHashByteWidth: pathHashByteWidth,
|
||||||
|
lastSeenLabel: lastSeenLabel,
|
||||||
|
unreadCount: unreadCount,
|
||||||
|
isFavorite: contact.isFavorite,
|
||||||
|
// The State's context: rows outlive the list's item context while the
|
||||||
|
// list is swapped for an empty state.
|
||||||
|
onTap: () => _openChat(this.context, contact),
|
||||||
|
onLongPress: () => _showContactOptions(this.context, connector, contact),
|
||||||
|
onManage: _manageAction(this.context, contact),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
List<Contact> _filterAndSortContacts(
|
List<Contact> _filterAndSortContacts(
|
||||||
List<Contact> contacts,
|
List<Contact> contacts,
|
||||||
MeshCoreConnector connector,
|
MeshCoreConnector connector,
|
||||||
@@ -1155,7 +1196,8 @@ class _ContactsScreenState extends State<ContactsScreen> {
|
|||||||
|
|
||||||
DateTime _lastMessageTime(MeshCoreConnector connector, Contact contact) {
|
DateTime _lastMessageTime(MeshCoreConnector connector, Contact contact) {
|
||||||
final messages = connector.getMessages(contact);
|
final messages = connector.getMessages(contact);
|
||||||
return messages.isEmpty ? DateTime(1970) : messages.last.timestamp;
|
// Local arrival time: sender clocks can be far off.
|
||||||
|
return messages.isEmpty ? DateTime(1970) : messages.last.receivedAt;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Contact> _computeFilteredContacts(
|
List<Contact> _computeFilteredContacts(
|
||||||
@@ -1203,16 +1245,24 @@ class _ContactsScreenState extends State<ContactsScreen> {
|
|||||||
|
|
||||||
switch (viewState.contactsSortOption) {
|
switch (viewState.contactsSortOption) {
|
||||||
case ContactSortOption.lastSeen:
|
case ContactSortOption.lastSeen:
|
||||||
filtered.sort(
|
final lastSeenAt = {
|
||||||
(a, b) =>
|
for (final c in filtered)
|
||||||
resolveContactLastSeen(b).compareTo(resolveContactLastSeen(a)),
|
c: resolveContactLastSeen(
|
||||||
);
|
c,
|
||||||
|
addedAt: connector.contactAddedAt(c.publicKeyHex),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
filtered.sort((a, b) => lastSeenAt[b]!.compareTo(lastSeenAt[a]!));
|
||||||
break;
|
break;
|
||||||
case ContactSortOption.recentMessages:
|
case ContactSortOption.recentMessages:
|
||||||
final lastMessageAt = {
|
final lastMessageAt = {
|
||||||
for (final c in filtered) c: _lastMessageTime(connector, c),
|
for (final c in filtered) c: _lastMessageTime(connector, c),
|
||||||
};
|
};
|
||||||
filtered.sort((a, b) => lastMessageAt[b]!.compareTo(lastMessageAt[a]!));
|
filtered.sort((a, b) {
|
||||||
|
final timeCompare = lastMessageAt[b]!.compareTo(lastMessageAt[a]!);
|
||||||
|
if (timeCompare != 0) return timeCompare;
|
||||||
|
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
|
||||||
|
});
|
||||||
break;
|
break;
|
||||||
case ContactSortOption.name:
|
case ContactSortOption.name:
|
||||||
filtered.sort(
|
filtered.sort(
|
||||||
@@ -1874,7 +1924,7 @@ void confirmRemoveContact(
|
|||||||
class _ContactTile extends StatelessWidget {
|
class _ContactTile extends StatelessWidget {
|
||||||
final Contact contact;
|
final Contact contact;
|
||||||
final int pathHashByteWidth;
|
final int pathHashByteWidth;
|
||||||
final DateTime lastSeen;
|
final String lastSeenLabel;
|
||||||
final int unreadCount;
|
final int unreadCount;
|
||||||
final bool isFavorite;
|
final bool isFavorite;
|
||||||
final VoidCallback onTap;
|
final VoidCallback onTap;
|
||||||
@@ -1884,7 +1934,7 @@ class _ContactTile extends StatelessWidget {
|
|||||||
const _ContactTile({
|
const _ContactTile({
|
||||||
required this.contact,
|
required this.contact,
|
||||||
required this.pathHashByteWidth,
|
required this.pathHashByteWidth,
|
||||||
required this.lastSeen,
|
required this.lastSeenLabel,
|
||||||
required this.unreadCount,
|
required this.unreadCount,
|
||||||
required this.isFavorite,
|
required this.isFavorite,
|
||||||
required this.onTap,
|
required this.onTap,
|
||||||
@@ -2016,7 +2066,7 @@ class _ContactTile extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
Text(
|
Text(
|
||||||
formatContactLastSeen(context.l10n, lastSeen),
|
lastSeenLabel,
|
||||||
maxLines: 2,
|
maxLines: 2,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
style: MeshTheme.mono(
|
style: MeshTheme.mono(
|
||||||
@@ -2121,7 +2171,7 @@ class _ContactTileEntrance extends StatelessWidget {
|
|||||||
final int index;
|
final int index;
|
||||||
final Contact contact;
|
final Contact contact;
|
||||||
final int pathHashByteWidth;
|
final int pathHashByteWidth;
|
||||||
final DateTime lastSeen;
|
final String lastSeenLabel;
|
||||||
final int unreadCount;
|
final int unreadCount;
|
||||||
final bool isFavorite;
|
final bool isFavorite;
|
||||||
final VoidCallback onTap;
|
final VoidCallback onTap;
|
||||||
@@ -2132,7 +2182,7 @@ class _ContactTileEntrance extends StatelessWidget {
|
|||||||
required this.index,
|
required this.index,
|
||||||
required this.contact,
|
required this.contact,
|
||||||
required this.pathHashByteWidth,
|
required this.pathHashByteWidth,
|
||||||
required this.lastSeen,
|
required this.lastSeenLabel,
|
||||||
required this.unreadCount,
|
required this.unreadCount,
|
||||||
required this.isFavorite,
|
required this.isFavorite,
|
||||||
required this.onTap,
|
required this.onTap,
|
||||||
@@ -2147,7 +2197,7 @@ class _ContactTileEntrance extends StatelessWidget {
|
|||||||
child: _ContactTile(
|
child: _ContactTile(
|
||||||
contact: contact,
|
contact: contact,
|
||||||
pathHashByteWidth: pathHashByteWidth,
|
pathHashByteWidth: pathHashByteWidth,
|
||||||
lastSeen: lastSeen,
|
lastSeenLabel: lastSeenLabel,
|
||||||
unreadCount: unreadCount,
|
unreadCount: unreadCount,
|
||||||
isFavorite: isFavorite,
|
isFavorite: isFavorite,
|
||||||
onTap: onTap,
|
onTap: onTap,
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ const String _encryptedBackupFormat = 'meshcore-open-encrypted-backup';
|
|||||||
const List<String> _contactPreferencePrefixes = [
|
const List<String> _contactPreferencePrefixes = [
|
||||||
'contacts',
|
'contacts',
|
||||||
'contact_groups',
|
'contact_groups',
|
||||||
|
'contact_added_at_',
|
||||||
'contact_smaz_',
|
'contact_smaz_',
|
||||||
'contact_cyr2lat_',
|
'contact_cyr2lat_',
|
||||||
'contact_url_images_',
|
'contact_url_images_',
|
||||||
@@ -1094,7 +1095,8 @@ class BackupService {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (items.contains(BackupItem.contacts) &&
|
if (items.contains(BackupItem.contacts) &&
|
||||||
key.startsWith('contacts$devicePrefix')) {
|
(key.startsWith('contacts$devicePrefix') ||
|
||||||
|
key.startsWith('contact_added_at_$devicePrefix'))) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (items.contains(BackupItem.perContactSettings) &&
|
if (items.contains(BackupItem.perContactSettings) &&
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import '../utils/app_logger.dart';
|
||||||
|
import 'prefs_manager.dart';
|
||||||
|
|
||||||
|
/// Phone time at which each contact was first added from a card, keyed by
|
||||||
|
/// contact public key hex. App-side only: the radio keeps advert time 0 for
|
||||||
|
/// these contacts, so this orders them until a real advert arrives.
|
||||||
|
class ContactAddedAtStore {
|
||||||
|
static const String _keyPrefix = 'contact_added_at_';
|
||||||
|
|
||||||
|
String publicKeyHex = '';
|
||||||
|
set setPublicKeyHex(String value) =>
|
||||||
|
publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
|
||||||
|
|
||||||
|
String get keyFor => '$_keyPrefix$publicKeyHex';
|
||||||
|
|
||||||
|
Map<String, DateTime> load() {
|
||||||
|
if (publicKeyHex.isEmpty) return {};
|
||||||
|
final jsonString = PrefsManager.instance.getString(keyFor);
|
||||||
|
if (jsonString == null || jsonString.isEmpty) return {};
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(jsonString) as Map<String, dynamic>;
|
||||||
|
return {
|
||||||
|
for (final entry in decoded.entries)
|
||||||
|
if (entry.value is int)
|
||||||
|
entry.key: DateTime.fromMillisecondsSinceEpoch(entry.value as int),
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
appLogger.warn('Stored contact added times are unreadable: $e');
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> save(Map<String, DateTime> addedAt) async {
|
||||||
|
if (publicKeyHex.isEmpty) return;
|
||||||
|
await PrefsManager.instance.setString(
|
||||||
|
keyFor,
|
||||||
|
jsonEncode({
|
||||||
|
for (final entry in addedAt.entries)
|
||||||
|
entry.key: entry.value.millisecondsSinceEpoch,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,14 +43,22 @@ ThemeIconSlot? contactTypeIconSlot(int type) {
|
|||||||
|
|
||||||
/// The most recent activity for [contact]: for chat nodes this includes the
|
/// The most recent activity for [contact]: for chat nodes this includes the
|
||||||
/// last message, for other node types only the last advert or telemetry fix.
|
/// last message, for other node types only the last advert or telemetry fix.
|
||||||
DateTime resolveContactLastSeen(Contact contact) {
|
/// [addedAt] (the phone time the contact was added from a card) stands in
|
||||||
final heard = contact.lastHeard;
|
/// while the radio has no advert time for it.
|
||||||
|
DateTime resolveContactLastSeen(Contact contact, {DateTime? addedAt}) {
|
||||||
|
final heard =
|
||||||
|
addedAt != null &&
|
||||||
|
contact.lastSeen.millisecondsSinceEpoch == 0 &&
|
||||||
|
addedAt.isAfter(contact.lastHeard)
|
||||||
|
? addedAt
|
||||||
|
: contact.lastHeard;
|
||||||
if (contact.type != advTypeChat) return heard;
|
if (contact.type != advTypeChat) return heard;
|
||||||
return contact.lastMessageAt.isAfter(heard) ? contact.lastMessageAt : heard;
|
return contact.lastMessageAt.isAfter(heard) ? contact.lastMessageAt : heard;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Short relative "last seen" label ("now", "5 mins ago", "2 days ago").
|
/// Short relative "last seen" label ("now", "5 mins ago", "2 days ago").
|
||||||
String formatContactLastSeen(AppLocalizations l10n, DateTime lastSeen) {
|
String formatContactLastSeen(AppLocalizations l10n, DateTime lastSeen) {
|
||||||
|
if (lastSeen.millisecondsSinceEpoch == 0) return l10n.contacts_lastSeenNever;
|
||||||
final diff = DateTime.now().difference(lastSeen);
|
final diff = DateTime.now().difference(lastSeen);
|
||||||
|
|
||||||
if (diff.isNegative || diff.inMinutes < 5) {
|
if (diff.isNegative || diff.inMinutes < 5) {
|
||||||
|
|||||||
+31
-11
@@ -699,6 +699,11 @@ class ErrorRetryCard extends StatelessWidget {
|
|||||||
|
|
||||||
/// Staggered fade + slide entrance for list items. Wrap each item and pass
|
/// Staggered fade + slide entrance for list items. Wrap each item and pass
|
||||||
/// its [index]; animation only plays once per widget lifecycle.
|
/// its [index]; animation only plays once per widget lifecycle.
|
||||||
|
///
|
||||||
|
/// Only rows built while their list is at rest at the top play it. Rows that
|
||||||
|
/// a scroll brings into view appear at once: a delayed fade there leaves
|
||||||
|
/// blank rows trailing the finger and adds a ticker and an opacity layer per
|
||||||
|
/// row during a fling.
|
||||||
class ListEntrance extends StatefulWidget {
|
class ListEntrance extends StatefulWidget {
|
||||||
final int index;
|
final int index;
|
||||||
final Widget child;
|
final Widget child;
|
||||||
@@ -711,41 +716,56 @@ class ListEntrance extends StatefulWidget {
|
|||||||
|
|
||||||
class _ListEntranceState extends State<ListEntrance>
|
class _ListEntranceState extends State<ListEntrance>
|
||||||
with SingleTickerProviderStateMixin {
|
with SingleTickerProviderStateMixin {
|
||||||
// Created eagerly: a lazy `late final` initializer would run on first
|
// Created in initState, not lazily: a lazy initializer would run on first
|
||||||
// access — which can be dispose(), where ticker creation throws.
|
// access — which can be dispose(), where ticker creation throws. Null when
|
||||||
late final AnimationController _controller;
|
// the row skips the entrance.
|
||||||
late final CurvedAnimation _curve;
|
AnimationController? _controller;
|
||||||
|
CurvedAnimation? _curve;
|
||||||
|
|
||||||
|
/// Whether the enclosing list has scrolled away from the top or is moving,
|
||||||
|
/// i.e. this row is entering because of a scroll.
|
||||||
|
bool _enteredByScroll() {
|
||||||
|
final scrollable = context.findAncestorStateOfType<ScrollableState>();
|
||||||
|
if (scrollable == null) return false;
|
||||||
|
final position = scrollable.position;
|
||||||
|
return position.isScrollingNotifier.value ||
|
||||||
|
(position.hasPixels && position.pixels != 0);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_controller = AnimationController(
|
// Decided once: changing the tree shape later would rebuild the row.
|
||||||
|
if (_enteredByScroll()) return;
|
||||||
|
final controller = _controller = AnimationController(
|
||||||
vsync: this,
|
vsync: this,
|
||||||
duration: const Duration(milliseconds: 280),
|
duration: const Duration(milliseconds: 280),
|
||||||
);
|
);
|
||||||
_curve = CurvedAnimation(parent: _controller, curve: Curves.easeOutCubic);
|
_curve = CurvedAnimation(parent: controller, curve: Curves.easeOutCubic);
|
||||||
final delay = Duration(milliseconds: 24 * widget.index.clamp(0, 12));
|
final delay = Duration(milliseconds: 24 * widget.index.clamp(0, 12));
|
||||||
Future.delayed(delay, () {
|
Future.delayed(delay, () {
|
||||||
if (mounted) _controller.forward();
|
if (mounted) controller.forward();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_curve.dispose();
|
_curve?.dispose();
|
||||||
_controller.dispose();
|
_controller?.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final curve = _curve;
|
||||||
|
if (curve == null) return widget.child;
|
||||||
return FadeTransition(
|
return FadeTransition(
|
||||||
opacity: _curve,
|
opacity: curve,
|
||||||
child: SlideTransition(
|
child: SlideTransition(
|
||||||
position: Tween(
|
position: Tween(
|
||||||
begin: const Offset(0, 0.04),
|
begin: const Offset(0, 0.04),
|
||||||
end: Offset.zero,
|
end: Offset.zero,
|
||||||
).animate(_curve),
|
).animate(curve),
|
||||||
child: widget.child,
|
child: widget.child,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||||
|
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||||
|
import 'package:meshcore_open/models/contact.dart';
|
||||||
|
import 'package:meshcore_open/review_mode/review_radio.dart';
|
||||||
|
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||||
|
import 'package:meshcore_open/services/path_history_service.dart';
|
||||||
|
import 'package:meshcore_open/services/storage_service.dart';
|
||||||
|
import 'package:meshcore_open/storage/contact_added_at_store.dart';
|
||||||
|
import 'package:meshcore_open/storage/last_radio_store.dart';
|
||||||
|
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||||
|
import 'package:meshcore_open/utils/contact_qr.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
Future<void> _waitFor(bool Function() condition, {int seconds = 8}) async {
|
||||||
|
final end = DateTime.now().add(Duration(seconds: seconds));
|
||||||
|
while (!condition()) {
|
||||||
|
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 25));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RecordingReviewRadio extends ReviewRadio {
|
||||||
|
final List<Uint8List> sent = [];
|
||||||
|
|
||||||
|
_RecordingReviewRadio()
|
||||||
|
: super(scheduledMessageInterval: const Duration(hours: 1));
|
||||||
|
|
||||||
|
@override
|
||||||
|
void handle(Uint8List frame) {
|
||||||
|
sent.add(frame);
|
||||||
|
super.handle(frame);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// [cmd][pub_key x32][type][flags][path_len][path x64][name x32][last_advert x4]
|
||||||
|
const _lastAdvertOffset = 1 + 32 + 1 + 1 + 1 + 64 + 32;
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
PrefsManager.reset();
|
||||||
|
await PrefsManager.initialize();
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'a card add records a local added time once, never on the radio',
|
||||||
|
() async {
|
||||||
|
final connector = MeshCoreConnector();
|
||||||
|
addTearDown(connector.dispose);
|
||||||
|
final retryService = MessageRetryService();
|
||||||
|
addTearDown(retryService.dispose);
|
||||||
|
connector.initialize(
|
||||||
|
retryService: retryService,
|
||||||
|
pathHistoryService: PathHistoryService(StorageService()),
|
||||||
|
);
|
||||||
|
final radio = _RecordingReviewRadio();
|
||||||
|
connector.reviewRadioFactoryForTest = () => radio;
|
||||||
|
await connector.connectReview();
|
||||||
|
await _waitFor(() => connector.hasLoadedContacts);
|
||||||
|
|
||||||
|
final key = Uint8List.fromList(List.generate(32, (i) => 0xA0 + (i % 16)));
|
||||||
|
final keyHex = pubKeyToHex(key);
|
||||||
|
final card = ScannedContact(publicKey: key, name: 'Card', type: 1);
|
||||||
|
|
||||||
|
final before = DateTime.now();
|
||||||
|
await connector.addContactFromCard(card);
|
||||||
|
final addedAt = connector.contactAddedAt(keyHex);
|
||||||
|
expect(addedAt, isNotNull);
|
||||||
|
expect(addedAt!.isBefore(before), isFalse);
|
||||||
|
|
||||||
|
// The radio still gets advert time 0 (its replay guard).
|
||||||
|
final addFrame = radio.sent.lastWhere(
|
||||||
|
(f) => f.first == cmdAddUpdateContact,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
ByteData.sublistView(
|
||||||
|
addFrame,
|
||||||
|
).getUint32(_lastAdvertOffset, Endian.little),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Re-adding keeps the first time.
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||||
|
await connector.addContactFromCard(card);
|
||||||
|
expect(connector.contactAddedAt(keyHex), addedAt);
|
||||||
|
|
||||||
|
// Persisted per radio.
|
||||||
|
final store = ContactAddedAtStore()
|
||||||
|
..setPublicKeyHex = connector.selfPublicKeyHex;
|
||||||
|
expect(
|
||||||
|
store.load()[keyHex]?.millisecondsSinceEpoch,
|
||||||
|
addedAt.millisecondsSinceEpoch,
|
||||||
|
);
|
||||||
|
final otherRadio = ContactAddedAtStore()
|
||||||
|
..setPublicKeyHex = 'ffffffffff00';
|
||||||
|
expect(otherRadio.load(), isEmpty);
|
||||||
|
|
||||||
|
// Removing the contact forgets it, so a later add starts fresh.
|
||||||
|
await connector.removeContact(
|
||||||
|
Contact(
|
||||||
|
publicKey: key,
|
||||||
|
name: 'Card',
|
||||||
|
type: 1,
|
||||||
|
pathLength: -1,
|
||||||
|
path: Uint8List(0),
|
||||||
|
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(connector.contactAddedAt(keyHex), isNull);
|
||||||
|
|
||||||
|
// So does the firmware deleting it to make room.
|
||||||
|
await connector.addContactFromCard(card);
|
||||||
|
expect(connector.contactAddedAt(keyHex), isNotNull);
|
||||||
|
connector.handleFrameForTest([pushCodeContactDeleted, ...key]);
|
||||||
|
expect(connector.contactAddedAt(keyHex), isNull);
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(store.load(), isNot(contains(keyHex)));
|
||||||
|
|
||||||
|
await connector.disconnect(manual: true);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('a saved radio restores its added times after a restart', () async {
|
||||||
|
const radioHex =
|
||||||
|
'a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf';
|
||||||
|
final contactHex = 'c1' * 32;
|
||||||
|
final addedAt = DateTime.fromMillisecondsSinceEpoch(1790000000000);
|
||||||
|
await (ContactAddedAtStore()..setPublicKeyHex = radioHex).save({
|
||||||
|
contactHex: addedAt,
|
||||||
|
});
|
||||||
|
await LastRadioStore().save(
|
||||||
|
LastRadio(
|
||||||
|
publicKeyHex: radioHex,
|
||||||
|
name: 'Base',
|
||||||
|
transport: LastRadio.transportBle,
|
||||||
|
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
|
||||||
|
savedAt: addedAt,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final connector = MeshCoreConnector();
|
||||||
|
addTearDown(connector.dispose);
|
||||||
|
await connector.restoreLastRadio();
|
||||||
|
|
||||||
|
expect(connector.contactAddedAt(contactHex), addedAt);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/material.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/models/channel.dart';
|
||||||
|
import 'package:meshcore_open/models/channel_message.dart';
|
||||||
|
import 'package:meshcore_open/models/contact.dart';
|
||||||
|
import 'package:meshcore_open/screens/channels_screen.dart';
|
||||||
|
import 'package:meshcore_open/screens/contacts_screen.dart';
|
||||||
|
import 'package:meshcore_open/services/app_settings_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';
|
||||||
|
import 'package:meshcore_open/widgets/mesh_ui.dart';
|
||||||
|
|
||||||
|
/// Repeatable stand-in for profiling rapid scrolling on a phone: builds the
|
||||||
|
/// contacts list with 500 contacts and the channels list with 40 channels,
|
||||||
|
/// flings each list, and counts widget builds and rows that are not fully
|
||||||
|
/// drawn while scrolling. Run with `flutter test
|
||||||
|
/// test/screens/list_scroll_perf_test.dart` and read the printed lines.
|
||||||
|
/// See documentation/performance-profiling.md for the on-device check.
|
||||||
|
|
||||||
|
const _contactCount = 500;
|
||||||
|
const _channelCount = 40;
|
||||||
|
|
||||||
|
class _Connector extends MeshCoreConnector {
|
||||||
|
List<Contact> nodes = [];
|
||||||
|
List<Channel> slots = [];
|
||||||
|
final Map<String, int> unread = {};
|
||||||
|
final Map<int, ChannelMessage> latest = {};
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<Contact> get contacts => List.unmodifiable(nodes);
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<Channel> get channels => List.unmodifiable(slots);
|
||||||
|
|
||||||
|
@override
|
||||||
|
int getUnreadCountForContact(Contact contact) =>
|
||||||
|
unread[contact.publicKeyHex] ?? 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
int getUnreadCountForChannel(Channel channel) => channel.unreadCount;
|
||||||
|
|
||||||
|
@override
|
||||||
|
ChannelMessage? latestVisibleChannelMessage(Channel channel) =>
|
||||||
|
latest[channel.index];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> getChannels({int? maxChannels, bool force = false}) async {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Contact _contact(int i, DateTime now) {
|
||||||
|
final key = Uint8List(32)
|
||||||
|
..[0] = i >> 8
|
||||||
|
..[1] = i & 0xff
|
||||||
|
..[2] = 0x5a;
|
||||||
|
final type = i % 10 == 0
|
||||||
|
? advTypeRepeater
|
||||||
|
: i % 25 == 0
|
||||||
|
? advTypeRoom
|
||||||
|
: advTypeChat;
|
||||||
|
return Contact(
|
||||||
|
publicKey: key,
|
||||||
|
name: 'Node ${i.toString().padLeft(3, '0')}',
|
||||||
|
type: type,
|
||||||
|
pathLength: i % 4,
|
||||||
|
path: Uint8List.fromList(List.filled(i % 4, i & 0xff)),
|
||||||
|
latitude: i.isEven ? 35.0 : null,
|
||||||
|
longitude: i.isEven ? -112.0 : null,
|
||||||
|
lastSeen: now.subtract(Duration(minutes: i * 7)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counts element builds per widget type, via the framework's debug hook.
|
||||||
|
class _BuildCounter {
|
||||||
|
final Map<String, int> counts = {};
|
||||||
|
|
||||||
|
void start() {
|
||||||
|
counts.clear();
|
||||||
|
debugOnRebuildDirtyWidget = (element, _) {
|
||||||
|
final name = element.widget.runtimeType.toString();
|
||||||
|
counts[name] = (counts[name] ?? 0) + 1;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
void stop() => debugOnRebuildDirtyWidget = null;
|
||||||
|
|
||||||
|
int operator [](String type) => counts[type] ?? 0;
|
||||||
|
int get total => counts.values.fold(0, (a, b) => a + b);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rows inside the visible list area whose entrance fade has not finished:
|
||||||
|
/// they are blank or partly transparent while the user scrolls.
|
||||||
|
int _rowsNotFullyDrawn(WidgetTester tester, Rect viewport) {
|
||||||
|
final fades = find.descendant(
|
||||||
|
of: find.byType(ListEntrance),
|
||||||
|
matching: find.byType(FadeTransition),
|
||||||
|
);
|
||||||
|
var count = 0;
|
||||||
|
for (final element in fades.evaluate()) {
|
||||||
|
final fade = element.widget as FadeTransition;
|
||||||
|
final box = element.renderObject as RenderBox?;
|
||||||
|
if (box == null || !box.attached || !box.hasSize) continue;
|
||||||
|
final rect = box.localToGlobal(Offset.zero) & box.size;
|
||||||
|
if (!rect.overlaps(viewport)) continue;
|
||||||
|
if (fade.opacity.value < 1) count++;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ScrollResult {
|
||||||
|
int frames = 0;
|
||||||
|
int notFullyDrawnRowFrames = 0;
|
||||||
|
int maxNotFullyDrawn = 0;
|
||||||
|
int notFullyDrawnAfterStop = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Flings [list] like a rapid swipe and pumps 60 Hz frames until the list
|
||||||
|
/// stops, firing a connector notify partway through.
|
||||||
|
Future<_ScrollResult> _fling(
|
||||||
|
WidgetTester tester,
|
||||||
|
Finder list,
|
||||||
|
_Connector connector, {
|
||||||
|
required Offset offset,
|
||||||
|
}) async {
|
||||||
|
final viewport = tester.getRect(list);
|
||||||
|
final position = tester.state<ScrollableState>(
|
||||||
|
find.descendant(of: list, matching: find.byType(Scrollable)).first,
|
||||||
|
);
|
||||||
|
final result = _ScrollResult();
|
||||||
|
await tester.fling(list, offset, 6000);
|
||||||
|
for (var i = 0; i < 400; i++) {
|
||||||
|
if (i == 10) connector.notifyListeners();
|
||||||
|
await tester.pump(const Duration(milliseconds: 16));
|
||||||
|
result.frames++;
|
||||||
|
final hidden = _rowsNotFullyDrawn(tester, viewport);
|
||||||
|
result.notFullyDrawnRowFrames += hidden;
|
||||||
|
if (hidden > result.maxNotFullyDrawn) result.maxNotFullyDrawn = hidden;
|
||||||
|
if (i > 12 && !position.position.isScrollingNotifier.value) break;
|
||||||
|
}
|
||||||
|
result.notFullyDrawnAfterStop = _rowsNotFullyDrawn(tester, viewport);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
late _Connector connector;
|
||||||
|
late AppSettingsService settings;
|
||||||
|
late UiViewStateService viewState;
|
||||||
|
final counter = _BuildCounter();
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
PrefsManager.reset();
|
||||||
|
await PrefsManager.initialize();
|
||||||
|
connector = _Connector();
|
||||||
|
settings = AppSettingsService();
|
||||||
|
viewState = UiViewStateService();
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() {
|
||||||
|
counter.stop();
|
||||||
|
connector.dispose();
|
||||||
|
settings.dispose();
|
||||||
|
viewState.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Opens [home] and returns how many rows played the entrance animation.
|
||||||
|
Future<int> open(WidgetTester tester, Widget home) async {
|
||||||
|
tester.view.physicalSize = const Size(1080, 2340);
|
||||||
|
tester.view.devicePixelRatio = 3;
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MultiProvider(
|
||||||
|
providers: [
|
||||||
|
ChangeNotifierProvider<MeshCoreConnector>.value(value: connector),
|
||||||
|
ChangeNotifierProvider.value(value: settings),
|
||||||
|
ChangeNotifierProvider.value(value: viewState),
|
||||||
|
],
|
||||||
|
child: MaterialApp(
|
||||||
|
theme: MeshTheme.light(),
|
||||||
|
locale: const Locale('en'),
|
||||||
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||||||
|
home: home,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
final animatedRows = find
|
||||||
|
.descendant(
|
||||||
|
of: find.byType(ListEntrance),
|
||||||
|
matching: find.byType(FadeTransition),
|
||||||
|
)
|
||||||
|
.evaluate()
|
||||||
|
.length;
|
||||||
|
// Let the first screen's entrance animations finish.
|
||||||
|
for (var i = 0; i < 40; i++) {
|
||||||
|
await tester.pump(const Duration(milliseconds: 16));
|
||||||
|
}
|
||||||
|
return animatedRows;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> notifyAndSettle(WidgetTester tester) async {
|
||||||
|
connector.notifyListeners();
|
||||||
|
await tester.pump(const Duration(milliseconds: 60));
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> close(WidgetTester tester) async {
|
||||||
|
counter.stop();
|
||||||
|
await tester.pumpWidget(const SizedBox.shrink());
|
||||||
|
// Drain entrance-delay timers.
|
||||||
|
await tester.pump(const Duration(seconds: 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('contacts list: rapid fling with 500 contacts', (tester) async {
|
||||||
|
final now = DateTime.now();
|
||||||
|
connector.nodes = [
|
||||||
|
for (var i = 0; i < _contactCount; i++) _contact(i, now),
|
||||||
|
];
|
||||||
|
for (var i = 1; i < _contactCount; i += 9) {
|
||||||
|
connector.unread[connector.nodes[i].publicKeyHex] = i % 5 + 1;
|
||||||
|
}
|
||||||
|
final animatedRows = await open(tester, const ContactsScreen());
|
||||||
|
final list = find.byType(ListView);
|
||||||
|
expect(list, findsOneWidget);
|
||||||
|
|
||||||
|
counter.start();
|
||||||
|
final down = await _fling(
|
||||||
|
tester,
|
||||||
|
list,
|
||||||
|
connector,
|
||||||
|
offset: const Offset(0, -2500),
|
||||||
|
);
|
||||||
|
final flingBuilds = Map.of(counter.counts);
|
||||||
|
final flingTotal = counter.total;
|
||||||
|
|
||||||
|
counter.start();
|
||||||
|
await notifyAndSettle(tester);
|
||||||
|
final notifyTiles = counter['_ContactTile'];
|
||||||
|
final notifyTotal = counter.total;
|
||||||
|
|
||||||
|
// A live change still reaches the visible tile.
|
||||||
|
final visible = tester
|
||||||
|
.widgetList(
|
||||||
|
find.byWidgetPredicate(
|
||||||
|
(w) => w.runtimeType.toString() == '_ContactTile',
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.map((w) => (w as dynamic).contact as Contact)
|
||||||
|
.toList();
|
||||||
|
final target = visible[visible.length ~/ 2];
|
||||||
|
connector.unread[target.publicKeyHex] = 42;
|
||||||
|
counter.start();
|
||||||
|
await notifyAndSettle(tester);
|
||||||
|
final changeTiles = counter['_ContactTile'];
|
||||||
|
expect(find.text('42'), findsOneWidget);
|
||||||
|
|
||||||
|
// So does a replaced contact.
|
||||||
|
final renamedAt = connector.nodes.indexOf(visible.first);
|
||||||
|
connector.nodes = List.of(connector.nodes)
|
||||||
|
..[renamedAt] = visible.first.copyWith(name: 'Renamed node');
|
||||||
|
await notifyAndSettle(tester);
|
||||||
|
expect(find.text('Renamed node'), findsOneWidget);
|
||||||
|
|
||||||
|
// ignore: avoid_print
|
||||||
|
print(
|
||||||
|
'[list-perf] contacts fling: frames=${down.frames} '
|
||||||
|
'itemBuilds=${flingBuilds['_ContactTileEntrance'] ?? 0} '
|
||||||
|
'tileBuilds=${flingBuilds['_ContactTile'] ?? 0} '
|
||||||
|
'entranceBuilds=${flingBuilds['ListEntrance'] ?? 0} '
|
||||||
|
'allBuilds=$flingTotal '
|
||||||
|
'rowFramesNotFullyDrawn=${down.notFullyDrawnRowFrames} '
|
||||||
|
'maxRowsNotFullyDrawn=${down.maxNotFullyDrawn} '
|
||||||
|
'rowsNotFullyDrawnAtStop=${down.notFullyDrawnAfterStop}\n'
|
||||||
|
'[list-perf] contacts notify (no change): tileBuilds=$notifyTiles '
|
||||||
|
'allBuilds=$notifyTotal; one unread change: tileBuilds=$changeTiles',
|
||||||
|
);
|
||||||
|
|
||||||
|
// The first screen still animates in; rows a fling brings in do not.
|
||||||
|
expect(animatedRows, greaterThan(0));
|
||||||
|
expect(down.notFullyDrawnRowFrames, 0);
|
||||||
|
// A notify that changes nothing rebuilds no rows; a change rebuilds one.
|
||||||
|
expect(notifyTiles, 0);
|
||||||
|
expect(changeTiles, 1);
|
||||||
|
|
||||||
|
await close(tester);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('channels list: rapid fling with 40 channels', (tester) async {
|
||||||
|
final now = DateTime.now();
|
||||||
|
connector.slots = [
|
||||||
|
for (var i = 0; i < _channelCount; i++)
|
||||||
|
Channel(
|
||||||
|
index: i,
|
||||||
|
name: i == 0 ? 'Public' : '#topic-$i',
|
||||||
|
psk: Uint8List.fromList(List.filled(16, i + 1)),
|
||||||
|
unreadCount: i % 3 == 0 ? i : 0,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (var i = 0; i < _channelCount; i++) {
|
||||||
|
connector.latest[i] = ChannelMessage(
|
||||||
|
senderName: 'Sender $i',
|
||||||
|
text: 'Message preview number $i on the mesh',
|
||||||
|
timestamp: now.subtract(Duration(minutes: i * 13)),
|
||||||
|
isOutgoing: false,
|
||||||
|
status: ChannelMessageStatus.sent,
|
||||||
|
channelIndex: i,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
viewState.setChannelsSortOption(ChannelSortOption.name);
|
||||||
|
final animatedRows = await open(tester, const ChannelsScreen());
|
||||||
|
final list = find.byType(ListView);
|
||||||
|
expect(list, findsOneWidget);
|
||||||
|
|
||||||
|
counter.start();
|
||||||
|
final down = await _fling(
|
||||||
|
tester,
|
||||||
|
list,
|
||||||
|
connector,
|
||||||
|
offset: const Offset(0, -2500),
|
||||||
|
);
|
||||||
|
final flingBuilds = Map.of(counter.counts);
|
||||||
|
final flingTotal = counter.total;
|
||||||
|
|
||||||
|
counter.start();
|
||||||
|
await notifyAndSettle(tester);
|
||||||
|
final notifyTiles = counter['MeshCard'];
|
||||||
|
|
||||||
|
// ignore: avoid_print
|
||||||
|
print(
|
||||||
|
'[list-perf] channels fling: frames=${down.frames} '
|
||||||
|
'itemBuilds=${flingBuilds['ListEntrance'] ?? 0} '
|
||||||
|
'cardBuilds=${flingBuilds['MeshCard'] ?? 0} '
|
||||||
|
'allBuilds=$flingTotal '
|
||||||
|
'rowFramesNotFullyDrawn=${down.notFullyDrawnRowFrames} '
|
||||||
|
'maxRowsNotFullyDrawn=${down.maxNotFullyDrawn} '
|
||||||
|
'rowsNotFullyDrawnAtStop=${down.notFullyDrawnAfterStop}\n'
|
||||||
|
'[list-perf] channels notify (no change): cardBuilds=$notifyTiles',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(animatedRows, greaterThan(0));
|
||||||
|
expect(down.notFullyDrawnRowFrames, 0);
|
||||||
|
|
||||||
|
await close(tester);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,456 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
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/models/channel.dart';
|
||||||
|
import 'package:meshcore_open/models/channel_message.dart';
|
||||||
|
import 'package:meshcore_open/models/contact.dart';
|
||||||
|
import 'package:meshcore_open/models/message.dart';
|
||||||
|
import 'package:meshcore_open/screens/channels_screen.dart';
|
||||||
|
import 'package:meshcore_open/screens/chat_screen.dart';
|
||||||
|
import 'package:meshcore_open/screens/contacts_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_filter/message_filter_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/channel_message_store.dart';
|
||||||
|
import 'package:meshcore_open/storage/channel_store.dart';
|
||||||
|
import 'package:meshcore_open/storage/contact_store.dart';
|
||||||
|
import 'package:meshcore_open/storage/last_radio_store.dart';
|
||||||
|
import 'package:meshcore_open/storage/message_store.dart';
|
||||||
|
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||||
|
import 'package:meshcore_open/theme/mesh_theme.dart';
|
||||||
|
import 'package:meshcore_open/utils/contact_filter_types.dart';
|
||||||
|
|
||||||
|
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
|
||||||
|
final _radioHex = pubKeyToHex(_radioKey);
|
||||||
|
|
||||||
|
Uint8List _key(int seed) =>
|
||||||
|
Uint8List.fromList(List<int>.generate(32, (i) => seed + i));
|
||||||
|
Uint8List _psk(int seed) =>
|
||||||
|
Uint8List.fromList(List<int>.generate(16, (i) => seed + i));
|
||||||
|
|
||||||
|
/// Local arrival times, an hour apart. Sender clocks are set far off them.
|
||||||
|
final _base = DateTime(2026, 11, 20, 12);
|
||||||
|
DateTime _arrived(int hours) => _base.add(Duration(hours: hours));
|
||||||
|
final _farFuture = DateTime(2099);
|
||||||
|
final _farPast = DateTime(2001);
|
||||||
|
|
||||||
|
ChannelMessage _channelMessage(
|
||||||
|
int slot,
|
||||||
|
String text, {
|
||||||
|
required DateTime sentAt,
|
||||||
|
required DateTime receivedAt,
|
||||||
|
String? filterReason,
|
||||||
|
}) => ChannelMessage(
|
||||||
|
senderName: 'Bob',
|
||||||
|
text: text,
|
||||||
|
timestamp: sentAt,
|
||||||
|
receivedAt: receivedAt,
|
||||||
|
isOutgoing: false,
|
||||||
|
status: ChannelMessageStatus.sent,
|
||||||
|
channelIndex: slot,
|
||||||
|
filterReason: filterReason,
|
||||||
|
);
|
||||||
|
|
||||||
|
Message _directMessage(
|
||||||
|
Uint8List senderKey,
|
||||||
|
String text, {
|
||||||
|
required DateTime sentAt,
|
||||||
|
required DateTime receivedAt,
|
||||||
|
}) => Message(
|
||||||
|
senderKey: senderKey,
|
||||||
|
text: text,
|
||||||
|
timestamp: sentAt,
|
||||||
|
receivedAt: receivedAt,
|
||||||
|
isOutgoing: false,
|
||||||
|
status: MessageStatus.delivered,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Seeds the remembered radio with channels (slots in map order) and
|
||||||
|
/// contacts, each with its saved messages.
|
||||||
|
Future<void> _seed({
|
||||||
|
Map<String, List<ChannelMessage> Function(int slot)> channelMessages =
|
||||||
|
const {},
|
||||||
|
Map<String, List<Message> Function(Uint8List key)> contactMessages = const {},
|
||||||
|
}) async {
|
||||||
|
final channelStore = ChannelStore()..setPublicKeyHex = _radioHex;
|
||||||
|
final messageStore = ChannelMessageStore()..setPublicKeyHex = _radioHex;
|
||||||
|
final channels = <Channel>[];
|
||||||
|
var slot = 0;
|
||||||
|
for (final entry in channelMessages.entries) {
|
||||||
|
final channel = Channel(index: slot, name: entry.key, psk: _psk(slot * 16));
|
||||||
|
channels.add(channel);
|
||||||
|
await messageStore.saveChannelMessages(
|
||||||
|
channel.storageId!,
|
||||||
|
entry.value(slot),
|
||||||
|
);
|
||||||
|
slot++;
|
||||||
|
}
|
||||||
|
await channelStore.saveChannels(channels);
|
||||||
|
await channelStore.saveSlotChannelIds({
|
||||||
|
for (final c in channels) c.index: c.storageId!,
|
||||||
|
});
|
||||||
|
|
||||||
|
final contacts = <Contact>[];
|
||||||
|
final directStore = MessageStore()..setPublicKeyHex = _radioHex;
|
||||||
|
var seed = 0x10;
|
||||||
|
for (final entry in contactMessages.entries) {
|
||||||
|
final key = _key(seed);
|
||||||
|
seed += 0x20;
|
||||||
|
final contact = Contact(
|
||||||
|
publicKey: key,
|
||||||
|
name: entry.key,
|
||||||
|
type: advTypeChat,
|
||||||
|
pathLength: 1,
|
||||||
|
path: Uint8List.fromList([0x22]),
|
||||||
|
lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000),
|
||||||
|
);
|
||||||
|
contacts.add(contact);
|
||||||
|
await directStore.saveMessages(contact.publicKeyHex, entry.value(key));
|
||||||
|
}
|
||||||
|
await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts(contacts);
|
||||||
|
|
||||||
|
await LastRadioStore().save(
|
||||||
|
LastRadio(
|
||||||
|
publicKeyHex: _radioHex,
|
||||||
|
name: 'Base',
|
||||||
|
transport: LastRadio.transportBle,
|
||||||
|
bleRemoteId: 'AA:BB:CC:DD:EE:FF',
|
||||||
|
savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
ChannelMessageStore().forgetArchive();
|
||||||
|
MessageStore().forgetArchive();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restores the seeded radio into a connector that never connects.
|
||||||
|
Future<MeshCoreConnector> _connector(
|
||||||
|
WidgetTester tester, {
|
||||||
|
MessageFilterService? filter,
|
||||||
|
}) async {
|
||||||
|
final connector = MeshCoreConnector();
|
||||||
|
addTearDown(connector.dispose);
|
||||||
|
if (filter != null) {
|
||||||
|
final retry = MessageRetryService();
|
||||||
|
addTearDown(retry.dispose);
|
||||||
|
connector.initialize(
|
||||||
|
retryService: retry,
|
||||||
|
pathHistoryService: PathHistoryService(StorageService()),
|
||||||
|
messageFilterService: filter,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await tester.runAsync(connector.restoreLastRadio);
|
||||||
|
return connector;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pumpScreen(
|
||||||
|
WidgetTester tester,
|
||||||
|
MeshCoreConnector connector,
|
||||||
|
UiViewStateService viewState,
|
||||||
|
Widget home,
|
||||||
|
) async {
|
||||||
|
final storage = StorageService();
|
||||||
|
final settings = AppSettingsService();
|
||||||
|
await tester.runAsync(settings.loadSettings);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MultiProvider(
|
||||||
|
providers: [
|
||||||
|
ChangeNotifierProvider.value(value: connector),
|
||||||
|
ChangeNotifierProvider.value(value: MessageRetryService()),
|
||||||
|
ChangeNotifierProvider.value(value: PathHistoryService(storage)),
|
||||||
|
ChangeNotifierProvider.value(value: settings),
|
||||||
|
ChangeNotifierProvider.value(value: BleDebugLogService()),
|
||||||
|
ChangeNotifierProvider.value(value: AppDebugLogService()),
|
||||||
|
ChangeNotifierProvider.value(value: ChatTextScaleService()),
|
||||||
|
ChangeNotifierProvider.value(value: TranslationService(settings)),
|
||||||
|
ChangeNotifierProvider.value(value: viewState),
|
||||||
|
Provider.value(value: storage),
|
||||||
|
ChangeNotifierProvider.value(
|
||||||
|
value: MapTileCacheService(appSettingsService: settings),
|
||||||
|
),
|
||||||
|
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
|
||||||
|
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
|
||||||
|
ChangeNotifierProvider.value(value: ReceivedImageStore()),
|
||||||
|
ChangeNotifierProvider.value(
|
||||||
|
value: NetworkMapUploadService(
|
||||||
|
connector: connector,
|
||||||
|
settings: settings,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
child: MaterialApp(
|
||||||
|
theme: MeshTheme.light(),
|
||||||
|
locale: const Locale('en'),
|
||||||
|
localizationsDelegates: const [
|
||||||
|
AppLocalizations.delegate,
|
||||||
|
GlobalMaterialLocalizations.delegate,
|
||||||
|
GlobalWidgetsLocalizations.delegate,
|
||||||
|
GlobalCupertinoLocalizations.delegate,
|
||||||
|
],
|
||||||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||||||
|
home: home,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
for (var i = 0; i < 10; i++) {
|
||||||
|
await tester.pump(const Duration(milliseconds: 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [names] in the order they appear on screen, top to bottom.
|
||||||
|
List<String> _screenOrder(WidgetTester tester, List<String> names) {
|
||||||
|
final top = {
|
||||||
|
for (final name in names) name: tester.getTopLeft(find.text(name).first).dy,
|
||||||
|
};
|
||||||
|
return [...names]..sort((a, b) => top[a]!.compareTo(top[b]!));
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
final tempDir = Directory.systemTemp.createTempSync('recency_sort_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();
|
||||||
|
ChannelMessageStore().forgetArchive();
|
||||||
|
MessageStore().forgetArchive();
|
||||||
|
});
|
||||||
|
|
||||||
|
Future<void> pumpChannels(
|
||||||
|
WidgetTester tester, {
|
||||||
|
MessageFilterService? filter,
|
||||||
|
}) async {
|
||||||
|
final connector = await _connector(tester, filter: filter);
|
||||||
|
final viewState = UiViewStateService()
|
||||||
|
..setChannelsSortOption(ChannelSortOption.latestMessages);
|
||||||
|
await _pumpScreen(tester, connector, viewState, const ChannelsScreen());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> pumpContacts(WidgetTester tester) async {
|
||||||
|
final connector = await _connector(tester);
|
||||||
|
final viewState = UiViewStateService()
|
||||||
|
..setContactsSortOption(ContactSortOption.recentMessages);
|
||||||
|
await _pumpScreen(tester, connector, viewState, const ContactsScreen());
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('Latest messages sorts channels by local arrival, not sender '
|
||||||
|
'clocks far in the future or past', (tester) async {
|
||||||
|
await _seed(
|
||||||
|
channelMessages: {
|
||||||
|
// Oldest arrival, but the sender's clock is decades ahead.
|
||||||
|
'Future Clock': (slot) => [
|
||||||
|
_channelMessage(
|
||||||
|
slot,
|
||||||
|
'from the future',
|
||||||
|
sentAt: _farFuture,
|
||||||
|
receivedAt: _arrived(0),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
// Newest arrival, but the sender's clock is decades behind.
|
||||||
|
'Past Clock': (slot) => [
|
||||||
|
_channelMessage(
|
||||||
|
slot,
|
||||||
|
'from the past',
|
||||||
|
sentAt: _farPast,
|
||||||
|
receivedAt: _arrived(2),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
'Correct Clock': (slot) => [
|
||||||
|
_channelMessage(
|
||||||
|
slot,
|
||||||
|
'on time',
|
||||||
|
sentAt: _arrived(1),
|
||||||
|
receivedAt: _arrived(1),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
'Quiet': (_) => [],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await pumpChannels(tester);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
_screenOrder(tester, [
|
||||||
|
'Future Clock',
|
||||||
|
'Past Clock',
|
||||||
|
'Correct Clock',
|
||||||
|
'Quiet',
|
||||||
|
]),
|
||||||
|
['Past Clock', 'Correct Clock', 'Future Clock', 'Quiet'],
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('A newer message hidden by the message filter does not bump '
|
||||||
|
'its channel', (tester) async {
|
||||||
|
await _seed(
|
||||||
|
channelMessages: {
|
||||||
|
'Spammed': (slot) => [
|
||||||
|
_channelMessage(
|
||||||
|
slot,
|
||||||
|
'real message',
|
||||||
|
sentAt: _arrived(0),
|
||||||
|
receivedAt: _arrived(0),
|
||||||
|
),
|
||||||
|
_channelMessage(
|
||||||
|
slot,
|
||||||
|
'buy now',
|
||||||
|
sentAt: _farFuture,
|
||||||
|
receivedAt: _arrived(5),
|
||||||
|
filterReason: 'rule',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
'Normal': (slot) => [
|
||||||
|
_channelMessage(
|
||||||
|
slot,
|
||||||
|
'hello',
|
||||||
|
sentAt: _arrived(1),
|
||||||
|
receivedAt: _arrived(1),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
final filter = MessageFilterService();
|
||||||
|
addTearDown(filter.dispose);
|
||||||
|
await tester.runAsync(filter.load);
|
||||||
|
await pumpChannels(tester, filter: filter);
|
||||||
|
|
||||||
|
expect(_screenOrder(tester, ['Spammed', 'Normal']), ['Normal', 'Spammed']);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Channels with equal arrival times fall back to name order', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
List<ChannelMessage> same(int slot) => [
|
||||||
|
_channelMessage(slot, 'tie $slot', sentAt: _farFuture, receivedAt: _base),
|
||||||
|
];
|
||||||
|
await _seed(
|
||||||
|
channelMessages: {'Charlie': same, 'Alpha': same, 'Bravo': same},
|
||||||
|
);
|
||||||
|
await pumpChannels(tester);
|
||||||
|
|
||||||
|
expect(_screenOrder(tester, ['Charlie', 'Alpha', 'Bravo']), [
|
||||||
|
'Alpha',
|
||||||
|
'Bravo',
|
||||||
|
'Charlie',
|
||||||
|
]);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Recent messages sorts contacts by local arrival, not sender '
|
||||||
|
'clocks far in the future or past', (tester) async {
|
||||||
|
await _seed(
|
||||||
|
contactMessages: {
|
||||||
|
'Fiona': (key) => [
|
||||||
|
_directMessage(
|
||||||
|
key,
|
||||||
|
'from the future',
|
||||||
|
sentAt: _farFuture,
|
||||||
|
receivedAt: _arrived(0),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
'Paul': (key) => [
|
||||||
|
_directMessage(
|
||||||
|
key,
|
||||||
|
'from the past',
|
||||||
|
sentAt: _farPast,
|
||||||
|
receivedAt: _arrived(2),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
'Carl': (key) => [
|
||||||
|
_directMessage(
|
||||||
|
key,
|
||||||
|
'on time',
|
||||||
|
sentAt: _arrived(1),
|
||||||
|
receivedAt: _arrived(1),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await pumpContacts(tester);
|
||||||
|
|
||||||
|
expect(_screenOrder(tester, ['Fiona', 'Paul', 'Carl']), [
|
||||||
|
'Paul',
|
||||||
|
'Carl',
|
||||||
|
'Fiona',
|
||||||
|
]);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Contacts with equal arrival times fall back to name order', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
List<Message> same(Uint8List key) => [
|
||||||
|
_directMessage(key, 'tie', sentAt: _farPast, receivedAt: _base),
|
||||||
|
];
|
||||||
|
await _seed(contactMessages: {'Zed': same, 'Amy': same, 'Mo': same});
|
||||||
|
await pumpContacts(tester);
|
||||||
|
|
||||||
|
expect(_screenOrder(tester, ['Zed', 'Amy', 'Mo']), ['Amy', 'Mo', 'Zed']);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Contact rows still open after the list was replaced by an '
|
||||||
|
'empty search result', (tester) async {
|
||||||
|
List<Message> none(Uint8List key) => [];
|
||||||
|
await _seed(
|
||||||
|
contactMessages: {
|
||||||
|
'Amy': none,
|
||||||
|
'Ben': none,
|
||||||
|
'Cal': none,
|
||||||
|
'Dee': none,
|
||||||
|
'Eve': none,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
final connector = await _connector(tester);
|
||||||
|
final viewState = UiViewStateService();
|
||||||
|
await _pumpScreen(tester, connector, viewState, const ContactsScreen());
|
||||||
|
expect(find.text('Amy'), findsOneWidget);
|
||||||
|
|
||||||
|
viewState.setContactsSearchText('no such contact');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Amy'), findsNothing);
|
||||||
|
viewState.setContactsSearchText('');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.longPress(find.text('Amy'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
expect(find.byType(BottomSheet), findsOneWidget);
|
||||||
|
Navigator.of(tester.element(find.byType(BottomSheet))).pop();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Amy'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
expect(find.byType(ChatScreen), findsOneWidget);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -132,6 +132,32 @@ void main() {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
test('keeps contact added times out of app settings', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({
|
||||||
|
'app_settings': jsonEncode({'theme_mode': 'dark'}),
|
||||||
|
'contact_added_at_0011223344': jsonEncode({'aa': 1}),
|
||||||
|
});
|
||||||
|
PrefsManager.reset();
|
||||||
|
await PrefsManager.initialize();
|
||||||
|
addTearDown(PrefsManager.reset);
|
||||||
|
final connector = MeshCoreConnector();
|
||||||
|
addTearDown(connector.dispose);
|
||||||
|
|
||||||
|
final json = await const BackupService().createBackup(
|
||||||
|
items: {BackupItem.appSettings},
|
||||||
|
connector: connector,
|
||||||
|
settings: AppSettings(),
|
||||||
|
password: '',
|
||||||
|
);
|
||||||
|
final payload = jsonDecode(json) as Map<String, dynamic>;
|
||||||
|
final section =
|
||||||
|
(payload['sections'] as Map<String, dynamic>)['appSettings']
|
||||||
|
as Map<String, dynamic>;
|
||||||
|
final preferences = section['preferences'] as Map<String, dynamic>;
|
||||||
|
expect(preferences, contains('app_settings'));
|
||||||
|
expect(preferences, isNot(contains('contact_added_at_0011223344')));
|
||||||
|
});
|
||||||
|
|
||||||
test('backs up a sensitive key without unrelated app settings', () async {
|
test('backs up a sensitive key without unrelated app settings', () async {
|
||||||
SharedPreferences.setMockInitialValues({
|
SharedPreferences.setMockInitialValues({
|
||||||
'app_settings': jsonEncode({
|
'app_settings': jsonEncode({
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:meshcore_open/l10n/app_localizations_en.dart';
|
||||||
|
import 'package:meshcore_open/models/contact.dart';
|
||||||
|
import 'package:meshcore_open/widgets/contact_visuals.dart';
|
||||||
|
|
||||||
|
Contact _contact(int seed, {required DateTime lastSeen, DateTime? message}) =>
|
||||||
|
Contact(
|
||||||
|
publicKey: Uint8List.fromList(List.filled(32, seed)),
|
||||||
|
name: 'c$seed',
|
||||||
|
type: 1,
|
||||||
|
pathLength: -1,
|
||||||
|
path: Uint8List(0),
|
||||||
|
lastSeen: lastSeen,
|
||||||
|
lastMessageAt: message,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final epoch = DateTime.fromMillisecondsSinceEpoch(0);
|
||||||
|
final now = DateTime.now();
|
||||||
|
|
||||||
|
test('added time orders a contact the radio has no advert time for', () {
|
||||||
|
final added = now.subtract(const Duration(minutes: 1));
|
||||||
|
final fromCard = _contact(1, lastSeen: epoch);
|
||||||
|
final heardHourAgo = _contact(
|
||||||
|
2,
|
||||||
|
lastSeen: now.subtract(const Duration(hours: 1)),
|
||||||
|
);
|
||||||
|
final addedAt = {fromCard: added};
|
||||||
|
final sorted = [heardHourAgo, fromCard]
|
||||||
|
..sort(
|
||||||
|
(a, b) => resolveContactLastSeen(
|
||||||
|
b,
|
||||||
|
addedAt: addedAt[b],
|
||||||
|
).compareTo(resolveContactLastSeen(a, addedAt: addedAt[a])),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolveContactLastSeen(fromCard, addedAt: added), added);
|
||||||
|
expect(sorted.first, fromCard);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a real advert time is never replaced by the added time', () {
|
||||||
|
final advert = now.subtract(const Duration(days: 30));
|
||||||
|
final contact = _contact(3, lastSeen: advert);
|
||||||
|
|
||||||
|
expect(resolveContactLastSeen(contact, addedAt: now), advert);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a newer message still wins over the added time', () {
|
||||||
|
final message = now;
|
||||||
|
final contact = _contact(4, lastSeen: epoch, message: message);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
resolveContactLastSeen(
|
||||||
|
contact,
|
||||||
|
addedAt: now.subtract(const Duration(hours: 1)),
|
||||||
|
),
|
||||||
|
message,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a contact never heard shows "not heard yet", not decades ago', () {
|
||||||
|
final l10n = AppLocalizationsEn();
|
||||||
|
|
||||||
|
expect(formatContactLastSeen(l10n, epoch), l10n.contacts_lastSeenNever);
|
||||||
|
expect(
|
||||||
|
resolveContactLastSeen(_contact(5, lastSeen: epoch)),
|
||||||
|
epoch,
|
||||||
|
reason: 'display label is driven by the advert/message time only',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user