commit e7a5b9e20938977bc8d93b870e044098ab4ab2c6 Author: zach Date: Fri Dec 26 11:42:02 2025 -0700 Initial commit: MeshCore Open Flutter client Open-source Flutter client for MeshCore LoRa mesh networking devices. Features: - BLE device scanning and connection - Nordic UART Service (NUS) integration - Material 3 design with system theme support - Provider-based state management - Placeholder screens for chat, contacts, and settings 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..97cafdb7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,82 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Flutter plugin generated files +.flutter-plugins +.flutter-plugins-dependencies + +# Environment and secrets +.env +*.env +secrets.dart + +# macOS +.DS_Store +.AppleDouble +.LSOverride + +# iOS +**/ios/Pods/ +**/ios/.symlinks/ +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Flutter.podspec + +# Android +**/android/.gradle/ +**/android/captures/ +**/android/local.properties +**/android/.externalNativeBuild/ +*.jks +keystore.properties + +# Generated files +*.g.dart +*.freezed.dart +*.mocks.dart + +# IDE +.vscode/launch.json +.vscode/settings.json diff --git a/.metadata b/.metadata new file mode 100644 index 00000000..5f4336f9 --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "adc901062556672b4138e18a4dc62a4be8f4b3c2" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + - platform: android + create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + - platform: ios + create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + - platform: linux + create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + - platform: macos + create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + - platform: web + create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + - platform: windows + create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..bac981d4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,34 @@ +# Repository Guidelines + +## Project Structure & Module Organization +- Core Flutter code is in `lib/`, with BLE protocol definitions in `lib/connector/meshcore_protocol.dart` and BLE transport/state in `lib/connector/meshcore_connector.dart`. +- UI lives in `lib/screens/` and `lib/widgets/`, models in `lib/models/`, tests in `test/`, and platform runners in `android/`, `ios/`, `macos/`, `linux/`, `windows/`, `web/`. + +## BLE Frames & Protocol Notes +- Nordic UART Service (NUS) UUIDs: Service `6e400001-b5a3-f393-e0a9-e50e24dcca9e`, RX `6e400002-b5a3-f393-e0a9-e50e24dcca9e`, TX `6e400003-b5a3-f393-e0a9-e50e24dcca9e`. +- Discovery: scans for device name prefix `MeshCore-` and filters by `platformName`/`advertisementData.advName`. +- Frames are capped at `maxFrameSize = 172` bytes; byte 0 is the command/response/push code. I/O is `MeshCoreConnector.sendFrame` and `MeshCoreConnector.receivedFrames`. +- Command codes (to device): `cmdAppStart`=1, `cmdSendTxtMsg`=2, `cmdSendChannelTxtMsg`=3, `cmdGetContacts`=4, `cmdGetDeviceTime`=5, `cmdSetDeviceTime`=6, `cmdSendSelfAdvert`=7, `cmdSetAdvertName`=8, `cmdAddUpdateContact`=9, `cmdSyncNextMessage`=10, `cmdSetRadioParams`=11, `cmdSetRadioTxPower`=12, `cmdResetPath`=13, `cmdSetAdvertLatLon`=14, `cmdRemoveContact`=15, `cmdShareContact`=16, `cmdExportContact`=17, `cmdImportContact`=18, `cmdReboot`=19, `cmdSendLogin`=26, `cmdGetChannel`=31, `cmdSetChannel`=32, `cmdGetRadioSettings`=57. +- Response codes (from device): `respCodeOk`=0, `respCodeErr`=1, `respCodeContactsStart`=2, `respCodeContact`=3, `respCodeEndOfContacts`=4, `respCodeSelfInfo`=5, `respCodeSent`=6, `respCodeContactMsgRecv`=7, `respCodeChannelMsgRecv`=8, `respCodeCurrTime`=9, `respCodeNoMoreMessages`=10, `respCodeContactMsgRecvV3`=16, `respCodeChannelMsgRecvV3`=17, `respCodeChannelInfo`=18, `respCodeRadioSettings`=25. +- Push codes (async): `pushCodeAdvert`=0x80, `pushCodePathUpdated`=0x81, `pushCodeSendConfirmed`=0x82, `pushCodeMsgWaiting`=0x83, `pushCodeLoginSuccess`=0x85, `pushCodeLoginFail`=0x86, `pushCodeLogRxData`=0x88, `pushCodeNewAdvert`=0x8A. +- Device info: `cmdAppStart` triggers `respCodeSelfInfo` with tx power, pubkey, lat/lon, telemetry flags, radio params, and node name (see offsets in `lib/connector/meshcore_connector.dart`). +- Radio/time helpers: `cmdGetRadioSettings` → `respCodeRadioSettings`; `cmdGetDeviceTime` → `respCodeCurrTime`; `cmdSetDeviceTime` updates device time. +- Reboot: the UI sends `sendCliCommand('reboot')` (the raw `cmdReboot` code exists but no frame builder is wired in yet). +- Companion radio format: `cmdSendTxtMsg` expects `[cmd][txt_type][attempt][timestamp x4][pub_key_prefix x6][text...]` (no flags/full pubkey). CLI commands use `txtTypeCliData` in the same format, and the app maps `forceFlood` to attempt `3` when sending. +- Group text packets (`PAYLOAD_TYPE_GRP_TXT`): payload is `[channel_hash (1)][MAC (2)][encrypted data...]`. Decrypted data layout is `[timestamp x4][txt_type][text...]` where text is `"sender: message"` (see MeshCore `BaseChatMesh::sendGroupMessage`). Sender identity is not in the payload; use `PUSH_CODE_LOG_RX_DATA` raw packet path bytes for origin hash when available. +- Identity hash: `PATH_HASH_SIZE` is 1 byte; it is the prefix of the public key (see `Identity::copyHashTo`). Flooded packets append this hash to the path as they traverse hops. Self-identification via log data should compare sender name and presence of self pubkey prefix within the path bytes. + +## Build, Test, and Development Commands +- `~/flutter/bin/flutter pub get` installs dependencies (or `flutter pub get` if Flutter is on PATH). +- `~/flutter/bin/flutter run` launches the app; `~/flutter/bin/flutter build apk|ios` produces release builds. +- `~/flutter/bin/flutter analyze` and `~/flutter/bin/flutter test` run linting and tests. + +## Coding Style & Naming Conventions +- Follow `flutter_lints`, use `lowerCamelCase`/`UpperCamelCase`/`snake_case`, prefer `StatelessWidget` + `Consumer`, and use `const` constructors. +- Material widgets only; keep screens simple, handle disconnects by returning to the scanner, and avoid premature abstractions. + +## Testing Guidelines +- Tests use `flutter_test`; add `*_test.dart` under `test/` and run `flutter test` before UI/protocol changes. + +## Commit & Pull Request Guidelines +- Keep commit subjects short and action-focused; PRs should describe behavior changes, link issues, include screenshots for UI changes, and call out BLE protocol changes explicitly. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..08ef342f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,136 @@ +# MeshCore Open - Flutter Client + +Open-source Flutter client for MeshCore LoRa mesh networking devices. + +## Build Commands + +```bash +# Install dependencies +~/flutter/bin/flutter pub get + +# Run in debug mode +~/flutter/bin/flutter run + +# Build Android APK +~/flutter/bin/flutter build apk + +# Build iOS +~/flutter/bin/flutter build ios + +# Run static analysis +~/flutter/bin/flutter analyze + +# Run tests +~/flutter/bin/flutter test +``` + +## Project Structure + +``` +lib/ +├── main.dart # App entry point, MaterialApp setup with Provider +├── connector/ +│ └── meshcore_connector.dart # BLE communication layer (MeshCoreConnector) +├── screens/ +│ ├── scanner_screen.dart # BLE device scanning (home screen) +│ ├── device_screen.dart # Connected device hub with navigation +│ ├── chat_screen.dart # Chat interface (placeholder) +│ ├── contacts_screen.dart # Contacts list (placeholder) +│ └── settings_screen.dart # Device info and app settings +└── widgets/ + └── device_tile.dart # Device list item with signal strength +``` + +## Architecture + +### State Management +- **Provider** with `ChangeNotifier` pattern +- `MeshCoreConnector` is the central state holder for BLE connection +- Screens use `Consumer` for reactive UI updates + +### Theming +- Material 3 design (`useMaterial3: true`) +- System-based dark/light mode (`ThemeMode.system`) +- Blue color scheme seed + +## BLE Protocol + +### Nordic UART Service (NUS) +- **Service UUID**: `6e400001-b5a3-f393-e0a9-e50e24dcca9e` +- **RX Characteristic**: `6e400002-b5a3-f393-e0a9-e50e24dcca9e` (Write to device) +- **TX Characteristic**: `6e400003-b5a3-f393-e0a9-e50e24dcca9e` (Notify from device) + +### Device Discovery +- Scans for devices with name prefix `MeshCore-` +- Filters by `platformName` or `advertisementData.advName` + +### Connection States +```dart +enum MeshCoreConnectionState { + disconnected, + scanning, + connecting, + connected, + disconnecting, +} +``` + +### Frame I/O +- **Send**: `MeshCoreConnector.sendFrame(Uint8List data)` +- **Receive**: `MeshCoreConnector.receivedFrames` stream of `Uint8List` + +## Dependencies + +| Package | Version | Purpose | +|---------|---------|---------| +| flutter_blue_plus | ^2.1.0 | BLE communication | +| provider | ^6.1.5+1 | State management | +| cupertino_icons | ^1.0.8 | iOS-style icons | + +## Platform Configuration + +### Android (`android/app/src/main/AndroidManifest.xml`) +- `BLUETOOTH`, `BLUETOOTH_ADMIN` (API 30 and below) +- `BLUETOOTH_SCAN`, `BLUETOOTH_CONNECT`, `BLUETOOTH_ADVERTISE` (API 31+) +- `ACCESS_FINE_LOCATION`, `ACCESS_COARSE_LOCATION` (for BLE scanning) + +### iOS (`ios/Runner/Info.plist`) +- `NSBluetoothAlwaysUsageDescription` +- `NSBluetoothPeripheralUsageDescription` + +## Coding Conventions + +### Code Philosophy +- **Minimal**: Only write code that is necessary. Avoid over-engineering. +- **Organized**: Keep related code together. One responsibility per file. +- **Maintainable**: Favor readability over cleverness. Simple is better. + +### Style +- Use `StatelessWidget` with `Consumer` for state-dependent UI +- Use `const` constructors where possible +- Prefix private methods/fields with `_` +- Center app bar titles (`centerTitle: true`) +- **Material widgets only** - no Cupertino or custom widgets +- Handle disconnection gracefully (auto-navigate back to scanner) + +### Avoid +- Premature abstractions - don't create helpers until needed in 3+ places +- Unnecessary comments - code should be self-explanatory +- Feature flags or backwards-compatibility shims +- Over-engineered error handling for impossible scenarios + +## Key Files + +| File | Purpose | +|------|---------| +| `lib/connector/meshcore_connector.dart` | All BLE logic - scanning, connecting, data transfer | +| `lib/screens/scanner_screen.dart` | Entry point UI, device list | +| `lib/main.dart` | App configuration, theme, Provider setup | +| `pubspec.yaml` | Dependencies and project metadata | + +## Placeholder Screens + +The following screens are implemented as placeholders and need full implementation: +- `chat_screen.dart` - Mesh chat functionality +- `contacts_screen.dart` - Contact management +- `settings_screen.dart` - Radio settings, node identity, location (partially implemented) diff --git a/README.md b/README.md new file mode 100644 index 00000000..8c9e5bce --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# meshcore_open + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 00000000..0d290213 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 00000000..be3943c9 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 00000000..d9723d2e --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.meshcore.meshcore_open" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + isCoreLibraryDesugaringEnabled = true + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.meshcore.meshcore_open" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} + +dependencies { + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.4") +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000..399f6981 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..1f6da2dc --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt b/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt new file mode 100644 index 00000000..4350b1e1 --- /dev/null +++ b/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt @@ -0,0 +1,5 @@ +package com.meshcore.meshcore_open + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 00000000..f74085f3 --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 00000000..304732f8 --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..db77bb4b Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..17987b79 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..09d43914 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..d5f1c8d3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..4d6372ee Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 00000000..06952be7 --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..cb1ef880 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 00000000..399f6981 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 00000000..dbee657b --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 00000000..f018a618 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ac3b4792 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 00000000..fb605bc8 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.9.1" apply false + id("org.jetbrains.kotlin.android") version "2.1.0" apply false +} + +include(":app") diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 00000000..7a7f9873 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 00000000..1dc6cf76 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 13.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 00000000..592ceee8 --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 00000000..592ceee8 --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..1cf3a4aa --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,616 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000..e3773d42 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..1d526a16 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 00000000..62666446 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..d36b1fab --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 00000000..dc9ada47 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 00000000..7353c41e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 00000000..797d452e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 00000000..6ed2d933 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 00000000..4cd7b009 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 00000000..fe730945 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 00000000..321773cd Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 00000000..797d452e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 00000000..502f463a Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 00000000..0ec30343 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 00000000..0ec30343 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 00000000..e9f5fea2 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 00000000..84ac32ae Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 00000000..8953cba0 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 00000000..0467bf12 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 00000000..0bedcf2f --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 00000000..89c2725b --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..f2e259c7 --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 00000000..f3c28516 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 00000000..2b505d0b --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,53 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Meshcore Open + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + meshcore_open + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + NSBluetoothAlwaysUsageDescription + This app uses Bluetooth to communicate with MeshCore devices. + NSBluetoothPeripheralUsageDescription + This app uses Bluetooth to communicate with MeshCore devices. + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 00000000..308a2a56 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000..86a7c3b1 --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart new file mode 100644 index 00000000..c756dfa9 --- /dev/null +++ b/lib/connector/meshcore_connector.dart @@ -0,0 +1,1595 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart' as crypto; +import 'package:pointycastle/export.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_blue_plus/flutter_blue_plus.dart'; + +import '../models/channel.dart'; +import '../models/channel_message.dart'; +import '../models/contact.dart'; +import '../models/message.dart'; +import '../models/path_selection.dart'; +import '../helpers/smaz.dart'; +import '../services/ble_debug_log_service.dart'; +import '../services/message_retry_service.dart'; +import '../services/path_history_service.dart'; +import '../services/app_settings_service.dart'; +import '../services/notification_service.dart'; +import '../storage/channel_message_store.dart'; +import '../storage/channel_order_store.dart'; +import '../storage/channel_settings_store.dart'; +import '../storage/contact_store.dart'; +import '../storage/message_store.dart'; +import 'meshcore_protocol.dart'; + +class MeshCoreUuids { + static const String service = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"; + static const String rxCharacteristic = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"; + static const String txCharacteristic = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"; +} + +enum MeshCoreConnectionState { + disconnected, + scanning, + connecting, + connected, + disconnecting, +} + +class MeshCoreConnector extends ChangeNotifier { + MeshCoreConnectionState _state = MeshCoreConnectionState.disconnected; + BluetoothDevice? _device; + BluetoothCharacteristic? _rxCharacteristic; + BluetoothCharacteristic? _txCharacteristic; + + final List _scanResults = []; + final List _contacts = []; + final List _channels = []; + final Map> _conversations = {}; + final Map> _channelMessages = {}; + final Set _loadedConversationKeys = {}; + + StreamSubscription>? _scanSubscription; + StreamSubscription? _connectionSubscription; + StreamSubscription>? _notifySubscription; + Timer? _selfInfoRetryTimer; + + final StreamController _receivedFramesController = + StreamController.broadcast(); + + Uint8List? _selfPublicKey; + String? _selfName; + int? _currentTxPower; + int? _maxTxPower; + int? _currentFreqHz; + int? _currentBwHz; + int? _currentSf; + int? _currentCr; + int? _batteryMillivolts; + double? _selfLatitude; + double? _selfLongitude; + bool _isLoadingContacts = false; + bool _isLoadingChannels = false; + bool _batteryRequested = false; + bool _awaitingSelfInfo = false; + bool _preserveContactsOnRefresh = false; + static const int _defaultMaxContacts = 32; + static const int _defaultMaxChannels = 8; + int _maxContacts = _defaultMaxContacts; + int _maxChannels = _defaultMaxChannels; + bool _isSyncingQueuedMessages = false; + bool _queuedMessageSyncInFlight = false; + bool _didInitialQueueSync = false; + bool _pendingQueueSync = false; + + // Services + MessageRetryService? _retryService; + PathHistoryService? _pathHistoryService; + AppSettingsService? _appSettingsService; + final NotificationService _notificationService = NotificationService(); + BleDebugLogService? _bleDebugLogService; + final ChannelMessageStore _channelMessageStore = ChannelMessageStore(); + final MessageStore _messageStore = MessageStore(); + final ChannelOrderStore _channelOrderStore = ChannelOrderStore(); + final ChannelSettingsStore _channelSettingsStore = ChannelSettingsStore(); + final ContactStore _contactStore = ContactStore(); + final Map _channelSmazEnabled = {}; + final Set _knownContactKeys = {}; + List _channelOrder = []; + + // Getters + MeshCoreConnectionState get state => _state; + BluetoothDevice? get device => _device; + List get scanResults => List.unmodifiable(_scanResults); + List get contacts => List.unmodifiable(_contacts); + List get channels => List.unmodifiable(_channels); + bool get isConnected => _state == MeshCoreConnectionState.connected; + bool get isLoadingContacts => _isLoadingContacts; + bool get isLoadingChannels => _isLoadingChannels; + Stream get receivedFrames => _receivedFramesController.stream; + Uint8List? get selfPublicKey => _selfPublicKey; + String? get selfName => _selfName; + double? get selfLatitude => _selfLatitude; + double? get selfLongitude => _selfLongitude; + int? get currentTxPower => _currentTxPower; + int? get maxTxPower => _maxTxPower; + int? get currentFreqHz => _currentFreqHz; + int? get currentBwHz => _currentBwHz; + int? get currentSf => _currentSf; + int? get currentCr => _currentCr; + int? get batteryMillivolts => _batteryMillivolts; + int get maxContacts => _maxContacts; + int get maxChannels => _maxChannels; + bool get isSyncingQueuedMessages => _isSyncingQueuedMessages; + int? get batteryPercent => _batteryMillivolts == null + ? null + : _estimateBatteryPercent( + _batteryMillivolts!, + _batteryChemistryForDevice(), + ); + + String _batteryChemistryForDevice() { + final deviceId = _device?.remoteId.toString(); + if (deviceId == null || _appSettingsService == null) return 'nmc'; + return _appSettingsService!.batteryChemistryForDevice(deviceId); + } + + int _estimateBatteryPercent(int millivolts, String chemistry) { + final range = _batteryVoltageRange(chemistry); + final minMv = range.$1; + final maxMv = range.$2; + if (millivolts <= minMv) return 0; + if (millivolts >= maxMv) return 100; + return (((millivolts - minMv) * 100) / (maxMv - minMv)).round(); + } + + (int, int) _batteryVoltageRange(String chemistry) { + switch (chemistry) { + case 'lifepo4': + return (2600, 3650); + case 'lipo': + return (3000, 4200); + case 'nmc': + default: + return (3000, 4200); + } + } + + List getMessages(Contact contact) { + return _conversations[contact.publicKeyHex] ?? []; + } + + Future _loadMessagesForContact(String contactKeyHex) async { + if (_loadedConversationKeys.contains(contactKeyHex)) return; + _loadedConversationKeys.add(contactKeyHex); + + final messages = await _messageStore.loadMessages(contactKeyHex); + if (messages.isNotEmpty) { + _conversations[contactKeyHex] = messages; + notifyListeners(); + } + } + + List getChannelMessages(Channel channel) { + return _channelMessages[channel.index] ?? []; + } + + bool isChannelSmazEnabled(int channelIndex) { + return _channelSmazEnabled[channelIndex] ?? false; + } + + Future setChannelSmazEnabled(int channelIndex, bool enabled) async { + _channelSmazEnabled[channelIndex] = enabled; + await _channelSettingsStore.saveSmazEnabled(channelIndex, enabled); + notifyListeners(); + } + + Future _loadChannelOrder() async { + _channelOrder = await _channelOrderStore.loadChannelOrder(); + _applyChannelOrder(); + notifyListeners(); + } + + /// Load persisted channel messages for a specific channel + Future _loadChannelMessages(int channelIndex) async { + final messages = await _channelMessageStore.loadChannelMessages(channelIndex); + if (messages.isNotEmpty) { + _channelMessages[channelIndex] = messages; + notifyListeners(); + } + } + + /// Load all persisted channel messages on startup + Future loadAllChannelMessages({int? maxChannels}) async { + final channelCount = maxChannels ?? _maxChannels; + // Load messages for all known channels (0-7 by default) + for (int i = 0; i < channelCount; i++) { + await _loadChannelMessages(i); + } + } + + void initialize({ + required MessageRetryService retryService, + required PathHistoryService pathHistoryService, + AppSettingsService? appSettingsService, + BleDebugLogService? bleDebugLogService, + }) { + _retryService = retryService; + _pathHistoryService = pathHistoryService; + _appSettingsService = appSettingsService; + _bleDebugLogService = bleDebugLogService; + + // Initialize notification service + _notificationService.initialize(); + _loadChannelOrder(); + + // Initialize retry service callbacks + _retryService?.initialize( + sendMessageCallback: _sendMessageDirect, + addMessageCallback: _addMessage, + updateMessageCallback: _updateMessage, + clearContactPathCallback: clearContactPath, + calculateTimeoutCallback: (pathLength, messageBytes) => + calculateTimeout(pathLength: pathLength, messageBytes: messageBytes), + appSettingsService: appSettingsService, + recordPathResultCallback: _recordPathResult, + ); + } + + Future loadContactCache() async { + final cached = await _contactStore.loadContacts(); + _knownContactKeys + ..clear() + ..addAll(cached.map((c) => c.publicKeyHex)); + } + + Future loadChannelSettings({int? maxChannels}) async { + _channelSmazEnabled.clear(); + final channelCount = maxChannels ?? _maxChannels; + for (int i = 0; i < channelCount; i++) { + _channelSmazEnabled[i] = await _channelSettingsStore.loadSmazEnabled(i); + } + } + + void _sendMessageDirect( + Contact contact, + String text, + bool forceFlood, + int attempt, + int timestampSeconds, + ) async { + if (!isConnected || text.isEmpty) return; + await sendFrame( + buildSendTextMsgFrame( + contact.publicKey, + text, + forceFlood: forceFlood, + attempt: attempt, + timestampSeconds: timestampSeconds, + ), + ); + } + + void _updateMessage(Message message) { + final contactKey = pubKeyToHex(message.senderKey); + final messages = _conversations[contactKey]; + if (messages != null) { + final index = messages.indexWhere((m) => m.messageId == message.messageId); + if (index != -1) { + messages[index] = message; + _messageStore.saveMessages(contactKey, messages); + notifyListeners(); + } + } + } + + void _recordPathResult( + String contactPubKeyHex, + PathSelection selection, + bool success, + int? tripTimeMs, + ) { + if (_pathHistoryService == null) return; + _pathHistoryService!.recordPathResult( + contactPubKeyHex, + selection, + success: success, + tripTimeMs: tripTimeMs, + ); + } + + Contact _applyAutoSelection(Contact contact, PathSelection? selection) { + if (selection == null || selection.useFlood || selection.pathBytes.isEmpty) { + return contact; + } + + return Contact( + publicKey: contact.publicKey, + name: contact.name, + type: contact.type, + pathLength: selection.hopCount >= 0 ? selection.hopCount : contact.pathLength, + path: Uint8List.fromList(selection.pathBytes), + latitude: contact.latitude, + longitude: contact.longitude, + lastSeen: contact.lastSeen, + ); + } + + Future startScan({Duration timeout = const Duration(seconds: 10)}) async { + if (_state == MeshCoreConnectionState.scanning) return; + + _scanResults.clear(); + _setState(MeshCoreConnectionState.scanning); + + _scanSubscription = FlutterBluePlus.scanResults.listen((results) { + _scanResults.clear(); + for (var result in results) { + if (result.device.platformName.startsWith("MeshCore-") || + result.advertisementData.advName.startsWith("MeshCore-")) { + _scanResults.add(result); + } + } + notifyListeners(); + }); + + await FlutterBluePlus.startScan( + timeout: timeout, + androidScanMode: AndroidScanMode.lowLatency, + ); + + await Future.delayed(timeout); + await stopScan(); + } + + Future stopScan() async { + await FlutterBluePlus.stopScan(); + await _scanSubscription?.cancel(); + _scanSubscription = null; + + if (_state == MeshCoreConnectionState.scanning) { + _setState(MeshCoreConnectionState.disconnected); + } + } + + Future connect(BluetoothDevice device) async { + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + return; + } + + await stopScan(); + _setState(MeshCoreConnectionState.connecting); + _device = device; + + try { + _connectionSubscription = device.connectionState.listen((state) { + if (state == BluetoothConnectionState.disconnected) { + _handleDisconnection(); + } + }); + + await device.connect( + timeout: const Duration(seconds: 15), + mtu: null, + license: License.free, + ); + + // Request larger MTU for sending larger frames + try { + final mtu = await device.requestMtu(185); + debugPrint('MTU set to: $mtu'); + } catch (e) { + debugPrint('MTU request failed: $e, using default'); + } + + List services = await device.discoverServices(); + + BluetoothService? uartService; + for (var service in services) { + if (service.uuid.toString().toLowerCase() == MeshCoreUuids.service) { + uartService = service; + break; + } + } + + if (uartService == null) { + throw Exception("MeshCore UART service not found"); + } + + for (var characteristic in uartService.characteristics) { + String uuid = characteristic.uuid.toString().toLowerCase(); + if (uuid == MeshCoreUuids.rxCharacteristic) { + _rxCharacteristic = characteristic; + } else if (uuid == MeshCoreUuids.txCharacteristic) { + _txCharacteristic = characteristic; + } + } + + if (_rxCharacteristic == null || _txCharacteristic == null) { + throw Exception("MeshCore characteristics not found"); + } + + await _txCharacteristic!.setNotifyValue(true); + _notifySubscription = _txCharacteristic!.onValueReceived.listen(_handleFrame); + + _setState(MeshCoreConnectionState.connected); + + await _requestDeviceInfo(); + + // Keep device clock aligned on every connection. + await syncTime(); + } catch (e) { + debugPrint("Connection error: $e"); + await disconnect(); + rethrow; + } + } + + Future disconnect() async { + if (_state == MeshCoreConnectionState.disconnecting) return; + + _setState(MeshCoreConnectionState.disconnecting); + + await _notifySubscription?.cancel(); + _notifySubscription = null; + + await _connectionSubscription?.cancel(); + _connectionSubscription = null; + _selfInfoRetryTimer?.cancel(); + _selfInfoRetryTimer = null; + + try { + await _device?.disconnect(); + } catch (e) { + debugPrint("Disconnect error: $e"); + } + + _device = null; + _rxCharacteristic = null; + _txCharacteristic = null; + _contacts.clear(); + _conversations.clear(); + _loadedConversationKeys.clear(); + _selfPublicKey = null; + _selfName = null; + _selfLatitude = null; + _selfLongitude = null; + _batteryMillivolts = null; + _batteryRequested = false; + _awaitingSelfInfo = false; + _maxContacts = _defaultMaxContacts; + _maxChannels = _defaultMaxChannels; + _isSyncingQueuedMessages = false; + _queuedMessageSyncInFlight = false; + _didInitialQueueSync = false; + _pendingQueueSync = false; + _pendingQueueSync = false; + _didInitialQueueSync = false; + + _setState(MeshCoreConnectionState.disconnected); + } + + Future sendFrame(Uint8List data) async { + if (!isConnected || _rxCharacteristic == null) { + throw Exception("Not connected to a MeshCore device"); + } + + _bleDebugLogService?.logFrame(data, outgoing: true); + + // Prefer write without response when supported; fall back to write with response. + final properties = _rxCharacteristic!.properties; + final canWriteWithoutResponse = properties.writeWithoutResponse; + final canWriteWithResponse = properties.write; + if (!canWriteWithoutResponse && !canWriteWithResponse) { + throw Exception("MeshCore RX characteristic does not support write"); + } + + await _rxCharacteristic!.write( + data.toList(), + withoutResponse: canWriteWithoutResponse, + ); + } + + Future requestBatteryStatus({bool force = false}) async { + if (!isConnected) return; + if (_batteryRequested && !force) return; + _batteryRequested = true; + await sendFrame(buildGetBattAndStorageFrame()); + } + + Future refreshDeviceInfo() async { + if (!isConnected) return; + _awaitingSelfInfo = true; + await sendFrame(buildDeviceQueryFrame()); + await sendFrame(buildAppStartFrame()); + await requestBatteryStatus(force: true); + await sendFrame(buildGetRadioSettingsFrame()); + } + + Future _requestDeviceInfo() async { + _awaitingSelfInfo = true; + await sendFrame(buildDeviceQueryFrame()); + await sendFrame(buildAppStartFrame()); + await requestBatteryStatus(); + + _selfInfoRetryTimer?.cancel(); + _selfInfoRetryTimer = Timer(const Duration(milliseconds: 3500), () { + if (!isConnected || !_awaitingSelfInfo) return; + sendFrame(buildAppStartFrame()); + }); + } + + Future getContacts({int? since, bool preserveExisting = false}) async { + if (!isConnected) return; + + _isLoadingContacts = true; + _preserveContactsOnRefresh = preserveExisting; + if (!preserveExisting) { + _contacts.clear(); + notifyListeners(); + } + + await sendFrame(buildGetContactsFrame(since: since)); + } + + Future refreshContacts() async { + await getContacts(preserveExisting: true); + } + + Future refreshContactsSinceLastmod() async { + await getContacts( + since: _latestContactLastmod(), + preserveExisting: true, + ); + } + + Future sendMessage( + Contact contact, + String text, { + bool forceFlood = false, + Uint8List? customPath, + int? customPathLen, + }) async { + if (!isConnected || text.isEmpty) return; + + // If custom path is provided, temporarily update the contact's path + if (customPath != null && customPathLen != null && customPathLen >= 0) { + await setContactPath(contact, customPath, customPathLen); + // Small delay to ensure the path update is processed + await Future.delayed(const Duration(milliseconds: 50)); + } + + PathSelection? autoSelection; + if (customPath == null && + _appSettingsService?.settings.autoRouteRotationEnabled == true && + !forceFlood) { + autoSelection = _pathHistoryService?.getNextAutoPathSelection(contact.publicKeyHex); + if (autoSelection != null) { + _pathHistoryService?.recordPathAttempt(contact.publicKeyHex, autoSelection); + if (!autoSelection.useFlood && autoSelection.pathBytes.isNotEmpty) { + await setContactPath( + contact, + Uint8List.fromList(autoSelection.pathBytes), + autoSelection.pathBytes.length, + ); + await Future.delayed(const Duration(milliseconds: 50)); + } + } + } + + if (_retryService != null) { + final pathBytes = + _resolveOutgoingPathBytes(contact, customPath, customPathLen, forceFlood, autoSelection); + final pathLength = + _resolveOutgoingPathLength(contact, customPathLen, forceFlood, autoSelection); + final selectedContact = _applyAutoSelection(contact, autoSelection); + await _retryService!.sendMessageWithRetry( + contact: selectedContact, + text: text, + forceFlood: forceFlood, + pathSelection: autoSelection, + pathBytes: pathBytes, + pathLength: pathLength, + ); + } else { + // Fallback to old behavior if retry service not initialized + final pathBytes = _resolveOutgoingPathBytes(contact, customPath, customPathLen, forceFlood, autoSelection); + final pathLength = _resolveOutgoingPathLength(contact, customPathLen, forceFlood, autoSelection); + final message = Message.outgoing( + contact.publicKey, + text, + pathLength: pathLength, + pathBytes: pathBytes, + ); + _addMessage(contact.publicKeyHex, message); + notifyListeners(); + await sendFrame(buildSendTextMsgFrame(contact.publicKey, text, forceFlood: forceFlood)); + } + } + + Future setContactPath(Contact contact, Uint8List customPath, int pathLen) async { + if (!isConnected) return; + + await sendFrame(buildUpdateContactPathFrame( + contact.publicKey, + customPath, + pathLen, + type: contact.type, + name: contact.name, + )); + } + + Future sendChannelMessage(Channel channel, String text) async { + if (!isConnected || text.isEmpty) return; + + final message = ChannelMessage.outgoing(text, _selfName ?? 'Me', channel.index); + _addChannelMessage(channel.index, message); + notifyListeners(); + + final trimmed = text.trim(); + final isStructuredPayload = trimmed.startsWith('g:') || trimmed.startsWith('m:'); + final outboundText = (isChannelSmazEnabled(channel.index) && !isStructuredPayload) + ? Smaz.encodeIfSmaller(text) + : text; + await sendFrame(buildSendChannelTextMsgFrame(channel.index, outboundText)); + } + + Future removeContact(Contact contact) async { + if (!isConnected) return; + + await sendFrame(buildRemoveContactFrame(contact.publicKey)); + _contacts.removeWhere((c) => c.publicKeyHex == contact.publicKeyHex); + _knownContactKeys.remove(contact.publicKeyHex); + unawaited(_persistContacts()); + _conversations.remove(contact.publicKeyHex); + _loadedConversationKeys.remove(contact.publicKeyHex); + _messageStore.clearMessages(contact.publicKeyHex); + notifyListeners(); + } + + Future clearContactPath(Contact contact) async { + if (!isConnected) return; + + await sendFrame(buildResetPathFrame(contact.publicKey)); + final existingIndex = + _contacts.indexWhere((c) => c.publicKeyHex == contact.publicKeyHex); + if (existingIndex >= 0) { + final existing = _contacts[existingIndex]; + _contacts[existingIndex] = Contact( + publicKey: existing.publicKey, + name: existing.name, + type: existing.type, + pathLength: -1, + path: Uint8List(0), + latitude: existing.latitude, + longitude: existing.longitude, + lastSeen: existing.lastSeen, + ); + notifyListeners(); + unawaited(_persistContacts()); + } + // The device will send updated contact info with path_len = -1 + } + + Future syncTime() async { + if (!isConnected) return; + + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + await sendFrame(buildSetDeviceTimeFrame(now)); + } + + Future syncQueuedMessages({bool force = false}) async { + if (!isConnected) return; + if (!force && _isSyncingQueuedMessages) return; + if (_awaitingSelfInfo || _isLoadingContacts) { + _pendingQueueSync = true; + return; + } + _isSyncingQueuedMessages = true; + await _requestNextQueuedMessage(); + } + + Future _requestNextQueuedMessage() async { + if (!isConnected) { + _isSyncingQueuedMessages = false; + _queuedMessageSyncInFlight = false; + return; + } + if (_queuedMessageSyncInFlight) return; + _queuedMessageSyncInFlight = true; + try { + await sendFrame(buildSyncNextMessageFrame()); + } catch (e) { + _queuedMessageSyncInFlight = false; + _isSyncingQueuedMessages = false; + } + } + + Future sendCliCommand(String command) async { + if (!isConnected) return; + + // CLI commands are sent as UTF-8 text with a special prefix + final commandBytes = utf8.encode(command); + final bytes = Uint8List.fromList([0x01, ...commandBytes, 0x00]); + await sendFrame(bytes); + } + + Future getChannels({int? maxChannels}) async { + if (!isConnected) return; + + _isLoadingChannels = true; + _channels.clear(); + notifyListeners(); + + // Request each channel index + final channelCount = maxChannels ?? _maxChannels; + for (int i = 0; i < channelCount; i++) { + await sendFrame(buildGetChannelFrame(i)); + } + + _isLoadingChannels = false; + notifyListeners(); + } + + Future setChannel(int index, String name, Uint8List psk) async { + if (!isConnected) return; + + await sendFrame(buildSetChannelFrame(index, name, psk)); + // Refresh channels after setting + await getChannels(); + } + + Future deleteChannel(int index) async { + if (!isConnected) return; + + // Delete by setting empty name and zero PSK + await sendFrame(buildSetChannelFrame(index, '', Uint8List(16))); + // Refresh channels after deleting + await getChannels(); + } + + void _handleFrame(List data) { + if (data.isEmpty) return; + + final frame = Uint8List.fromList(data); + _receivedFramesController.add(frame); + _bleDebugLogService?.logFrame(frame, outgoing: false); + + final code = frame[0]; + debugPrint('RX frame: code=$code len=${frame.length}'); + + switch (code) { + case respCodeDeviceInfo: + _handleDeviceInfo(frame); + break; + case respCodeSelfInfo: + debugPrint('Got SELF_INFO'); + _handleSelfInfo(frame); + break; + case respCodeContactsStart: + debugPrint('Got CONTACTS_START'); + if (!_preserveContactsOnRefresh) { + _contacts.clear(); + } + _isLoadingContacts = true; + notifyListeners(); + break; + case respCodeContact: + debugPrint('Got CONTACT'); + _handleContact(frame); + break; + case respCodeEndOfContacts: + debugPrint('Got END_OF_CONTACTS'); + _isLoadingContacts = false; + _preserveContactsOnRefresh = false; + notifyListeners(); + unawaited(_persistContacts()); + if (!_didInitialQueueSync || _pendingQueueSync) { + _didInitialQueueSync = true; + _pendingQueueSync = false; + unawaited(syncQueuedMessages(force: true)); + } + break; + case respCodeContactMsgRecv: + case respCodeContactMsgRecvV3: + _handleIncomingMessage(frame); + break; + case respCodeChannelMsgRecv: + case respCodeChannelMsgRecvV3: + _handleIncomingChannelMessage(frame); + break; + case respCodeSent: + _handleMessageSent(frame); + break; + case respCodeNoMoreMessages: + _handleNoMoreMessages(); + break; + case pushCodeMsgWaiting: + unawaited(syncQueuedMessages(force: true)); + break; + case pushCodeSendConfirmed: + _handleSendConfirmed(frame); + break; + case pushCodePathUpdated: + _handlePathUpdated(frame); + break; + case pushCodeLoginSuccess: + case pushCodeLoginFail: + case pushCodeStatusResponse: + break; + case pushCodeLogRxData: + _handleLogRxData(frame); + break; + case respCodeChannelInfo: + _handleChannelInfo(frame); + break; + case respCodeRadioSettings: + _handleRadioSettings(frame); + break; + case respCodeBattAndStorage: + _handleBatteryAndStorage(frame); + break; + default: + debugPrint('Unknown frame code: $code'); + } + } + + void _handlePathUpdated(Uint8List frame) { + // Frame format: [0]=code, [1-32]=pub_key + if (frame.length >= 33 && _pathHistoryService != null) { + final pubKey = Uint8List.fromList(frame.sublist(1, 33)); + final contact = _contacts.cast().firstWhere( + (c) => c != null && listEquals(c.publicKey, pubKey), + orElse: () => null, + ); + + if (contact != null) { + _pathHistoryService!.handlePathUpdated(contact); + refreshContactsSinceLastmod(); + } + } + } + + void _handleSelfInfo(Uint8List frame) { + // SELF_INFO format: + // [0] = RESP_CODE_SELF_INFO + // [1] = ADV_TYPE + // [2] = tx_power_dbm + // [3] = MAX_LORA_TX_POWER + // [4-35] = pub_key (32 bytes) + // [36-39] = lat (int32 LE) + // [40-43] = lon (int32 LE) + // [44] = multi_acks + // [45] = advert_loc_policy + // [46] = telemetry modes + // [47] = manual_add_contacts + // [48-51] = freq (uint32 LE, in Hz) + // [52-55] = bw (uint32 LE, in Hz) + // [56] = sf + // [57] = cr + // [58+] = node_name + if (frame.length < 4 + pubKeySize) return; + + _currentTxPower = frame[2]; + _maxTxPower = frame[3]; + _selfPublicKey = Uint8List.fromList(frame.sublist(4, 4 + pubKeySize)); + _selfLatitude = readInt32LE(frame, 36) / 1000000.0; + _selfLongitude = readInt32LE(frame, 40) / 1000000.0; + + // Radio settings (if frame is long enough) + if (frame.length >= 58) { + _currentFreqHz = readUint32LE(frame, 48); + _currentBwHz = readUint32LE(frame, 52); + _currentSf = frame[56]; + _currentCr = frame[57]; + } + + // Node name starts at offset 58 if frame is long enough + if (frame.length > 58) { + _selfName = readCString(frame, 58, frame.length - 58); + } + _awaitingSelfInfo = false; + notifyListeners(); + + // Auto-fetch contacts after getting self info + getContacts(); + } + + void _handleDeviceInfo(Uint8List frame) { + if (frame.length < 4) return; + // Firmware reports MAX_CONTACTS / 2 for v3+ device info. + final reportedContacts = frame[2]; + final reportedChannels = frame[3]; + final nextMaxContacts = reportedContacts > 0 ? reportedContacts * 2 : _maxContacts; + final nextMaxChannels = reportedChannels > 0 ? reportedChannels : _maxChannels; + final previousMaxChannels = _maxChannels; + if (nextMaxContacts != _maxContacts || nextMaxChannels != _maxChannels) { + _maxContacts = nextMaxContacts; + _maxChannels = nextMaxChannels; + if (nextMaxChannels > previousMaxChannels) { + unawaited(loadChannelSettings(maxChannels: nextMaxChannels)); + unawaited(loadAllChannelMessages(maxChannels: nextMaxChannels)); + if (isConnected) { + unawaited(getChannels(maxChannels: nextMaxChannels)); + } + } + notifyListeners(); + } + } + + void _handleNoMoreMessages() { + _isSyncingQueuedMessages = false; + _queuedMessageSyncInFlight = false; + } + + void _handleQueuedMessageReceived() { + if (!_isSyncingQueuedMessages) return; + _queuedMessageSyncInFlight = false; + unawaited(_requestNextQueuedMessage()); + } + + void _handleRadioSettings(Uint8List frame) { + // Frame format from C++: + // [0] = RESP_CODE_RADIO_SETTINGS + // [1-4] = freq (uint32 LE, in Hz) + // [5-8] = bw (uint32 LE, in Hz) + // [9] = sf + // [10] = cr + if (frame.length >= 11) { + _currentFreqHz = readUint32LE(frame, 1); + _currentBwHz = readUint32LE(frame, 5); + _currentSf = frame[9]; + _currentCr = frame[10]; + debugPrint('Radio settings: freq=$_currentFreqHz bw=$_currentBwHz sf=$_currentSf cr=$_currentCr'); + notifyListeners(); + } + } + + void _handleBatteryAndStorage(Uint8List frame) { + // Frame format from C++: + // [0] = RESP_CODE_BATT_AND_STORAGE + // [1-2] = battery_mv (uint16 LE) + // [3-6] = storage_used_kb (uint32 LE) + // [7-10] = storage_total_kb (uint32 LE) + if (frame.length >= 3) { + _batteryMillivolts = readUint16LE(frame, 1); + notifyListeners(); + } + } + + /// Calculate timeout for a message based on radio settings and path length + /// Returns timeout in milliseconds, considering number of hops + int calculateTimeout({required int pathLength, int messageBytes = 100}) { + // If we have radio settings, use them for accurate calculation + if (_currentFreqHz != null && + _currentBwHz != null && + _currentSf != null && + _currentCr != null) { + final cr = _currentCr! <= 4 ? _currentCr! : _currentCr! - 4; + return calculateMessageTimeout( + freqHz: _currentFreqHz!, + bwHz: _currentBwHz!, + sf: _currentSf!, + cr: cr, + pathLength: pathLength, + messageBytes: messageBytes, + ); + } + + // Fallback: Conservative estimates based on typical settings + // Assume SF7, BW125, which gives ~50ms airtime for 100 bytes + const estimatedAirtime = 50; + + if (pathLength < 0) { + // Flood mode: Base delay + 16× airtime + return 500 + (16 * estimatedAirtime); + } else { + // Direct path: Base delay + ((airtime×6 + 250ms)×(hops+1)) + return 500 + ((estimatedAirtime * 6 + 250) * (pathLength + 1)); + } + } + + void _handleContact(Uint8List frame) { + final contact = Contact.fromFrame(frame); + if (contact != null) { + // Check if this is a new contact + final isNewContact = !_knownContactKeys.contains(contact.publicKeyHex); + final existingIndex = _contacts.indexWhere( + (c) => c.publicKeyHex == contact.publicKeyHex, + ); + + if (existingIndex >= 0) { + _contacts[existingIndex] = contact; + } else { + _contacts.add(contact); + } + _knownContactKeys.add(contact.publicKeyHex); + _loadMessagesForContact(contact.publicKeyHex); + notifyListeners(); + + // Show notification for new contact (advertisement) + if (isNewContact && _appSettingsService != null) { + final settings = _appSettingsService!.settings; + if (settings.notificationsEnabled && settings.notifyOnNewAdvert) { + _notificationService.showAdvertNotification( + contactName: contact.name, + contactType: contact.typeLabel, + contactId: contact.publicKeyHex, + ); + } + } + + if (!_isLoadingContacts) { + unawaited(_persistContacts()); + } + } + } + + Future _persistContacts() async { + await _contactStore.saveContacts(_contacts); + } + + int _latestContactLastmod() { + if (_contacts.isEmpty) return 0; + var latest = 0; + for (final contact in _contacts) { + final seconds = contact.lastSeen.millisecondsSinceEpoch ~/ 1000; + if (seconds > latest) { + latest = seconds; + } + } + return latest; + } + + void _handleIncomingMessage(Uint8List frame) { + if (_selfPublicKey == null) return; + + var message = _parseContactMessage(frame); + if (message != null) { + final contact = _contacts.cast().firstWhere( + (c) => c?.publicKeyHex == message!.senderKeyHex, + orElse: () => null, + ); + if (contact != null) { + message = message.copyWith( + pathLength: contact.pathLength < 0 ? -1 : contact.pathLength, + pathBytes: contact.pathLength < 0 ? Uint8List(0) : contact.path, + ); + } + if (!message.isOutgoing) { + final existing = _conversations[message.senderKeyHex]; + final incomingTimestamp = message.timestamp.millisecondsSinceEpoch; + if (existing != null && existing.isNotEmpty) { + final startIndex = existing.length > 10 ? existing.length - 10 : 0; + for (int i = existing.length - 1; i >= startIndex; i--) { + final recent = existing[i]; + if (!recent.isOutgoing && + recent.timestamp.millisecondsSinceEpoch == incomingTimestamp && + recent.text == message.text) { + return; + } + } + } + } + _addMessage(message.senderKeyHex, message); + notifyListeners(); + + // Show notification for new incoming message + if (!message.isOutgoing && !message.isCli && _appSettingsService != null) { + final settings = _appSettingsService!.settings; + if (settings.notificationsEnabled && settings.notifyOnNewMessage) { + // Find the contact name + _notificationService.showMessageNotification( + contactName: contact?.name ?? 'Unknown', + message: message.text, + contactId: message.senderKeyHex, + ); + } + } + _handleQueuedMessageReceived(); + } else if (_isSyncingQueuedMessages) { + _handleQueuedMessageReceived(); + } + } + + Message? _parseContactMessage(Uint8List frame) { + if (frame.isEmpty) return null; + final code = frame[0]; + if (code != respCodeContactMsgRecv && code != respCodeContactMsgRecvV3) { + return null; + } + + // Companion radio layout: + // [code][snr?][res?][res?][prefix x6][path_len][txt_type][timestamp x4][extra?][text...] + final prefixOffset = code == respCodeContactMsgRecvV3 ? 4 : 1; + const prefixLen = 6; + final pathLenOffset = prefixOffset + prefixLen; + final txtTypeOffset = pathLenOffset + 1; + final timestampOffset = txtTypeOffset + 1; + final baseTextOffset = timestampOffset + 4; + + if (frame.length <= baseTextOffset) return null; + + final senderPrefix = frame.sublist(prefixOffset, prefixOffset + prefixLen); + final flags = frame[txtTypeOffset]; + final shiftedType = flags >> 2; + final rawType = flags; + final isPlain = shiftedType == txtTypePlain || rawType == txtTypePlain; + final isCli = shiftedType == txtTypeCliData || rawType == txtTypeCliData; + if (!isPlain && !isCli) { + return null; + } + + // Try base text offset; if empty and there is room for the optional 4-byte extra + // (used by signed/plain variants), try again skipping those bytes. + var text = readCString(frame, baseTextOffset, frame.length - baseTextOffset); + if (text.isEmpty && frame.length > baseTextOffset + 4) { + text = readCString(frame, baseTextOffset + 4, frame.length - (baseTextOffset + 4)); + } + if (text.isEmpty) return null; + + final timestampRaw = readUint32LE(frame, timestampOffset); + final pathLenByte = frame[pathLenOffset]; + + final contact = _contacts.cast().firstWhere( + (c) => c != null && _matchesPrefix(c.publicKey, senderPrefix), + orElse: () => null, + ); + if (contact == null) return null; + + return Message( + senderKey: contact.publicKey, + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), + isOutgoing: false, + isCli: isCli, + status: MessageStatus.delivered, + pathLength: pathLenByte == 0xFF ? 0 : pathLenByte, + pathBytes: Uint8List(0), + ); + } + + bool _matchesPrefix(Uint8List fullKey, Uint8List prefix) { + if (fullKey.length < prefix.length) return false; + for (int i = 0; i < prefix.length; i++) { + if (fullKey[i] != prefix[i]) return false; + } + return true; + } + + void _handleIncomingChannelMessage(Uint8List frame) { + final message = ChannelMessage.fromFrame(frame); + if (message != null && message.channelIndex != null) { + if (_shouldDropSelfChannelMessage(message.senderName, message.pathBytes)) { + return; + } + _addChannelMessage(message.channelIndex!, message); + notifyListeners(); + _handleQueuedMessageReceived(); + } else if (_isSyncingQueuedMessages) { + _handleQueuedMessageReceived(); + } + } + + void _handleLogRxData(Uint8List frame) { + if (frame.length < 4) return; + final raw = Uint8List.fromList(frame.sublist(3)); + final packet = _parseRawPacket(raw); + if (packet == null || packet.payloadType != _payloadTypeGroupText) return; + + final payload = packet.payload; + if (payload.length <= _cipherMacSize) return; + final channelHash = payload[0]; + final encrypted = Uint8List.fromList(payload.sublist(1)); + + for (final channel in _channels) { + if (channel.isEmpty) continue; + final hash = _computeChannelHash(channel.psk); + if (hash != channelHash) continue; + + final decrypted = _decryptPayload(channel.psk, encrypted); + if (decrypted == null || decrypted.length < 6) return; + + final txtType = decrypted[4]; + if ((txtType >> 2) != 0) { + return; + } + + final timestampRaw = readUint32LE(decrypted, 0); + final text = readCString(decrypted, 5, decrypted.length - 5); + final parsed = _splitSenderText(text); + final decodedText = Smaz.tryDecodePrefixed(parsed.text) ?? parsed.text; + if (_shouldDropSelfChannelMessage(parsed.senderName, packet.pathBytes)) { + return; + } + + final message = ChannelMessage( + senderKey: null, + senderName: parsed.senderName, + text: decodedText, + timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), + isOutgoing: false, + status: ChannelMessageStatus.sent, + pathLength: packet.isFlood ? packet.pathBytes.length : 0, + pathBytes: packet.pathBytes, + channelIndex: channel.index, + ); + + _addChannelMessage(channel.index, message); + notifyListeners(); + return; + } + } + + void _handleMessageSent(Uint8List frame) { + // Frame format from C++: + // [0] = RESP_CODE_SENT + // [1] = is_flood (1 or 0) + // [2-5] = expected_ack_hash (uint32) + // [6-9] = estimated_timeout_ms (uint32) + + if (frame.length >= 10 && _retryService != null) { + final ackHash = Uint8List.fromList(frame.sublist(2, 6)); + final timeoutMs = readUint32LE(frame, 6); + + _retryService!.updateMessageFromSent(ackHash, timeoutMs); + } else { + // Fallback to old behavior + for (var messages in _conversations.values) { + for (int i = messages.length - 1; i >= 0; i--) { + if (messages[i].isOutgoing && messages[i].status == MessageStatus.pending) { + messages[i] = messages[i].copyWith(status: MessageStatus.sent); + notifyListeners(); + return; + } + } + } + } + } + + void _handleSendConfirmed(Uint8List frame) { + // Frame format from C++: + // [0] = PUSH_CODE_SEND_CONFIRMED + // [1-4] = ack_hash (uint32) + // [5-8] = trip_time_ms (uint32) + + if (frame.length >= 9) { + final ackHash = Uint8List.fromList(frame.sublist(1, 5)); + final tripTimeMs = readUint32LE(frame, 5); + + // Handle ACK in retry service + if (_retryService != null) { + _retryService!.handleAckReceived(ackHash, tripTimeMs); + } + } else { + // Fallback to old behavior + for (var messages in _conversations.values) { + for (int i = messages.length - 1; i >= 0; i--) { + if (messages[i].isOutgoing && messages[i].status == MessageStatus.sent) { + messages[i] = messages[i].copyWith(status: MessageStatus.delivered); + notifyListeners(); + return; + } + } + } + } + } + + void _handleChannelInfo(Uint8List frame) { + final channel = Channel.fromFrame(frame); + if (channel != null && !channel.isEmpty) { + _channels.add(channel); + _applyChannelOrder(); + notifyListeners(); + } + } + + void _applyChannelOrder() { + if (_channelOrder.isEmpty) { + _channels.sort((a, b) => a.index.compareTo(b.index)); + return; + } + + final orderIndex = {}; + for (int i = 0; i < _channelOrder.length; i++) { + orderIndex[_channelOrder[i]] = i; + } + + _channels.sort((a, b) { + final aPos = orderIndex[a.index]; + final bPos = orderIndex[b.index]; + if (aPos != null && bPos != null) return aPos.compareTo(bPos); + if (aPos != null) return -1; + if (bPos != null) return 1; + return a.index.compareTo(b.index); + }); + } + + Future setChannelOrder(List order) async { + _channelOrder = List.from(order); + _applyChannelOrder(); + await _channelOrderStore.saveChannelOrder(_channelOrder); + notifyListeners(); + } + + void _addMessage(String pubKeyHex, Message message) { + _conversations.putIfAbsent(pubKeyHex, () => []); + _conversations[pubKeyHex]!.add(message); + _messageStore.saveMessages(pubKeyHex, _conversations[pubKeyHex]!); + notifyListeners(); + } + + _RawPacket? _parseRawPacket(Uint8List raw) { + if (raw.length < 3) return null; + var index = 0; + final header = raw[index++]; + final routeType = header & _phRouteMask; + final hasTransport = routeType == _routeTransportFlood || routeType == _routeTransportDirect; + if (hasTransport) { + if (raw.length < index + 4) return null; + index += 4; + } + if (raw.length <= index) return null; + final pathLen = raw[index++]; + if (raw.length < index + pathLen) return null; + final pathBytes = Uint8List.fromList(raw.sublist(index, index + pathLen)); + index += pathLen; + if (raw.length <= index) return null; + final payload = Uint8List.fromList(raw.sublist(index)); + + return _RawPacket( + header: header, + routeType: routeType, + payloadType: (header >> _phTypeShift) & _phTypeMask, + payloadVer: (header >> _phVerShift) & _phVerMask, + pathBytes: pathBytes, + payload: payload, + ); + } + + int _computeChannelHash(Uint8List psk) { + final digest = crypto.sha256.convert(psk).bytes; + return digest[0]; + } + + Uint8List? _decryptPayload(Uint8List psk, Uint8List encrypted) { + if (encrypted.length <= _cipherMacSize) return null; + final mac = encrypted.sublist(0, _cipherMacSize); + final cipherText = encrypted.sublist(_cipherMacSize); + + final key32 = Uint8List(32); + final copyLen = psk.length < 32 ? psk.length : 32; + key32.setRange(0, copyLen, psk); + + final hmac = crypto.Hmac(crypto.sha256, key32).convert(cipherText).bytes; + if (hmac[0] != mac[0] || hmac[1] != mac[1]) { + return null; + } + + if (cipherText.isEmpty || cipherText.length % 16 != 0) return null; + final key16 = Uint8List(16); + final keyLen = psk.length < 16 ? psk.length : 16; + key16.setRange(0, keyLen, psk); + + final cipher = ECBBlockCipher(AESFastEngine()); + cipher.init(false, KeyParameter(key16)); + final out = Uint8List(cipherText.length); + for (var i = 0; i < cipherText.length; i += 16) { + cipher.processBlock(cipherText, i, out, i); + } + return out; + } + + _ParsedText _splitSenderText(String text) { + final colonIndex = text.indexOf(':'); + if (colonIndex > 0 && colonIndex < text.length - 1 && colonIndex < 50) { + final potentialSender = text.substring(0, colonIndex); + if (RegExp(r'[:\[\]]').hasMatch(potentialSender)) { + return _ParsedText(senderName: 'Unknown', text: text); + } + final offset = (colonIndex + 1 < text.length && text[colonIndex + 1] == ' ') + ? colonIndex + 2 + : colonIndex + 1; + return _ParsedText( + senderName: potentialSender, + text: text.substring(offset), + ); + } + return _ParsedText(senderName: 'Unknown', text: text); + } + + Uint8List _resolveOutgoingPathBytes( + Contact contact, + Uint8List? customPath, + int? customPathLen, + bool forceFlood, + PathSelection? selection, + ) { + if (forceFlood || contact.pathLength < 0 || selection?.useFlood == true) { + return Uint8List(0); + } + if (customPath != null && customPathLen != null && customPathLen > 0) { + return Uint8List.fromList(customPath.sublist(0, customPathLen)); + } + if (selection != null && selection.pathBytes.isNotEmpty) { + return Uint8List.fromList(selection.pathBytes); + } + return contact.path; + } + + int? _resolveOutgoingPathLength( + Contact contact, + int? customPathLen, + bool forceFlood, + PathSelection? selection, + ) { + if (forceFlood || contact.pathLength < 0 || selection?.useFlood == true) { + return -1; + } + if (customPathLen != null && customPathLen > 0) { + return customPathLen; + } + if (selection != null && selection.pathBytes.isNotEmpty) { + return selection.hopCount; + } + return contact.pathLength; + } + + void _addChannelMessage(int channelIndex, ChannelMessage message) { + _channelMessages.putIfAbsent(channelIndex, () => []); + final messages = _channelMessages[channelIndex]!; + final existingIndex = _findChannelRepeatIndex(messages, message); + if (existingIndex >= 0) { + final existing = messages[existingIndex]; + final mergedPathBytes = existing.pathBytes.isEmpty ? message.pathBytes : existing.pathBytes; + messages[existingIndex] = existing.copyWith( + repeatCount: existing.repeatCount + 1, + pathLength: message.pathLength ?? existing.pathLength, + pathBytes: mergedPathBytes, + ); + } else { + messages.add(message); + } + + // Save to persistent storage + _channelMessageStore.saveChannelMessages( + channelIndex, + messages, + ); + } + + int _findChannelRepeatIndex(List messages, ChannelMessage incoming) { + for (int i = messages.length - 1; i >= 0; i--) { + final existing = messages[i]; + if (_isChannelRepeat(existing, incoming)) { + return i; + } + } + return -1; + } + + bool _isChannelRepeat(ChannelMessage existing, ChannelMessage incoming) { + if (existing.text != incoming.text) return false; + + final diffMs = (existing.timestamp.millisecondsSinceEpoch - + incoming.timestamp.millisecondsSinceEpoch) + .abs(); + if (diffMs > 5000) return false; + + if (existing.senderName == incoming.senderName) return true; + + if (existing.isOutgoing && !incoming.isOutgoing) { + final selfName = _selfName ?? 'Me'; + if (incoming.senderName == selfName || existing.senderName == selfName) { + return true; + } + } + + return false; + } + + bool _shouldDropSelfChannelMessage(String senderName, Uint8List pathBytes) { + final selfKey = _selfPublicKey; + if (selfKey == null) return false; + if (pathBytes.length < pathHashSize) return false; + final trimmed = senderName.trim(); + if (trimmed.isEmpty) return false; + final selfName = _selfName?.trim(); + if (selfName == null || selfName.isEmpty) return false; + if (trimmed != selfName) return false; + final prefix = selfKey.sublist(0, pathHashSize); + for (int i = 0; i + pathHashSize <= pathBytes.length; i += pathHashSize) { + var match = true; + for (int j = 0; j < pathHashSize; j++) { + if (pathBytes[i + j] != prefix[j]) { + match = false; + break; + } + } + if (match) { + return true; + } + } + return false; + } + + void _handleDisconnection() { + _notifySubscription?.cancel(); + _notifySubscription = null; + _connectionSubscription?.cancel(); + _connectionSubscription = null; + + _device = null; + _rxCharacteristic = null; + _txCharacteristic = null; + _maxContacts = _defaultMaxContacts; + _maxChannels = _defaultMaxChannels; + _isSyncingQueuedMessages = false; + _queuedMessageSyncInFlight = false; + + _setState(MeshCoreConnectionState.disconnected); + } + + void _setState(MeshCoreConnectionState newState) { + if (_state != newState) { + _state = newState; + notifyListeners(); + } + } + + @override + void dispose() { + _scanSubscription?.cancel(); + _connectionSubscription?.cancel(); + _notifySubscription?.cancel(); + _receivedFramesController.close(); + super.dispose(); + } +} + +const int _phRouteMask = 0x03; +const int _phTypeShift = 2; +const int _phTypeMask = 0x0F; +const int _phVerShift = 6; +const int _phVerMask = 0x03; + +const int _routeTransportFlood = 0x00; +const int _routeFlood = 0x01; +const int _routeDirect = 0x02; +const int _routeTransportDirect = 0x03; + +const int _payloadTypeGroupText = 0x05; +const int _cipherMacSize = 2; + +class _RawPacket { + final int header; + final int routeType; + final int payloadType; + final int payloadVer; + final Uint8List pathBytes; + final Uint8List payload; + + _RawPacket({ + required this.header, + required this.routeType, + required this.payloadType, + required this.payloadVer, + required this.pathBytes, + required this.payload, + }); + + bool get isFlood => routeType == _routeFlood || routeType == _routeTransportFlood; +} + +class _ParsedText { + final String senderName; + final String text; + + _ParsedText({ + required this.senderName, + required this.text, + }); +} diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart new file mode 100644 index 00000000..b46d372e --- /dev/null +++ b/lib/connector/meshcore_protocol.dart @@ -0,0 +1,534 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +// Command codes (to device) +const int cmdAppStart = 1; +const int cmdSendTxtMsg = 2; +const int cmdSendChannelTxtMsg = 3; +const int cmdGetContacts = 4; +const int cmdGetDeviceTime = 5; +const int cmdSetDeviceTime = 6; +const int cmdSendSelfAdvert = 7; +const int cmdSetAdvertName = 8; +const int cmdAddUpdateContact = 9; +const int cmdSyncNextMessage = 10; +const int cmdSetRadioParams = 11; +const int cmdSetRadioTxPower = 12; +const int cmdResetPath = 13; +const int cmdSetAdvertLatLon = 14; +const int cmdRemoveContact = 15; +const int cmdShareContact = 16; +const int cmdExportContact = 17; +const int cmdImportContact = 18; +const int cmdReboot = 19; +const int cmdGetBattAndStorage = 20; +const int cmdDeviceQuery = 22; +const int cmdSendLogin = 26; +const int cmdSendStatusReq = 27; +const int cmdGetChannel = 31; +const int cmdSetChannel = 32; +const int cmdGetRadioSettings = 57; + +// Text message types +const int txtTypePlain = 0; +const int txtTypeCliData = 1; + +// Repeater request types (for server requests) +const int reqTypeGetStatus = 0x01; +const int reqTypeKeepAlive = 0x02; +const int reqTypeGetTelemetry = 0x03; +const int reqTypeGetAccessList = 0x05; +const int reqTypeGetNeighbours = 0x06; + +// Repeater response codes +const int respServerLoginOk = 0; + +// Response codes (from device) +const int respCodeOk = 0; +const int respCodeErr = 1; +const int respCodeContactsStart = 2; +const int respCodeContact = 3; +const int respCodeEndOfContacts = 4; +const int respCodeSelfInfo = 5; +const int respCodeSent = 6; +const int respCodeContactMsgRecv = 7; +const int respCodeChannelMsgRecv = 8; +const int respCodeCurrTime = 9; +const int respCodeNoMoreMessages = 10; +const int respCodeBattAndStorage = 12; +const int respCodeDeviceInfo = 13; +const int respCodeContactMsgRecvV3 = 16; +const int respCodeChannelMsgRecvV3 = 17; +const int respCodeChannelInfo = 18; +const int respCodeRadioSettings = 25; + +// Push codes (async from device) +const int pushCodeAdvert = 0x80; +const int pushCodePathUpdated = 0x81; +const int pushCodeSendConfirmed = 0x82; +const int pushCodeMsgWaiting = 0x83; +const int pushCodeLoginSuccess = 0x85; +const int pushCodeLoginFail = 0x86; +const int pushCodeStatusResponse = 0x87; +const int pushCodeLogRxData = 0x88; +const int pushCodeNewAdvert = 0x8A; + +// Contact/advertisement types +const int advTypeChat = 1; +const int advTypeRepeater = 2; +const int advTypeRoom = 3; +const int advTypeSensor = 4; + +// Sizes +const int pubKeySize = 32; +const int maxPathSize = 64; +const int pathHashSize = 1; +const int maxNameSize = 32; +const int maxFrameSize = 172; +const int appProtocolVersion = 3; + +// Contact frame offsets +const int contactPubKeyOffset = 1; +const int contactTypeOffset = 33; +const int contactFlagsOffset = 34; +const int contactPathLenOffset = 35; +const int contactPathOffset = 36; +const int contactNameOffset = 100; +const int contactTimestampOffset = 132; +const int contactLatOffset = 136; +const int contactLonOffset = 140; +const int contactLastmodOffset = 144; +const int contactFrameSize = 148; + +// Message frame offsets +const int msgPubKeyOffset = 1; +const int msgTimestampOffset = 33; +const int msgFlagsOffset = 37; +const int msgTextOffset = 38; + +class ParsedContactText { + final Uint8List senderPrefix; + final String text; + + const ParsedContactText({ + required this.senderPrefix, + required this.text, + }); +} + +ParsedContactText? parseContactMessageText(Uint8List frame) { + if (frame.isEmpty) return null; + final code = frame[0]; + if (code != respCodeContactMsgRecv && code != respCodeContactMsgRecvV3) { + return null; + } + + // Companion radio layout: + // [code][snr?][res?][res?][prefix x6][path_len][txt_type][timestamp x4][extra?][text...] + final isV3 = code == respCodeContactMsgRecvV3; + final prefixOffset = isV3 ? 4 : 1; + const prefixLen = 6; + final txtTypeOffset = prefixOffset + prefixLen + 1; + final timestampOffset = txtTypeOffset + 1; + final baseTextOffset = timestampOffset + 4; + if (frame.length <= baseTextOffset) return null; + + final flags = frame[txtTypeOffset]; + final shiftedType = flags >> 2; + final rawType = flags; + final isPlain = shiftedType == txtTypePlain || rawType == txtTypePlain; + final isCli = shiftedType == txtTypeCliData || rawType == txtTypeCliData; + if (!isPlain && !isCli) { + return null; + } + + var text = readCString(frame, baseTextOffset, frame.length - baseTextOffset).trim(); + if (text.isEmpty && frame.length > baseTextOffset + 4) { + text = + readCString(frame, baseTextOffset + 4, frame.length - (baseTextOffset + 4)).trim(); + } + if (text.isEmpty) return null; + + final senderPrefix = frame.sublist(prefixOffset, prefixOffset + prefixLen); + return ParsedContactText(senderPrefix: senderPrefix, text: text); +} + +// Helper to read uint32 little-endian +int readUint32LE(Uint8List data, int offset) { + return data[offset] | + (data[offset + 1] << 8) | + (data[offset + 2] << 16) | + (data[offset + 3] << 24); +} + +// Helper to read uint16 little-endian +int readUint16LE(Uint8List data, int offset) { + return data[offset] | (data[offset + 1] << 8); +} + +// Helper to read int32 little-endian +int readInt32LE(Uint8List data, int offset) { + int val = readUint32LE(data, offset); + if (val >= 0x80000000) val -= 0x100000000; + return val; +} + +// Helper to write uint32 little-endian +void writeUint32LE(Uint8List data, int offset, int value) { + data[offset] = value & 0xFF; + data[offset + 1] = (value >> 8) & 0xFF; + data[offset + 2] = (value >> 16) & 0xFF; + data[offset + 3] = (value >> 24) & 0xFF; +} + +// Helper to read null-terminated UTF-8 string +String readCString(Uint8List data, int offset, int maxLen) { + int end = offset; + while (end < offset + maxLen && end < data.length && data[end] != 0) { + end++; + } + try { + return utf8.decode(data.sublist(offset, end), allowMalformed: true); + } catch (e) { + // Fallback to Latin-1 if UTF-8 decoding fails + return String.fromCharCodes(data.sublist(offset, end)); + } +} + +// Helper to convert public key to hex string +String pubKeyToHex(Uint8List pubKey) { + return pubKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); +} + +// Helper to convert hex string to public key +Uint8List hexToPubKey(String hex) { + final result = Uint8List(pubKeySize); + for (int i = 0; i < pubKeySize && i * 2 + 1 < hex.length; i++) { + result[i] = int.parse(hex.substring(i * 2, i * 2 + 2), radix: 16); + } + return result; +} + +// Build CMD_GET_CONTACTS frame +Uint8List buildGetContactsFrame({int? since}) { + if (since != null) { + final frame = Uint8List(5); + frame[0] = cmdGetContacts; + writeUint32LE(frame, 1, since); + return frame; + } + return Uint8List.fromList([cmdGetContacts]); +} + +// Build CMD_SEND_LOGIN frame +// Format: [cmd][pub_key x32][password...]\0 +Uint8List buildSendLoginFrame(Uint8List recipientPubKey, String password) { + final passwordBytes = utf8.encode(password); + final frame = Uint8List(1 + pubKeySize + passwordBytes.length + 1); + frame[0] = cmdSendLogin; + frame.setRange(1, 1 + pubKeySize, recipientPubKey); + frame.setRange(1 + pubKeySize, 1 + pubKeySize + passwordBytes.length, passwordBytes); + frame[frame.length - 1] = 0; + return frame; +} + +// Build CMD_SEND_STATUS_REQ frame +// Format: [cmd][pub_key x32] +Uint8List buildSendStatusRequestFrame(Uint8List recipientPubKey) { + final frame = Uint8List(1 + pubKeySize); + frame[0] = cmdSendStatusReq; + frame.setRange(1, 1 + pubKeySize, recipientPubKey); + return frame; +} + +// Build CMD_SEND_TXT_MSG frame (companion_radio format) +// Format: [cmd][txt_type][attempt][timestamp x4][pub_key_prefix x6][text...]\0 +Uint8List buildSendTextMsgFrame( + Uint8List recipientPubKey, + String text, { + bool forceFlood = false, + int attempt = 0, + int? timestampSeconds, +}) { + final textBytes = utf8.encode(text); + final timestamp = timestampSeconds ?? (DateTime.now().millisecondsSinceEpoch ~/ 1000); + const prefixSize = 6; + final safeAttempt = forceFlood ? 3 : (attempt & 0xFF); + final frame = Uint8List(1 + 1 + 1 + 4 + prefixSize + textBytes.length + 1); + int offset = 0; + + frame[offset++] = cmdSendTxtMsg; + frame[offset++] = txtTypePlain; + frame[offset++] = safeAttempt; + writeUint32LE(frame, offset, timestamp); + offset += 4; + + frame.setRange(offset, offset + prefixSize, recipientPubKey.sublist(0, prefixSize)); + offset += prefixSize; + + frame.setRange(offset, offset + textBytes.length, textBytes); + frame[frame.length - 1] = 0; // null terminator + return frame; +} + +// Build CMD_SEND_CHANNEL_TXT_MSG frame +// Format: [cmd][txt_type][channel_idx][timestamp x4][text...] +Uint8List buildSendChannelTextMsgFrame(int channelIndex, String text) { + final textBytes = utf8.encode(text); + final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final frame = Uint8List(1 + 1 + 1 + 4 + textBytes.length + 1); + frame[0] = cmdSendChannelTxtMsg; + frame[1] = 0; // TXT_TYPE_PLAIN + frame[2] = channelIndex; + writeUint32LE(frame, 3, timestamp); + frame.setRange(7, 7 + textBytes.length, textBytes); + frame[frame.length - 1] = 0; // null terminator + return frame; +} + +// Build CMD_REMOVE_CONTACT frame +Uint8List buildRemoveContactFrame(Uint8List pubKey) { + final frame = Uint8List(1 + pubKeySize); + frame[0] = cmdRemoveContact; + frame.setRange(1, 1 + pubKeySize, pubKey); + return frame; +} + +// Build CMD_APP_START frame +// Format: [cmd][reserved x7][app_name...] +Uint8List buildAppStartFrame({String appName = 'MeshCoreOpen'}) { + final nameBytes = utf8.encode(appName); + final frame = Uint8List(8 + nameBytes.length + 1); + frame[0] = cmdAppStart; + // bytes 1-7 are reserved (zeros) + frame.setRange(8, 8 + nameBytes.length, nameBytes); + frame[frame.length - 1] = 0; // null terminator + return frame; +} + +// Build CMD_DEVICE_QUERY frame +Uint8List buildDeviceQueryFrame({int appVersion = appProtocolVersion}) { + return Uint8List.fromList([cmdDeviceQuery, appVersion]); +} + +// Build CMD_GET_DEVICE_TIME frame +Uint8List buildGetDeviceTimeFrame() { + return Uint8List.fromList([cmdGetDeviceTime]); +} + +// Build CMD_GET_BATT_AND_STORAGE frame +Uint8List buildGetBattAndStorageFrame() { + return Uint8List.fromList([cmdGetBattAndStorage]); +} + +// Build CMD_SET_DEVICE_TIME frame +Uint8List buildSetDeviceTimeFrame(int timestamp) { + final frame = Uint8List(5); + frame[0] = cmdSetDeviceTime; + writeUint32LE(frame, 1, timestamp); + return frame; +} + +// Build CMD_SYNC_NEXT_MESSAGE frame +Uint8List buildSyncNextMessageFrame() { + return Uint8List.fromList([cmdSyncNextMessage]); +} + +// Build CMD_GET_CHANNEL frame +Uint8List buildGetChannelFrame(int channelIndex) { + return Uint8List.fromList([cmdGetChannel, channelIndex]); +} + +// Build CMD_SET_CHANNEL frame +// Format: [cmd][idx][name x32][psk x16] +Uint8List buildSetChannelFrame(int channelIndex, String name, Uint8List psk) { + final frame = Uint8List(2 + 32 + 16); + frame[0] = cmdSetChannel; + frame[1] = channelIndex; + // Write name (max 32 bytes UTF-8, null-padded) + final nameBytes = utf8.encode(name); + final nameLen = nameBytes.length < 32 ? nameBytes.length : 31; // Reserve 1 byte for null + for (int i = 0; i < nameLen; i++) { + frame[2 + i] = nameBytes[i]; + } + // frame[2 + nameLen] is already 0 (null terminator) + // Write PSK (16 bytes) + for (int i = 0; i < 16 && i < psk.length; i++) { + frame[34 + i] = psk[i]; + } + return frame; +} + +// Build CMD_SET_RADIO_PARAMS frame +// Format: [cmd][freq x4][bw x4][sf][cr] +// freq: frequency in Hz (300000-2500000) +// bw: bandwidth in Hz (7000-500000) +// sf: spreading factor (5-12) +// cr: coding rate (5-8) +Uint8List buildSetRadioParamsFrame(int freqHz, int bwHz, int sf, int cr) { + final frame = Uint8List(11); + frame[0] = cmdSetRadioParams; + writeUint32LE(frame, 1, freqHz); + writeUint32LE(frame, 5, bwHz); + frame[9] = sf; + frame[10] = cr; + return frame; +} + +// Build CMD_SET_RADIO_TX_POWER frame +// Format: [cmd][power_dbm] +Uint8List buildSetRadioTxPowerFrame(int powerDbm) { + return Uint8List.fromList([cmdSetRadioTxPower, powerDbm]); +} + +// Build CMD_RESET_PATH frame +// Format: [cmd][pub_key x32] +Uint8List buildResetPathFrame(Uint8List pubKey) { + final frame = Uint8List(1 + pubKeySize); + frame[0] = cmdResetPath; + frame.setRange(1, 1 + pubKeySize, pubKey); + return frame; +} + +// Build CMD_ADD_UPDATE_CONTACT frame to set custom path +// Format: [cmd][pub_key x32][type][flags][path_len][path x64][name x32][timestamp x4] +Uint8List buildUpdateContactPathFrame( + Uint8List pubKey, + Uint8List customPath, + int pathLen, { + int type = 1, // ADV_TYPE_CHAT + int flags = 0, + String name = '', +}) { + // Frame size: 1 + 32 + 1 + 1 + 1 + 64 + 32 + 4 = 136 bytes minimum + final frame = Uint8List(1 + pubKeySize + 1 + 1 + 1 + maxPathSize + maxNameSize + 4); + int offset = 0; + + frame[offset++] = cmdAddUpdateContact; + + // Public key (32 bytes) + frame.setRange(offset, offset + pubKeySize, pubKey); + offset += pubKeySize; + + // Type and flags + frame[offset++] = type; + frame[offset++] = flags; + + // Path length and path data + frame[offset++] = pathLen; + if (customPath.isNotEmpty && pathLen > 0) { + final copyLen = customPath.length < maxPathSize ? customPath.length : maxPathSize; + frame.setRange(offset, offset + copyLen, customPath.sublist(0, copyLen)); + } + offset += maxPathSize; + + // Name (32 bytes, null-padded) + if (name.isNotEmpty) { + final nameBytes = utf8.encode(name); + final nameLen = nameBytes.length < maxNameSize ? nameBytes.length : maxNameSize - 1; + frame.setRange(offset, offset + nameLen, nameBytes.sublist(0, nameLen)); + } + offset += maxNameSize; + + // Timestamp (current time) + final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000; + writeUint32LE(frame, offset, timestamp); + + return frame; +} + +// Build CMD_GET_RADIO_SETTINGS frame +Uint8List buildGetRadioSettingsFrame() { + return Uint8List.fromList([cmdGetRadioSettings]); +} + +// Calculate LoRa airtime for a packet +// Based on Semtech SX127x datasheet formula +// Returns airtime in milliseconds +int calculateLoRaAirtime({ + required int payloadBytes, + required int spreadingFactor, + required int bandwidthHz, + required int codingRate, + int preambleSymbols = 8, + bool lowDataRateOptimize = false, + bool explicitHeader = true, +}) { + // Symbol duration (Ts) in milliseconds + final symbolDuration = (1 << spreadingFactor) / (bandwidthHz / 1000.0); + + // Preamble time + final preambleTime = (preambleSymbols + 4.25) * symbolDuration; + + // Payload symbol count + final headerBytes = explicitHeader ? 0 : 20; + final crc = 1; // CRC enabled + final de = lowDataRateOptimize ? 1 : 0; + + final numerator = 8 * payloadBytes - 4 * spreadingFactor + 28 + 16 * crc - headerBytes; + final denominator = 4 * (spreadingFactor - 2 * de); + var payloadSymbols = 8 + ((numerator / denominator).ceil()) * (codingRate + 4); + + if (payloadSymbols < 0) { + payloadSymbols = 8; + } + + final payloadTime = payloadSymbols * symbolDuration; + + return (preambleTime + payloadTime).ceil(); +} + +// Calculate timeout for a message based on radio settings +// Returns timeout in milliseconds +int calculateMessageTimeout({ + required int freqHz, + required int bwHz, + required int sf, + required int cr, + required int pathLength, + int messageBytes = 100, // Average message size +}) { + // Calculate airtime for one packet + final airtime = calculateLoRaAirtime( + payloadBytes: messageBytes, + spreadingFactor: sf, + bandwidthHz: bwHz, + codingRate: cr, + lowDataRateOptimize: sf >= 11, + ); + + if (pathLength < 0) { + // Flood mode: Base delay + 16× airtime + return 500 + (16 * airtime); + } else { + // Direct path: Base delay + ((airtime×6 + 250ms)×(hops+1)) + return 500 + ((airtime * 6 + 250) * (pathLength + 1)); + } +} + +// Build CLI command text message frame (companion_radio format) +// Format: [cmd][txt_type][attempt][timestamp x4][pub_key_prefix x6][text...]\0 +Uint8List buildSendCliCommandFrame( + Uint8List repeaterPubKey, + String command, { + int attempt = 0, +}) { + final textBytes = utf8.encode(command); + final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000; + const prefixSize = 6; + final frame = Uint8List(1 + 1 + 1 + 4 + prefixSize + textBytes.length + 1); + int offset = 0; + + frame[offset++] = cmdSendTxtMsg; + frame[offset++] = txtTypeCliData; + frame[offset++] = attempt & 0xFF; + writeUint32LE(frame, offset, timestamp); + offset += 4; + + frame.setRange(offset, offset + prefixSize, repeaterPubKey.sublist(0, prefixSize)); + offset += prefixSize; + + frame.setRange(offset, offset + textBytes.length, textBytes); + frame[frame.length - 1] = 0; // null terminator + return frame; +} diff --git a/lib/helpers/smaz.dart b/lib/helpers/smaz.dart new file mode 100644 index 00000000..0e3e6c94 --- /dev/null +++ b/lib/helpers/smaz.dart @@ -0,0 +1,411 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +class Smaz { + static const int _verbatimSingle = 254; + static const int _verbatimRun = 255; + + static const List _rcb = [ + " ", + "the", + "e", + "t", + "a", + "of", + "o", + "and", + "i", + "n", + "s", + "e ", + "r", + " th", + " t", + "in", + "he", + "th", + "h", + "he ", + "to", + "\r\n", + "l", + "s ", + "d", + " a", + "an", + "er", + "c", + " o", + "d ", + "on", + " of", + "re", + "of ", + "t ", + ", ", + "is", + "u", + "at", + " ", + "n ", + "or", + "which", + "f", + "m", + "as", + "it", + "that", + "\n", + "was", + "en", + " ", + " w", + "es", + " an", + " i", + "\r", + "f ", + "g", + "p", + "nd", + " s", + "nd ", + "ed ", + "w", + "ed", + "http://", + "for", + "te", + "ing", + "y ", + "The", + " c", + "ti", + "r ", + "his", + "st", + " in", + "ar", + "nt", + ",", + " to", + "y", + "ng", + " h", + "with", + "le", + "al", + "to ", + "b", + "ou", + "be", + "were", + " b", + "se", + "o ", + "ent", + "ha", + "ng ", + "their", + "\"", + "hi", + "from", + " f", + "in ", + "de", + "ion", + "me", + "v", + ".", + "ve", + "all", + "re ", + "ri", + "ro", + "is ", + "co", + "f t", + "are", + "ea", + ". ", + "her", + " m", + "er ", + " p", + "es ", + "by", + "they", + "di", + "ra", + "ic", + "not", + "s, ", + "d t", + "at ", + "ce", + "la", + "h ", + "ne", + "as ", + "tio", + "on ", + "n t", + "io", + "we", + " a ", + "om", + ", a", + "s o", + "ur", + "li", + "ll", + "ch", + "had", + "this", + "e t", + "g ", + "e\r\n", + " wh", + "ere", + " co", + "e o", + "a ", + "us", + " d", + "ss", + "\n\r\n", + "\r\n\r", + "=\"", + " be", + " e", + "s a", + "ma", + "one", + "t t", + "or ", + "but", + "el", + "so", + "l ", + "e s", + "s,", + "no", + "ter", + " wa", + "iv", + "ho", + "e a", + " r", + "hat", + "s t", + "ns", + "ch ", + "wh", + "tr", + "ut", + "/", + "have", + "ly ", + "ta", + " ha", + " on", + "tha", + "-", + " l", + "ati", + "en ", + "pe", + " re", + "there", + "ass", + "si", + " fo", + "wa", + "ec", + "our", + "who", + "its", + "z", + "fo", + "rs", + ">", + "ot", + "un", + "<", + "im", + "th ", + "nc", + "ate", + "><", + "ver", + "ad", + " we", + "ly", + "ee", + " n", + "id", + " cl", + "ac", + "il", + " _rcbBytes = + _rcb.map((s) => Uint8List.fromList(ascii.encode(s))).toList(growable: false); + static final int _maxEntryLen = _rcbBytes.fold(0, (maxLen, entry) { + return entry.length > maxLen ? entry.length : maxLen; + }); + + static String encodeIfSmaller(String text) { + if (text.isEmpty || text.startsWith('s:')) return text; + final originalBytes = Uint8List.fromList(utf8.encode(text)); + final compressed = compressBytes(originalBytes); + final encoded = base64Encode(compressed); + final candidate = 's:$encoded'; + if (utf8.encode(candidate).length < originalBytes.length) { + return candidate; + } + return text; + } + + static String? tryDecodePrefixed(String text) { + final trimmedLeft = text.trimLeft(); + if (!trimmedLeft.startsWith('s:') || trimmedLeft.length <= 2) return null; + final encoded = trimmedLeft.substring(2); + try { + final compressed = _decodeBase64Flexible(encoded); + final decompressed = decompressBytes(compressed); + return utf8.decode(decompressed, allowMalformed: true); + } catch (_) { + return null; + } + } + + static Uint8List compressBytes(Uint8List input) { + final out = BytesBuilder(copy: false); + final verbatim = []; + int index = 0; + + void flushVerbatim() { + if (verbatim.isEmpty) return; + if (verbatim.length == 1) { + out.addByte(_verbatimSingle); + out.addByte(verbatim[0]); + } else { + out.addByte(_verbatimRun); + out.addByte(verbatim.length - 1); + out.add(verbatim); + } + verbatim.clear(); + } + + while (index < input.length) { + int bestLen = 0; + int bestCode = -1; + final remaining = input.length - index; + final maxLen = remaining < _maxEntryLen ? remaining : _maxEntryLen; + + for (int code = 0; code < _rcbBytes.length; code++) { + final entry = _rcbBytes[code]; + final entryLen = entry.length; + if (entryLen == 0 || entryLen > maxLen || entryLen <= bestLen) { + continue; + } + if (_matches(input, index, entry)) { + bestLen = entryLen; + bestCode = code; + if (bestLen == maxLen) { + break; + } + } + } + + if (bestCode >= 0) { + flushVerbatim(); + out.addByte(bestCode); + index += bestLen; + continue; + } + + verbatim.add(input[index]); + index++; + if (verbatim.length == 256) { + flushVerbatim(); + } + } + + flushVerbatim(); + return out.toBytes(); + } + + static Uint8List decompressBytes(Uint8List input) { + final out = BytesBuilder(copy: false); + int index = 0; + + while (index < input.length) { + final code = input[index]; + if (code == _verbatimSingle) { + if (index + 1 >= input.length) { + throw const FormatException('Invalid SMAZ stream: truncated verbatim byte.'); + } + out.addByte(input[index + 1]); + index += 2; + } else if (code == _verbatimRun) { + if (index + 1 >= input.length) { + throw const FormatException('Invalid SMAZ stream: truncated verbatim length.'); + } + final len = input[index + 1] + 1; + final end = index + 2 + len; + if (end > input.length) { + throw const FormatException('Invalid SMAZ stream: truncated verbatim run.'); + } + out.add(input.sublist(index + 2, end)); + index = end; + } else { + if (code >= _rcbBytes.length) { + throw const FormatException('Invalid SMAZ stream: code out of range.'); + } + out.add(_rcbBytes[code]); + index += 1; + } + } + + return out.toBytes(); + } + + static bool _matches(Uint8List input, int offset, Uint8List entry) { + final len = entry.length; + if (offset + len > input.length) return false; + for (int i = 0; i < len; i++) { + if (input[offset + i] != entry[i]) return false; + } + return true; + } + + static Uint8List _decodeBase64Flexible(String encoded) { + final trimmed = encoded.trim(); + try { + return base64Decode(trimmed); + } catch (_) { + // Try base64url with missing padding. + var normalized = trimmed.replaceAll('-', '+').replaceAll('_', '/'); + final pad = normalized.length % 4; + if (pad != 0) { + normalized = normalized.padRight(normalized.length + (4 - pad), '='); + } + return base64Decode(normalized); + } + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 00000000..2909bf9a --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,118 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import 'connector/meshcore_connector.dart'; +import 'screens/scanner_screen.dart'; +import 'services/storage_service.dart'; +import 'services/message_retry_service.dart'; +import 'services/path_history_service.dart'; +import 'services/app_settings_service.dart'; +import 'services/notification_service.dart'; +import 'services/ble_debug_log_service.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Initialize services + final storage = StorageService(); + final connector = MeshCoreConnector(); + final pathHistoryService = PathHistoryService(storage); + final retryService = MessageRetryService(storage); + final appSettingsService = AppSettingsService(); + final bleDebugLogService = BleDebugLogService(); + + // Load settings + await appSettingsService.loadSettings(); + + // Initialize notification service + final notificationService = NotificationService(); + await notificationService.initialize(); + + // Wire up connector with services + connector.initialize( + retryService: retryService, + pathHistoryService: pathHistoryService, + appSettingsService: appSettingsService, + bleDebugLogService: bleDebugLogService, + ); + + await connector.loadContactCache(); + await connector.loadChannelSettings(); + + // Load persisted channel messages + await connector.loadAllChannelMessages(); + + runApp(MeshCoreApp( + connector: connector, + retryService: retryService, + pathHistoryService: pathHistoryService, + storage: storage, + appSettingsService: appSettingsService, + bleDebugLogService: bleDebugLogService, + )); +} + +class MeshCoreApp extends StatelessWidget { + final MeshCoreConnector connector; + final MessageRetryService retryService; + final PathHistoryService pathHistoryService; + final StorageService storage; + final AppSettingsService appSettingsService; + final BleDebugLogService bleDebugLogService; + + const MeshCoreApp({ + super.key, + required this.connector, + required this.retryService, + required this.pathHistoryService, + required this.storage, + required this.appSettingsService, + required this.bleDebugLogService, + }); + + @override + Widget build(BuildContext context) { + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retryService), + ChangeNotifierProvider.value(value: pathHistoryService), + ChangeNotifierProvider.value(value: appSettingsService), + ChangeNotifierProvider.value(value: bleDebugLogService), + Provider.value(value: storage), + ], + child: Consumer( + builder: (context, settingsService, child) { + return MaterialApp( + title: 'MeshCore Open', + debugShowCheckedModeBanner: false, + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), + useMaterial3: true, + ), + darkTheme: ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.blue, + brightness: Brightness.dark, + ), + useMaterial3: true, + ), + themeMode: _themeModeFromSetting(settingsService.settings.themeMode), + home: const ScannerScreen(), + ); + }, + ), + ); + } + + ThemeMode _themeModeFromSetting(String value) { + switch (value) { + case 'light': + return ThemeMode.light; + case 'dark': + return ThemeMode.dark; + default: + return ThemeMode.system; + } + } +} diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart new file mode 100644 index 00000000..9b648348 --- /dev/null +++ b/lib/models/app_settings.dart @@ -0,0 +1,108 @@ +class AppSettings { + final bool clearPathOnMaxRetry; + final bool mapShowRepeaters; + final bool mapShowChatNodes; + final bool mapShowOtherNodes; + final double mapTimeFilterHours; // 0 = all time + final bool mapKeyPrefixEnabled; + final String mapKeyPrefix; + final bool mapShowMarkers; + final bool notificationsEnabled; + final bool notifyOnNewMessage; + final bool notifyOnNewAdvert; + final bool autoRouteRotationEnabled; + final String themeMode; + final Map batteryChemistryByDeviceId; + + AppSettings({ + this.clearPathOnMaxRetry = false, + this.mapShowRepeaters = true, + this.mapShowChatNodes = true, + this.mapShowOtherNodes = true, + this.mapTimeFilterHours = 0, // Default to all time + this.mapKeyPrefixEnabled = false, + this.mapKeyPrefix = '', + this.mapShowMarkers = true, + this.notificationsEnabled = true, + this.notifyOnNewMessage = true, + this.notifyOnNewAdvert = true, + this.autoRouteRotationEnabled = false, + this.themeMode = 'system', + Map? batteryChemistryByDeviceId, + }) : batteryChemistryByDeviceId = batteryChemistryByDeviceId ?? {}; + + Map toJson() { + return { + 'clear_path_on_max_retry': clearPathOnMaxRetry, + 'map_show_repeaters': mapShowRepeaters, + 'map_show_chat_nodes': mapShowChatNodes, + 'map_show_other_nodes': mapShowOtherNodes, + 'map_time_filter_hours': mapTimeFilterHours, + 'map_key_prefix_enabled': mapKeyPrefixEnabled, + 'map_key_prefix': mapKeyPrefix, + 'map_show_markers': mapShowMarkers, + 'notifications_enabled': notificationsEnabled, + 'notify_on_new_message': notifyOnNewMessage, + 'notify_on_new_advert': notifyOnNewAdvert, + 'auto_route_rotation_enabled': autoRouteRotationEnabled, + 'theme_mode': themeMode, + 'battery_chemistry_by_device_id': batteryChemistryByDeviceId, + }; + } + + factory AppSettings.fromJson(Map json) { + return AppSettings( + clearPathOnMaxRetry: json['clear_path_on_max_retry'] as bool? ?? false, + mapShowRepeaters: json['map_show_repeaters'] as bool? ?? true, + mapShowChatNodes: json['map_show_chat_nodes'] as bool? ?? true, + mapShowOtherNodes: json['map_show_other_nodes'] as bool? ?? true, + mapTimeFilterHours: (json['map_time_filter_hours'] as num?)?.toDouble() ?? 0, + mapKeyPrefixEnabled: json['map_key_prefix_enabled'] as bool? ?? false, + mapKeyPrefix: json['map_key_prefix'] as String? ?? '', + mapShowMarkers: json['map_show_markers'] as bool? ?? true, + notificationsEnabled: json['notifications_enabled'] as bool? ?? true, + notifyOnNewMessage: json['notify_on_new_message'] as bool? ?? true, + notifyOnNewAdvert: json['notify_on_new_advert'] as bool? ?? true, + autoRouteRotationEnabled: json['auto_route_rotation_enabled'] as bool? ?? false, + themeMode: json['theme_mode'] as String? ?? 'system', + batteryChemistryByDeviceId: (json['battery_chemistry_by_device_id'] as Map?)?.map( + (key, value) => MapEntry(key.toString(), value.toString()), + ) ?? + {}, + ); + } + + AppSettings copyWith({ + bool? clearPathOnMaxRetry, + bool? mapShowRepeaters, + bool? mapShowChatNodes, + bool? mapShowOtherNodes, + double? mapTimeFilterHours, + bool? mapKeyPrefixEnabled, + String? mapKeyPrefix, + bool? mapShowMarkers, + bool? notificationsEnabled, + bool? notifyOnNewMessage, + bool? notifyOnNewAdvert, + bool? autoRouteRotationEnabled, + String? themeMode, + Map? batteryChemistryByDeviceId, + }) { + return AppSettings( + clearPathOnMaxRetry: clearPathOnMaxRetry ?? this.clearPathOnMaxRetry, + mapShowRepeaters: mapShowRepeaters ?? this.mapShowRepeaters, + mapShowChatNodes: mapShowChatNodes ?? this.mapShowChatNodes, + mapShowOtherNodes: mapShowOtherNodes ?? this.mapShowOtherNodes, + mapTimeFilterHours: mapTimeFilterHours ?? this.mapTimeFilterHours, + mapKeyPrefixEnabled: mapKeyPrefixEnabled ?? this.mapKeyPrefixEnabled, + mapKeyPrefix: mapKeyPrefix ?? this.mapKeyPrefix, + mapShowMarkers: mapShowMarkers ?? this.mapShowMarkers, + notificationsEnabled: notificationsEnabled ?? this.notificationsEnabled, + notifyOnNewMessage: notifyOnNewMessage ?? this.notifyOnNewMessage, + notifyOnNewAdvert: notifyOnNewAdvert ?? this.notifyOnNewAdvert, + autoRouteRotationEnabled: autoRouteRotationEnabled ?? this.autoRouteRotationEnabled, + themeMode: themeMode ?? this.themeMode, + batteryChemistryByDeviceId: batteryChemistryByDeviceId ?? this.batteryChemistryByDeviceId, + ); + } +} diff --git a/lib/models/channel.dart b/lib/models/channel.dart new file mode 100644 index 00000000..40a3ebbe --- /dev/null +++ b/lib/models/channel.dart @@ -0,0 +1,57 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import '../connector/meshcore_protocol.dart'; + +class Channel { + final int index; + final String name; + final Uint8List psk; // 16 bytes + + Channel({ + required this.index, + required this.name, + required this.psk, + }); + + String get pskBase64 => base64Encode(psk); + + bool get isEmpty => name.isEmpty && psk.every((b) => b == 0); + + bool get isPublicChannel => pskBase64 == publicChannelPsk; + + static Channel? fromFrame(Uint8List data) { + // CHANNEL_INFO format: + // [0] = RESP_CODE_CHANNEL_INFO (18) + // [1] = channel_idx + // [2-33] = name (32 bytes, null-terminated) + // [34-49] = psk (16 bytes) + if (data.length < 50) return null; + if (data[0] != respCodeChannelInfo) return null; + + final index = data[1]; + final name = readCString(data, 2, 32); + final psk = Uint8List.fromList(data.sublist(34, 50)); + + return Channel(index: index, name: name, psk: psk); + } + + static Channel empty(int index) { + return Channel( + index: index, + name: '', + psk: Uint8List(16), + ); + } + + static Channel fromPsk(int index, String name, String pskBase64) { + final pskBytes = base64Decode(pskBase64); + final psk = Uint8List(16); + for (int i = 0; i < pskBytes.length && i < 16; i++) { + psk[i] = pskBytes[i]; + } + return Channel(index: index, name: name, psk: psk); + } + + static const String publicChannelPsk = 'izOH6cXN6mrJ5e26oRXNcg=='; +} diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart new file mode 100644 index 00000000..0fdb679d --- /dev/null +++ b/lib/models/channel_message.dart @@ -0,0 +1,170 @@ +import 'dart:typed_data'; +import '../connector/meshcore_protocol.dart'; +import '../helpers/smaz.dart'; + +enum ChannelMessageStatus { pending, sent, failed } + +class Repeat { + final Uint8List? repeaterKey; + final String repeaterName; + final int tripTimeMs; + final List? path; + + Repeat({ + this.repeaterKey, + required this.repeaterName, + required this.tripTimeMs, + this.path, + }); + + String? get repeaterKeyHex => + repeaterKey != null ? pubKeyToHex(repeaterKey!) : null; +} + +class ChannelMessage { + final Uint8List? senderKey; + final String senderName; + final String text; + final DateTime timestamp; + final bool isOutgoing; + final ChannelMessageStatus status; + final List repeats; + final int repeatCount; + final int? pathLength; + final Uint8List pathBytes; + final int? channelIndex; + + ChannelMessage({ + this.senderKey, + required this.senderName, + required this.text, + required this.timestamp, + required this.isOutgoing, + this.status = ChannelMessageStatus.pending, + this.repeats = const [], + this.repeatCount = 0, + this.pathLength, + Uint8List? pathBytes, + this.channelIndex, + }) : pathBytes = pathBytes ?? Uint8List(0); + + String? get senderKeyHex => senderKey != null ? pubKeyToHex(senderKey!) : null; + + ChannelMessage copyWith({ + ChannelMessageStatus? status, + List? repeats, + int? repeatCount, + int? pathLength, + Uint8List? pathBytes, + }) { + return ChannelMessage( + senderKey: senderKey, + senderName: senderName, + text: text, + timestamp: timestamp, + isOutgoing: isOutgoing, + status: status ?? this.status, + repeats: repeats ?? this.repeats, + repeatCount: repeatCount ?? this.repeatCount, + pathLength: pathLength ?? this.pathLength, + pathBytes: pathBytes ?? this.pathBytes, + channelIndex: channelIndex, + ); + } + + static ChannelMessage? fromFrame(Uint8List data) { + // CHANNEL_MSG_RECV format varies by version: + // V3: [0]=code [1]=SNR [2]=rsv1 [3]=rsv2 [4]=channel_idx [5]=path_len [path... optional] [txt_type] [timestamp x4] [text...] + // Non-V3: [0]=code [1]=channel_idx [2]=path_len [3]=txt_type [4-7]=timestamp [8+]=text + if (data.length < 8) return null; + + final code = data[0]; + if (code != respCodeChannelMsgRecv && code != respCodeChannelMsgRecvV3) { + return null; + } + + int timestampOffset, textOffset, pathLenOffset, txtTypeOffset; + Uint8List pathBytes = Uint8List(0); + int channelIdx; + + if (code == respCodeChannelMsgRecvV3) { + channelIdx = data[4]; + pathLenOffset = 5; + final pathLen = data[pathLenOffset].toSigned(8); + var cursor = 6; + final hasPathBytesFlag = (data[2] & 0x01) != 0; + final canFitPath = pathLen > 0 && data.length >= cursor + pathLen + 5; + final hasValidTxtType = + cursor < data.length && (data[cursor] == txtTypePlain || data[cursor] == txtTypeCliData); + if ((hasPathBytesFlag || (canFitPath && !hasValidTxtType)) && canFitPath) { + pathBytes = Uint8List.fromList(data.sublist(cursor, cursor + pathLen)); + cursor += pathLen; + } + txtTypeOffset = cursor; + cursor += 1; // txt_type + timestampOffset = cursor; + textOffset = cursor + 4; + } else { + channelIdx = data[1]; + pathLenOffset = 2; + txtTypeOffset = 3; + timestampOffset = 4; + textOffset = 8; + } + + if (data.length < textOffset + 1) return null; + + final txtType = data[txtTypeOffset]; + if (txtType != txtTypePlain) { + return null; + } + + final pathLen = data[pathLenOffset].toSigned(8); + final timestampRaw = readUint32LE(data, timestampOffset); + final text = readCString(data, textOffset, data.length - textOffset); + + // Extract sender name and actual message from "name: msg" format + String senderName = 'Unknown'; + String actualText = text; + + final colonIndex = text.indexOf(':'); + if (colonIndex > 0 && colonIndex < text.length - 1 && colonIndex < 50) { + final potentialSender = text.substring(0, colonIndex); + if (!RegExp(r'[:\[\]]').hasMatch(potentialSender)) { + senderName = potentialSender; + final offset = (colonIndex + 1 < text.length && text[colonIndex + 1] == ' ') + ? colonIndex + 2 + : colonIndex + 1; + actualText = text.substring(offset); + } + } + + final decodedText = Smaz.tryDecodePrefixed(actualText) ?? actualText; + + return ChannelMessage( + senderKey: null, + senderName: senderName, + text: decodedText, + timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), + isOutgoing: false, + status: ChannelMessageStatus.sent, + pathLength: pathLen, + pathBytes: pathBytes, + channelIndex: channelIdx, + ); + } + + static ChannelMessage outgoing(String text, String senderName, int channelIndex) { + return ChannelMessage( + senderKey: null, + senderName: senderName, + text: text, + timestamp: DateTime.now(), + isOutgoing: true, + status: ChannelMessageStatus.pending, + pathLength: null, + pathBytes: Uint8List(0), + channelIndex: channelIndex, + ); + } +} diff --git a/lib/models/contact.dart b/lib/models/contact.dart new file mode 100644 index 00000000..80e2e8a6 --- /dev/null +++ b/lib/models/contact.dart @@ -0,0 +1,110 @@ +import 'dart:typed_data'; +import '../connector/meshcore_protocol.dart'; + +class Contact { + final Uint8List publicKey; + final String name; + final int type; + final int pathLength; // -1 = flood, 0+ = direct hops + final Uint8List path; + final double? latitude; + final double? longitude; + final DateTime lastSeen; + + Contact({ + required this.publicKey, + required this.name, + required this.type, + required this.pathLength, + required this.path, + this.latitude, + this.longitude, + required this.lastSeen, + }); + + String get publicKeyHex => pubKeyToHex(publicKey); + + String get typeLabel { + switch (type) { + case advTypeChat: + return 'Chat'; + case advTypeRepeater: + return 'Repeater'; + case advTypeRoom: + return 'Room'; + case advTypeSensor: + return 'Sensor'; + default: + return 'Unknown'; + } + } + + String get pathLabel { + if (pathLength < 0) return 'Flood'; + if (pathLength == 0) return 'Direct'; + return '$pathLength hops'; + } + + bool get hasLocation => latitude != null && longitude != null; + + String get pathIdList { + if (path.isEmpty) return ''; + final parts = []; + final groupSize = pathHashSize; + for (int i = 0; i < path.length; i += groupSize) { + final end = (i + groupSize) <= path.length ? (i + groupSize) : path.length; + final chunk = path.sublist(i, end); + parts.add( + chunk.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()).join(), + ); + } + return parts.join(','); + } + + static Contact? fromFrame(Uint8List data) { + if (data.length < contactFrameSize) return null; + if (data[0] != respCodeContact) return null; + + final pubKey = Uint8List.fromList( + data.sublist(contactPubKeyOffset, contactPubKeyOffset + pubKeySize), + ); + final type = data[contactTypeOffset]; + final pathLen = data[contactPathLenOffset].toSigned(8); + final safePathLen = pathLen > 0 + ? (pathLen > maxPathSize ? maxPathSize : pathLen) + : 0; + final pathBytes = safePathLen > 0 + ? Uint8List.fromList( + data.sublist(contactPathOffset, contactPathOffset + safePathLen), + ) + : Uint8List(0); + final name = readCString(data, contactNameOffset, maxNameSize); + final lastmod = readUint32LE(data, contactLastmodOffset); + + double? lat, lon; + final latRaw = readInt32LE(data, contactLatOffset); + final lonRaw = readInt32LE(data, contactLonOffset); + if (latRaw != 0 || lonRaw != 0) { + lat = latRaw / 1e6; + lon = lonRaw / 1e6; + } + + return Contact( + publicKey: pubKey, + name: name.isEmpty ? 'Unknown' : name, + type: type, + pathLength: pathLen, + path: pathBytes, + latitude: lat, + longitude: lon, + lastSeen: DateTime.fromMillisecondsSinceEpoch(lastmod * 1000), + ); + } + + @override + bool operator ==(Object other) => + other is Contact && publicKeyHex == other.publicKeyHex; + + @override + int get hashCode => publicKeyHex.hashCode; +} diff --git a/lib/models/contact_group.dart b/lib/models/contact_group.dart new file mode 100644 index 00000000..000a4748 --- /dev/null +++ b/lib/models/contact_group.dart @@ -0,0 +1,37 @@ +class ContactGroup { + final String name; + final List memberKeys; + + const ContactGroup({ + required this.name, + required this.memberKeys, + }); + + ContactGroup copyWith({ + String? name, + List? memberKeys, + }) { + return ContactGroup( + name: name ?? this.name, + memberKeys: memberKeys ?? List.from(this.memberKeys), + ); + } + + Map toJson() { + return { + 'name': name, + 'members': memberKeys, + }; + } + + factory ContactGroup.fromJson(Map json) { + final members = (json['members'] as List?) + ?.map((value) => value.toString()) + .toList() ?? + []; + return ContactGroup( + name: json['name'] as String? ?? '', + memberKeys: members, + ); + } +} diff --git a/lib/models/message.dart b/lib/models/message.dart new file mode 100644 index 00000000..4c347d46 --- /dev/null +++ b/lib/models/message.dart @@ -0,0 +1,125 @@ +import 'dart:typed_data'; +import '../connector/meshcore_protocol.dart'; + +enum MessageStatus { pending, sent, delivered, failed } + +class Message { + final Uint8List senderKey; + final String text; + final DateTime timestamp; + final bool isOutgoing; + final bool isCli; + final MessageStatus status; + + // NEW: Retry logic fields + final String? messageId; + final int retryCount; + final int? estimatedTimeoutMs; + final Uint8List? expectedAckHash; + final DateTime? sentAt; + final DateTime? deliveredAt; + final int? tripTimeMs; + final bool forceFlood; + final int? pathLength; + final Uint8List pathBytes; + + Message({ + required this.senderKey, + required this.text, + required this.timestamp, + required this.isOutgoing, + this.isCli = false, + this.status = MessageStatus.pending, + this.messageId, + this.retryCount = 0, + this.estimatedTimeoutMs, + this.expectedAckHash, + this.sentAt, + this.deliveredAt, + this.tripTimeMs, + this.forceFlood = false, + this.pathLength, + Uint8List? pathBytes, + }) : pathBytes = pathBytes ?? Uint8List(0); + + String get senderKeyHex => pubKeyToHex(senderKey); + + Message copyWith({ + MessageStatus? status, + int? retryCount, + int? estimatedTimeoutMs, + Uint8List? expectedAckHash, + DateTime? sentAt, + DateTime? deliveredAt, + int? tripTimeMs, + int? pathLength, + Uint8List? pathBytes, + bool? isCli, + }) { + return Message( + senderKey: senderKey, + text: text, + timestamp: timestamp, + isOutgoing: isOutgoing, + isCli: isCli ?? this.isCli, + status: status ?? this.status, + messageId: messageId, + retryCount: retryCount ?? this.retryCount, + estimatedTimeoutMs: estimatedTimeoutMs ?? this.estimatedTimeoutMs, + expectedAckHash: expectedAckHash ?? this.expectedAckHash, + sentAt: sentAt ?? this.sentAt, + deliveredAt: deliveredAt ?? this.deliveredAt, + tripTimeMs: tripTimeMs ?? this.tripTimeMs, + forceFlood: forceFlood, + pathLength: pathLength ?? this.pathLength, + pathBytes: pathBytes ?? this.pathBytes, + ); + } + + static Message? fromFrame(Uint8List data, Uint8List selfPubKey) { + if (data.length < msgTextOffset + 1) return null; + + final code = data[0]; + if (code != respCodeContactMsgRecv && code != respCodeContactMsgRecvV3) { + return null; + } + + final senderKey = Uint8List.fromList( + data.sublist(msgPubKeyOffset, msgPubKeyOffset + pubKeySize), + ); + final timestampRaw = readUint32LE(data, msgTimestampOffset); + final flags = data[msgFlagsOffset]; + if ((flags >> 2) != txtTypePlain) { + return null; + } + final text = readCString(data, msgTextOffset, data.length - msgTextOffset); + + return Message( + senderKey: senderKey, + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), + isOutgoing: false, + isCli: false, + status: MessageStatus.delivered, + pathBytes: Uint8List(0), + ); + } + + static Message outgoing( + Uint8List recipientKey, + String text, { + int? pathLength, + Uint8List? pathBytes, + }) { + return Message( + senderKey: recipientKey, + text: text, + timestamp: DateTime.now(), + isOutgoing: true, + isCli: false, + status: MessageStatus.pending, + pathLength: pathLength, + pathBytes: pathBytes, + ); + } +} diff --git a/lib/models/path_history.dart b/lib/models/path_history.dart new file mode 100644 index 00000000..1e2426a0 --- /dev/null +++ b/lib/models/path_history.dart @@ -0,0 +1,85 @@ +class PathRecord { + final int hopCount; + final int tripTimeMs; + final DateTime timestamp; + final bool wasFloodDiscovery; + final List pathBytes; + final int successCount; + final int failureCount; + + PathRecord({ + required this.hopCount, + required this.tripTimeMs, + required this.timestamp, + required this.wasFloodDiscovery, + required this.pathBytes, + required this.successCount, + required this.failureCount, + }); + + String get displayText => + '$hopCount ${hopCount == 1 ? 'hop' : 'hops'} - ${(tripTimeMs / 1000).toStringAsFixed(2)}s'; + + Map toJson() { + return { + 'hop_count': hopCount, + 'trip_time_ms': tripTimeMs, + 'timestamp': timestamp.toIso8601String(), + 'was_flood': wasFloodDiscovery, + 'path_bytes': pathBytes, + 'success_count': successCount, + 'failure_count': failureCount, + }; + } + + factory PathRecord.fromJson(Map json) { + return PathRecord( + hopCount: json['hop_count'] as int, + tripTimeMs: json['trip_time_ms'] as int, + timestamp: DateTime.parse(json['timestamp'] as String), + wasFloodDiscovery: json['was_flood'] as bool, + pathBytes: (json['path_bytes'] as List?)?.map((b) => b as int).toList() ?? [], + successCount: json['success_count'] as int? ?? 0, + failureCount: json['failure_count'] as int? ?? 0, + ); + } +} + +class ContactPathHistory { + final String contactPubKeyHex; + final List recentPaths; + + ContactPathHistory({ + required this.contactPubKeyHex, + required this.recentPaths, + }); + + PathRecord? get fastest { + if (recentPaths.isEmpty) return null; + return recentPaths.reduce((a, b) => a.tripTimeMs < b.tripTimeMs ? a : b); + } + + PathRecord? get mostRecent { + if (recentPaths.isEmpty) return null; + return recentPaths.first; + } + + Map toJson() { + return { + 'recent_paths': recentPaths.map((p) => p.toJson()).toList(), + }; + } + + factory ContactPathHistory.fromJson( + String contactPubKeyHex, Map json) { + final pathsList = (json['recent_paths'] as List?) + ?.map((p) => PathRecord.fromJson(p as Map)) + .toList() ?? + []; + + return ContactPathHistory( + contactPubKeyHex: contactPubKeyHex, + recentPaths: pathsList, + ); + } +} diff --git a/lib/models/path_selection.dart b/lib/models/path_selection.dart new file mode 100644 index 00000000..65f2f278 --- /dev/null +++ b/lib/models/path_selection.dart @@ -0,0 +1,11 @@ +class PathSelection { + final List pathBytes; + final int hopCount; + final bool useFlood; + + const PathSelection({ + required this.pathBytes, + required this.hopCount, + required this.useFlood, + }); +} diff --git a/lib/models/radio_settings.dart b/lib/models/radio_settings.dart new file mode 100644 index 00000000..9df96be1 --- /dev/null +++ b/lib/models/radio_settings.dart @@ -0,0 +1,107 @@ +enum LoRaBandwidth { + bw7_8(7800, '7.8 kHz'), + bw10_4(10400, '10.4 kHz'), + bw15_6(15600, '15.6 kHz'), + bw20_8(20800, '20.8 kHz'), + bw31_25(31250, '31.25 kHz'), + bw41_7(41700, '41.7 kHz'), + bw62_5(62500, '62.5 kHz'), + bw125(125000, '125 kHz'), + bw250(250000, '250 kHz'), + bw500(500000, '500 kHz'); + + final int hz; + final String label; + + const LoRaBandwidth(this.hz, this.label); +} + +enum LoRaSpreadingFactor { + sf5(5, 'SF5'), + sf6(6, 'SF6'), + sf7(7, 'SF7'), + sf8(8, 'SF8'), + sf9(9, 'SF9'), + sf10(10, 'SF10'), + sf11(11, 'SF11'), + sf12(12, 'SF12'); + + final int value; + final String label; + + const LoRaSpreadingFactor(this.value, this.label); +} + +enum LoRaCodingRate { + cr4_5(5, '4/5'), + cr4_6(6, '4/6'), + cr4_7(7, '4/7'), + cr4_8(8, '4/8'); + + final int value; + final String label; + + const LoRaCodingRate(this.value, this.label); +} + +class RadioSettings { + final double frequencyMHz; + final LoRaBandwidth bandwidth; + final LoRaSpreadingFactor spreadingFactor; + final LoRaCodingRate codingRate; + final int txPowerDbm; + + RadioSettings({ + required this.frequencyMHz, + required this.bandwidth, + required this.spreadingFactor, + required this.codingRate, + required this.txPowerDbm, + }); + + // Preset configurations + static RadioSettings get preset915MHz => RadioSettings( + frequencyMHz: 915.0, + bandwidth: LoRaBandwidth.bw125, + spreadingFactor: LoRaSpreadingFactor.sf7, + codingRate: LoRaCodingRate.cr4_5, + txPowerDbm: 20, + ); + + static RadioSettings get preset868MHz => RadioSettings( + frequencyMHz: 868.0, + bandwidth: LoRaBandwidth.bw125, + spreadingFactor: LoRaSpreadingFactor.sf7, + codingRate: LoRaCodingRate.cr4_5, + txPowerDbm: 14, + ); + + static RadioSettings get preset433MHz => RadioSettings( + frequencyMHz: 433.0, + bandwidth: LoRaBandwidth.bw125, + spreadingFactor: LoRaSpreadingFactor.sf7, + codingRate: LoRaCodingRate.cr4_5, + txPowerDbm: 20, + ); + + static RadioSettings get presetLongRange => RadioSettings( + frequencyMHz: 915.0, + bandwidth: LoRaBandwidth.bw125, + spreadingFactor: LoRaSpreadingFactor.sf12, + codingRate: LoRaCodingRate.cr4_8, + txPowerDbm: 20, + ); + + static RadioSettings get presetFastSpeed => RadioSettings( + frequencyMHz: 915.0, + bandwidth: LoRaBandwidth.bw500, + spreadingFactor: LoRaSpreadingFactor.sf7, + codingRate: LoRaCodingRate.cr4_5, + txPowerDbm: 20, + ); + + int get frequencyHz => (frequencyMHz * 1000).round(); + int get bandwidthHz => bandwidth.hz; + int get sf => spreadingFactor.value; + int get cr => codingRate.value; +} diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart new file mode 100644 index 00000000..2592a972 --- /dev/null +++ b/lib/screens/app_settings_screen.dart @@ -0,0 +1,484 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../services/app_settings_service.dart'; +import '../services/notification_service.dart'; + +class AppSettingsScreen extends StatelessWidget { + const AppSettingsScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('App Settings'), + centerTitle: true, + ), + body: Consumer2( + builder: (context, settingsService, connector, child) { + return ListView( + padding: const EdgeInsets.all(16), + children: [ + _buildAppearanceCard(context, settingsService), + const SizedBox(height: 16), + _buildNotificationsCard(context, settingsService), + const SizedBox(height: 16), + _buildMessagingCard(context, settingsService), + const SizedBox(height: 16), + _buildBatteryCard(context, settingsService, connector), + const SizedBox(height: 16), + _buildMapSettingsCard(context, settingsService), + ], + ); + }, + ), + ); + } + + Widget _buildAppearanceCard(BuildContext context, AppSettingsService settingsService) { + return Card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text( + 'Appearance', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + ListTile( + leading: const Icon(Icons.brightness_6_outlined), + title: const Text('Theme'), + subtitle: Text(_themeModeLabel(settingsService.settings.themeMode)), + trailing: const Icon(Icons.chevron_right), + onTap: () => _showThemeModeDialog(context, settingsService), + ), + ], + ), + ); + } + + Widget _buildNotificationsCard(BuildContext context, AppSettingsService settingsService) { + return Card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text( + 'Notifications', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + SwitchListTile( + secondary: const Icon(Icons.notifications_outlined), + title: const Text('Enable Notifications'), + subtitle: const Text('Receive notifications for messages and adverts'), + value: settingsService.settings.notificationsEnabled, + onChanged: (value) async { + if (value) { + // Request permission when enabling + final granted = await NotificationService().requestPermissions(); + if (!granted) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Notification permission denied'), + duration: Duration(seconds: 2), + ), + ); + } + return; + } + } + + await settingsService.setNotificationsEnabled(value); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(value + ? 'Notifications enabled' + : 'Notifications disabled'), + duration: const Duration(seconds: 2), + ), + ); + } + }, + ), + const Divider(height: 1), + SwitchListTile( + secondary: Icon( + Icons.message_outlined, + color: settingsService.settings.notificationsEnabled ? null : Colors.grey, + ), + title: Text( + 'Message Notifications', + style: TextStyle( + color: settingsService.settings.notificationsEnabled ? null : Colors.grey, + ), + ), + subtitle: Text( + 'Show notification when receiving new messages', + style: TextStyle( + color: settingsService.settings.notificationsEnabled ? null : Colors.grey, + ), + ), + value: settingsService.settings.notifyOnNewMessage, + onChanged: settingsService.settings.notificationsEnabled + ? (value) { + settingsService.setNotifyOnNewMessage(value); + } + : null, + ), + const Divider(height: 1), + SwitchListTile( + secondary: Icon( + Icons.cell_tower, + color: settingsService.settings.notificationsEnabled ? null : Colors.grey, + ), + title: Text( + 'Advertisement Notifications', + style: TextStyle( + color: settingsService.settings.notificationsEnabled ? null : Colors.grey, + ), + ), + subtitle: Text( + 'Show notification when new nodes are discovered', + style: TextStyle( + color: settingsService.settings.notificationsEnabled ? null : Colors.grey, + ), + ), + value: settingsService.settings.notifyOnNewAdvert, + onChanged: settingsService.settings.notificationsEnabled + ? (value) { + settingsService.setNotifyOnNewAdvert(value); + } + : null, + ), + ], + ), + ); + } + + Widget _buildMessagingCard(BuildContext context, AppSettingsService settingsService) { + return Card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text( + 'Messaging', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + SwitchListTile( + secondary: const Icon(Icons.refresh_outlined), + title: const Text('Clear Path on Max Retry'), + subtitle: const Text('Reset contact path after 5 failed send attempts'), + value: settingsService.settings.clearPathOnMaxRetry, + onChanged: (value) { + settingsService.setClearPathOnMaxRetry(value); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(value + ? 'Paths will be cleared after 5 failed retries' + : 'Paths will not be auto-cleared'), + duration: const Duration(seconds: 2), + ), + ); + }, + ), + const Divider(height: 1), + SwitchListTile( + secondary: const Icon(Icons.alt_route), + title: const Text('Auto Route Rotation'), + subtitle: const Text('Cycle between best paths and flood mode'), + value: settingsService.settings.autoRouteRotationEnabled, + onChanged: (value) { + settingsService.setAutoRouteRotationEnabled(value); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(value + ? 'Auto route rotation enabled' + : 'Auto route rotation disabled'), + duration: const Duration(seconds: 2), + ), + ); + }, + ), + ], + ), + ); + } + + Widget _buildMapSettingsCard(BuildContext context, AppSettingsService settingsService) { + return Card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text( + 'Map Display', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + SwitchListTile( + secondary: const Icon(Icons.router_outlined), + title: const Text('Show Repeaters'), + subtitle: const Text('Display repeater nodes on the map'), + value: settingsService.settings.mapShowRepeaters, + onChanged: (value) { + settingsService.setMapShowRepeaters(value); + }, + ), + const Divider(height: 1), + SwitchListTile( + secondary: const Icon(Icons.chat_outlined), + title: const Text('Show Chat Nodes'), + subtitle: const Text('Display chat nodes on the map'), + value: settingsService.settings.mapShowChatNodes, + onChanged: (value) { + settingsService.setMapShowChatNodes(value); + }, + ), + const Divider(height: 1), + SwitchListTile( + secondary: const Icon(Icons.people_outline), + title: const Text('Show Other Nodes'), + subtitle: const Text('Display other node types on the map'), + value: settingsService.settings.mapShowOtherNodes, + onChanged: (value) { + settingsService.setMapShowOtherNodes(value); + }, + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.timer_outlined), + title: const Text('Time Filter'), + subtitle: Text( + settingsService.settings.mapTimeFilterHours == 0 + ? 'Show all nodes' + : 'Show nodes from last ${settingsService.settings.mapTimeFilterHours.toInt()} hours', + ), + trailing: const Icon(Icons.chevron_right), + onTap: () => _showTimeFilterDialog(context, settingsService), + ), + ], + ), + ); + } + + Widget _buildBatteryCard( + BuildContext context, + AppSettingsService settingsService, + MeshCoreConnector connector, + ) { + final deviceId = connector.device?.remoteId.toString(); + final isConnected = connector.isConnected && deviceId != null; + final selection = + isConnected ? settingsService.batteryChemistryForDevice(deviceId) : 'nmc'; + + return Card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text( + 'Battery', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + ListTile( + leading: const Icon(Icons.battery_full), + title: const Text('Battery Chemistry'), + subtitle: Text( + isConnected + ? 'Set per device (${connector.device!.platformName})' + : 'Connect to a device to choose', + ), + trailing: DropdownButton( + value: selection, + onChanged: isConnected + ? (value) { + if (value != null) { + settingsService.setBatteryChemistryForDevice(deviceId, value); + } + } + : null, + items: const [ + DropdownMenuItem( + value: 'nmc', + child: Text('18650 NMC (3.0-4.2V)'), + ), + DropdownMenuItem( + value: 'lifepo4', + child: Text('LiFePO4 (2.6-3.65V)'), + ), + DropdownMenuItem( + value: 'lipo', + child: Text('LiPo (3.0-4.2V)'), + ), + ], + ), + ), + ], + ), + ); + } + + void _showThemeModeDialog(BuildContext context, AppSettingsService settingsService) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Theme'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + RadioListTile( + title: const Text('System default'), + value: 'system', + groupValue: settingsService.settings.themeMode, + onChanged: (value) { + if (value != null) { + settingsService.setThemeMode(value); + Navigator.pop(context); + } + }, + ), + RadioListTile( + title: const Text('Light'), + value: 'light', + groupValue: settingsService.settings.themeMode, + onChanged: (value) { + if (value != null) { + settingsService.setThemeMode(value); + Navigator.pop(context); + } + }, + ), + RadioListTile( + title: const Text('Dark'), + value: 'dark', + groupValue: settingsService.settings.themeMode, + onChanged: (value) { + if (value != null) { + settingsService.setThemeMode(value); + Navigator.pop(context); + } + }, + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } + + String _themeModeLabel(String value) { + switch (value) { + case 'light': + return 'Light'; + case 'dark': + return 'Dark'; + default: + return 'System default'; + } + } + + void _showTimeFilterDialog(BuildContext context, AppSettingsService settingsService) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Map Time Filter'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Show nodes discovered within:'), + const SizedBox(height: 16), + ListTile( + title: const Text('All time'), + leading: Radio( + value: 0, + groupValue: settingsService.settings.mapTimeFilterHours, + onChanged: (value) { + if (value != null) { + settingsService.setMapTimeFilterHours(value); + Navigator.pop(context); + } + }, + ), + ), + ListTile( + title: const Text('Last hour'), + leading: Radio( + value: 1, + groupValue: settingsService.settings.mapTimeFilterHours, + onChanged: (value) { + if (value != null) { + settingsService.setMapTimeFilterHours(value); + Navigator.pop(context); + } + }, + ), + ), + ListTile( + title: const Text('Last 6 hours'), + leading: Radio( + value: 6, + groupValue: settingsService.settings.mapTimeFilterHours, + onChanged: (value) { + if (value != null) { + settingsService.setMapTimeFilterHours(value); + Navigator.pop(context); + } + }, + ), + ), + ListTile( + title: const Text('Last 24 hours'), + leading: Radio( + value: 24, + groupValue: settingsService.settings.mapTimeFilterHours, + onChanged: (value) { + if (value != null) { + settingsService.setMapTimeFilterHours(value); + Navigator.pop(context); + } + }, + ), + ), + ListTile( + title: const Text('Last week'), + leading: Radio( + value: 168, + groupValue: settingsService.settings.mapTimeFilterHours, + onChanged: (value) { + if (value != null) { + settingsService.setMapTimeFilterHours(value); + Navigator.pop(context); + } + }, + ), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } +} diff --git a/lib/screens/ble_debug_log_screen.dart b/lib/screens/ble_debug_log_screen.dart new file mode 100644 index 00000000..f7689d2a --- /dev/null +++ b/lib/screens/ble_debug_log_screen.dart @@ -0,0 +1,384 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:flutter/services.dart'; +import '../services/ble_debug_log_service.dart'; +import '../connector/meshcore_protocol.dart'; + +enum _BleLogView { frames, rawLogRx } + +class BleDebugLogScreen extends StatefulWidget { + const BleDebugLogScreen({super.key}); + + @override + State createState() => _BleDebugLogScreenState(); +} + +class _BleDebugLogScreenState extends State { + _BleLogView _view = _BleLogView.frames; + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, logService, _) { + final entries = logService.entries.reversed.toList(); + final rawEntries = logService.rawLogRxEntries.reversed.toList(); + final showingFrames = _view == _BleLogView.frames; + final hasEntries = showingFrames ? entries.isNotEmpty : rawEntries.isNotEmpty; + return Scaffold( + appBar: AppBar( + title: const Text('BLE Debug Log'), + actions: [ + IconButton( + tooltip: 'Copy log', + icon: const Icon(Icons.copy), + onPressed: hasEntries + ? () async { + final text = showingFrames + ? entries + .map((entry) => '${entry.description}\n${entry.hexPreview}\n') + .join('\n') + : rawEntries + .map((entry) => 'RX RAW_LOG_RX_DATA\n${entry.hexPreview}\n') + .join('\n'); + await Clipboard.setData(ClipboardData(text: text)); + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('BLE log copied')), + ); + } + : null, + ), + IconButton( + tooltip: 'Clear log', + icon: const Icon(Icons.delete_outline), + onPressed: hasEntries + ? () { + logService.clear(); + } + : null, + ), + ], + ), + body: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), + child: SegmentedButton<_BleLogView>( + segments: const [ + ButtonSegment(value: _BleLogView.frames, label: Text('Frames')), + ButtonSegment(value: _BleLogView.rawLogRx, label: Text('Raw Log-RX')), + ], + selected: {_view}, + onSelectionChanged: (selection) { + setState(() => _view = selection.first); + }, + ), + ), + const SizedBox(height: 8), + Expanded( + child: hasEntries + ? ListView.separated( + itemCount: showingFrames ? entries.length : rawEntries.length, + separatorBuilder: (_, __) => const Divider(height: 1), + itemBuilder: (context, index) { + if (showingFrames) { + final entry = entries[index]; + final time = + '${entry.timestamp.hour.toString().padLeft(2, '0')}:${entry.timestamp.minute.toString().padLeft(2, '0')}:${entry.timestamp.second.toString().padLeft(2, '0')}'; + return ListTile( + dense: true, + title: Text(entry.description), + subtitle: Text('${entry.hexPreview}\n$time'), + isThreeLine: true, + leading: Icon( + entry.outgoing ? Icons.upload : Icons.download, + size: 18, + ), + ); + } + + final entry = rawEntries[index]; + final info = _decodeRawPacket(entry.payload); + final time = + '${entry.timestamp.hour.toString().padLeft(2, '0')}:${entry.timestamp.minute.toString().padLeft(2, '0')}:${entry.timestamp.second.toString().padLeft(2, '0')}'; + return ListTile( + dense: true, + title: Text(info.title), + subtitle: Text('${info.summary}\n$time'), + isThreeLine: true, + leading: const Icon(Icons.download, size: 18), + onTap: () => _showRawDialog(context, info), + ); + }, + ) + : const Center( + child: Text('No BLE activity yet'), + ), + ), + ], + ), + ); + }, + ); + } + + void _showRawDialog(BuildContext context, _RawPacketInfo info) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(info.title), + content: SingleChildScrollView( + child: SelectableText(info.rawHex), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } + + _RawPacketInfo _decodeRawPacket(Uint8List raw) { + if (raw.length < 2) { + return _RawPacketInfo( + title: 'RX RAW_LOG_RX_DATA • invalid', + summary: 'Packet too short', + rawHex: _bytesToHex(raw), + ); + } + + var index = 0; + final header = raw[index++]; + final routeType = header & 0x03; + final payloadType = (header >> 2) & 0x0F; + final payloadVer = (header >> 6) & 0x03; + final hasTransport = routeType == 0 || routeType == 3; + if (hasTransport) { + if (raw.length < index + 4) { + return _RawPacketInfo( + title: 'RX RAW_LOG_RX_DATA • ${_payloadTypeLabel(payloadType)}', + summary: 'Missing transport codes', + rawHex: _bytesToHex(raw), + ); + } + index += 4; + } + if (raw.length <= index) { + return _RawPacketInfo( + title: 'RX RAW_LOG_RX_DATA • ${_payloadTypeLabel(payloadType)}', + summary: 'Missing path length', + rawHex: _bytesToHex(raw), + ); + } + final pathLen = raw[index++]; + if (raw.length < index + pathLen) { + return _RawPacketInfo( + title: 'RX RAW_LOG_RX_DATA • ${_payloadTypeLabel(payloadType)}', + summary: 'Truncated path', + rawHex: _bytesToHex(raw), + ); + } + final pathBytes = raw.sublist(index, index + pathLen); + index += pathLen; + if (raw.length <= index) { + return _RawPacketInfo( + title: 'RX RAW_LOG_RX_DATA • ${_payloadTypeLabel(payloadType)}', + summary: 'Missing payload', + rawHex: _bytesToHex(raw), + ); + } + final payload = raw.sublist(index); + + final title = 'RX ${_payloadTypeLabel(payloadType)} • ${_routeLabel(routeType)} • v$payloadVer'; + final summary = _decodePayloadSummary(payloadType, payload); + final pathSummary = pathLen > 0 ? 'Path=${_bytesToHex(pathBytes)}' : 'Path=none'; + final detail = '$summary • $pathSummary • len=${raw.length}'; + return _RawPacketInfo(title: title, summary: detail, rawHex: _bytesToHex(raw)); + } + + String _decodePayloadSummary(int payloadType, Uint8List payload) { + switch (payloadType) { + case 0x00: // REQ + return 'REQ payload=${payload.length} bytes'; + case 0x01: // RESP + return 'RESP payload=${payload.length} bytes'; + case 0x02: // TXT + return 'TXT payload=${payload.length} bytes'; + case 0x03: // ACK + if (payload.length < 4) return 'ACK (short)'; + return 'ACK crc=${_bytesToHex(payload.sublist(0, 4))}'; + case 0x04: // ADVERT + return _decodeAdvertSummary(payload); + case 0x05: // GROUP_TXT + if (payload.length < 3) return 'GRP_TXT (short)'; + final channelHash = payload[0].toRadixString(16).padLeft(2, '0'); + final mac = _bytesToHex(payload.sublist(1, 3)); + final cipherLen = payload.length - 3; + return 'GRP_TXT hash=$channelHash mac=$mac cipher=$cipherLen'; + case 0x06: // GROUP_DATA + return 'GRP_DATA payload=${payload.length} bytes'; + case 0x07: // ANON_REQ + return 'ANON_REQ payload=${payload.length} bytes'; + case 0x08: // PATH + return 'PATH payload=${payload.length} bytes'; + case 0x09: // TRACE + return 'TRACE payload=${payload.length} bytes'; + case 0x0A: // MULTIPART + return 'MULTIPART payload=${payload.length} bytes'; + case 0x0B: // CONTROL + return _decodeControlSummary(payload); + case 0x0F: // RAW + return 'RAW payload=${payload.length} bytes'; + default: + return 'TYPE_$payloadType payload=${payload.length} bytes'; + } + } + + String _decodeAdvertSummary(Uint8List payload) { + if (payload.length < 101) { + return 'ADVERT (short)'; + } + var offset = 0; + final pubKey = _bytesToHex(payload.sublist(offset, offset + 32), spaced: false); + offset += 32; + final timestamp = readUint32LE(payload, offset); + offset += 4; + offset += 64; // signature + final flags = payload[offset++]; + final role = _deviceRoleLabel(flags & 0x0F); + final hasLocation = (flags & 0x10) != 0; + final hasFeature1 = (flags & 0x20) != 0; + final hasFeature2 = (flags & 0x40) != 0; + final hasName = (flags & 0x80) != 0; + String? name; + double? lat; + double? lon; + if (hasLocation && payload.length >= offset + 8) { + lat = readInt32LE(payload, offset) / 1000000.0; + lon = readInt32LE(payload, offset + 4) / 1000000.0; + offset += 8; + } + if (hasFeature1) offset += 2; + if (hasFeature2) offset += 2; + if (hasName && payload.length > offset) { + final rawName = String.fromCharCodes(payload.sublist(offset)); + final nul = rawName.indexOf('\u0000'); + name = nul >= 0 ? rawName.substring(0, nul) : rawName; + name = name.trim(); + } + final namePart = (name != null && name.isNotEmpty) ? ' name="$name"' : ''; + final locPart = (lat != null && lon != null) + ? ' loc=${lat.toStringAsFixed(6)},${lon.toStringAsFixed(6)}' + : ''; + return 'ADVERT role=$role ts=$timestamp$namePart$locPart key=${pubKey.substring(0, 12)}…'; + } + + String _decodeControlSummary(Uint8List payload) { + if (payload.isEmpty) return 'CONTROL (empty)'; + final flags = payload[0]; + final subType = flags & 0xF0; + if (subType == 0x80) { + if (payload.length < 6) return 'CONTROL DISCOVER_REQ (short)'; + final typeFilter = payload[1]; + final tag = readUint32LE(payload, 2); + final since = payload.length >= 10 ? readUint32LE(payload, 6) : 0; + return 'CONTROL DISCOVER_REQ filter=0x${typeFilter.toRadixString(16).padLeft(2, '0')} tag=$tag since=$since'; + } + if (subType == 0x90) { + if (payload.length < 14) return 'CONTROL DISCOVER_RESP (short)'; + final nodeType = flags & 0x0F; + final snrRaw = payload[1]; + final snrSigned = snrRaw > 127 ? snrRaw - 256 : snrRaw; + final snr = snrSigned / 4.0; + final tag = readUint32LE(payload, 2); + final keyLen = payload.length - 6; + return 'CONTROL DISCOVER_RESP node=${_deviceRoleLabel(nodeType)} snr=${snr.toStringAsFixed(2)} tag=$tag key=$keyLen'; + } + return 'CONTROL subtype=0x${subType.toRadixString(16).padLeft(2, '0')}'; + } + + String _payloadTypeLabel(int payloadType) { + switch (payloadType) { + case 0x00: + return 'REQ'; + case 0x01: + return 'RESP'; + case 0x02: + return 'TXT'; + case 0x03: + return 'ACK'; + case 0x04: + return 'ADVERT'; + case 0x05: + return 'GRP_TXT'; + case 0x06: + return 'GRP_DATA'; + case 0x07: + return 'ANON_REQ'; + case 0x08: + return 'PATH'; + case 0x09: + return 'TRACE'; + case 0x0A: + return 'MULTIPART'; + case 0x0B: + return 'CONTROL'; + case 0x0F: + return 'RAW'; + default: + return 'TYPE_$payloadType'; + } + } + + String _routeLabel(int routeType) { + switch (routeType) { + case 0: + return 'TRANS_FLOOD'; + case 1: + return 'FLOOD'; + case 2: + return 'DIRECT'; + case 3: + return 'TRANS_DIRECT'; + default: + return 'ROUTE_$routeType'; + } + } + + String _deviceRoleLabel(int role) { + switch (role) { + case 0x01: + return 'Chat'; + case 0x02: + return 'Repeater'; + case 0x03: + return 'Room'; + case 0x04: + return 'Sensor'; + default: + return 'Unknown'; + } + } + + String _bytesToHex(Uint8List bytes, {bool spaced = true}) { + if (bytes.isEmpty) return ''; + if (!spaced) { + return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); + } + return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' '); + } +} + +class _RawPacketInfo { + final String title; + final String summary; + final String rawHex; + + _RawPacketInfo({ + required this.title, + required this.summary, + required this.rawHex, + }); +} diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart new file mode 100644 index 00000000..e9b7476d --- /dev/null +++ b/lib/screens/channel_chat_screen.dart @@ -0,0 +1,555 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../models/channel.dart'; +import '../models/channel_message.dart'; +import '../utils/emoji_utils.dart'; +import '../widgets/gif_message.dart'; +import '../widgets/gif_picker.dart'; +import 'map_screen.dart'; + +class ChannelChatScreen extends StatefulWidget { + final Channel channel; + + const ChannelChatScreen({ + super.key, + required this.channel, + }); + + @override + State createState() => _ChannelChatScreenState(); +} + +class _ChannelChatScreenState extends State { + final TextEditingController _textController = TextEditingController(); + final ScrollController _scrollController = ScrollController(); + + @override + void dispose() { + _textController.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + void _scrollToBottom() { + if (_scrollController.hasClients) { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Row( + children: [ + Icon( + widget.channel.isPublicChannel ? Icons.public : Icons.tag, + size: 20, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.channel.name.isEmpty + ? 'Channel ${widget.channel.index}' + : widget.channel.name, + style: const TextStyle(fontSize: 16), + ), + Text( + widget.channel.isPublicChannel ? 'Public' : 'Private', + style: const TextStyle(fontSize: 12), + ), + ], + ), + ), + ], + ), + centerTitle: false, + ), + body: Column( + children: [ + Expanded( + child: Consumer( + builder: (context, connector, child) { + final messages = connector.getChannelMessages(widget.channel); + + WidgetsBinding.instance.addPostFrameCallback((_) { + _scrollToBottom(); + }); + + if (messages.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + widget.channel.isPublicChannel + ? Icons.public + : Icons.tag, + size: 64, + color: Colors.grey[400], + ), + const SizedBox(height: 16), + Text( + 'No messages yet', + style: TextStyle( + fontSize: 16, + color: Colors.grey[600], + ), + ), + const SizedBox(height: 8), + Text( + 'Send a message to get started', + style: TextStyle( + fontSize: 14, + color: Colors.grey[500], + ), + ), + ], + ), + ); + } + + return ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.all(8), + cacheExtent: 0, + addAutomaticKeepAlives: false, + itemCount: messages.length, + itemBuilder: (context, index) { + final message = messages[index]; + return _buildMessageBubble(message); + }, + ); + }, + ), + ), + _buildMessageComposer(), + ], + ), + ); + } + + Widget _buildMessageBubble(ChannelMessage message) { + final isOutgoing = message.isOutgoing; + final gifId = _parseGifId(message.text); + final poi = _parsePoiMessage(message.text); + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), + child: Row( + mainAxisAlignment: isOutgoing ? MainAxisAlignment.end : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isOutgoing) ...[ + _buildAvatar(message.senderName), + const SizedBox(width: 8), + ], + Flexible( + child: GestureDetector( + onLongPress: () => _showMessagePathInfo(message), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width * 0.65, + ), + decoration: BoxDecoration( + color: isOutgoing + ? Theme.of(context).colorScheme.primaryContainer + : Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isOutgoing) ...[ + Text( + message.senderName, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.primary, + ), + ), + const SizedBox(height: 4), + ], + if (poi != null) + _buildPoiMessage(context, poi, isOutgoing) + else if (gifId != null) + GifMessage( + url: 'https://media.giphy.com/media/$gifId/giphy.gif', + backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest, + fallbackTextColor: isOutgoing + ? Theme.of(context).colorScheme.onPrimaryContainer.withValues(alpha: 0.7) + : Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.6), + ) + else + Text( + message.text, + style: const TextStyle(fontSize: 14), + ), + if (message.pathBytes.isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + 'via ${_formatPathPrefixes(message.pathBytes)}', + style: TextStyle(fontSize: 11, color: Colors.grey[600]), + ), + ], + const SizedBox(height: 4), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _formatTime(message.timestamp), + style: TextStyle( + fontSize: 11, + color: Colors.grey[600], + ), + ), + if (message.repeatCount > 0) ...[ + const SizedBox(width: 6), + Icon(Icons.repeat, size: 12, color: Colors.grey[600]), + const SizedBox(width: 2), + Text( + '${message.repeatCount}', + style: TextStyle(fontSize: 11, color: Colors.grey[600]), + ), + ], + if (isOutgoing) ...[ + const SizedBox(width: 4), + Icon( + message.status == ChannelMessageStatus.sent + ? Icons.check + : message.status == ChannelMessageStatus.pending + ? Icons.schedule + : Icons.error_outline, + size: 14, + color: message.status == ChannelMessageStatus.failed + ? Colors.red + : Colors.grey[600], + ), + ], + ], + ), + ], + ), + ), + ), + ), + ], + ), + ); + } + + String? _parseGifId(String text) { + final trimmed = text.trim(); + final match = RegExp(r'^g:([A-Za-z0-9_-]+)$').firstMatch(trimmed); + return match?.group(1); + } + + _PoiInfo? _parsePoiMessage(String text) { + final trimmed = text.trim(); + final match = RegExp(r'm:([\-0-9.]+),([\-0-9.]+)\|([^|]*)\|').firstMatch(trimmed); + if (match == null) return null; + final lat = double.tryParse(match.group(1) ?? ''); + final lon = double.tryParse(match.group(2) ?? ''); + if (lat == null || lon == null) return null; + final label = match.group(3) ?? ''; + return _PoiInfo(lat: lat, lon: lon, label: label); + } + + Widget _buildPoiMessage(BuildContext context, _PoiInfo poi, bool isOutgoing) { + final colorScheme = Theme.of(context).colorScheme; + final textColor = + isOutgoing ? colorScheme.onPrimaryContainer : colorScheme.onSurface; + final metaColor = textColor.withValues(alpha: 0.7); + final channelColor = widget.channel.isPublicChannel ? Colors.orange : Colors.blue; + + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + IconButton( + icon: Icon(Icons.location_on_outlined, color: channelColor), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => MapScreen( + highlightPosition: LatLng(poi.lat, poi.lon), + highlightLabel: poi.label, + ), + ), + ); + }, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'POI Shared', + style: TextStyle( + color: textColor, + fontWeight: FontWeight.w600, + ), + ), + if (poi.label.isNotEmpty) + Text( + poi.label, + style: TextStyle( + color: metaColor, + fontSize: 12, + ), + ), + ], + ), + ), + ], + ); + } + + void _showGifPicker(BuildContext context) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + builder: (context) => GifPicker( + onGifSelected: (gifId) { + _textController.text = 'g:$gifId'; + }, + ), + ); + } + + Widget _buildAvatar(String senderName) { + final initial = _getFirstCharacterOrEmoji(senderName); + final color = _getColorForName(senderName); + + return CircleAvatar( + radius: 18, + backgroundColor: color.withValues(alpha: 0.2), + child: Text( + initial, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: color, + ), + ), + ); + } + + String _getFirstCharacterOrEmoji(String name) { + if (name.isEmpty) return '?'; + + final emoji = firstEmoji(name); + if (emoji != null) return emoji; + + final runes = name.runes.toList(); + if (runes.isEmpty) return '?'; + return String.fromCharCode(runes[0]).toUpperCase(); + } + + Color _getColorForName(String name) { + // Generate a consistent color based on the name hash + final hash = name.hashCode; + final colors = [ + Colors.blue, + Colors.green, + Colors.orange, + Colors.purple, + Colors.pink, + Colors.teal, + Colors.indigo, + Colors.cyan, + Colors.amber, + Colors.deepOrange, + ]; + + return colors[hash.abs() % colors.length]; + } + + Widget _buildMessageComposer() { + return Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.1), + blurRadius: 4, + offset: const Offset(0, -2), + ), + ], + ), + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.gif_box), + onPressed: () => _showGifPicker(context), + tooltip: 'Send GIF', + ), + Expanded( + child: ValueListenableBuilder( + valueListenable: _textController, + builder: (context, value, child) { + final gifId = _parseGifId(value.text); + if (gifId != null) { + return Row( + children: [ + Expanded( + child: GifMessage( + url: 'https://media.giphy.com/media/$gifId/giphy.gif', + backgroundColor: + Theme.of(context).colorScheme.surfaceContainerHighest, + fallbackTextColor: + Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.6), + width: 160, + height: 110, + ), + ), + const SizedBox(width: 8), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => _textController.clear(), + ), + ], + ); + } + + return TextField( + controller: _textController, + decoration: InputDecoration( + hintText: 'Type a message...', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(24), + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + ), + maxLines: null, + textInputAction: TextInputAction.send, + onSubmitted: (_) => _sendMessage(), + ); + }, + ), + ), + const SizedBox(width: 8), + IconButton( + icon: const Icon(Icons.send), + onPressed: _sendMessage, + color: Theme.of(context).colorScheme.primary, + ), + ], + ), + ); + } + + void _sendMessage() { + final text = _textController.text.trim(); + if (text.isEmpty) return; + + context.read().sendChannelMessage(widget.channel, text); + _textController.clear(); + } + + String _formatTime(DateTime time) { + final now = DateTime.now(); + final diff = now.difference(time); + + if (diff.inDays > 0) { + return '${time.day}/${time.month} ${time.hour}:${time.minute.toString().padLeft(2, '0')}'; + } else { + return '${time.hour}:${time.minute.toString().padLeft(2, '0')}'; + } + } + + void _showMessagePathInfo(ChannelMessage message) { + final pathPrefixes = + message.pathBytes.isNotEmpty ? _formatPathPrefixes(message.pathBytes) : null; + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Packet Path'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildDetailRow('Sender', message.senderName), + _buildDetailRow('Time', _formatTime(message.timestamp)), + _buildDetailRow('Repeats', message.repeatCount.toString()), + _buildDetailRow('Path', _formatPathLabel(message.pathLength)), + if (pathPrefixes != null) _buildDetailRow('Prefixes', pathPrefixes), + if (pathPrefixes == null) ...[ + const SizedBox(height: 8), + const Text( + 'Hop details are not provided for this packet.', + style: TextStyle(fontSize: 11, color: Colors.grey), + ), + ], + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } + + String _formatPathLabel(int? pathLength) { + if (pathLength == null) return 'Unknown'; + if (pathLength < 0) return 'Flood'; + if (pathLength == 0) return 'Direct'; + return '$pathLength hops'; + } + + String _formatPathPrefixes(Uint8List pathBytes) { + return pathBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(','); + } + + Widget _buildDetailRow(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 70, + child: Text(label, style: TextStyle(color: Colors.grey[600])), + ), + Expanded(child: Text(value)), + ], + ), + ); + } +} + +class _PoiInfo { + final double lat; + final double lon; + final String label; + + const _PoiInfo({ + required this.lat, + required this.lon, + required this.label, + }); +} diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart new file mode 100644 index 00000000..fe5e061c --- /dev/null +++ b/lib/screens/channels_screen.dart @@ -0,0 +1,439 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../models/channel.dart'; +import 'channel_chat_screen.dart'; + +class ChannelsScreen extends StatefulWidget { + const ChannelsScreen({super.key}); + + @override + State createState() => _ChannelsScreenState(); +} + +class _ChannelsScreenState extends State { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().getChannels(); + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Channels'), + centerTitle: true, + actions: [ + IconButton( + icon: const Icon(Icons.refresh), + onPressed: () => context.read().getChannels(), + ), + ], + ), + body: Consumer( + builder: (context, connector, child) { + if (connector.isLoadingChannels) { + return const Center(child: CircularProgressIndicator()); + } + + final channels = connector.channels; + + if (channels.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.tag, size: 64, color: Colors.grey[400]), + const SizedBox(height: 16), + Text( + 'No channels configured', + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + const SizedBox(height: 24), + FilledButton.icon( + onPressed: () => _addPublicChannel(context, connector), + icon: const Icon(Icons.public), + label: const Text('Add Public Channel'), + ), + ], + ), + ); + } + + return ReorderableListView.builder( + padding: const EdgeInsets.all(8), + itemCount: channels.length, + onReorder: (oldIndex, newIndex) async { + if (newIndex > oldIndex) newIndex -= 1; + final reordered = List.from(channels); + final item = reordered.removeAt(oldIndex); + reordered.insert(newIndex, item); + await connector.setChannelOrder( + reordered.map((c) => c.index).toList(), + ); + }, + itemBuilder: (context, index) { + final channel = channels[index]; + return _buildChannelTile(context, connector, channel); + }, + ); + }, + ), + floatingActionButton: FloatingActionButton( + onPressed: () => _showAddChannelDialog(context), + child: const Icon(Icons.add), + ), + ); + } + + Widget _buildChannelTile( + BuildContext context, + MeshCoreConnector connector, + Channel channel, + ) { + return Card( + key: ValueKey('channel_${channel.index}'), + child: ListTile( + leading: CircleAvatar( + backgroundColor: channel.isPublicChannel + ? Colors.green.withValues(alpha: 0.2) + : Colors.blue.withValues(alpha: 0.2), + child: Icon( + channel.isPublicChannel + ? Icons.public + : channel.name.startsWith('#') + ? Icons.tag + : Icons.lock, + color: channel.isPublicChannel ? Colors.green : Colors.blue, + ), + ), + title: Text( + channel.name.isEmpty ? 'Channel ${channel.index}' : channel.name, + style: const TextStyle(fontWeight: FontWeight.w500), + ), + subtitle: Text( + channel.name.startsWith('#') + ? 'Hashtag channel' + : channel.isPublicChannel + ? 'Public channel' + : 'Private channel', + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.edit_outlined), + onPressed: () => _showEditChannelDialog(context, connector, channel), + ), + PopupMenuButton( + onSelected: (value) { + if (value == 'delete') { + _confirmDeleteChannel(context, connector, channel); + } + }, + itemBuilder: (context) => [ + const PopupMenuItem( + value: 'delete', + child: Text('Delete'), + ), + ], + ), + ], + ), + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (context) => ChannelChatScreen(channel: channel), + ), + ), + ), + ); + } + + void _showAddChannelDialog(BuildContext context) { + final connector = context.read(); + final nameController = TextEditingController(); + final pskController = TextEditingController(); + final maxChannels = connector.maxChannels; + int selectedIndex = _findNextAvailableIndex(connector.channels, maxChannels); + bool usePublicPsk = false; + + showDialog( + context: context, + builder: (context) => StatefulBuilder( + builder: (context, setDialogState) => AlertDialog( + title: const Text('Add Channel'), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + DropdownButtonFormField( + initialValue: selectedIndex, + decoration: const InputDecoration( + labelText: 'Channel Index', + border: OutlineInputBorder(), + ), + items: List.generate(maxChannels, (i) => i) + .map((i) => DropdownMenuItem( + value: i, + child: Text('Channel $i'), + )) + .toList(), + onChanged: (value) { + if (value != null) { + setDialogState(() => selectedIndex = value); + } + }, + ), + const SizedBox(height: 16), + TextField( + controller: nameController, + decoration: const InputDecoration( + labelText: 'Channel Name', + border: OutlineInputBorder(), + ), + maxLength: 31, + ), + const SizedBox(height: 8), + CheckboxListTile( + title: const Text('Use Public Channel'), + subtitle: const Text('Standard public PSK'), + value: usePublicPsk, + onChanged: (value) { + setDialogState(() { + usePublicPsk = value ?? false; + if (usePublicPsk) { + nameController.text = 'Public'; + pskController.text = Channel.publicChannelPsk; + } else { + pskController.clear(); + } + }); + }, + ), + if (!usePublicPsk) ...[ + const SizedBox(height: 8), + TextField( + controller: pskController, + decoration: InputDecoration( + labelText: 'PSK (Base64)', + border: const OutlineInputBorder(), + suffixIcon: IconButton( + icon: const Icon(Icons.casino), + tooltip: 'Generate random PSK', + onPressed: () { + final random = Random.secure(); + final bytes = Uint8List(16); + for (int i = 0; i < 16; i++) { + bytes[i] = random.nextInt(256); + } + pskController.text = base64Encode(bytes); + }, + ), + ), + ), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () { + final name = nameController.text.trim(); + final pskBase64 = usePublicPsk + ? Channel.publicChannelPsk + : pskController.text.trim(); + + if (name.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Please enter a channel name')), + ); + return; + } + + Uint8List psk; + try { + final decoded = base64Decode(pskBase64); + psk = Uint8List(16); + for (int i = 0; i < decoded.length && i < 16; i++) { + psk[i] = decoded[i]; + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Invalid PSK format')), + ); + return; + } + + Navigator.pop(context); + connector.setChannel(selectedIndex, name, psk); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Channel "$name" added')), + ); + }, + child: const Text('Add'), + ), + ], + ), + ), + ); + } + + void _showEditChannelDialog( + BuildContext context, + MeshCoreConnector connector, + Channel channel, + ) { + final nameController = TextEditingController(text: channel.name); + final pskController = TextEditingController(text: channel.pskBase64); + bool smazEnabled = connector.isChannelSmazEnabled(channel.index); + + showDialog( + context: context, + builder: (context) => StatefulBuilder( + builder: (context, setState) => AlertDialog( + title: Text('Edit Channel ${channel.index}'), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: nameController, + decoration: const InputDecoration( + labelText: 'Channel Name', + border: OutlineInputBorder(), + ), + maxLength: 31, + ), + const SizedBox(height: 16), + TextField( + controller: pskController, + decoration: InputDecoration( + labelText: 'PSK (Base64)', + border: const OutlineInputBorder(), + suffixIcon: IconButton( + icon: const Icon(Icons.casino), + tooltip: 'Generate random PSK', + onPressed: () { + final random = Random.secure(); + final bytes = Uint8List(16); + for (int i = 0; i < 16; i++) { + bytes[i] = random.nextInt(256); + } + pskController.text = base64Encode(bytes); + }, + ), + ), + ), + const SizedBox(height: 16), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('SMAZ compression'), + value: smazEnabled, + onChanged: (value) => setState(() => smazEnabled = value), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () { + final name = nameController.text.trim(); + final pskBase64 = pskController.text.trim(); + + Uint8List psk; + try { + final decoded = base64Decode(pskBase64); + psk = Uint8List(16); + for (int i = 0; i < decoded.length && i < 16; i++) { + psk[i] = decoded[i]; + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Invalid PSK format')), + ); + return; + } + + Navigator.pop(context); + connector.setChannel(channel.index, name, psk); + connector.setChannelSmazEnabled(channel.index, smazEnabled); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Channel "$name" updated')), + ); + }, + child: const Text('Save'), + ), + ], + ), + ), + ); + } + + void _confirmDeleteChannel( + BuildContext context, + MeshCoreConnector connector, + Channel channel, + ) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Delete Channel'), + content: Text('Delete "${channel.name}"? This cannot be undone.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + Navigator.pop(context); + connector.deleteChannel(channel.index); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Channel "${channel.name}" deleted')), + ); + }, + child: const Text('Delete', style: TextStyle(color: Colors.red)), + ), + ], + ), + ); + } + + void _addPublicChannel(BuildContext context, MeshCoreConnector connector) { + final psk = Uint8List(16); + final decoded = base64Decode(Channel.publicChannelPsk); + for (int i = 0; i < decoded.length && i < 16; i++) { + psk[i] = decoded[i]; + } + connector.setChannel(0, 'Public', psk); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Public channel added')), + ); + } + + int _findNextAvailableIndex(List channels, int maxChannels) { + final usedIndices = channels.map((c) => c.index).toSet(); + for (int i = 0; i < maxChannels; i++) { + if (!usedIndices.contains(i)) return i; + } + return 0; + } +} diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart new file mode 100644 index 00000000..8dfddb88 --- /dev/null +++ b/lib/screens/chat_screen.dart @@ -0,0 +1,1272 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:latlong2/latlong.dart'; + +import '../connector/meshcore_connector.dart'; +import '../models/contact.dart'; +import '../models/message.dart'; +import '../services/path_history_service.dart'; +import 'map_screen.dart'; +import '../utils/emoji_utils.dart'; +import '../widgets/gif_message.dart'; +import '../widgets/gif_picker.dart'; + +class ChatScreen extends StatefulWidget { + final Contact contact; + + const ChatScreen({super.key, required this.contact}); + + @override + State createState() => _ChatScreenState(); +} + +class _ChatScreenState extends State { + final _textController = TextEditingController(); + final _scrollController = ScrollController(); + bool _forceFlood = false; + + @override + void dispose() { + _textController.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Consumer2( + builder: (context, pathService, connector, _) { + final paths = pathService.getRecentPaths(widget.contact.publicKeyHex); + final contact = _resolveContact(connector); + final showRecentPath = paths.isNotEmpty && contact.pathLength >= 0; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(contact.name), + if (showRecentPath) + GestureDetector( + behavior: HitTestBehavior.opaque, + onLongPress: () => _showFullPathDialog(context, paths.first.pathBytes), + child: Text( + paths.first.displayText, + style: const TextStyle(fontSize: 11, fontWeight: FontWeight.normal), + ), + ) + else if (contact.pathLength >= 0) + Text( + '${contact.pathLength} ${contact.pathLength == 1 ? 'hop' : 'hops'}', + style: const TextStyle(fontSize: 11, fontWeight: FontWeight.normal), + ) + else + const Text( + 'No path', + style: TextStyle(fontSize: 11, fontWeight: FontWeight.normal), + ), + ], + ); + }, + ), + centerTitle: false, + actions: [ + PopupMenuButton( + icon: Icon(_forceFlood ? Icons.waves : Icons.route), + tooltip: 'Routing mode', + onSelected: (mode) { + setState(() { + _forceFlood = (mode == 'flood'); + }); + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: 'auto', + child: Row( + children: [ + Icon(Icons.auto_mode, size: 20, color: !_forceFlood ? Theme.of(context).primaryColor : null), + const SizedBox(width: 8), + Text( + 'Auto (use saved path)', + style: TextStyle( + fontWeight: !_forceFlood ? FontWeight.bold : FontWeight.normal, + ), + ), + ], + ), + ), + PopupMenuItem( + value: 'flood', + child: Row( + children: [ + Icon(Icons.waves, size: 20, color: _forceFlood ? Theme.of(context).primaryColor : null), + const SizedBox(width: 8), + Text( + 'Force Flood Mode', + style: TextStyle( + fontWeight: _forceFlood ? FontWeight.bold : FontWeight.normal, + ), + ), + ], + ), + ), + ], + ), + IconButton( + icon: const Icon(Icons.timeline), + tooltip: 'Path management', + onPressed: () => _showPathHistory(context), + ), + IconButton( + icon: const Icon(Icons.info_outline), + onPressed: () => _showContactInfo(context), + ), + ], + ), + body: Consumer( + builder: (context, connector, child) { + final messages = connector.getMessages(widget.contact); + + return Column( + children: [ + Expanded( + child: messages.isEmpty + ? _buildEmptyState() + : _buildMessageList(messages), + ), + _buildInputBar(connector), + ], + ); + }, + ), + ); + } + + Widget _buildEmptyState() { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.chat_bubble_outline, size: 64, color: Colors.grey[400]), + const SizedBox(height: 16), + Text( + 'No messages yet', + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + const SizedBox(height: 8), + Text( + 'Send a message to ${widget.contact.name}', + style: TextStyle(fontSize: 14, color: Colors.grey[500]), + ), + ], + ), + ); + } + + Widget _buildMessageList(List messages) { + return ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), + cacheExtent: 0, + addAutomaticKeepAlives: false, + itemCount: messages.length, + itemBuilder: (context, index) { + final message = messages[index]; + return _MessageBubble( + message: message, + senderName: widget.contact.name, + onLongPress: message.isOutgoing && message.status == MessageStatus.failed + ? () => _showMessageRetry(context, message) + : null, + ); + }, + ); + } + + Widget _buildInputBar(MeshCoreConnector connector) { + return Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + border: Border( + top: BorderSide(color: Theme.of(context).dividerColor), + ), + ), + child: SafeArea( + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.gif_box), + onPressed: () => _showGifPicker(context), + tooltip: 'Send GIF', + ), + Expanded( + child: ValueListenableBuilder( + valueListenable: _textController, + builder: (context, value, child) { + final gifId = _parseGifId(value.text); + if (gifId != null) { + return Row( + children: [ + Expanded( + child: GifMessage( + url: 'https://media.giphy.com/media/$gifId/giphy.gif', + backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest, + fallbackTextColor: + Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.6), + width: 160, + height: 110, + ), + ), + const SizedBox(width: 8), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => _textController.clear(), + ), + ], + ); + } + + return TextField( + controller: _textController, + decoration: const InputDecoration( + hintText: 'Type a message...', + border: OutlineInputBorder(), + contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + textInputAction: TextInputAction.send, + onSubmitted: (_) => _sendMessage(connector), + ); + }, + ), + ), + const SizedBox(width: 8), + IconButton.filled( + icon: const Icon(Icons.send), + onPressed: () => _sendMessage(connector), + ), + ], + ), + ), + ); + } + + String? _parseGifId(String text) { + final trimmed = text.trim(); + final match = RegExp(r'^g:([A-Za-z0-9_-]+)$').firstMatch(trimmed); + return match?.group(1); + } + + void _showGifPicker(BuildContext context) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + builder: (context) => GifPicker( + onGifSelected: (gifId) { + _textController.text = 'g:$gifId'; + }, + ), + ); + } + + void _sendMessage(MeshCoreConnector connector) { + final text = _textController.text.trim(); + if (text.isEmpty) return; + + connector.sendMessage( + widget.contact, + text, + forceFlood: _forceFlood, + ); + _textController.clear(); + + Future.delayed(const Duration(milliseconds: 100), () { + if (_scrollController.hasClients) { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 200), + curve: Curves.easeOut, + ); + } + }); + } + + void _showPathHistory(BuildContext context) { + final connector = Provider.of(context, listen: false); + + showDialog( + context: context, + builder: (context) => Consumer( + builder: (context, pathService, _) { + final paths = pathService.getRecentPaths(widget.contact.publicKeyHex); + return AlertDialog( + title: const Row( + children: [ + Icon(Icons.timeline), + SizedBox(width: 8), + Text('Path Management'), + ], + ), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (paths.isNotEmpty) ...[ + const Text( + 'Recent ACK Paths (tap to use):', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12), + ), + if (paths.length >= 100) ...[ + const SizedBox(height: 8), + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.amber[100], + borderRadius: BorderRadius.circular(8), + ), + child: const Text( + 'Path history is full. Remove entries to add new ones.', + style: TextStyle(fontSize: 12), + ), + ), + ], + const SizedBox(height: 8), + ...paths.map((path) { + return Card( + margin: const EdgeInsets.symmetric(vertical: 4), + child: ListTile( + dense: true, + leading: CircleAvatar( + radius: 16, + backgroundColor: path.wasFloodDiscovery ? Colors.blue : Colors.green, + child: Text( + '${path.hopCount}', + style: const TextStyle(fontSize: 12), + ), + ), + title: Text( + '${path.hopCount} ${path.hopCount == 1 ? 'hop' : 'hops'}', + style: const TextStyle(fontSize: 14), + ), + subtitle: Text( + '${(path.tripTimeMs / 1000).toStringAsFixed(2)}s • ${_formatRelativeTime(path.timestamp)} • ${path.successCount} successes', + style: const TextStyle(fontSize: 11), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.close, size: 16), + tooltip: 'Remove path', + onPressed: () async { + await pathService.removePathRecord( + widget.contact.publicKeyHex, + path.pathBytes, + ); + }, + ), + path.wasFloodDiscovery + ? const Icon(Icons.waves, size: 16, color: Colors.grey) + : const Icon(Icons.route, size: 16, color: Colors.grey), + ], + ), + onLongPress: () => _showFullPathDialog(context, path.pathBytes), + onTap: () async { + if (path.pathBytes.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Path details not available yet. Try sending a message to refresh.'), + duration: Duration(seconds: 2), + ), + ); + return; + } + + await connector.setContactPath( + widget.contact, + Uint8List.fromList(path.pathBytes), + path.pathBytes.length, + ); + + if (!context.mounted) return; + setState(() { + _forceFlood = false; + }); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Using ${path.hopCount} ${path.hopCount == 1 ? 'hop' : 'hops'} path'), + duration: const Duration(seconds: 2), + ), + ); + Navigator.pop(context); + }, + ), + ); + }), + const Divider(), + ] else ...[ + const Text('No path history yet.\nSend a message to discover paths.'), + const Divider(), + ], + const SizedBox(height: 8), + const Text( + 'Path Actions:', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12), + ), + const SizedBox(height: 8), + ListTile( + dense: true, + leading: const CircleAvatar( + radius: 16, + backgroundColor: Colors.purple, + child: Icon(Icons.edit_road, size: 16), + ), + title: const Text('Set Custom Path', style: TextStyle(fontSize: 14)), + subtitle: const Text('Manually specify routing path', style: TextStyle(fontSize: 11)), + onTap: () { + Navigator.pop(context); + _showCustomPathDialog(context); + }, + ), + ListTile( + dense: true, + leading: const CircleAvatar( + radius: 16, + backgroundColor: Colors.orange, + child: Icon(Icons.clear_all, size: 16), + ), + title: const Text('Clear Path', style: TextStyle(fontSize: 14)), + subtitle: const Text('Force rediscovery on next send', style: TextStyle(fontSize: 11)), + onTap: () async { + await connector.clearContactPath(widget.contact); + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Path cleared. Next message will rediscover route.'), + duration: Duration(seconds: 2), + ), + ); + Navigator.pop(context); + }, + ), + ListTile( + dense: true, + leading: const CircleAvatar( + radius: 16, + backgroundColor: Colors.blue, + child: Icon(Icons.waves, size: 16), + ), + title: const Text('Force Flood Mode', style: TextStyle(fontSize: 14)), + subtitle: const Text('Use routing toggle in app bar', style: TextStyle(fontSize: 11)), + onTap: () { + setState(() { + _forceFlood = true; + }); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Flood mode enabled. Toggle back via routing icon in app bar.'), + duration: Duration(seconds: 2), + ), + ); + Navigator.pop(context); + }, + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ); + }, + ), + ); + } + + String _formatRelativeTime(DateTime time) { + final diff = DateTime.now().difference(time); + if (diff.inSeconds < 60) return 'Just now'; + if (diff.inMinutes < 60) return '${diff.inMinutes}m ago'; + if (diff.inHours < 24) return '${diff.inHours}h ago'; + return '${diff.inDays}d ago'; + } + + void _showFullPathDialog(BuildContext context, List pathBytes) { + if (pathBytes.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Path details not available yet. Try sending a message to refresh.'), + duration: Duration(seconds: 2), + ), + ); + return; + } + + final formattedPath = pathBytes + .map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()) + .join(','); + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Full Path'), + content: SelectableText(formattedPath), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } + + Contact _resolveContact(MeshCoreConnector connector) { + return connector.contacts.firstWhere( + (c) => c.publicKeyHex == widget.contact.publicKeyHex, + orElse: () => widget.contact, + ); + } + + String _currentPathLabel(Contact contact) { + if (contact.pathLength < 0) return 'Flood (auto)'; + if (contact.pathLength == 0) return 'Direct'; + if (contact.pathIdList.isNotEmpty) return contact.pathIdList; + return '${contact.pathLength} hops'; + } + + void _showContactInfo(BuildContext context) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(widget.contact.name), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildInfoRow('Type', widget.contact.typeLabel), + _buildInfoRow('Path', widget.contact.pathLabel), + if (widget.contact.hasLocation) + _buildInfoRow( + 'Location', + '${widget.contact.latitude?.toStringAsFixed(4)}, ${widget.contact.longitude?.toStringAsFixed(4)}', + ), + _buildInfoRow('Public Key', widget.contact.publicKeyHex.substring(0, 16) + '...'), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } + + Widget _buildInfoRow(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 80, + child: Text(label, style: TextStyle(color: Colors.grey[600])), + ), + Expanded(child: Text(value)), + ], + ), + ); + } + + void _showCustomPathDialog(BuildContext context) { + final connector = Provider.of(context, listen: false); + + final currentContact = _resolveContact(connector); + if (currentContact.pathLength > 0 && currentContact.path.isEmpty && connector.isConnected) { + connector.getContacts(); + } + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Row( + children: [ + Icon(Icons.edit_road), + SizedBox(width: 8), + Text('Set Custom Path'), + ], + ), + content: Consumer( + builder: (context, connector, _) { + final contact = _resolveContact(connector); + final pathForInput = contact.pathIdList; + final currentPathLabel = _currentPathLabel(contact); + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Text( + 'Current path', + style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold), + ), + const Spacer(), + TextButton.icon( + onPressed: connector.isConnected ? connector.getContacts : null, + icon: const Icon(Icons.refresh, size: 16), + label: const Text('Reload'), + ), + ], + ), + Text( + currentPathLabel, + style: const TextStyle(fontSize: 11, color: Colors.grey), + ), + const SizedBox(height: 16), + const Text( + 'Choose how to set the message path:', + style: TextStyle(fontSize: 14), + ), + const SizedBox(height: 16), + ListTile( + dense: true, + leading: const CircleAvatar( + radius: 16, + backgroundColor: Colors.blue, + child: Icon(Icons.text_fields, size: 16), + ), + title: const Text('Enter Path Manually', style: TextStyle(fontSize: 14)), + subtitle: const Text('Type IDs like: A1B2C3D4,FFEEDDCC', style: TextStyle(fontSize: 11)), + onTap: () { + Navigator.pop(context); + _showManualPathInput( + context, + initialPath: pathForInput.isEmpty ? null : pathForInput, + ); + }, + ), + const SizedBox(height: 8), + ListTile( + dense: true, + leading: const CircleAvatar( + radius: 16, + backgroundColor: Colors.green, + child: Icon(Icons.contacts, size: 16), + ), + title: const Text('Select from Contacts', style: TextStyle(fontSize: 14)), + subtitle: const Text('Pick repeaters/rooms as hops', style: TextStyle(fontSize: 11)), + onTap: () { + Navigator.pop(context); + _showContactPathPicker(context); + }, + ), + ], + ); + }, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ], + ), + ); + } + + void _showManualPathInput(BuildContext context, {String? initialPath}) { + final connector = Provider.of(context, listen: false); + final controller = TextEditingController(text: initialPath ?? ''); + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Enter Custom Path'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Enter node IDs separated by commas.', + style: TextStyle(fontSize: 12, color: Colors.grey), + ), + const SizedBox(height: 8), + const Text( + 'Example: A1B2C3D4,FFEEDDCC', + style: TextStyle(fontSize: 11, color: Colors.grey), + ), + const SizedBox(height: 16), + TextField( + controller: controller, + decoration: const InputDecoration( + labelText: 'Path', + hintText: 'A1,A2,A3', + border: OutlineInputBorder(), + helperText: 'Node identifiers from your mesh network', + ), + textCapitalization: TextCapitalization.characters, + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () async { + final path = controller.text.trim(); + if (path.isNotEmpty) { + // Parse comma-separated hex strings and convert to bytes + final pathIds = path.split(',').map((s) => s.trim()).where((s) => s.isNotEmpty).toList(); + final pathBytesList = []; + + for (final id in pathIds) { + if (id.length >= 2) { + try { + pathBytesList.add(int.parse(id.substring(0, 2), radix: 16)); + } catch (e) { + // Skip invalid hex + } + } + } + + if (pathBytesList.isNotEmpty) { + await connector.setContactPath( + widget.contact, + Uint8List.fromList(pathBytesList), + pathBytesList.length, + ); + + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Custom path set: $path'), + duration: const Duration(seconds: 2), + ), + ); + } + } + } + if (context.mounted) { + Navigator.pop(context); + } + }, + child: const Text('Set Path'), + ), + ], + ), + ); + } + + void _showContactPathPicker(BuildContext context) { + final connector = Provider.of(context, listen: false); + final selectedContacts = []; + + // Filter to only repeaters and room servers + final validContacts = connector.contacts + .where((c) => (c.type == 2 || c.type == 3) && c != widget.contact) + .toList(); + + showDialog( + context: context, + builder: (context) => StatefulBuilder( + builder: (context, setDialogState) => AlertDialog( + title: const Text('Build Path from Contacts'), + content: SizedBox( + width: double.maxFinite, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (validContacts.isEmpty) ...[ + const Icon(Icons.info_outline, size: 48, color: Colors.grey), + const SizedBox(height: 16), + const Text( + 'No repeaters or room servers found.', + style: TextStyle(fontSize: 14), + textAlign: TextAlign.center, + ), + const SizedBox(height: 8), + const Text( + 'Custom paths require intermediate hops that can relay messages.', + style: TextStyle(fontSize: 12, color: Colors.grey), + textAlign: TextAlign.center, + ), + ] else if (selectedContacts.isNotEmpty) ...[ + const Text( + 'Selected Path:', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 8, + children: selectedContacts.asMap().entries.map((entry) { + final idx = entry.key; + final contact = entry.value; + return Chip( + avatar: CircleAvatar( + child: Text('${idx + 1}'), + ), + label: Text(contact.name), + onDeleted: () { + setDialogState(() { + selectedContacts.removeAt(idx); + }); + }, + ); + }).toList(), + ), + const Divider(), + ] else + const Text( + 'Tap repeaters/rooms to add them to the path:', + style: TextStyle(fontSize: 12, color: Colors.grey), + ), + const SizedBox(height: 8), + if (validContacts.isNotEmpty) + Flexible( + child: ListView.builder( + shrinkWrap: true, + itemCount: validContacts.length, + itemBuilder: (context, index) { + final contact = validContacts[index]; + final isSelected = selectedContacts.contains(contact); + + return ListTile( + dense: true, + leading: CircleAvatar( + radius: 16, + backgroundColor: isSelected ? Colors.green : (contact.type == 2 ? Colors.blue : Colors.purple), + child: Icon( + contact.type == 2 ? Icons.router : Icons.meeting_room, + size: 16, + color: Colors.white, + ), + ), + title: Text(contact.name, style: const TextStyle(fontSize: 14)), + subtitle: Text( + '${contact.typeLabel} • ${contact.publicKeyHex.substring(0, 8)}', + style: const TextStyle(fontSize: 10), + ), + trailing: isSelected + ? const Icon(Icons.check_circle, color: Colors.green) + : const Icon(Icons.add_circle_outline), + onTap: () { + setDialogState(() { + if (isSelected) { + selectedContacts.remove(contact); + } else { + selectedContacts.add(contact); + } + }); + }, + ); + }, + ), + ), + ], + ), + ), + actions: [ + if (selectedContacts.isNotEmpty) + TextButton( + onPressed: () { + setDialogState(() { + selectedContacts.clear(); + }); + }, + child: const Text('Clear'), + ), + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: selectedContacts.isEmpty + ? null + : () async { + // Build path bytes from selected contacts (prefix byte of each pub key) + final pathBytesList = []; + for (final contact in selectedContacts) { + if (contact.publicKeyHex.length >= 2) { + try { + pathBytesList.add(int.parse(contact.publicKeyHex.substring(0, 2), radix: 16)); + } catch (e) { + // Skip invalid hex + } + } + } + + if (pathBytesList.isNotEmpty) { + await connector.setContactPath( + widget.contact, + Uint8List.fromList(pathBytesList), + pathBytesList.length, + ); + + final pathIds = selectedContacts + .map((c) => c.publicKeyHex.substring(0, 8)) + .join(','); + + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Custom path set: $pathIds'), + duration: const Duration(seconds: 2), + ), + ); + Navigator.pop(context); + } + } + }, + child: const Text('Set Path'), + ), + ], + ), + ), + ); + } + + void _showMessageRetry(BuildContext context, Message message) { + showModalBottomSheet( + context: context, + builder: (context) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.refresh), + title: const Text('Retry'), + onTap: () { + Navigator.pop(context); + _retryMessage(message); + }, + ), + ], + ), + ), + ); + } + + void _retryMessage(Message message) { + final connector = Provider.of(context, listen: false); + connector.sendMessage( + widget.contact, + message.text, + forceFlood: message.forceFlood, + ); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Retrying message')), + ); + } +} + +class _MessageBubble extends StatelessWidget { + final Message message; + final String senderName; + final VoidCallback? onLongPress; + + const _MessageBubble({ + required this.message, + required this.senderName, + this.onLongPress, + }); + + @override + Widget build(BuildContext context) { + final isOutgoing = message.isOutgoing; + final colorScheme = Theme.of(context).colorScheme; + final gifId = _parseGifId(message.text); + final poi = _parsePoiMessage(message.text); + final isFailed = message.status == MessageStatus.failed; + final attempts = message.retryCount + 1; + final bubbleColor = isFailed + ? colorScheme.errorContainer + : (isOutgoing ? colorScheme.primary : colorScheme.surfaceContainerHighest); + final textColor = isFailed + ? colorScheme.onErrorContainer + : (isOutgoing ? colorScheme.onPrimary : colorScheme.onSurface); + final metaColor = textColor.withValues(alpha: 0.7); + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: GestureDetector( + onLongPress: onLongPress, + child: Row( + mainAxisAlignment: isOutgoing ? MainAxisAlignment.end : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isOutgoing) ...[ + _buildAvatar(senderName, colorScheme), + const SizedBox(width: 8), + ], + Flexible( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width * 0.65, + ), + decoration: BoxDecoration( + color: bubbleColor, + borderRadius: BorderRadius.circular(16), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isOutgoing) ...[ + Text( + senderName, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: colorScheme.primary, + ), + ), + const SizedBox(height: 4), + ], + if (poi != null) + _buildPoiMessage(context, poi, textColor, metaColor) + else if (gifId != null) + GifMessage( + url: 'https://media.giphy.com/media/$gifId/giphy.gif', + backgroundColor: bubbleColor, + fallbackTextColor: textColor.withValues(alpha: 0.7), + ) + else + Text( + message.text, + style: TextStyle( + color: textColor, + ), + ), + if (isOutgoing) ...[ + const SizedBox(height: 4), + Text( + 'Attempts: $attempts', + style: TextStyle( + fontSize: 10, + color: metaColor, + ), + ), + ], + const SizedBox(height: 4), + Wrap( + spacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + _formatTime(message.timestamp), + style: TextStyle( + fontSize: 10, + color: metaColor, + ), + ), + if (isOutgoing) ...[ + const SizedBox(width: 4), + _buildStatusIcon(metaColor), + ], + if (message.tripTimeMs != null && + message.status == MessageStatus.delivered) ...[ + const SizedBox(width: 4), + Icon( + Icons.speed, + size: 10, + color: isOutgoing ? metaColor : Colors.green[700], + ), + Text( + '${(message.tripTimeMs! / 1000).toStringAsFixed(1)}s', + style: TextStyle( + fontSize: 9, + color: isOutgoing ? metaColor : Colors.green[700], + ), + ), + ], + ], + ), + ], + ), + ), + ), + ], + ), + ), + ); + } + + String? _parseGifId(String text) { + final trimmed = text.trim(); + final match = RegExp(r'^g:([A-Za-z0-9_-]+)$').firstMatch(trimmed); + return match?.group(1); + } + + _PoiInfo? _parsePoiMessage(String text) { + final trimmed = text.trim(); + final match = RegExp(r'^m:([\-0-9.]+),([\-0-9.]+)\|([^|]*)\|.*$') + .firstMatch(trimmed); + if (match == null) return null; + final lat = double.tryParse(match.group(1) ?? ''); + final lon = double.tryParse(match.group(2) ?? ''); + if (lat == null || lon == null) return null; + final label = match.group(3) ?? ''; + return _PoiInfo(lat: lat, lon: lon, label: label); + } + + Widget _buildPoiMessage( + BuildContext context, + _PoiInfo poi, + Color textColor, + Color metaColor, + ) { + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + IconButton( + icon: Icon(Icons.location_on_outlined, color: textColor), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => MapScreen( + highlightPosition: LatLng(poi.lat, poi.lon), + highlightLabel: poi.label, + ), + ), + ); + }, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'POI Shared', + style: TextStyle( + color: textColor, + fontWeight: FontWeight.w600, + ), + ), + if (poi.label.isNotEmpty) + Text( + poi.label, + style: TextStyle( + color: metaColor, + fontSize: 12, + ), + ), + ], + ), + ), + ], + ); + } + + String _formatPathPrefixes(Uint8List pathBytes) { + return pathBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(','); + } + + Widget _buildAvatar(String senderName, ColorScheme colorScheme) { + final initial = _getFirstCharacterOrEmoji(senderName); + final color = _getColorForName(senderName); + + return CircleAvatar( + radius: 18, + backgroundColor: color.withValues(alpha: 0.2), + child: Text( + initial, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: color, + ), + ), + ); + } + + String _getFirstCharacterOrEmoji(String name) { + if (name.isEmpty) return '?'; + + final emoji = firstEmoji(name); + if (emoji != null) return emoji; + + final runes = name.runes.toList(); + if (runes.isEmpty) return '?'; + return String.fromCharCode(runes[0]).toUpperCase(); + } + + Color _getColorForName(String name) { + // Generate a consistent color based on the name hash + final hash = name.hashCode; + final colors = [ + Colors.blue, + Colors.green, + Colors.orange, + Colors.purple, + Colors.pink, + Colors.teal, + Colors.indigo, + Colors.cyan, + Colors.amber, + Colors.deepOrange, + ]; + + return colors[hash.abs() % colors.length]; + } + + Widget _buildStatusIcon(Color color) { + IconData icon; + switch (message.status) { + case MessageStatus.pending: + icon = Icons.access_time; + break; + case MessageStatus.sent: + icon = Icons.schedule; + break; + case MessageStatus.delivered: + icon = Icons.check; + break; + case MessageStatus.failed: + icon = Icons.error_outline; + break; + } + + return Icon( + icon, + size: 12, + color: color, + ); + } + + String _formatTime(DateTime time) { + final hour = time.hour.toString().padLeft(2, '0'); + final minute = time.minute.toString().padLeft(2, '0'); + return '$hour:$minute'; + } +} + +class _PoiInfo { + final double lat; + final double lon; + final String label; + + const _PoiInfo({ + required this.lat, + required this.lon, + required this.label, + }); +} diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart new file mode 100644 index 00000000..26e2209c --- /dev/null +++ b/lib/screens/contacts_screen.dart @@ -0,0 +1,791 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../models/contact.dart'; +import '../models/contact_group.dart'; +import '../storage/contact_group_store.dart'; +import '../widgets/repeater_login_dialog.dart'; +import '../utils/emoji_utils.dart'; +import 'chat_screen.dart'; +import 'repeater_hub_screen.dart'; + +enum ContactSortOption { + lastSeen, + recentMessages, + name, + type, +} + +class ContactsScreen extends StatefulWidget { + const ContactsScreen({super.key}); + + @override + State createState() => _ContactsScreenState(); +} + +class _ContactsScreenState extends State { + final TextEditingController _searchController = TextEditingController(); + String _searchQuery = ''; + ContactSortOption _sortOption = ContactSortOption.lastSeen; + final ContactGroupStore _groupStore = ContactGroupStore(); + List _groups = []; + + @override + void initState() { + super.initState(); + _loadGroups(); + } + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + Future _loadGroups() async { + final groups = await _groupStore.loadGroups(); + if (!mounted) return; + setState(() { + _groups = groups; + }); + } + + Future _saveGroups() async { + await _groupStore.saveGroups(_groups); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Contacts'), + centerTitle: true, + actions: [ + PopupMenuButton( + icon: const Icon(Icons.sort), + tooltip: 'Sort by', + onSelected: (option) { + setState(() { + _sortOption = option; + }); + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: ContactSortOption.lastSeen, + child: Row( + children: [ + Icon( + Icons.access_time, + size: 20, + color: _sortOption == ContactSortOption.lastSeen + ? Theme.of(context).primaryColor + : null, + ), + const SizedBox(width: 12), + Text( + 'Last Seen', + style: TextStyle( + fontWeight: _sortOption == ContactSortOption.lastSeen + ? FontWeight.bold + : FontWeight.normal, + ), + ), + ], + ), + ), + PopupMenuItem( + value: ContactSortOption.recentMessages, + child: Row( + children: [ + Icon( + Icons.chat_bubble, + size: 20, + color: _sortOption == ContactSortOption.recentMessages + ? Theme.of(context).primaryColor + : null, + ), + const SizedBox(width: 12), + Text( + 'Recent Messages', + style: TextStyle( + fontWeight: _sortOption == ContactSortOption.recentMessages + ? FontWeight.bold + : FontWeight.normal, + ), + ), + ], + ), + ), + PopupMenuItem( + value: ContactSortOption.name, + child: Row( + children: [ + Icon( + Icons.sort_by_alpha, + size: 20, + color: _sortOption == ContactSortOption.name + ? Theme.of(context).primaryColor + : null, + ), + const SizedBox(width: 12), + Text( + 'Name', + style: TextStyle( + fontWeight: _sortOption == ContactSortOption.name + ? FontWeight.bold + : FontWeight.normal, + ), + ), + ], + ), + ), + PopupMenuItem( + value: ContactSortOption.type, + child: Row( + children: [ + Icon( + Icons.category, + size: 20, + color: _sortOption == ContactSortOption.type + ? Theme.of(context).primaryColor + : null, + ), + const SizedBox(width: 12), + Text( + 'Type', + style: TextStyle( + fontWeight: _sortOption == ContactSortOption.type + ? FontWeight.bold + : FontWeight.normal, + ), + ), + ], + ), + ), + ], + ), + IconButton( + icon: const Icon(Icons.group_add), + tooltip: 'New group', + onPressed: () { + final contacts = context.read().contacts; + _showGroupEditor(context, contacts); + }, + ), + Consumer( + builder: (context, connector, child) { + return IconButton( + icon: connector.isLoadingContacts + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.refresh), + onPressed: connector.isLoadingContacts + ? null + : () => connector.getContacts(), + ); + }, + ), + ], + ), + body: Consumer( + builder: (context, connector, child) { + final contacts = connector.contacts; + + if (contacts.isEmpty && connector.isLoadingContacts && _groups.isEmpty) { + return const Center(child: CircularProgressIndicator()); + } + + if (contacts.isEmpty && _groups.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.people_outline, size: 64, color: Colors.grey[400]), + const SizedBox(height: 16), + Text( + 'No contacts yet', + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + const SizedBox(height: 8), + Text( + 'Contacts will appear when devices advertise', + style: TextStyle(fontSize: 14, color: Colors.grey[500]), + ), + ], + ), + ); + } + + final filteredAndSorted = _filterAndSortContacts(contacts, connector); + final filteredGroups = _filterAndSortGroups(_groups, contacts); + + return Column( + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: 'Search contacts...', + prefixIcon: const Icon(Icons.search), + suffixIcon: _searchQuery.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear), + onPressed: () { + _searchController.clear(); + setState(() { + _searchQuery = ''; + }); + }, + ) + : null, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + onChanged: (value) { + setState(() { + _searchQuery = value.toLowerCase(); + }); + }, + ), + ), + Expanded( + child: filteredAndSorted.isEmpty && filteredGroups.isEmpty + ? Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.search_off, size: 64, color: Colors.grey[400]), + const SizedBox(height: 16), + Text( + 'No contacts or groups found', + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + ], + ), + ) + : RefreshIndicator( + onRefresh: () => connector.getContacts(), + child: ListView.builder( + itemCount: filteredGroups.length + filteredAndSorted.length, + itemBuilder: (context, index) { + if (index < filteredGroups.length) { + final group = filteredGroups[index]; + return _buildGroupTile(context, group, contacts); + } + final contact = filteredAndSorted[index - filteredGroups.length]; + return _ContactTile( + contact: contact, + onTap: () => _openChat(context, contact), + onLongPress: () => _showContactOptions(context, connector, contact), + ); + }, + ), + ), + ), + ], + ); + }, + ), + ); + } + + List _filterAndSortGroups(List groups, List contacts) { + final query = _searchQuery.trim().toLowerCase(); + final contactNames = {}; + for (final contact in contacts) { + contactNames[contact.publicKeyHex] = contact.name.toLowerCase(); + } + + final filtered = groups.where((group) { + if (query.isEmpty) return true; + if (group.name.toLowerCase().contains(query)) return true; + for (final key in group.memberKeys) { + final name = contactNames[key]; + if (name != null && name.contains(query)) return true; + } + return false; + }).toList(); + + filtered.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + return filtered; + } + + List _filterAndSortContacts(List contacts, MeshCoreConnector connector) { + var filtered = contacts.where((contact) { + if (_searchQuery.isEmpty) return true; + return contact.name.toLowerCase().contains(_searchQuery); + }).toList(); + + switch (_sortOption) { + case ContactSortOption.lastSeen: + filtered.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); + break; + case ContactSortOption.recentMessages: + filtered.sort((a, b) { + final aMessages = connector.getMessages(a); + final bMessages = connector.getMessages(b); + final aLastMsg = aMessages.isEmpty ? DateTime(1970) : aMessages.last.timestamp; + final bLastMsg = bMessages.isEmpty ? DateTime(1970) : bMessages.last.timestamp; + return bLastMsg.compareTo(aLastMsg); + }); + break; + case ContactSortOption.name: + filtered.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + break; + case ContactSortOption.type: + filtered.sort((a, b) { + final typeCompare = a.type.compareTo(b.type); + if (typeCompare != 0) return typeCompare; + return a.name.toLowerCase().compareTo(b.name.toLowerCase()); + }); + break; + } + + return filtered; + } + + Widget _buildGroupTile(BuildContext context, ContactGroup group, List contacts) { + final memberContacts = _resolveGroupContacts(group, contacts); + final subtitle = _formatGroupMembers(memberContacts); + return ListTile( + leading: const CircleAvatar( + backgroundColor: Colors.teal, + child: Icon(Icons.group, color: Colors.white, size: 20), + ), + title: Text(group.name), + subtitle: Text(subtitle), + trailing: Text( + memberContacts.length.toString(), + style: TextStyle(fontSize: 12, color: Colors.grey[600]), + ), + onTap: () => _showGroupOptions(context, group, contacts), + onLongPress: () => _showGroupOptions(context, group, contacts), + ); + } + + List _resolveGroupContacts(ContactGroup group, List contacts) { + final byKey = {}; + for (final contact in contacts) { + byKey[contact.publicKeyHex] = contact; + } + final resolved = []; + for (final key in group.memberKeys) { + final contact = byKey[key]; + if (contact != null) { + resolved.add(contact); + } + } + resolved.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + return resolved; + } + + String _formatGroupMembers(List members) { + if (members.isEmpty) return 'No members'; + final names = members.map((c) => c.name).toList(); + if (names.length <= 2) return names.join(', '); + return '${names.take(2).join(', ')} +${names.length - 2}'; + } + + void _openChat(BuildContext context, Contact contact) { + // Check if this is a repeater + if (contact.type == advTypeRepeater) { + _showRepeaterLogin(context, contact); + } else { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => ChatScreen(contact: contact)), + ); + } + } + + void _showRepeaterLogin(BuildContext context, Contact repeater) { + showDialog( + context: context, + builder: (context) => RepeaterLoginDialog( + repeater: repeater, + onLogin: (password) { + // Navigate to repeater hub screen after successful login + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RepeaterHubScreen( + repeater: repeater, + password: password, + ), + ), + ); + }, + ), + ); + } + + void _showGroupOptions(BuildContext context, ContactGroup group, List contacts) { + final members = _resolveGroupContacts(group, contacts); + showModalBottomSheet( + context: context, + builder: (sheetContext) => SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.edit), + title: const Text('Edit Group'), + onTap: () { + Navigator.pop(sheetContext); + _showGroupEditor(context, contacts, group: group); + }, + ), + ListTile( + leading: const Icon(Icons.delete, color: Colors.red), + title: const Text('Delete Group', style: TextStyle(color: Colors.red)), + onTap: () { + Navigator.pop(sheetContext); + _confirmDeleteGroup(context, group); + }, + ), + if (members.isNotEmpty) const Divider(), + ...members.map((member) { + return ListTile( + leading: const Icon(Icons.person), + title: Text(member.name), + subtitle: Text(member.typeLabel), + onTap: () { + Navigator.pop(sheetContext); + _openChat(context, member); + }, + ); + }), + ], + ), + ), + ), + ); + } + + void _confirmDeleteGroup(BuildContext context, ContactGroup group) { + showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('Delete Group'), + content: Text('Remove "${group.name}"?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () async { + Navigator.pop(dialogContext); + setState(() { + _groups.removeWhere((g) => g.name == group.name); + }); + await _saveGroups(); + }, + child: const Text('Delete', style: TextStyle(color: Colors.red)), + ), + ], + ), + ); + } + + void _showGroupEditor( + BuildContext context, + List contacts, { + ContactGroup? group, + }) { + final isEditing = group != null; + final nameController = TextEditingController(text: group?.name ?? ''); + final selectedKeys = {...group?.memberKeys ?? []}; + String filterQuery = ''; + final sortedContacts = List.from(contacts) + ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + + showDialog( + context: context, + builder: (dialogContext) => StatefulBuilder( + builder: (builderContext, setDialogState) { + final filteredContacts = filterQuery.isEmpty + ? sortedContacts + : sortedContacts + .where((contact) => contact.name.toLowerCase().contains(filterQuery)) + .toList(); + return AlertDialog( + title: Text(isEditing ? 'Edit Group' : 'New Group'), + content: SizedBox( + width: double.maxFinite, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: nameController, + decoration: const InputDecoration( + labelText: 'Group name', + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: 12), + TextField( + decoration: const InputDecoration( + hintText: 'Filter contacts...', + prefixIcon: Icon(Icons.search), + border: OutlineInputBorder(), + isDense: true, + ), + onChanged: (value) { + setDialogState(() { + filterQuery = value.toLowerCase(); + }); + }, + ), + const SizedBox(height: 12), + SizedBox( + height: 240, + child: filteredContacts.isEmpty + ? const Center(child: Text('No contacts match your filter')) + : ListView.builder( + itemCount: filteredContacts.length, + itemBuilder: (context, index) { + final contact = filteredContacts[index]; + final isSelected = selectedKeys.contains(contact.publicKeyHex); + return CheckboxListTile( + value: isSelected, + title: Text(contact.name), + subtitle: Text(contact.typeLabel), + onChanged: (value) { + setDialogState(() { + if (value == true) { + selectedKeys.add(contact.publicKeyHex); + } else { + selectedKeys.remove(contact.publicKeyHex); + } + }); + }, + ); + }, + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () async { + final name = nameController.text.trim(); + if (name.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Group name is required')), + ); + return; + } + final exists = _groups.any((g) { + if (isEditing && g.name == group!.name) return false; + return g.name.toLowerCase() == name.toLowerCase(); + }); + if (exists) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Group "$name" already exists')), + ); + return; + } + setState(() { + if (isEditing) { + final index = _groups.indexWhere((g) => g.name == group!.name); + if (index != -1) { + _groups[index] = ContactGroup( + name: name, + memberKeys: selectedKeys.toList(), + ); + } + } else { + _groups.add(ContactGroup(name: name, memberKeys: selectedKeys.toList())); + } + }); + await _saveGroups(); + if (dialogContext.mounted) { + Navigator.pop(dialogContext); + } + }, + child: Text(isEditing ? 'Save' : 'Create'), + ), + ], + ); + }, + ), + ); + } + + void _showContactOptions( + BuildContext context, + MeshCoreConnector connector, + Contact contact, + ) { + final isRepeater = contact.type == advTypeRepeater; + + showModalBottomSheet( + context: context, + builder: (context) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (isRepeater) + ListTile( + leading: const Icon(Icons.cell_tower, color: Colors.orange), + title: const Text('Manage Repeater'), + onTap: () { + Navigator.pop(context); + _showRepeaterLogin(context, contact); + }, + ) + else + ListTile( + leading: const Icon(Icons.chat), + title: const Text('Open Chat'), + onTap: () { + Navigator.pop(context); + _openChat(context, contact); + }, + ), + ListTile( + leading: const Icon(Icons.delete, color: Colors.red), + title: const Text('Delete Contact', style: TextStyle(color: Colors.red)), + onTap: () { + Navigator.pop(context); + _confirmDelete(context, connector, contact); + }, + ), + ], + ), + ), + ); + } + + void _confirmDelete( + BuildContext context, + MeshCoreConnector connector, + Contact contact, + ) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Delete Contact'), + content: Text('Remove ${contact.name} from contacts?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + Navigator.pop(context); + connector.removeContact(contact); + }, + child: const Text('Delete', style: TextStyle(color: Colors.red)), + ), + ], + ), + ); + } +} + +class _ContactTile extends StatelessWidget { + final Contact contact; + final VoidCallback onTap; + final VoidCallback onLongPress; + + const _ContactTile({ + required this.contact, + required this.onTap, + required this.onLongPress, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + leading: CircleAvatar( + backgroundColor: _getTypeColor(contact.type), + child: _buildContactAvatar(contact), + ), + title: Text(contact.name), + subtitle: Text('${contact.typeLabel} • ${contact.pathLabel}'), + trailing: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + _formatLastSeen(contact.lastSeen), + style: TextStyle(fontSize: 12, color: Colors.grey[600]), + ), + if (contact.hasLocation) + Icon(Icons.location_on, size: 14, color: Colors.grey[400]), + ], + ), + onTap: onTap, + onLongPress: onLongPress, + ); + } + + Widget _buildContactAvatar(Contact contact) { + final emoji = firstEmoji(contact.name); + if (emoji != null) { + return Text( + emoji, + style: const TextStyle(fontSize: 18), + ); + } + return Icon(_getTypeIcon(contact.type), color: Colors.white, size: 20); + } + + IconData _getTypeIcon(int type) { + switch (type) { + case advTypeChat: + return Icons.chat; + case advTypeRepeater: + return Icons.cell_tower; + case advTypeRoom: + return Icons.group; + case advTypeSensor: + return Icons.sensors; + default: + return Icons.device_unknown; + } + } + + Color _getTypeColor(int type) { + switch (type) { + case advTypeChat: + return Colors.blue; + case advTypeRepeater: + return Colors.orange; + case advTypeRoom: + return Colors.purple; + case advTypeSensor: + return Colors.green; + default: + return Colors.grey; + } + } + + String _formatLastSeen(DateTime lastSeen) { + final now = DateTime.now(); + final diff = now.difference(lastSeen); + + if (diff.inMinutes < 1) return 'Just now'; + if (diff.inMinutes < 60) return '${diff.inMinutes}m ago'; + if (diff.inHours < 24) return '${diff.inHours}h ago'; + if (diff.inDays < 7) return '${diff.inDays}d ago'; + return '${lastSeen.month}/${lastSeen.day}'; + } +} diff --git a/lib/screens/device_screen.dart b/lib/screens/device_screen.dart new file mode 100644 index 00000000..e464141c --- /dev/null +++ b/lib/screens/device_screen.dart @@ -0,0 +1,292 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import 'channels_screen.dart'; +import 'contacts_screen.dart'; +import 'map_screen.dart'; +import 'settings_screen.dart'; + +/// Main hub screen after connecting to a MeshCore device +class DeviceScreen extends StatefulWidget { + const DeviceScreen({super.key}); + + @override + State createState() => _DeviceScreenState(); +} + +class _DeviceScreenState extends State { + bool _showBatteryVoltage = false; + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, connector, child) { + // If disconnected, pop back to scanner + if (!connector.isConnected) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (context.mounted) { + Navigator.popUntil(context, (route) => route.isFirst); + } + }); + } + + return PopScope( + canPop: false, + child: Scaffold( + appBar: AppBar( + title: Text(connector.device?.platformName ?? 'MeshCore Device'), + centerTitle: true, + automaticallyImplyLeading: false, + actions: [ + IconButton( + icon: const Icon(Icons.bluetooth_disabled), + tooltip: 'Disconnect', + onPressed: () => _disconnect(context, connector), + ), + ], + ), + body: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Connection status card + _buildStatusCard(connector, context), + + const SizedBox(height: 24), + + // Navigation grid + Expanded( + child: _buildNavigationGrid(context), + ), + ], + ), + ), + ), + ); + }, + ); + } + + Widget _buildStatusCard(MeshCoreConnector connector, BuildContext context) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + children: [ + const Icon(Icons.bluetooth_connected, color: Colors.green, size: 32), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + connector.device?.platformName ?? 'Unknown Device', + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 4), + Text( + connector.device?.remoteId.toString() ?? '', + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + ), + ), + ], + ), + ), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: Colors.green.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(16), + ), + child: const Text( + 'Connected', + style: TextStyle( + color: Colors.green, + fontWeight: FontWeight.w500, + ), + ), + ), + const SizedBox(height: 8), + _buildBatteryIndicator(connector, context), + ], + ), + ], + ), + ), + ); + } + + Widget _buildBatteryIndicator(MeshCoreConnector connector, BuildContext context) { + final percent = connector.batteryPercent; + final millivolts = connector.batteryMillivolts; + final percentLabel = percent != null ? '$percent%' : '--%'; + final voltageLabel = millivolts == null + ? '-- V' + : '${(millivolts / 1000.0).toStringAsFixed(2)} V'; + final displayLabel = _showBatteryVoltage ? voltageLabel : percentLabel; + final icon = _batteryIcon(percent); + + return InkWell( + borderRadius: BorderRadius.circular(16), + onTap: () { + setState(() { + _showBatteryVoltage = !_showBatteryVoltage; + }); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 18, color: Colors.grey[700]), + const SizedBox(width: 4), + Text( + displayLabel, + style: TextStyle( + fontSize: 12, + color: Colors.grey[700], + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ); + } + + IconData _batteryIcon(int? percent) { + if (percent == null) return Icons.battery_unknown; + if (percent <= 15) return Icons.battery_alert; + return Icons.battery_full; + } + + Widget _buildNavigationGrid(BuildContext context) { + final items = [ + _NavItem( + icon: Icons.people_outline, + label: 'Contacts', + color: Colors.blue, + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) => const ContactsScreen()), + ), + ), + _NavItem( + icon: Icons.tag, + label: 'Channels', + color: Colors.green, + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) => const ChannelsScreen()), + ), + ), + _NavItem( + icon: Icons.map_outlined, + label: 'Map', + color: Colors.orange, + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) => const MapScreen()), + ), + ), + _NavItem( + icon: Icons.settings_outlined, + label: 'Settings', + color: Colors.grey, + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) => const SettingsScreen()), + ), + ), + ]; + + return GridView.builder( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + childAspectRatio: 1.2, + ), + itemCount: items.length, + itemBuilder: (context, index) { + final item = items[index]; + return _buildNavCard(item); + }, + ); + } + + Widget _buildNavCard(_NavItem item) { + return Card( + child: InkWell( + onTap: item.onTap, + borderRadius: BorderRadius.circular(12), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + item.icon, + size: 48, + color: item.color, + ), + const SizedBox(height: 12), + Text( + item.label, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ); + } + + Future _disconnect(BuildContext context, MeshCoreConnector connector) async { + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Disconnect'), + content: const Text('Are you sure you want to disconnect from this device?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Disconnect'), + ), + ], + ), + ); + + if (confirmed == true) { + await connector.disconnect(); + } + } +} + +class _NavItem { + final IconData icon; + final String label; + final Color color; + final VoidCallback onTap; + + _NavItem({ + required this.icon, + required this.label, + required this.color, + required this.onTap, + }); +} diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart new file mode 100644 index 00000000..eb15eb36 --- /dev/null +++ b/lib/screens/map_screen.dart @@ -0,0 +1,1109 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../models/channel.dart'; +import '../models/contact.dart'; +import '../services/app_settings_service.dart'; +import '../services/map_marker_service.dart'; +import 'chat_screen.dart'; + +class MapScreen extends StatefulWidget { + final LatLng? highlightPosition; + final String? highlightLabel; + final double highlightZoom; + + const MapScreen({ + super.key, + this.highlightPosition, + this.highlightLabel, + this.highlightZoom = 15.0, + }); + + @override + State createState() => _MapScreenState(); +} + +class _MapScreenState extends State { + final MapController _mapController = MapController(); + final MapMarkerService _markerService = MapMarkerService(); + final Set _hiddenMarkerIds = {}; + Set _removedMarkerIds = {}; + bool _isSelectingPoi = false; + + @override + void initState() { + super.initState(); + _loadRemovedMarkers(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + context.read().getChannels(); + if (widget.highlightPosition != null) { + _mapController.move(widget.highlightPosition!, widget.highlightZoom); + } + } + }); + } + + Future _loadRemovedMarkers() async { + final ids = await _markerService.loadRemovedIds(); + if (!mounted) return; + setState(() { + _removedMarkerIds = ids; + }); + } + + @override + Widget build(BuildContext context) { + return Consumer2( + builder: (context, connector, settingsService, child) { + final settings = settingsService.settings; + final contacts = connector.contacts; + final highlightPosition = widget.highlightPosition; + final sharedMarkers = settings.mapShowMarkers + ? _collectSharedMarkers(connector) + .where((marker) => + !_hiddenMarkerIds.contains(marker.id) && + !_removedMarkerIds.contains(marker.id)) + .toList() + : <_SharedMarker>[]; + + // Filter by time + final now = DateTime.now(); + final filteredByTime = settings.mapTimeFilterHours == 0 + ? contacts + : contacts.where((c) { + final hoursSinceLastSeen = + now.difference(c.lastSeen).inHours; + return hoursSinceLastSeen <= settings.mapTimeFilterHours; + }).toList(); + + // Filter by key prefix + final keyPrefix = settings.mapKeyPrefix.trim(); + final filteredByKeyPrefix = (settings.mapKeyPrefixEnabled && keyPrefix.isNotEmpty) + ? filteredByTime.where((c) { + return c.publicKeyHex.toLowerCase().startsWith(keyPrefix.toLowerCase()); + }).toList() + : filteredByTime; + + // Filter by location + final contactsWithLocation = filteredByKeyPrefix + .where((c) => c.hasLocation) + .toList(); + + // Calculate center of all nodes, or default to (0, 0) + LatLng center = const LatLng(0, 0); + final hasMapContent = contactsWithLocation.isNotEmpty || + sharedMarkers.isNotEmpty || + _isSelectingPoi || + highlightPosition != null; + if (contactsWithLocation.isNotEmpty || sharedMarkers.isNotEmpty) { + double avgLat = contactsWithLocation + .map((c) => c.latitude!) + .fold(0, (sum, lat) => sum + lat); + double avgLon = contactsWithLocation + .map((c) => c.longitude!) + .fold(0, (sum, lon) => sum + lon); + for (final marker in sharedMarkers) { + avgLat += marker.position.latitude; + avgLon += marker.position.longitude; + } + final total = contactsWithLocation.length + sharedMarkers.length; + if (total > 0) { + center = LatLng(avgLat / total, avgLon / total); + } + } + if (highlightPosition != null) { + center = highlightPosition; + } + + return Scaffold( + appBar: AppBar( + title: const Text('Node Map'), + centerTitle: true, + ), + body: !hasMapContent + ? _buildEmptyState() + : Stack( + children: [ + FlutterMap( + mapController: _mapController, + options: MapOptions( + initialCenter: center, + initialZoom: 13.0, + minZoom: 2.0, + maxZoom: 18.0, + onTap: (_, latLng) { + if (_isSelectingPoi) { + setState(() { + _isSelectingPoi = false; + }); + _shareMarker( + context: context, + connector: connector, + position: latLng, + defaultLabel: 'Point of interest', + flags: 'poi', + ); + } + }, + onLongPress: (_, latLng) { + if (_isSelectingPoi) { + setState(() { + _isSelectingPoi = false; + }); + _shareMarker( + context: context, + connector: connector, + position: latLng, + defaultLabel: 'Point of interest', + flags: 'poi', + ); + return; + } + _showShareMarkerAtPositionSheet( + context: context, + connector: connector, + position: latLng, + ); + }, + ), + children: [ + TileLayer( + urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', + userAgentPackageName: 'com.meshcore.open', + maxZoom: 19, + ), + MarkerLayer( + markers: [ + if (highlightPosition != null) + Marker( + point: highlightPosition, + width: 40, + height: 40, + child: Icon( + Icons.location_on_outlined, + color: Colors.red[600], + size: 34, + ), + ), + ..._buildMarkers(contactsWithLocation, settings), + ...sharedMarkers.map(_buildSharedMarker), + ], + ), + ], + ), + _buildLegend(contactsWithLocation.length, sharedMarkers.length), + ], + ), + floatingActionButton: FloatingActionButton( + onPressed: () => _showFilterDialog(context, settingsService), + child: const Icon(Icons.filter_list), + ), + ); + }, + ); + } + + Widget _buildEmptyState() { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.location_off, + size: 64, + color: Colors.grey[400], + ), + const SizedBox(height: 16), + Text( + 'No nodes with location data', + style: TextStyle( + fontSize: 18, + color: Colors.grey[600], + ), + ), + const SizedBox(height: 8), + Text( + 'Nodes need to share their GPS coordinates\nto appear on the map', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 14, + color: Colors.grey[500], + ), + ), + ], + ), + ); + } + + List _buildMarkers(List contacts, settings) { + final markers = []; + + for (final contact in contacts) { + if (!contact.hasLocation) continue; + + // Apply node type filters + if (contact.type == advTypeRepeater && !settings.mapShowRepeaters) continue; + if (contact.type == advTypeChat && !settings.mapShowChatNodes) continue; + if (contact.type != advTypeChat && + contact.type != advTypeRepeater && + !settings.mapShowOtherNodes) { + continue; + } + + final marker = Marker( + point: LatLng(contact.latitude!, contact.longitude!), + width: 80, + height: 80, + child: GestureDetector( + onTap: () => _showNodeInfo(context, contact), + child: Column( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: _getNodeColor(contact.type), + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 2), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.3), + blurRadius: 4, + offset: const Offset(0, 2), + ), + ], + ), + child: Icon( + _getNodeIcon(contact.type), + color: Colors.white, + size: 24, + ), + ), + ], + ), + ), + ); + + markers.add(marker); + } + + return markers; + } + + Color _getNodeColor(int type) { + switch (type) { + case advTypeChat: + return Colors.blue; + case advTypeRepeater: + return Colors.green; + case advTypeRoom: + return Colors.purple; + case advTypeSensor: + return Colors.orange; + default: + return Colors.grey; + } + } + + IconData _getNodeIcon(int type) { + switch (type) { + case advTypeChat: + return Icons.person; + case advTypeRepeater: + return Icons.router; + case advTypeRoom: + return Icons.meeting_room; + case advTypeSensor: + return Icons.sensors; + default: + return Icons.device_unknown; + } + } + + Widget _buildLegend(int nodeCount, int markerCount) { + return Positioned( + top: 16, + right: 16, + child: Card( + child: Padding( + padding: const EdgeInsets.all(12.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Nodes: $nodeCount', + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + ), + ), + Text( + 'Pins: $markerCount', + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 12, + ), + ), + const SizedBox(height: 8), + _buildLegendItem(Icons.person, 'Chat', Colors.blue), + _buildLegendItem(Icons.router, 'Repeater', Colors.green), + _buildLegendItem(Icons.meeting_room, 'Room', Colors.purple), + _buildLegendItem(Icons.sensors, 'Sensor', Colors.orange), + _buildLegendItem(Icons.flag, 'Pin (DM)', Colors.blue), + _buildLegendItem(Icons.flag, 'Pin (Private)', Colors.purple), + _buildLegendItem(Icons.flag, 'Pin (Public)', Colors.orange), + ], + ), + ), + ), + ); + } + + Widget _buildLegendItem(IconData icon, String label, Color color) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 16, color: color), + const SizedBox(width: 8), + Text( + label, + style: const TextStyle(fontSize: 12), + ), + ], + ), + ); + } + + List<_SharedMarker> _collectSharedMarkers(MeshCoreConnector connector) { + final markers = <_SharedMarker>[]; + final selfName = connector.selfName ?? 'Me'; + + for (final contact in connector.contacts) { + final messages = connector.getMessages(contact); + for (final message in messages) { + final payload = _parseMarkerText(message.text); + if (payload == null) continue; + final fromName = message.isOutgoing ? selfName : contact.name; + final id = _buildMarkerId( + sourceId: contact.publicKeyHex, + timestamp: message.timestamp, + text: message.text, + ); + markers.add( + _SharedMarker( + id: id, + position: payload.position, + label: payload.label, + flags: payload.flags, + fromName: fromName, + sourceLabel: contact.name, + isChannel: false, + isPublicChannel: false, + ), + ); + } + } + + for (final channel in connector.channels.where((c) => !c.isEmpty)) { + final isPublic = _isPublicChannel(channel); + final messages = connector.getChannelMessages(channel); + for (final message in messages) { + final payload = _parseMarkerText(message.text); + if (payload == null) continue; + final id = _buildMarkerId( + sourceId: 'channel:${channel.index}', + timestamp: message.timestamp, + text: message.text, + ); + markers.add( + _SharedMarker( + id: id, + position: payload.position, + label: payload.label, + flags: payload.flags, + fromName: message.senderName, + sourceLabel: channel.name.isEmpty ? 'Channel ${channel.index}' : channel.name, + isChannel: true, + isPublicChannel: isPublic, + ), + ); + } + } + + return markers; + } + + _MarkerPayload? _parseMarkerText(String text) { + final trimmed = text.trim(); + if (!trimmed.startsWith('m:')) return null; + + final parts = trimmed.substring(2).split('|'); + if (parts.isEmpty) return null; + final coords = parts[0].split(','); + if (coords.length != 2) return null; + final lat = double.tryParse(coords[0].trim()); + final lon = double.tryParse(coords[1].trim()); + if (lat == null || lon == null) return null; + + final label = parts.length > 1 ? parts[1].trim() : ''; + final flags = parts.length > 2 ? parts[2].trim() : ''; + return _MarkerPayload( + position: LatLng(lat, lon), + label: label.isEmpty ? 'Shared pin' : label, + flags: flags, + ); + } + + String _buildMarkerId({ + required String sourceId, + required DateTime timestamp, + required String text, + }) { + return '$sourceId|${timestamp.millisecondsSinceEpoch}|$text'; + } + + Marker _buildSharedMarker(_SharedMarker marker) { + final markerColor = marker.isChannel + ? (marker.isPublicChannel ? Colors.orange : Colors.purple) + : Colors.blue; + return Marker( + point: marker.position, + width: 60, + height: 60, + child: GestureDetector( + onTap: () => _showMarkerInfo(marker), + child: Column( + children: [ + Container( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: markerColor, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 2), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.3), + blurRadius: 4, + offset: const Offset(0, 2), + ), + ], + ), + child: const Icon( + Icons.flag, + color: Colors.white, + size: 20, + ), + ), + ], + ), + ), + ); + } + + void _showNodeInfo(BuildContext context, Contact contact) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Row( + children: [ + Icon( + _getNodeIcon(contact.type), + color: _getNodeColor(contact.type), + ), + const SizedBox(width: 8), + Expanded(child: Text(contact.name)), + ], + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildInfoRow('Type', contact.typeLabel), + _buildInfoRow('Path', contact.pathLabel), + _buildInfoRow('Location', + '${contact.latitude!.toStringAsFixed(6)}, ${contact.longitude!.toStringAsFixed(6)}'), + _buildInfoRow('Last Seen', _formatLastSeen(contact.lastSeen)), + _buildInfoRow('Public Key', contact.publicKeyHex), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + if (contact.type == advTypeChat) // Only show chat button for chat nodes + TextButton( + onPressed: () { + Navigator.pop(context); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => ChatScreen(contact: contact), + ), + ); + }, + child: const Text('Open Chat'), + ), + ], + ), + ); + } + + void _showMarkerInfo(_SharedMarker marker) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(marker.label), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildInfoRow('From', marker.fromName), + _buildInfoRow('Source', marker.sourceLabel), + _buildInfoRow( + 'Location', + '${marker.position.latitude.toStringAsFixed(6)}, ${marker.position.longitude.toStringAsFixed(6)}', + ), + if (marker.flags.isNotEmpty) _buildInfoRow('Flags', marker.flags), + ], + ), + actions: [ + TextButton( + onPressed: () { + setState(() { + _hiddenMarkerIds.add(marker.id); + }); + Navigator.pop(context); + }, + child: const Text('Hide'), + ), + TextButton( + onPressed: () async { + setState(() { + _hiddenMarkerIds.add(marker.id); + _removedMarkerIds.add(marker.id); + }); + await _markerService.saveRemovedIds(_removedMarkerIds); + if (context.mounted) { + Navigator.pop(context); + } + }, + child: const Text('Remove'), + ), + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } + + Widget _buildInfoRow(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 2), + Text( + value, + style: const TextStyle(fontSize: 14), + ), + ], + ), + ); + } + + String _formatLastSeen(DateTime lastSeen) { + final now = DateTime.now(); + final difference = now.difference(lastSeen); + + if (difference.inSeconds < 60) { + return 'Just now'; + } else if (difference.inMinutes < 60) { + return '${difference.inMinutes}m ago'; + } else if (difference.inHours < 24) { + return '${difference.inHours}h ago'; + } else { + return '${difference.inDays}d ago'; + } + } + + void _showShareMarkerAtPositionSheet({ + required BuildContext context, + required MeshCoreConnector connector, + required LatLng position, + }) { + showModalBottomSheet( + context: context, + builder: (sheetContext) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.place), + title: const Text('Share marker here'), + onTap: () { + Navigator.pop(sheetContext); + _shareMarker( + context: context, + connector: connector, + position: position, + defaultLabel: 'Point of interest', + flags: 'poi', + ); + }, + ), + ListTile( + leading: const Icon(Icons.close), + title: const Text('Cancel'), + onTap: () => Navigator.pop(sheetContext), + ), + ], + ), + ), + ); + } + + Future _shareMarker({ + required BuildContext context, + required MeshCoreConnector connector, + required LatLng position, + required String defaultLabel, + required String flags, + }) async { + if (!connector.isConnected) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Connect to a device to share markers')), + ); + return; + } + + final label = await _promptForLabel(context, defaultLabel); + if (label == null) return; + + final markerText = _formatMarkerMessage(position, label, flags); + await _showRecipientSheet( + context: context, + connector: connector, + markerText: markerText, + ); + } + + Future _promptForLabel(BuildContext context, String defaultLabel) async { + final controller = TextEditingController(text: defaultLabel); + return showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('Pin label'), + content: TextField( + controller: controller, + decoration: const InputDecoration( + hintText: 'Label', + border: OutlineInputBorder(), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + final label = controller.text.trim().replaceAll('|', '/'); + Navigator.pop(dialogContext, label.isEmpty ? defaultLabel : label); + }, + child: const Text('Continue'), + ), + ], + ), + ); + } + + String _formatMarkerMessage(LatLng position, String label, String flags) { + final lat = position.latitude.toStringAsFixed(6); + final lon = position.longitude.toStringAsFixed(6); + return 'm:$lat,$lon|$label|$flags'; + } + + Future _showRecipientSheet({ + required BuildContext context, + required MeshCoreConnector connector, + required String markerText, + }) async { + if (!connector.isLoadingChannels && connector.channels.isEmpty) { + connector.getChannels(); + } + String query = ''; + + await showModalBottomSheet( + context: context, + builder: (sheetContext) => StatefulBuilder( + builder: (sheetContext, setSheetState) { + return Consumer( + builder: (context, liveConnector, child) { + final allContacts = liveConnector.contacts + .where((contact) => + contact.type != advTypeRepeater && contact.type != advTypeRoom) + .toList(); + return SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text('Send to contact', style: TextStyle(fontWeight: FontWeight.bold)), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), + child: TextField( + decoration: InputDecoration( + hintText: 'Search contacts...', + prefixIcon: const Icon(Icons.search), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + onChanged: (value) { + setSheetState(() { + query = value.toLowerCase(); + }); + }, + ), + ), + ...allContacts + .where((contact) => + query.isEmpty || + contact.name.toLowerCase().contains(query)) + .map((contact) { + return ListTile( + leading: const Icon(Icons.person), + title: Text(contact.name), + onTap: () { + Navigator.pop(sheetContext); + liveConnector.sendMessage(contact, markerText); + }, + ); + }), + const Padding( + padding: EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text('Send to channel', style: TextStyle(fontWeight: FontWeight.bold)), + ), + if (liveConnector.isLoadingChannels) + const Padding( + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: LinearProgressIndicator(), + ) + else if (liveConnector.channels.where((c) => !c.isEmpty).isEmpty) + const Padding( + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Text('No channels available'), + ) + else + ...liveConnector.channels.where((c) => !c.isEmpty).map((channel) { + final isPublic = _isPublicChannel(channel); + final label = channel.name.isEmpty ? 'Channel ${channel.index}' : channel.name; + return ListTile( + leading: Icon( + isPublic ? Icons.public : Icons.tag, + color: isPublic ? Colors.orange : Colors.blue, + ), + title: Text(label), + subtitle: isPublic ? const Text('Public channel') : null, + onTap: () async { + Navigator.pop(sheetContext); + final canSend = isPublic + ? await _confirmPublicShare(context, label) + : true; + if (canSend) { + liveConnector.sendChannelMessage(channel, markerText); + } + }, + ); + }), + ], + ), + ), + ); + }, + ); + }, + ), + ); + } + + bool _isPublicChannel(Channel channel) { + return channel.pskBase64 == Channel.publicChannelPsk; + } + + Future _confirmPublicShare(BuildContext context, String channelLabel) async { + final result = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('Public location share'), + content: Text( + 'You are about to share a location in $channelLabel. ' + 'This channel is public and anyone with the PSK can see it.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: const Text('Share'), + ), + ], + ), + ); + return result ?? false; + } + + void _showFilterDialog(BuildContext context, AppSettingsService settingsService) { + showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('Filter Nodes'), + contentPadding: const EdgeInsets.fromLTRB(24, 20, 24, 0), + content: SingleChildScrollView( + child: Consumer( + builder: (context, service, child) { + final settings = service.settings; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Node Types', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + const SizedBox(height: 8), + CheckboxListTile( + title: const Text('Chat Nodes'), + value: settings.mapShowChatNodes, + onChanged: (value) { + service.setMapShowChatNodes(value ?? true); + }, + contentPadding: EdgeInsets.zero, + ), + CheckboxListTile( + title: const Text('Repeaters'), + value: settings.mapShowRepeaters, + onChanged: (value) { + service.setMapShowRepeaters(value ?? true); + }, + contentPadding: EdgeInsets.zero, + ), + CheckboxListTile( + title: const Text('Other Nodes'), + value: settings.mapShowOtherNodes, + onChanged: (value) { + service.setMapShowOtherNodes(value ?? true); + }, + contentPadding: EdgeInsets.zero, + ), + const SizedBox(height: 16), + const Text( + 'Key Prefix', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + const SizedBox(height: 8), + CheckboxListTile( + title: const Text('Filter by key prefix'), + value: settings.mapKeyPrefixEnabled, + onChanged: (value) { + service.setMapKeyPrefixEnabled(value ?? false); + }, + contentPadding: EdgeInsets.zero, + ), + TextFormField( + initialValue: settings.mapKeyPrefix, + enabled: settings.mapKeyPrefixEnabled, + decoration: const InputDecoration( + labelText: 'Public key prefix', + hintText: 'e.g. ab12', + border: OutlineInputBorder(), + isDense: true, + ), + onChanged: (value) { + service.setMapKeyPrefix(value); + }, + ), + const SizedBox(height: 16), + const Text( + 'Markers', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + const SizedBox(height: 8), + CheckboxListTile( + title: const Text('Show shared markers'), + value: settings.mapShowMarkers, + onChanged: (value) { + service.setMapShowMarkers(value ?? true); + }, + contentPadding: EdgeInsets.zero, + ), + const SizedBox(height: 16), + const Text( + 'Last Seen Time', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + const SizedBox(height: 8), + Text( + _getTimeFilterLabel(settings.mapTimeFilterHours), + style: TextStyle( + fontSize: 14, + color: Colors.grey[700], + ), + ), + Slider( + value: _hoursToSliderValue(settings.mapTimeFilterHours), + min: 0, + max: 100, + divisions: 100, + onChanged: (value) { + final hours = _sliderValueToHours(value); + service.setMapTimeFilterHours(hours); + }, + ), + ], + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: const Text('Close'), + ), + ], + ), + ); + } + + // Convert hours to slider value (0-100) with exponential scaling + double _hoursToSliderValue(double hours) { + if (hours == 0) return 100; // All time + + // Map hours exponentially + // 0-24h: 0-40 + // 24h-7d: 40-60 + // 7d-30d: 60-80 + // 30d-6mo: 80-99 + // All time: 100 + + if (hours <= 24) { + return (hours / 24) * 40; + } else if (hours <= 168) { // 7 days + return 40 + ((hours - 24) / (168 - 24)) * 20; + } else if (hours <= 720) { // 30 days + return 60 + ((hours - 168) / (720 - 168)) * 20; + } else if (hours <= 4380) { // 6 months + return 80 + ((hours - 720) / (4380 - 720)) * 19; + } else { + return 100; + } + } + + // Convert slider value (0-100) to hours with exponential scaling + double _sliderValueToHours(double value) { + if (value >= 99.5) return 0; // All time + + if (value <= 40) { + return (value / 40) * 24; // 0-24 hours + } else if (value <= 60) { + return 24 + ((value - 40) / 20) * (168 - 24); // 1-7 days + } else if (value <= 80) { + return 168 + ((value - 60) / 20) * (720 - 168); // 7-30 days + } else { + return 720 + ((value - 80) / 19) * (4380 - 720); // 30 days - 6 months + } + } + + String _getTimeFilterLabel(double hours) { + if (hours == 0) return 'All Time'; + + if (hours < 1) { + return '${(hours * 60).round()} minutes'; + } else if (hours < 24) { + return '${hours.round()} ${hours.round() == 1 ? 'hour' : 'hours'}'; + } else if (hours < 168) { + final days = (hours / 24).round(); + return '$days ${days == 1 ? 'day' : 'days'}'; + } else if (hours < 720) { + final weeks = (hours / 168).round(); + return '$weeks ${weeks == 1 ? 'week' : 'weeks'}'; + } else if (hours < 4380) { + final months = (hours / 730).round(); + return '$months ${months == 1 ? 'month' : 'months'}'; + } else { + return 'All Time'; + } + } +} + +class _MarkerPayload { + final LatLng position; + final String label; + final String flags; + + _MarkerPayload({ + required this.position, + required this.label, + required this.flags, + }); +} + +class _SharedMarker { + final String id; + final LatLng position; + final String label; + final String flags; + final String fromName; + final String sourceLabel; + final bool isChannel; + final bool isPublicChannel; + + _SharedMarker({ + required this.id, + required this.position, + required this.label, + required this.flags, + required this.fromName, + required this.sourceLabel, + required this.isChannel, + required this.isPublicChannel, + }); +} diff --git a/lib/screens/repeater_cli_screen.dart b/lib/screens/repeater_cli_screen.dart new file mode 100644 index 00000000..d91a4f60 --- /dev/null +++ b/lib/screens/repeater_cli_screen.dart @@ -0,0 +1,528 @@ +import 'dart:async'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../models/contact.dart'; +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../widgets/debug_frame_viewer.dart'; +import '../services/repeater_command_service.dart'; + +class RepeaterCliScreen extends StatefulWidget { + final Contact repeater; + final String password; + + const RepeaterCliScreen({ + super.key, + required this.repeater, + required this.password, + }); + + @override + State createState() => _RepeaterCliScreenState(); +} + +class _RepeaterCliScreenState extends State { + final TextEditingController _commandController = TextEditingController(); + final ScrollController _scrollController = ScrollController(); + final List> _commandHistory = []; + int _historyIndex = -1; + StreamSubscription? _frameSubscription; + RepeaterCommandService? _commandService; + + // Common commands for quick access + final List> _quickCommands = [ + {'label': 'Get Name', 'command': 'get name'}, + {'label': 'Get Radio', 'command': 'get radio'}, + {'label': 'Get TX', 'command': 'get tx'}, + {'label': 'Neighbors', 'command': 'neighbors'}, + {'label': 'Version', 'command': 'ver'}, + {'label': 'Advertise', 'command': 'advert'}, + {'label': 'Clock', 'command': 'clock'}, + ]; + + @override + void initState() { + super.initState(); + final connector = Provider.of(context, listen: false); + _commandService = RepeaterCommandService(connector); + _setupMessageListener(); + } + + @override + void dispose() { + _frameSubscription?.cancel(); + _commandService?.dispose(); + _commandController.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + void _setupMessageListener() { + final connector = Provider.of(context, listen: false); + + // Listen for incoming text messages from the repeater + _frameSubscription = connector.receivedFrames.listen((frame) { + if (frame.isEmpty) return; + + // Check if it's a text message response + if (frame[0] == respCodeContactMsgRecv || + frame[0] == respCodeContactMsgRecvV3) { + _handleTextMessageResponse(frame); + } + }); + } + + void _handleTextMessageResponse(Uint8List frame) { + final parsed = parseContactMessageText(frame); + if (parsed == null) return; + if (!_matchesRepeaterPrefix(parsed.senderPrefix)) return; + + // Notify command service of response (for retry handling) + _commandService?.handleResponse(widget.repeater, parsed.text); + + // Note: The command service will handle the response via the Future + // We don't need to add it to history here anymore as _sendCommand will do it + } + + bool _matchesRepeaterPrefix(Uint8List prefix) { + final target = widget.repeater.publicKey; + if (target.length < 6 || prefix.length < 6) return false; + for (int i = 0; i < 6; i++) { + if (prefix[i] != target[i]) return false; + } + return true; + } + + void _sendCommand({bool showDebug = false}) async { + final command = _commandController.text.trim(); + if (command.isEmpty) return; + + setState(() { + _commandHistory.add({ + 'type': 'command', + 'text': command, + 'timestamp': DateTime.now().toString(), + }); + }); + + // Show debug info if requested + if (showDebug && mounted) { + final frame = buildSendCliCommandFrame(widget.repeater.publicKey, command); + DebugFrameViewer.showFrameDebug(context, frame, 'CLI Command Frame'); + } + + // Send CLI command to repeater with retry + try { + if (_commandService != null) { + final response = await _commandService!.sendCommand( + widget.repeater, + command, + ); + + if (mounted) { + setState(() { + _commandHistory.add({ + 'type': 'response', + 'text': response, + 'timestamp': DateTime.now().toString(), + }); + }); + } + } + } catch (e) { + if (mounted) { + setState(() { + _commandHistory.add({ + 'type': 'response', + 'text': 'Error: $e', + 'timestamp': DateTime.now().toString(), + }); + }); + } + } + + _commandController.clear(); + _historyIndex = -1; + + // Auto-scroll to bottom + Future.delayed(const Duration(milliseconds: 100), () { + if (_scrollController.hasClients) { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 200), + curve: Curves.easeOut, + ); + } + }); + } + + void _useQuickCommand(String command) { + _commandController.text = command; + _sendCommand(); + } + + void _navigateHistory(bool up) { + final commands = _commandHistory + .where((entry) => entry['type'] == 'command') + .toList() + .reversed + .toList(); + + if (commands.isEmpty) return; + + if (up) { + if (_historyIndex < commands.length - 1) { + _historyIndex++; + } + } else { + if (_historyIndex > 0) { + _historyIndex--; + } else { + _historyIndex = -1; + _commandController.clear(); + return; + } + } + + if (_historyIndex >= 0 && _historyIndex < commands.length) { + _commandController.text = commands[_historyIndex]['text'] ?? ''; + _commandController.selection = TextSelection.fromPosition( + TextPosition(offset: _commandController.text.length), + ); + } + } + + void _clearHistory() { + setState(() { + _commandHistory.clear(); + _historyIndex = -1; + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Repeater CLI'), + Text( + widget.repeater.name, + style: const TextStyle(fontSize: 14, fontWeight: FontWeight.normal), + ), + ], + ), + centerTitle: false, + actions: [ + IconButton( + icon: const Icon(Icons.bug_report), + tooltip: 'Debug Next Command', + onPressed: () { + // Set a flag or just send next command with debug + if (_commandController.text.trim().isNotEmpty) { + _sendCommand(showDebug: true); + } else { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Enter a command first')), + ); + } + }, + ), + IconButton( + icon: const Icon(Icons.help_outline), + tooltip: 'Command Help', + onPressed: () => _showCommandHelp(context), + ), + IconButton( + icon: const Icon(Icons.clear_all), + tooltip: 'Clear History', + onPressed: _commandHistory.isEmpty ? null : _clearHistory, + ), + ], + ), + body: Column( + children: [ + _buildQuickCommandsBar(), + const Divider(height: 1), + Expanded( + child: _commandHistory.isEmpty + ? _buildEmptyState() + : _buildCommandHistory(), + ), + const Divider(height: 1), + _buildCommandInput(), + ], + ), + ); + } + + Widget _buildQuickCommandsBar() { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: _quickCommands.map((cmd) { + return Padding( + padding: const EdgeInsets.only(right: 8), + child: ActionChip( + label: Text(cmd['label']!), + onPressed: () => _useQuickCommand(cmd['command']!), + avatar: const Icon(Icons.play_arrow, size: 16), + ), + ); + }).toList(), + ), + ), + ); + } + + Widget _buildEmptyState() { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.terminal, size: 64, color: Colors.grey[400]), + const SizedBox(height: 16), + Text( + 'No commands sent yet', + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + const SizedBox(height: 8), + Text( + 'Type a command below or use quick commands', + style: TextStyle(fontSize: 14, color: Colors.grey[500]), + ), + ], + ), + ); + } + + Widget _buildCommandHistory() { + return ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.all(16), + itemCount: _commandHistory.length, + itemBuilder: (context, index) { + final entry = _commandHistory[index]; + final isCommand = entry['type'] == 'command'; + + return Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: isCommand + ? Theme.of(context).colorScheme.primaryContainer + : Theme.of(context).colorScheme.secondaryContainer, + borderRadius: BorderRadius.circular(4), + ), + child: Icon( + isCommand ? Icons.chevron_right : Icons.arrow_back, + size: 16, + color: isCommand + ? Theme.of(context).colorScheme.onPrimaryContainer + : Theme.of(context).colorScheme.onSecondaryContainer, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SelectableText( + entry['text']!, + style: TextStyle( + fontFamily: 'monospace', + fontSize: 13, + color: isCommand + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurface, + ), + ), + ], + ), + ), + ], + ), + ); + }, + ); + } + + Widget _buildCommandInput() { + return Container( + padding: const EdgeInsets.all(12), + color: Theme.of(context).colorScheme.surface, + child: SafeArea( + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_upward, size: 20), + tooltip: 'Previous command', + onPressed: () => _navigateHistory(true), + ), + IconButton( + icon: const Icon(Icons.arrow_downward, size: 20), + tooltip: 'Next command', + onPressed: () => _navigateHistory(false), + ), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: _commandController, + decoration: const InputDecoration( + hintText: 'Enter command...', + border: OutlineInputBorder(), + contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 12), + prefixText: '> ', + ), + style: const TextStyle(fontFamily: 'monospace'), + textInputAction: TextInputAction.send, + onSubmitted: (_) => _sendCommand(), + ), + ), + const SizedBox(width: 8), + IconButton.filled( + icon: const Icon(Icons.send), + onPressed: _sendCommand, + ), + ], + ), + ), + ); + } + + void _showCommandHelp(BuildContext context) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Commands List'), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'NOTE: for the various "set ..." commands, there is also a "get ..." command.', + style: TextStyle(fontSize: 13), + ), + const SizedBox(height: 16), + _buildHelpSection('General', [ + 'advert - Sends an advertisement packet', + "reboot - Reboots the device. (note, you'll prob get 'Timeout' which is normal)", + "clock - Displays current time per device's clock.", + 'password {new-password} - Sets a new admin password for the device.', + 'ver - Shows the device version and firmware build date.', + 'clear stats - Resets various stats counters to zero.', + ]), + const SizedBox(height: 16), + _buildHelpSection('Settings', [ + 'set af {air-time-factor} - Sets the air-time-factor.', + 'set tx {tx-power-dbm} - Sets LoRa transmit power in dBm. (reboot to apply)', + 'set repeat {on|off} - Enables or disables the repeater role for this node.', + "set allow.read.only {on|off} - (Room server) If 'on', then login in blank password will be allowed, but cannot Post to room. (just read only)", + 'set flood.max {max-hops} - Sets the maximum number of hops of inbound flood packet (if >= max, packet is not forwarded)', + 'set int.thresh {db} - Sets the Interference Threshold (in DB). Default is 14. Set to 0 to disable channel interference detection.', + 'set agc.reset.interval {seconds} - Sets the interval to reset the Auto Gain Controller. Set to 0 to disable.', + "set multi.acks {0|1} - Enables or disables the 'double ACKs' feature.", + 'set advert.interval {minutes} - Sets the timer interval in minutes to send a local (zero-hop) advertisement packet. Set to 0 to disable.', + 'set flood.advert.interval {hours} - Sets the timer interval in hours to send a flood advertisement packet. Set to 0 to disable.', + 'set guest.password {guess-password} - Sets/updates the guest password. (for repeaters, guest logins can send the "Get Stats" request)', + 'set name {name} - Sets the advertisement name.', + 'set lat {latitude} - Sets the advertisement map latitude. (decimal degrees)', + 'set lon {longitude} - Sets the advertisement map longitude. (decimal degrees)', + 'set radio {freq},{bw},{sf},{cr} - Sets completely new radio params, and saves to preferences. Requires a "reboot" command to apply.', + 'set rxdelay {base} - Sets (experimental) base (must be > 1 for effect) for applying slight delay to received packets, based on signal strength/score. Set to 0 to disable.', + 'set txdelay {factor} - Sets a factor multiplied with time-on-air for a flood-mode packet and with a randomized slot system, to delay its forwarding. (to decrease likelihood of collisions)', + 'set direct.txdelay {factor} - Same as txdelay, but for applying a random delay to the forwarding of direct-mode packets.', + 'set bridge.enabled {on|off} - Enable/Disable bridge.', + 'set bridge.delay {0-10000} - Set delay before retransmitting packets.', + 'set bridge.source {rx|tx} - Choose wether the bridge will retransmit received packets or transmitted packets.', + 'set bridge.baud {speed} - Set serial link baudrate for rs232 bridges.', + 'set bridge.secret {shared-secret} - Set bridge secret for espnow bridges.', + 'set adc.multiplier {factor} - Sets custom factor to adjust reported battery voltage (only supported on select boards).', + 'tempradio {freq},{bw},{sf},{cr},{minutes} - Sets temporary radio params for the given number of {minutes}, reverting to original radio params afterward. (does NOT save to preferences).', + 'setperm {pubkey-hex} {permissions} - Modifies the ACL. Removes matching entry (by pubkey prefix) if "permissions" is zero. Adds new entry if pubkey-hex is full length and is not currently in ACL. Updates entry by matching pubkey prefix. Permission bits vary per firmware role, but low 2 bits are: 0 (Guest), 1 (Read only), 2 (Read write), 3 (Admin)', + ]), + const SizedBox(height: 16), + _buildHelpSection('Bridge', [ + 'get bridge.type - Gets bridge type none, rs232, espnow', + ]), + const SizedBox(height: 16), + _buildHelpSection('Logging', [ + 'log start - Starts packet logging to file system.', + 'log stop - Stops packet logging to file system.', + 'log erase - Erases the packet logs from file system.', + ]), + const SizedBox(height: 16), + _buildHelpSection('Neighbors (Repeater only)', [ + 'neighbors - Shows a list of other repeater nodes heard via zero-hop adverts. Each line is {id-prefix-hex}:{timestamp}:{snr-times-4}', + 'neighbor.remove {pubkey-prefix} - Removes first matching entry (by pubkey prefix (hex)), from neighbors list.', + ]), + const SizedBox(height: 16), + _buildHelpSection('Region Management (Repeater only)', [ + 'region commands have been introduced to manage region definitions and permissions.', + 'region - (serial only) Lists all defined regions and current flood permissions.', + 'region load - NOTE: this is a special multi-command invocation. Each subsequent command is a region name (indented with spaces to indicate parent hierarchy, with one space at minimum). Terminated by sending a blank line/command.', + "region get {* | name-prefix} - Searches for region with given name prefix (or '*' for the global scope). Replies with \"-> {region-name} ({parent-name}) {'F'}\"", + 'region put {name} {* | parent-name-prefix} - Adds or updates a region definition with given name.', + 'region remove {name} - Removes a region definition with given name. (must match exactly, and have no child regions)', + "region allowf {* | name-prefix} - Sets the 'F'lood permission for the given region. ('*' for the global/legacy scope)", + "region denyf {* | name-prefix} - Removes the 'F'lood permission for the given region. (NOTE: at this stage NOT advised to use this on the global/legacy scope!!)", + "region home - Replies with the current 'home' region. (Note applied anywhere yet, reserved for future)", + "region home {* | name-prefix} - Sets the 'home' region.", + 'region save - Persists the region list/map to storage.', + ]), + const SizedBox(height: 16), + _buildHelpSection('GPS Management', [ + 'gps command has been introduced to manage location related topics.', + 'gps - Gives status of gps. When gps is off, it replies only off, if on it replies with on, {status}, {fix}, {sat count}', + 'gps {on|off} - Toggles gps power state.', + 'gps sync - Syncs node time with gps clock.', + "gps setloc - Sets node's position to gps coordinates and save preferences.", + 'gps advert - Gives location advert configuration of the node:', + "none: don't include location in adverts", + 'share: share gps location (from SensorManager)', + 'prefs: advert the location stored in preferences', + 'gps advert {none|share|prefs} - Sets location advert configuration.', + ]), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } + + Widget _buildHelpSection(String title, List commands) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ), + const SizedBox(height: 8), + ...commands.map((cmd) => Padding( + padding: const EdgeInsets.only(left: 8, bottom: 4), + child: Text( + '• $cmd', + style: const TextStyle(fontSize: 13, fontFamily: 'monospace'), + ), + )), + ], + ); + } +} diff --git a/lib/screens/repeater_hub_screen.dart b/lib/screens/repeater_hub_screen.dart new file mode 100644 index 00000000..f28763e6 --- /dev/null +++ b/lib/screens/repeater_hub_screen.dart @@ -0,0 +1,204 @@ +import 'package:flutter/material.dart'; +import '../models/contact.dart'; +import 'repeater_status_screen.dart'; +import 'repeater_cli_screen.dart'; +import 'repeater_settings_screen.dart'; + +class RepeaterHubScreen extends StatelessWidget { + final Contact repeater; + final String password; + + const RepeaterHubScreen({ + super.key, + required this.repeater, + required this.password, + }); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Repeater Management'), + Text( + repeater.name, + style: const TextStyle(fontSize: 14, fontWeight: FontWeight.normal), + ), + ], + ), + centerTitle: false, + ), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Repeater info card + Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + CircleAvatar( + radius: 40, + backgroundColor: Colors.orange, + child: const Icon(Icons.cell_tower, size: 40, color: Colors.white), + ), + const SizedBox(height: 16), + Text( + repeater.name, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Text( + repeater.pathLabel, + style: TextStyle(fontSize: 14, color: Colors.grey[600]), + ), + if (repeater.hasLocation) ...[ + const SizedBox(height: 4), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.location_on, size: 14, color: Colors.grey[600]), + const SizedBox(width: 4), + Text( + '${repeater.latitude?.toStringAsFixed(4)}, ${repeater.longitude?.toStringAsFixed(4)}', + style: TextStyle(fontSize: 12, color: Colors.grey[600]), + ), + ], + ), + ], + ], + ), + ), + ), + const SizedBox(height: 24), + const Text( + 'Management Tools', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 16), + // Status button + _buildManagementCard( + context, + icon: Icons.analytics, + title: 'Status', + subtitle: 'View repeater status, stats, and neighbors', + color: Colors.blue, + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RepeaterStatusScreen( + repeater: repeater, + password: password, + ), + ), + ); + }, + ), + const SizedBox(height: 12), + // CLI button + _buildManagementCard( + context, + icon: Icons.terminal, + title: 'CLI', + subtitle: 'Send commands to the repeater', + color: Colors.green, + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RepeaterCliScreen( + repeater: repeater, + password: password, + ), + ), + ); + }, + ), + const SizedBox(height: 12), + // Settings button + _buildManagementCard( + context, + icon: Icons.settings, + title: 'Settings', + subtitle: 'Configure repeater parameters', + color: Colors.orange, + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RepeaterSettingsScreen( + repeater: repeater, + password: password, + ), + ), + ); + }, + ), + ], + ), + ), + ); + } + + Widget _buildManagementCard( + BuildContext context, { + required IconData icon, + required String title, + required String subtitle, + required Color color, + required VoidCallback onTap, + }) { + return Card( + elevation: 2, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), + ), + child: Icon(icon, color: color, size: 32), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 4), + Text( + subtitle, + style: TextStyle( + fontSize: 14, + color: Colors.grey[600], + ), + ), + ], + ), + ), + Icon(Icons.chevron_right, color: Colors.grey[400]), + ], + ), + ), + ), + ); + } +} diff --git a/lib/screens/repeater_settings_screen.dart b/lib/screens/repeater_settings_screen.dart new file mode 100644 index 00000000..494022d7 --- /dev/null +++ b/lib/screens/repeater_settings_screen.dart @@ -0,0 +1,1039 @@ +import 'dart:async'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../models/contact.dart'; +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../services/repeater_command_service.dart'; + +class RepeaterSettingsScreen extends StatefulWidget { + final Contact repeater; + final String password; + + const RepeaterSettingsScreen({ + super.key, + required this.repeater, + required this.password, + }); + + @override + State createState() => _RepeaterSettingsScreenState(); +} + +class _RepeaterSettingsScreenState extends State { + bool _isLoading = false; + bool _hasChanges = false; + bool _refreshingBasic = false; + bool _refreshingRadio = false; + bool _refreshingLocation = false; + bool _refreshingFeatures = false; + bool _refreshingAdvertisement = false; + StreamSubscription? _frameSubscription; + RepeaterCommandService? _commandService; + final Map _fetchedSettings = {}; + + // Basic settings + final TextEditingController _nameController = TextEditingController(); + final TextEditingController _passwordController = TextEditingController(); + final TextEditingController _guestPasswordController = TextEditingController(); + + // Radio settings + final TextEditingController _freqController = TextEditingController(); + final TextEditingController _txPowerController = TextEditingController(); + int _bandwidth = 125000; + int _spreadingFactor = 9; + int _codingRate = 7; + + // Location settings + final TextEditingController _latController = TextEditingController(); + final TextEditingController _lonController = TextEditingController(); + + // Feature toggles + bool _repeatEnabled = true; + bool _allowReadOnly = false; + bool _privacyMode = false; + + // Advertisement settings + int _advertInterval = 120; // minutes/2 + int _floodAdvertInterval = 12; // hours + int _privAdvertInterval = 60; // minutes + + final List _bandwidthOptions = [ + 7800, + 10400, + 15600, + 20800, + 31250, + 41700, + 62500, + 125000, + 250000, + 500000, + ]; + final List _spreadingFactorOptions = [5, 6, 7, 8, 9, 10, 11, 12]; + final List _codingRateOptions = [5, 6, 7, 8]; + + @override + void initState() { + super.initState(); + final connector = Provider.of(context, listen: false); + _commandService = RepeaterCommandService(connector); + _setupMessageListener(); + _loadSettings(); + } + + @override + void dispose() { + _frameSubscription?.cancel(); + _commandService?.dispose(); + _nameController.dispose(); + _passwordController.dispose(); + _guestPasswordController.dispose(); + _freqController.dispose(); + _txPowerController.dispose(); + _latController.dispose(); + _lonController.dispose(); + super.dispose(); + } + + void _setupMessageListener() { + final connector = Provider.of(context, listen: false); + + // Listen for incoming text messages from the repeater + _frameSubscription = connector.receivedFrames.listen((frame) { + if (frame.isEmpty) return; + + // Check if it's a text message response + if (frame[0] == respCodeContactMsgRecv || + frame[0] == respCodeContactMsgRecvV3) { + _handleTextMessageResponse(frame); + } + }); + } + + void _handleTextMessageResponse(Uint8List frame) { + final parsed = parseContactMessageText(frame); + if (parsed == null) return; + if (!_matchesRepeaterPrefix(parsed.senderPrefix)) return; + + // Notify command service of response (for retry handling) + _commandService?.handleResponse(widget.repeater, parsed.text); + } + + bool _matchesRepeaterPrefix(Uint8List prefix) { + final target = widget.repeater.publicKey; + if (target.length < 6 || prefix.length < 6) return false; + for (int i = 0; i < 6; i++) { + if (prefix[i] != target[i]) return false; + } + return true; + } + + void _updateUIFromFetchedSettings() { + if (_fetchedSettings.isEmpty) return; + + setState(() { + // Update name + if (_fetchedSettings.containsKey('name')) { + _nameController.text = _fetchedSettings['name']!; + } + + // Update radio settings - parse "915.00,250.00,9,7" or unit-labeled variants + if (_fetchedSettings.containsKey('radio')) { + final radioStr = _fetchedSettings['radio']!; + final parts = radioStr.split(','); + final parsed = []; + for (final part in parts) { + final trimmed = part.trim(); + if (trimmed.isNotEmpty) { + parsed.add(trimmed); + } + } + if (parsed.isNotEmpty) { + final freqText = parsed.first + .replaceAll('MHz', '') + .replaceAll('mhz', '') + .trim(); + if (freqText.isNotEmpty) { + _freqController.text = freqText; + } + } + if (parsed.length > 1) { + final bwText = parsed[1] + .replaceAll('kHz', '') + .replaceAll('khz', '') + .trim(); + final bw = double.tryParse(bwText); + if (bw != null) { + _bandwidth = (bw * 1000).toInt(); + if (!_bandwidthOptions.contains(_bandwidth)) { + _bandwidthOptions.add(_bandwidth); + _bandwidthOptions.sort(); + } + } + } + if (parsed.length > 2) { + final sfText = parsed[2].replaceAll('SF', '').replaceAll('sf', '').trim(); + _spreadingFactor = int.tryParse(sfText) ?? _spreadingFactor; + } + if (parsed.length > 3) { + final crText = parsed[3].replaceAll('CR', '').replaceAll('cr', '').trim(); + _codingRate = int.tryParse(crText) ?? _codingRate; + } + } + + if (_fetchedSettings.containsKey('tx')) { + _txPowerController.text = _fetchedSettings['tx']!; + } + + if (_fetchedSettings.containsKey('lat')) { + _latController.text = _fetchedSettings['lat']!; + } + if (_fetchedSettings.containsKey('lon')) { + _lonController.text = _fetchedSettings['lon']!; + } + + if (_fetchedSettings.containsKey('repeat')) { + _repeatEnabled = _normalizeOnOff(_fetchedSettings['repeat']!); + } + if (_fetchedSettings.containsKey('allow.read.only')) { + _allowReadOnly = _normalizeOnOff(_fetchedSettings['allow.read.only']!); + } + if (_fetchedSettings.containsKey('privacy')) { + _privacyMode = _normalizeOnOff(_fetchedSettings['privacy']!); + } + + if (_fetchedSettings.containsKey('advert.interval')) { + _advertInterval = _parseIntWithFallback( + _fetchedSettings['advert.interval']!, + _advertInterval, + ); + } + if (_fetchedSettings.containsKey('flood.advert.interval')) { + _floodAdvertInterval = _parseIntWithFallback( + _fetchedSettings['flood.advert.interval']!, + _floodAdvertInterval, + ); + } + if (_fetchedSettings.containsKey('priv.advert.interval')) { + _privAdvertInterval = _parseIntWithFallback( + _fetchedSettings['priv.advert.interval']!, + _privAdvertInterval, + ); + } + }); + } + + bool _isAnySectionRefreshing() { + return _refreshingBasic || + _refreshingRadio || + _refreshingLocation || + _refreshingFeatures || + _refreshingAdvertisement; + } + + bool _normalizeOnOff(String value) { + final normalized = value.trim().toLowerCase(); + return normalized == 'on' || + normalized == 'true' || + normalized == '1' || + normalized == 'enabled'; + } + + int _parseIntWithFallback(String value, int fallback) { + final parsed = int.tryParse(value.replaceAll(RegExp(r'[^0-9-]'), '')); + return parsed ?? fallback; + } + + String _formatBandwidthLabel(int bandwidthHz) { + final bandwidthKHz = bandwidthHz / 1000; + var text = bandwidthKHz.toStringAsFixed(2); + text = text.replaceAll(RegExp(r'0+$'), '').replaceAll(RegExp(r'\.$'), ''); + return '$text kHz'; + } + + void _applySettingResponse(String command, String response) { + final value = _extractCliValue(response); + if (value == null) return; + + final normalized = command.trim().toLowerCase(); + if (!normalized.startsWith('get ')) return; + final key = normalized.substring(4); + + switch (key) { + case 'name': + case 'radio': + case 'tx': + case 'lat': + case 'lon': + case 'repeat': + case 'allow.read.only': + case 'privacy': + case 'advert.interval': + case 'flood.advert.interval': + case 'priv.advert.interval': + _fetchedSettings[key] = value; + break; + } + } + + String? _extractCliValue(String response) { + final lines = response.split('\n'); + for (final line in lines) { + final trimmed = line.trim(); + if (trimmed.isEmpty) continue; + if (trimmed.startsWith('>')) { + final value = trimmed.substring(1).trim(); + if (value.isNotEmpty) return value; + } + final colonIndex = trimmed.indexOf(':'); + if (colonIndex > 0) { + final value = trimmed.substring(colonIndex + 1).trim(); + if (value.isNotEmpty) return value; + } + } + return null; + } + + Future _refreshSection({ + required String label, + required List commands, + required ValueSetter setRefreshing, + }) async { + if (_commandService == null) return; + + setState(() { + setRefreshing(true); + _fetchedSettings.clear(); + }); + + var successCount = 0; + for (final command in commands) { + try { + final response = await _commandService!.sendCommand(widget.repeater, command); + _applySettingResponse(command, response); + successCount += 1; + await Future.delayed(const Duration(milliseconds: 200)); + } catch (e) { + debugPrint('Error fetching $command: $e'); + } + } + + if (mounted) { + if (successCount > 0) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('$label refreshed'), + backgroundColor: Colors.green, + ), + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Error refreshing $label'), + backgroundColor: Colors.red, + ), + ); + } + + if (_fetchedSettings.isNotEmpty) { + _updateUIFromFetchedSettings(); + } + setState(() { + setRefreshing(false); + }); + } + } + + Future _refreshBasicSettings() async { + await _refreshSection( + label: 'Basic settings', + commands: const ['get name'], + setRefreshing: (value) => _refreshingBasic = value, + ); + } + + Future _refreshRadioSettings() async { + await _refreshSection( + label: 'Radio settings', + commands: const ['get radio', 'get tx'], + setRefreshing: (value) => _refreshingRadio = value, + ); + } + + Future _refreshLocationSettings() async { + await _refreshSection( + label: 'Location settings', + commands: const ['get lat', 'get lon'], + setRefreshing: (value) => _refreshingLocation = value, + ); + } + + Future _refreshFeatureSettings() async { + await _refreshSection( + label: 'Feature toggles', + commands: const ['get repeat', 'get allow.read.only', 'get privacy'], + setRefreshing: (value) => _refreshingFeatures = value, + ); + } + + Future _refreshAdvertisementSettings() async { + await _refreshSection( + label: 'Advertisement settings', + commands: const [ + 'get advert.interval', + 'get flood.advert.interval', + 'get priv.advert.interval', + ], + setRefreshing: (value) => _refreshingAdvertisement = value, + ); + } + + Future _loadSettings() async { + // Just populate with current repeater data on initial load + // User must click sync button to fetch from device + setState(() { + _nameController.text = widget.repeater.name; + + if (widget.repeater.hasLocation) { + _latController.text = widget.repeater.latitude?.toString() ?? ''; + _lonController.text = widget.repeater.longitude?.toString() ?? ''; + } + }); + } + + Future _saveSettings() async { + final connector = Provider.of(context, listen: false); + + setState(() { + _isLoading = true; + }); + + try { + final commands = []; + + // Build set commands for each setting + if (_nameController.text.isNotEmpty) { + commands.add('set name ${_nameController.text}'); + } + + if (_passwordController.text.isNotEmpty) { + commands.add('password ${_passwordController.text}'); + } + + if (_guestPasswordController.text.isNotEmpty) { + commands.add('set guest.password ${_guestPasswordController.text}'); + } + + // Radio parameters + final freqMHz = double.tryParse(_freqController.text) ?? 915.0; + final bwKHz = _bandwidth / 1000; + commands.add('set radio ${freqMHz.toStringAsFixed(1)} $bwKHz $_spreadingFactor $_codingRate'); + + // Location + if (_latController.text.isNotEmpty) { + commands.add('set lat ${_latController.text}'); + } + if (_lonController.text.isNotEmpty) { + commands.add('set lon ${_lonController.text}'); + } + + // Feature toggles + commands.add('set repeat ${_repeatEnabled ? "on" : "off"}'); + commands.add('set allow.read.only ${_allowReadOnly ? "on" : "off"}'); + commands.add('set privacy ${_privacyMode ? "on" : "off"}'); + + // Advertisement intervals + commands.add('set advert.interval ${_advertInterval}'); + commands.add('set flood.advert.interval ${_floodAdvertInterval}'); + if (_privacyMode) { + commands.add('set priv.advert.interval ${_privAdvertInterval}'); + } + + // Send all commands + for (final command in commands) { + final frame = buildSendCliCommandFrame(widget.repeater.publicKey, command); + await connector.sendFrame(frame); + await Future.delayed(const Duration(milliseconds: 200)); // Delay between commands + } + + setState(() { + _isLoading = false; + _hasChanges = false; + }); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Settings saved successfully'), + backgroundColor: Colors.green, + ), + ); + } + } catch (e) { + setState(() { + _isLoading = false; + }); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Error saving settings: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + } + + void _markChanged() { + if (!_hasChanges) { + setState(() { + _hasChanges = true; + }); + } + } + + Widget _buildSectionHeader({ + required IconData icon, + required String title, + required bool isRefreshing, + required VoidCallback onRefresh, + }) { + return Row( + children: [ + Icon(icon, color: Theme.of(context).primaryColor), + const SizedBox(width: 8), + Text( + title, + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + const Spacer(), + IconButton( + icon: isRefreshing + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.refresh), + onPressed: isRefreshing ? null : onRefresh, + tooltip: 'Refresh $title', + ), + ], + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Repeater Settings'), + Text( + widget.repeater.name, + style: const TextStyle(fontSize: 14, fontWeight: FontWeight.normal), + ), + ], + ), + centerTitle: false, + actions: [ + if (_hasChanges) + TextButton.icon( + onPressed: _isLoading ? null : _saveSettings, + icon: const Icon(Icons.save), + label: const Text('Save'), + ), + ], + ), + body: _isLoading && _nameController.text.isEmpty + ? const Center(child: CircularProgressIndicator()) + : ListView( + padding: const EdgeInsets.all(16), + children: [ + _buildBasicSettingsCard(), + const SizedBox(height: 16), + _buildRadioSettingsCard(), + const SizedBox(height: 16), + _buildLocationSettingsCard(), + const SizedBox(height: 16), + _buildFeatureTogglesCard(), + const SizedBox(height: 16), + _buildAdvertisementSettingsCard(), + const SizedBox(height: 32), + _buildDangerZoneCard(), + ], + ), + ); + } + + Widget _buildBasicSettingsCard() { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionHeader( + icon: Icons.settings, + title: 'Basic Settings', + isRefreshing: _refreshingBasic, + onRefresh: _refreshBasicSettings, + ), + const Divider(), + TextField( + controller: _nameController, + decoration: const InputDecoration( + labelText: 'Repeater Name', + helperText: 'Display name for this repeater', + border: OutlineInputBorder(), + ), + onChanged: (_) => _markChanged(), + ), + const SizedBox(height: 16), + TextField( + controller: _passwordController, + decoration: const InputDecoration( + labelText: 'Admin Password', + helperText: 'Full access password', + border: OutlineInputBorder(), + ), + obscureText: true, + onChanged: (_) => _markChanged(), + ), + const SizedBox(height: 16), + TextField( + controller: _guestPasswordController, + decoration: const InputDecoration( + labelText: 'Guest Password', + helperText: 'Read-only access password', + border: OutlineInputBorder(), + ), + obscureText: true, + onChanged: (_) => _markChanged(), + ), + ], + ), + ), + ); + } + + Widget _buildRadioSettingsCard() { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionHeader( + icon: Icons.radio, + title: 'Radio Settings', + isRefreshing: _refreshingRadio, + onRefresh: _refreshRadioSettings, + ), + const Divider(), + TextField( + controller: _freqController, + decoration: const InputDecoration( + labelText: 'Frequency (MHz)', + helperText: '300-2500 MHz', + border: OutlineInputBorder(), + suffixText: 'MHz', + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + onChanged: (_) => _markChanged(), + ), + const SizedBox(height: 16), + TextField( + controller: _txPowerController, + decoration: const InputDecoration( + labelText: 'TX Power', + helperText: '1-30 dBm', + border: OutlineInputBorder(), + suffixText: 'dBm', + ), + keyboardType: TextInputType.number, + onChanged: (_) => _markChanged(), + ), + const SizedBox(height: 16), + DropdownButtonFormField( + value: _bandwidth, + decoration: const InputDecoration( + labelText: 'Bandwidth', + border: OutlineInputBorder(), + ), + items: _bandwidthOptions.map((bw) { + return DropdownMenuItem( + value: bw, + child: Text(_formatBandwidthLabel(bw)), + ); + }).toList(), + onChanged: (value) { + if (value != null) { + setState(() { + _bandwidth = value; + }); + _markChanged(); + } + }, + ), + const SizedBox(height: 16), + DropdownButtonFormField( + value: _spreadingFactor, + decoration: const InputDecoration( + labelText: 'Spreading Factor', + border: OutlineInputBorder(), + ), + items: _spreadingFactorOptions.map((sf) { + return DropdownMenuItem( + value: sf, + child: Text('SF$sf'), + ); + }).toList(), + onChanged: (value) { + if (value != null) { + setState(() { + _spreadingFactor = value; + }); + _markChanged(); + } + }, + ), + const SizedBox(height: 16), + DropdownButtonFormField( + value: _codingRate, + decoration: const InputDecoration( + labelText: 'Coding Rate', + border: OutlineInputBorder(), + ), + items: _codingRateOptions.map((cr) { + return DropdownMenuItem( + value: cr, + child: Text('4/$cr'), + ); + }).toList(), + onChanged: (value) { + if (value != null) { + setState(() { + _codingRate = value; + }); + _markChanged(); + } + }, + ), + ], + ), + ), + ); + } + + Widget _buildLocationSettingsCard() { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionHeader( + icon: Icons.location_on, + title: 'Location Settings', + isRefreshing: _refreshingLocation, + onRefresh: _refreshLocationSettings, + ), + const Divider(), + TextField( + controller: _latController, + decoration: const InputDecoration( + labelText: 'Latitude', + helperText: 'Decimal degrees (e.g., 37.7749)', + border: OutlineInputBorder(), + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true, signed: true), + onChanged: (_) => _markChanged(), + ), + const SizedBox(height: 16), + TextField( + controller: _lonController, + decoration: const InputDecoration( + labelText: 'Longitude', + helperText: 'Decimal degrees (e.g., -122.4194)', + border: OutlineInputBorder(), + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true, signed: true), + onChanged: (_) => _markChanged(), + ), + ], + ), + ), + ); + } + + Widget _buildFeatureTogglesCard() { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionHeader( + icon: Icons.toggle_on, + title: 'Features', + isRefreshing: _refreshingFeatures, + onRefresh: _refreshFeatureSettings, + ), + const Divider(), + SwitchListTile( + title: const Text('Packet Forwarding'), + subtitle: const Text('Enable repeater to forward packets'), + value: _repeatEnabled, + onChanged: (value) { + setState(() { + _repeatEnabled = value; + }); + _markChanged(); + }, + ), + SwitchListTile( + title: const Text('Guest Access'), + subtitle: const Text('Allow read-only guest access'), + value: _allowReadOnly, + onChanged: (value) { + setState(() { + _allowReadOnly = value; + }); + _markChanged(); + }, + ), + SwitchListTile( + title: const Text('Privacy Mode'), + subtitle: const Text('Hide name/location in advertisements'), + value: _privacyMode, + onChanged: (value) { + setState(() { + _privacyMode = value; + }); + _markChanged(); + }, + ), + ], + ), + ), + ); + } + + Widget _buildAdvertisementSettingsCard() { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionHeader( + icon: Icons.broadcast_on_personal, + title: 'Advertisement Settings', + isRefreshing: _refreshingAdvertisement, + onRefresh: _refreshAdvertisementSettings, + ), + const Divider(), + ListTile( + title: const Text('Local Advertisement Interval'), + subtitle: Text('${_advertInterval} minutes'), + trailing: Text('${_advertInterval}m'), + ), + Slider( + value: _advertInterval.toDouble(), + min: 60, + max: 240, + divisions: 18, + label: '${_advertInterval}m', + onChanged: (value) { + setState(() { + _advertInterval = value.toInt(); + }); + _markChanged(); + }, + ), + const SizedBox(height: 16), + ListTile( + title: const Text('Flood Advertisement Interval'), + subtitle: Text('${_floodAdvertInterval} hours'), + trailing: Text('${_floodAdvertInterval}h'), + ), + Slider( + value: _floodAdvertInterval.toDouble(), + min: 3, + max: 48, + divisions: 45, + label: '${_floodAdvertInterval}h', + onChanged: (value) { + setState(() { + _floodAdvertInterval = value.toInt(); + }); + _markChanged(); + }, + ), + if (_privacyMode) ...[ + const SizedBox(height: 16), + ListTile( + title: const Text('Encrypted Advertisement Interval'), + subtitle: Text('${_privAdvertInterval} minutes'), + trailing: Text('${_privAdvertInterval}m'), + ), + Slider( + value: _privAdvertInterval.toDouble(), + min: 30, + max: 240, + divisions: 21, + label: '${_privAdvertInterval}m', + onChanged: (value) { + setState(() { + _privAdvertInterval = value.toInt(); + }); + _markChanged(); + }, + ), + ], + ], + ), + ), + ); + } + + Widget _buildDangerZoneCard() { + final colorScheme = Theme.of(context).colorScheme; + return Card( + color: colorScheme.errorContainer, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.warning, color: colorScheme.onErrorContainer), + const SizedBox(width: 8), + Text( + 'Danger Zone', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: colorScheme.onErrorContainer, + ), + ), + ], + ), + const Divider(), + ListTile( + leading: Icon(Icons.refresh, color: colorScheme.onErrorContainer), + title: Text('Reboot Repeater', style: TextStyle(color: colorScheme.onErrorContainer)), + subtitle: Text( + 'Restart the repeater device', + style: TextStyle(color: colorScheme.onErrorContainer.withValues(alpha: 0.8)), + ), + onTap: () => _confirmAction( + 'Reboot Repeater', + 'Are you sure you want to reboot this repeater?', + () => _sendDangerCommand('reboot'), + ), + ), + ListTile( + leading: Icon(Icons.vpn_key, color: colorScheme.onErrorContainer), + title: Text('Regenerate Identity Key', style: TextStyle(color: colorScheme.onErrorContainer)), + subtitle: Text( + 'Generate new public/private key pair', + style: TextStyle(color: colorScheme.onErrorContainer.withValues(alpha: 0.8)), + ), + onTap: () => _confirmAction( + 'Regenerate Identity', + 'This will generate a new identity for the repeater. Continue?', + () => _sendDangerCommand('regen key'), + ), + ), + ListTile( + leading: Icon(Icons.delete_forever, color: colorScheme.onErrorContainer), + title: Text('Erase File System', style: TextStyle(color: colorScheme.onErrorContainer)), + subtitle: Text( + 'Format the repeater file system', + style: TextStyle(color: colorScheme.onErrorContainer.withValues(alpha: 0.8)), + ), + onTap: () => _confirmAction( + 'Erase File System', + 'WARNING: This will erase all data on the repeater. This cannot be undone!', + () => _sendDangerCommand('erase'), + isDestructive: true, + ), + ), + ], + ), + ), + ); + } + + Future _sendDangerCommand(String command) async { + final connector = Provider.of(context, listen: false); + + if (command == 'erase') { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Erase is only available over serial console.')), + ); + } + return; + } + + try { + final frame = buildSendCliCommandFrame(widget.repeater.publicKey, command); + await connector.sendFrame(frame); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Command sent: $command')), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Error sending command: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + } + + void _confirmAction( + String title, + String message, + VoidCallback onConfirm, { + bool isDestructive = false, + }) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () { + Navigator.pop(context); + onConfirm(); + }, + style: isDestructive + ? FilledButton.styleFrom(backgroundColor: Colors.red) + : null, + child: const Text('Confirm'), + ), + ], + ), + ); + } +} diff --git a/lib/screens/repeater_status_screen.dart b/lib/screens/repeater_status_screen.dart new file mode 100644 index 00000000..f27be228 --- /dev/null +++ b/lib/screens/repeater_status_screen.dart @@ -0,0 +1,508 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../models/contact.dart'; +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../services/repeater_command_service.dart'; + +class RepeaterStatusScreen extends StatefulWidget { + final Contact repeater; + final String password; + + const RepeaterStatusScreen({ + super.key, + required this.repeater, + required this.password, + }); + + @override + State createState() => _RepeaterStatusScreenState(); +} + +class _RepeaterStatusScreenState extends State { + bool _isLoading = false; + StreamSubscription? _frameSubscription; + RepeaterCommandService? _commandService; + Timer? _statusTimeout; + DateTime? _statusRequestedAt; + int? _batteryMv; + int? _uptimeSecs; + int? _queueLen; + int? _debugFlags; + int? _lastRssi; + double? _lastSnr; + int? _noiseFloor; + int? _txAirSecs; + int? _rxAirSecs; + int? _packetsSent; + int? _packetsRecv; + int? _floodTx; + int? _directTx; + int? _floodRx; + int? _directRx; + int? _dupFlood; + int? _dupDirect; + + @override + void initState() { + super.initState(); + final connector = Provider.of(context, listen: false); + _commandService = RepeaterCommandService(connector); + _setupMessageListener(); + _loadStatus(); + } + + @override + void dispose() { + _frameSubscription?.cancel(); + _commandService?.dispose(); + _statusTimeout?.cancel(); + super.dispose(); + } + + void _setupMessageListener() { + final connector = Provider.of(context, listen: false); + + // Listen for incoming text messages from the repeater + _frameSubscription = connector.receivedFrames.listen((frame) { + if (frame.isEmpty) return; + + // Check if it's a text message response + if (frame[0] == pushCodeStatusResponse) { + _handleStatusResponse(frame); + } else if (frame[0] == respCodeContactMsgRecv || + frame[0] == respCodeContactMsgRecvV3) { + _handleTextMessageResponse(frame); + } + }); + } + + void _handleTextMessageResponse(Uint8List frame) { + final parsed = parseContactMessageText(frame); + if (parsed == null) return; + if (!_matchesRepeaterPrefix(parsed.senderPrefix)) return; + + // Notify command service of response (for retry handling) + _commandService?.handleResponse(widget.repeater, parsed.text); + + // Parse status responses + _parseStatusResponse(parsed.text); + } + + void _handleStatusResponse(Uint8List frame) { + if (frame.length < 8) return; + final prefix = frame.sublist(2, 8); + if (!_matchesRepeaterPrefix(prefix)) return; + + const payloadOffset = 8; + const statsSize = 52; + if (frame.length < payloadOffset + statsSize) return; + + final data = ByteData.sublistView(frame, payloadOffset, payloadOffset + statsSize); + int offset = 0; + + final batteryMv = data.getUint16(offset, Endian.little); + offset += 2; + final queueLen = data.getUint16(offset, Endian.little); + offset += 2; + final noiseFloor = data.getInt16(offset, Endian.little); + offset += 2; + final lastRssi = data.getInt16(offset, Endian.little); + offset += 2; + final packetsRecv = data.getUint32(offset, Endian.little); + offset += 4; + final packetsSent = data.getUint32(offset, Endian.little); + offset += 4; + final txAirSecs = data.getUint32(offset, Endian.little); + offset += 4; + final uptimeSecs = data.getUint32(offset, Endian.little); + offset += 4; + final floodTx = data.getUint32(offset, Endian.little); + offset += 4; + final directTx = data.getUint32(offset, Endian.little); + offset += 4; + final floodRx = data.getUint32(offset, Endian.little); + offset += 4; + final directRx = data.getUint32(offset, Endian.little); + offset += 4; + final errEvents = data.getUint16(offset, Endian.little); + offset += 2; + final lastSnrRaw = data.getInt16(offset, Endian.little); + offset += 2; + final directDups = data.getUint16(offset, Endian.little); + offset += 2; + final floodDups = data.getUint16(offset, Endian.little); + offset += 2; + final rxAirSecs = data.getUint32(offset, Endian.little); + + _statusTimeout?.cancel(); + if (!mounted) return; + setState(() { + _isLoading = false; + _batteryMv = batteryMv; + _queueLen = queueLen; + _noiseFloor = noiseFloor; + _lastRssi = lastRssi; + _packetsRecv = packetsRecv; + _packetsSent = packetsSent; + _txAirSecs = txAirSecs; + _rxAirSecs = rxAirSecs; + _uptimeSecs = uptimeSecs; + _floodTx = floodTx; + _directTx = directTx; + _floodRx = floodRx; + _directRx = directRx; + _debugFlags = errEvents; + _lastSnr = lastSnrRaw / 4.0; + _dupDirect = directDups; + _dupFlood = floodDups; + }); + } + + bool _matchesRepeaterPrefix(Uint8List prefix) { + final target = widget.repeater.publicKey; + if (target.length < 6 || prefix.length < 6) return false; + for (int i = 0; i < 6; i++) { + if (prefix[i] != target[i]) return false; + } + return true; + } + + void _parseStatusResponse(String response) { + final trimmed = response.trim(); + if (trimmed.startsWith('{') && trimmed.endsWith('}')) { + try { + final data = jsonDecode(trimmed) as Map; + if (data.containsKey('battery_mv')) { + _batteryMv = _asInt(data['battery_mv']); + _uptimeSecs = _asInt(data['uptime_secs']); + _queueLen = _asInt(data['queue_len']); + _debugFlags = _asInt(data['errors']); + } else if (data.containsKey('noise_floor')) { + _noiseFloor = _asInt(data['noise_floor']); + _lastRssi = _asInt(data['last_rssi']); + _lastSnr = _asDouble(data['last_snr']); + _txAirSecs = _asInt(data['tx_air_secs']); + _rxAirSecs = _asInt(data['rx_air_secs']); + } else if (data.containsKey('recv') || data.containsKey('sent')) { + _packetsRecv = _asInt(data['recv']); + _packetsSent = _asInt(data['sent']); + _floodTx = _asInt(data['flood_tx']); + _directTx = _asInt(data['direct_tx']); + _floodRx = _asInt(data['flood_rx']); + _directRx = _asInt(data['direct_rx']); + _dupFlood = _asInt(data['dup_flood']); + _dupDirect = _asInt(data['dup_direct']); + } + } catch (_) { + // Ignore parse failures for non-JSON responses. + } + } + + if (mounted) { + setState(() {}); + } + } + + Future _loadStatus() async { + if (_commandService == null) return; + + setState(() { + _isLoading = true; + _statusRequestedAt = DateTime.now(); + _batteryMv = null; + _uptimeSecs = null; + _queueLen = null; + _debugFlags = null; + _lastRssi = null; + _lastSnr = null; + _noiseFloor = null; + _txAirSecs = null; + _rxAirSecs = null; + _packetsSent = null; + _packetsRecv = null; + _floodTx = null; + _directTx = null; + _floodRx = null; + _directRx = null; + _dupFlood = null; + _dupDirect = null; + }); + + try { + final connector = Provider.of(context, listen: false); + final frame = buildSendStatusRequestFrame(widget.repeater.publicKey); + await connector.sendFrame(frame); + + _statusTimeout?.cancel(); + _statusTimeout = Timer(const Duration(seconds: 12), () { + if (!mounted) return; + setState(() { + _isLoading = false; + }); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Status request timed out.'), + backgroundColor: Colors.red, + ), + ); + }); + } catch (e) { + if (mounted) { + setState(() { + _isLoading = false; + }); + + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Error loading status: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Repeater Status'), + Text( + widget.repeater.name, + style: const TextStyle(fontSize: 14, fontWeight: FontWeight.normal), + ), + ], + ), + centerTitle: false, + actions: [ + IconButton( + icon: _isLoading + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.refresh), + onPressed: _isLoading ? null : _loadStatus, + tooltip: 'Refresh', + ), + ], + ), + body: RefreshIndicator( + onRefresh: _loadStatus, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + _buildSystemInfoCard(), + const SizedBox(height: 16), + _buildRadioStatsCard(), + const SizedBox(height: 16), + _buildPacketStatsCard(), + ], + ), + ), + ); + } + + Widget _buildSystemInfoCard() { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.info_outline, color: Theme.of(context).primaryColor), + const SizedBox(width: 8), + const Text( + 'System Information', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ], + ), + const Divider(), + _buildInfoRow('Battery', _batteryText()), + _buildInfoRow('Clock (at login)', _clockText()), + _buildInfoRow('Uptime', _formatDuration(_uptimeSecs)), + _buildInfoRow('Queue Length', _formatValue(_queueLen)), + _buildInfoRow('Debug Flags', _formatValue(_debugFlags)), + ], + ), + ), + ); + } + + Widget _buildRadioStatsCard() { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.radio, color: Theme.of(context).primaryColor), + const SizedBox(width: 8), + const Text( + 'Radio Statistics', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ], + ), + const Divider(), + _buildInfoRow('Last RSSI', _formatValue(_lastRssi, suffix: ' dB')), + _buildInfoRow('Last SNR', _formatSnr(_lastSnr)), + _buildInfoRow('Noise Floor', _formatValue(_noiseFloor, suffix: ' dB')), + _buildInfoRow('TX Airtime', _formatDuration(_txAirSecs)), + _buildInfoRow('RX Airtime', _formatDuration(_rxAirSecs)), + ], + ), + ), + ); + } + + Widget _buildPacketStatsCard() { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.analytics, color: Theme.of(context).primaryColor), + const SizedBox(width: 8), + const Text( + 'Packet Statistics', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ], + ), + const Divider(), + _buildInfoRow('Sent', _packetTxText()), + _buildInfoRow('Received', _packetRxText()), + _buildInfoRow('Duplicates', _duplicateText()), + ], + ), + ), + ); + } + + Widget _buildInfoRow(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 130, + child: Text( + label, + style: TextStyle( + color: Colors.grey[600], + fontWeight: FontWeight.w500, + ), + ), + ), + Expanded( + child: Text( + value, + style: const TextStyle(fontWeight: FontWeight.w400), + ), + ), + ], + ), + ); + } + + int? _asInt(dynamic value) { + if (value == null) return null; + if (value is int) return value; + if (value is double) return value.round(); + return int.tryParse(value.toString()); + } + + double? _asDouble(dynamic value) { + if (value == null) return null; + if (value is double) return value; + if (value is int) return value.toDouble(); + return double.tryParse(value.toString()); + } + + String _batteryText() { + if (_batteryMv == null) return '—'; + final percent = _batteryPercentFromMv(_batteryMv!); + final volts = (_batteryMv! / 1000.0).toStringAsFixed(2); + return '$percent% / ${volts}V'; + } + + int _batteryPercentFromMv(int millivolts) { + const minMv = 3000; + const maxMv = 4200; + if (millivolts <= minMv) return 0; + if (millivolts >= maxMv) return 100; + return (((millivolts - minMv) * 100) / (maxMv - minMv)).round(); + } + + String _clockText() { + if (_statusRequestedAt == null) return '—'; + final dt = _statusRequestedAt!; + final date = '${dt.day}/${dt.month}/${dt.year}'; + final time = '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}'; + return '$date $time'; + } + + String _formatDuration(int? seconds) { + if (seconds == null) return '—'; + final days = seconds ~/ 86400; + final hours = (seconds % 86400) ~/ 3600; + final minutes = (seconds % 3600) ~/ 60; + final secs = seconds % 60; + return '$days days ${hours}h ${minutes}m ${secs}s'; + } + + String _packetTxText() { + if (_packetsSent == null) return '—'; + final flood = _formatValue(_floodTx); + final direct = _formatValue(_directTx); + return 'Total: $_packetsSent, Flood: $flood, Direct: $direct'; + } + + String _packetRxText() { + if (_packetsRecv == null) return '—'; + final flood = _formatValue(_floodRx); + final direct = _formatValue(_directRx); + return 'Total: $_packetsRecv, Flood: $flood, Direct: $direct'; + } + + String _duplicateText() { + if (_dupFlood != null || _dupDirect != null) { + final flood = _formatValue(_dupFlood); + final direct = _formatValue(_dupDirect); + return 'Flood: $flood, Direct: $direct'; + } + if (_packetsRecv == null || _floodRx == null || _directRx == null) return '—'; + final dupTotal = _packetsRecv! - _floodRx! - _directRx!; + if (dupTotal < 0) return '—'; + return 'Total: $dupTotal'; + } + + String _formatValue(num? value, {String? suffix}) { + if (value == null) return '—'; + return suffix == null ? value.toString() : '$value$suffix'; + } + + String _formatSnr(double? snr) { + if (snr == null) return '—'; + return snr.toStringAsFixed(2); + } +} diff --git a/lib/screens/scanner_screen.dart b/lib/screens/scanner_screen.dart new file mode 100644 index 00000000..db3f83c9 --- /dev/null +++ b/lib/screens/scanner_screen.dart @@ -0,0 +1,176 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_blue_plus/flutter_blue_plus.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../widgets/device_tile.dart'; +import 'device_screen.dart'; + +/// Screen for scanning and connecting to MeshCore devices +class ScannerScreen extends StatelessWidget { + const ScannerScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('MeshCore Open'), + centerTitle: true, + automaticallyImplyLeading: false, + ), + body: Consumer( + builder: (context, connector, child) { + return Column( + children: [ + // Status bar + _buildStatusBar(context, connector), + + // Device list + Expanded( + child: _buildDeviceList(context, connector), + ), + ], + ); + }, + ), + floatingActionButton: Consumer( + builder: (context, connector, child) { + final isScanning = connector.state == MeshCoreConnectionState.scanning; + + return FloatingActionButton.extended( + onPressed: () { + if (isScanning) { + connector.stopScan(); + } else { + connector.startScan(); + } + }, + icon: isScanning + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : const Icon(Icons.bluetooth_searching), + label: Text(isScanning ? 'Stop' : 'Scan'), + ); + }, + ), + ); + } + + Widget _buildStatusBar(BuildContext context, MeshCoreConnector connector) { + String statusText; + Color statusColor; + + switch (connector.state) { + case MeshCoreConnectionState.scanning: + statusText = 'Scanning for devices...'; + statusColor = Colors.blue; + break; + case MeshCoreConnectionState.connecting: + statusText = 'Connecting...'; + statusColor = Colors.orange; + break; + case MeshCoreConnectionState.connected: + statusText = 'Connected to ${connector.device?.platformName}'; + statusColor = Colors.green; + break; + case MeshCoreConnectionState.disconnecting: + statusText = 'Disconnecting...'; + statusColor = Colors.orange; + break; + case MeshCoreConnectionState.disconnected: + statusText = 'Not connected'; + statusColor = Colors.grey; + break; + } + + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + color: statusColor.withValues(alpha: 0.1), + child: Row( + children: [ + Icon(Icons.circle, size: 12, color: statusColor), + const SizedBox(width: 8), + Text( + statusText, + style: TextStyle(color: statusColor, fontWeight: FontWeight.w500), + ), + ], + ), + ); + } + + Widget _buildDeviceList(BuildContext context, MeshCoreConnector connector) { + if (connector.scanResults.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.bluetooth, + size: 64, + color: Colors.grey[400], + ), + const SizedBox(height: 16), + Text( + connector.state == MeshCoreConnectionState.scanning + ? 'Searching for MeshCore devices...' + : 'Tap Scan to find MeshCore devices', + style: TextStyle( + fontSize: 16, + color: Colors.grey[600], + ), + ), + ], + ), + ); + } + + return ListView.separated( + padding: const EdgeInsets.all(8), + itemCount: connector.scanResults.length, + separatorBuilder: (context, index) => const Divider(), + itemBuilder: (context, index) { + final result = connector.scanResults[index]; + return DeviceTile( + scanResult: result, + onTap: () => _connectToDevice(context, connector, result), + ); + }, + ); + } + + Future _connectToDevice( + BuildContext context, + MeshCoreConnector connector, + ScanResult result, + ) async { + try { + await connector.connect(result.device); + + if (context.mounted && connector.isConnected) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const DeviceScreen(), + ), + ); + } + } catch (e) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Connection failed: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + } +} diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart new file mode 100644 index 00000000..cee2237e --- /dev/null +++ b/lib/screens/settings_screen.dart @@ -0,0 +1,693 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../models/radio_settings.dart'; +import '../services/app_settings_service.dart'; +import 'app_settings_screen.dart'; +import 'ble_debug_log_screen.dart'; + +class SettingsScreen extends StatelessWidget { + const SettingsScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Settings'), + centerTitle: true, + ), + body: Consumer( + builder: (context, connector, child) { + return ListView( + padding: const EdgeInsets.all(16), + children: [ + _buildDeviceInfoCard(connector), + const SizedBox(height: 16), + _buildAppSettingsCard(context), + const SizedBox(height: 16), + _buildNodeSettingsCard(context, connector), + const SizedBox(height: 16), + _buildActionsCard(context, connector), + const SizedBox(height: 16), + _buildDebugCard(context), + const SizedBox(height: 16), + _buildAboutCard(context), + ], + ); + }, + ), + ); + } + + Widget _buildDeviceInfoCard(MeshCoreConnector connector) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Device Info', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 16), + _buildInfoRow('Name', connector.device?.platformName ?? 'Unknown'), + _buildInfoRow('ID', connector.device?.remoteId.toString() ?? 'Unknown'), + _buildInfoRow('Status', connector.isConnected ? 'Connected' : 'Disconnected'), + if (connector.selfName != null) + _buildInfoRow('Node Name', connector.selfName!), + if (connector.selfPublicKey != null) + _buildInfoRow('Public Key', '${pubKeyToHex(connector.selfPublicKey!).substring(0, 16)}...'), + ], + ), + ), + ); + } + + Widget _buildAppSettingsCard(BuildContext context) { + return Card( + child: ListTile( + leading: const Icon(Icons.settings_outlined), + title: const Text('App Settings'), + subtitle: const Text('Notifications, messaging, and map preferences'), + trailing: const Icon(Icons.chevron_right), + onTap: () { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => const AppSettingsScreen()), + ); + }, + ), + ); + } + + Widget _buildNodeSettingsCard(BuildContext context, MeshCoreConnector connector) { + return Card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text( + 'Node Settings', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + ListTile( + leading: const Icon(Icons.person_outline), + title: const Text('Node Name'), + subtitle: Text(connector.selfName ?? 'Not set'), + trailing: const Icon(Icons.chevron_right), + onTap: () => _editNodeName(context, connector), + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.radio), + title: const Text('Radio Settings'), + subtitle: const Text('Frequency, power, spreading factor'), + trailing: const Icon(Icons.chevron_right), + onTap: () => _showRadioSettings(context, connector), + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.location_on_outlined), + title: const Text('Location'), + subtitle: const Text('GPS coordinates'), + trailing: const Icon(Icons.chevron_right), + onTap: () => _editLocation(context, connector), + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.visibility_off_outlined), + title: const Text('Privacy Mode'), + subtitle: const Text('Hide name/location in advertisements'), + trailing: const Icon(Icons.chevron_right), + onTap: () => _togglePrivacy(context, connector), + ), + ], + ), + ); + } + + Widget _buildActionsCard(BuildContext context, MeshCoreConnector connector) { + return Card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text( + 'Actions', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + ListTile( + leading: const Icon(Icons.cell_tower), + title: const Text('Send Advertisement'), + subtitle: const Text('Broadcast presence now'), + onTap: () => _sendAdvert(context, connector), + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.sync), + title: const Text('Sync Time'), + subtitle: const Text('Set device clock to phone time'), + onTap: () => _syncTime(context, connector), + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.refresh), + title: const Text('Refresh Contacts'), + subtitle: const Text('Reload contact list from device'), + onTap: () => connector.getContacts(), + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.restart_alt, color: Colors.orange), + title: const Text('Reboot Device'), + subtitle: const Text('Restart the MeshCore device'), + onTap: () => _confirmReboot(context, connector), + ), + ], + ), + ); + } + + Widget _buildAboutCard(BuildContext context) { + return Card( + child: ListTile( + leading: const Icon(Icons.info_outline), + title: const Text('About'), + subtitle: const Text('MeshCore Open v0.1.0'), + onTap: () => _showAbout(context), + ), + ); + } + + Widget _buildDebugCard(BuildContext context) { + return Card( + child: ListTile( + leading: const Icon(Icons.bug_report_outlined), + title: const Text('BLE Debug Log'), + subtitle: const Text('Commands, responses, and status'), + trailing: const Icon(Icons.chevron_right), + onTap: () { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => const BleDebugLogScreen()), + ); + }, + ), + ); + } + + Widget _buildInfoRow(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(label, style: TextStyle(color: Colors.grey[600])), + Flexible( + child: Text( + value, + style: const TextStyle(fontWeight: FontWeight.w500), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ); + } + + void _editNodeName(BuildContext context, MeshCoreConnector connector) { + final controller = TextEditingController(text: connector.selfName ?? ''); + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Node Name'), + content: TextField( + controller: controller, + decoration: const InputDecoration( + hintText: 'Enter node name', + border: OutlineInputBorder(), + ), + maxLength: 31, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () async { + Navigator.pop(context); + await connector.sendCliCommand('set name ${controller.text}'); + await connector.refreshDeviceInfo(); + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Name updated')), + ); + }, + child: const Text('Save'), + ), + ], + ), + ); + } + + void _showRadioSettings(BuildContext context, MeshCoreConnector connector) { + showDialog( + context: context, + builder: (context) => _RadioSettingsDialog(connector: connector), + ); + } + + void _editLocation(BuildContext context, MeshCoreConnector connector) { + final latController = TextEditingController(); + final lonController = TextEditingController(); + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Location'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: latController, + decoration: const InputDecoration( + labelText: 'Latitude', + border: OutlineInputBorder(), + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true, signed: true), + ), + const SizedBox(height: 16), + TextField( + controller: lonController, + decoration: const InputDecoration( + labelText: 'Longitude', + border: OutlineInputBorder(), + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true, signed: true), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () async { + Navigator.pop(context); + var updated = false; + if (latController.text.isNotEmpty) { + await connector.sendCliCommand('set lat ${latController.text}'); + updated = true; + } + if (lonController.text.isNotEmpty) { + await connector.sendCliCommand('set lon ${lonController.text}'); + updated = true; + } + if (updated) { + await connector.refreshDeviceInfo(); + } + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Location updated')), + ); + }, + child: const Text('Save'), + ), + ], + ), + ); + } + + void _togglePrivacy(BuildContext context, MeshCoreConnector connector) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Privacy Mode'), + content: const Text('Toggle privacy mode to hide your name and location in advertisements.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () async { + Navigator.pop(context); + await connector.sendCliCommand('set privacy on'); + await connector.refreshDeviceInfo(); + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Privacy mode enabled')), + ); + }, + child: const Text('Enable'), + ), + TextButton( + onPressed: () async { + Navigator.pop(context); + await connector.sendCliCommand('set privacy off'); + await connector.refreshDeviceInfo(); + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Privacy mode disabled')), + ); + }, + child: const Text('Disable'), + ), + ], + ), + ); + } + + void _sendAdvert(BuildContext context, MeshCoreConnector connector) { + connector.sendCliCommand('advert'); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Advertisement sent')), + ); + } + + void _syncTime(BuildContext context, MeshCoreConnector connector) { + connector.syncTime(); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Time synchronized')), + ); + } + + void _confirmReboot(BuildContext context, MeshCoreConnector connector) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Reboot Device'), + content: const Text('Are you sure you want to reboot the device? You will be disconnected.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + Navigator.pop(context); + connector.sendCliCommand('reboot'); + }, + child: const Text('Reboot', style: TextStyle(color: Colors.orange)), + ), + ], + ), + ); + } + + void _showAbout(BuildContext context) { + showAboutDialog( + context: context, + applicationName: 'MeshCore Open', + applicationVersion: '0.1.0', + applicationLegalese: '2024 MeshCore Open Source Project', + children: [ + const SizedBox(height: 16), + const Text( + 'An open-source Flutter client for MeshCore LoRa mesh networking devices.', + ), + ], + ); + } +} + +class _RadioSettingsDialog extends StatefulWidget { + final MeshCoreConnector connector; + + const _RadioSettingsDialog({required this.connector}); + + @override + State<_RadioSettingsDialog> createState() => _RadioSettingsDialogState(); +} + +class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { + final _frequencyController = TextEditingController(); + LoRaBandwidth _bandwidth = LoRaBandwidth.bw125; + LoRaSpreadingFactor _spreadingFactor = LoRaSpreadingFactor.sf7; + LoRaCodingRate _codingRate = LoRaCodingRate.cr4_5; + final _txPowerController = TextEditingController(text: '20'); + + @override + void initState() { + super.initState(); + + // Populate with current settings if available + if (widget.connector.currentFreqHz != null) { + _frequencyController.text = (widget.connector.currentFreqHz! / 1000.0).toStringAsFixed(3); + } else { + _frequencyController.text = '915.0'; + } + + if (widget.connector.currentBwHz != null) { + // Find matching bandwidth enum + final bwValue = widget.connector.currentBwHz!; + for (var bw in LoRaBandwidth.values) { + if (bw.hz == bwValue) { + _bandwidth = bw; + break; + } + } + } + + if (widget.connector.currentSf != null) { + // Find matching spreading factor enum + final sfValue = widget.connector.currentSf!; + for (var sf in LoRaSpreadingFactor.values) { + if (sf.value == sfValue) { + _spreadingFactor = sf; + break; + } + } + } + + if (widget.connector.currentCr != null) { + // Find matching coding rate enum + final crValue = _toUiCodingRate(widget.connector.currentCr!); + for (var cr in LoRaCodingRate.values) { + if (cr.value == crValue) { + _codingRate = cr; + break; + } + } + } + + if (widget.connector.currentTxPower != null) { + _txPowerController.text = widget.connector.currentTxPower.toString(); + } + } + + @override + void dispose() { + _frequencyController.dispose(); + _txPowerController.dispose(); + super.dispose(); + } + + void _applyPreset(RadioSettings preset) { + setState(() { + _frequencyController.text = preset.frequencyMHz.toString(); + _bandwidth = preset.bandwidth; + _spreadingFactor = preset.spreadingFactor; + _codingRate = preset.codingRate; + _txPowerController.text = preset.txPowerDbm.toString(); + }); + } + + Future _saveSettings() async { + final freqMHz = double.tryParse(_frequencyController.text); + final txPower = int.tryParse(_txPowerController.text); + + if (freqMHz == null || freqMHz < 300 || freqMHz > 2500) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Invalid frequency (300-2500 MHz)')), + ); + return; + } + + if (txPower == null || txPower < 0 || txPower > 22) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Invalid TX power (0-22 dBm)')), + ); + return; + } + + final freqHz = (freqMHz * 1000).round(); + final bwHz = _bandwidth.hz; + final sf = _spreadingFactor.value; + final cr = _toDeviceCodingRate(_codingRate.value, widget.connector.currentCr); + + try { + await widget.connector.sendFrame(buildSetRadioParamsFrame(freqHz, bwHz, sf, cr)); + await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower)); + await widget.connector.refreshDeviceInfo(); + + if (!mounted) return; + Navigator.pop(context); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Radio settings updated')), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: $e')), + ); + } + } + + int _toUiCodingRate(int deviceCr) { + return deviceCr <= 4 ? deviceCr + 4 : deviceCr; + } + + int _toDeviceCodingRate(int uiCr, int? deviceCr) { + if (deviceCr != null && deviceCr <= 4) { + return uiCr - 4; + } + return uiCr; + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text('Radio Settings'), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Presets', style: TextStyle(fontWeight: FontWeight.bold)), + const SizedBox(height: 8), + Wrap( + spacing: 8, + children: [ + _PresetChip( + label: '915 MHz', + onTap: () => _applyPreset(RadioSettings.preset915MHz), + ), + _PresetChip( + label: '868 MHz', + onTap: () => _applyPreset(RadioSettings.preset868MHz), + ), + _PresetChip( + label: '433 MHz', + onTap: () => _applyPreset(RadioSettings.preset433MHz), + ), + _PresetChip( + label: 'Long Range', + onTap: () => _applyPreset(RadioSettings.presetLongRange), + ), + _PresetChip( + label: 'Fast Speed', + onTap: () => _applyPreset(RadioSettings.presetFastSpeed), + ), + ], + ), + const SizedBox(height: 24), + TextField( + controller: _frequencyController, + decoration: const InputDecoration( + labelText: 'Frequency (MHz)', + border: OutlineInputBorder(), + helperText: '300.0 - 2500.0', + ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + ), + const SizedBox(height: 16), + DropdownButtonFormField( + value: _bandwidth, + decoration: const InputDecoration( + labelText: 'Bandwidth', + border: OutlineInputBorder(), + ), + items: LoRaBandwidth.values + .map((bw) => DropdownMenuItem( + value: bw, + child: Text(bw.label), + )) + .toList(), + onChanged: (value) { + if (value != null) setState(() => _bandwidth = value); + }, + ), + const SizedBox(height: 16), + DropdownButtonFormField( + value: _spreadingFactor, + decoration: const InputDecoration( + labelText: 'Spreading Factor', + border: OutlineInputBorder(), + ), + items: LoRaSpreadingFactor.values + .map((sf) => DropdownMenuItem( + value: sf, + child: Text(sf.label), + )) + .toList(), + onChanged: (value) { + if (value != null) setState(() => _spreadingFactor = value); + }, + ), + const SizedBox(height: 16), + DropdownButtonFormField( + value: _codingRate, + decoration: const InputDecoration( + labelText: 'Coding Rate', + border: OutlineInputBorder(), + ), + items: LoRaCodingRate.values + .map((cr) => DropdownMenuItem( + value: cr, + child: Text(cr.label), + )) + .toList(), + onChanged: (value) { + if (value != null) setState(() => _codingRate = value); + }, + ), + const SizedBox(height: 16), + TextField( + controller: _txPowerController, + decoration: const InputDecoration( + labelText: 'TX Power (dBm)', + border: OutlineInputBorder(), + helperText: '0 - 22', + ), + keyboardType: TextInputType.number, + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: _saveSettings, + child: const Text('Save'), + ), + ], + ); + } +} + +class _PresetChip extends StatelessWidget { + final String label; + final VoidCallback onTap; + + const _PresetChip({required this.label, required this.onTap}); + + @override + Widget build(BuildContext context) { + return ActionChip( + label: Text(label), + onPressed: onTap, + ); + } +} diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart new file mode 100644 index 00000000..ac8e64c0 --- /dev/null +++ b/lib/services/app_settings_service.dart @@ -0,0 +1,101 @@ +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../models/app_settings.dart'; + +class AppSettingsService extends ChangeNotifier { + static const String _settingsKey = 'app_settings'; + + AppSettings _settings = AppSettings(); + + AppSettings get settings => _settings; + + String batteryChemistryForDevice(String deviceId) { + final stored = _settings.batteryChemistryByDeviceId[deviceId]; + if (stored == 'liion') return 'nmc'; + return stored ?? 'nmc'; + } + + Future loadSettings() async { + final prefs = await SharedPreferences.getInstance(); + final jsonStr = prefs.getString(_settingsKey); + + if (jsonStr != null) { + try { + final json = jsonDecode(jsonStr) as Map; + _settings = AppSettings.fromJson(json); + notifyListeners(); + } catch (e) { + // If parsing fails, use defaults + _settings = AppSettings(); + } + } + } + + Future updateSettings(AppSettings newSettings) async { + _settings = newSettings; + notifyListeners(); + + final prefs = await SharedPreferences.getInstance(); + final jsonStr = jsonEncode(_settings.toJson()); + await prefs.setString(_settingsKey, jsonStr); + } + + Future setClearPathOnMaxRetry(bool value) async { + await updateSettings(_settings.copyWith(clearPathOnMaxRetry: value)); + } + + Future setMapShowRepeaters(bool value) async { + await updateSettings(_settings.copyWith(mapShowRepeaters: value)); + } + + Future setMapShowChatNodes(bool value) async { + await updateSettings(_settings.copyWith(mapShowChatNodes: value)); + } + + Future setMapShowOtherNodes(bool value) async { + await updateSettings(_settings.copyWith(mapShowOtherNodes: value)); + } + + Future setMapTimeFilterHours(double value) async { + await updateSettings(_settings.copyWith(mapTimeFilterHours: value)); + } + + Future setMapKeyPrefixEnabled(bool value) async { + await updateSettings(_settings.copyWith(mapKeyPrefixEnabled: value)); + } + + Future setMapKeyPrefix(String value) async { + await updateSettings(_settings.copyWith(mapKeyPrefix: value)); + } + + Future setMapShowMarkers(bool value) async { + await updateSettings(_settings.copyWith(mapShowMarkers: value)); + } + + Future setNotificationsEnabled(bool value) async { + await updateSettings(_settings.copyWith(notificationsEnabled: value)); + } + + Future setNotifyOnNewMessage(bool value) async { + await updateSettings(_settings.copyWith(notifyOnNewMessage: value)); + } + + Future setNotifyOnNewAdvert(bool value) async { + await updateSettings(_settings.copyWith(notifyOnNewAdvert: value)); + } + + Future setAutoRouteRotationEnabled(bool value) async { + await updateSettings(_settings.copyWith(autoRouteRotationEnabled: value)); + } + + Future setThemeMode(String value) async { + await updateSettings(_settings.copyWith(themeMode: value)); + } + + Future setBatteryChemistryForDevice(String deviceId, String chemistry) async { + final updated = Map.from(_settings.batteryChemistryByDeviceId); + updated[deviceId] = chemistry; + await updateSettings(_settings.copyWith(batteryChemistryByDeviceId: updated)); + } +} diff --git a/lib/services/ble_debug_log_service.dart b/lib/services/ble_debug_log_service.dart new file mode 100644 index 00000000..b52aebb5 --- /dev/null +++ b/lib/services/ble_debug_log_service.dart @@ -0,0 +1,220 @@ +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import '../connector/meshcore_protocol.dart'; + +class BleDebugLogEntry { + final DateTime timestamp; + final bool outgoing; + final String description; + final Uint8List payload; + + BleDebugLogEntry({ + required this.timestamp, + required this.outgoing, + required this.description, + required this.payload, + }); + + String get hexPreview { + const maxBytes = 64; + final bytes = payload.length > maxBytes ? payload.sublist(0, maxBytes) : payload; + final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' '); + return payload.length > maxBytes ? '$hex …' : hex; + } +} + +class BleRawLogRxEntry { + final DateTime timestamp; + final Uint8List payload; + + BleRawLogRxEntry({ + required this.timestamp, + required this.payload, + }); + + String get hexPreview { + const maxBytes = 64; + final bytes = payload.length > maxBytes ? payload.sublist(0, maxBytes) : payload; + final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' '); + return payload.length > maxBytes ? '$hex …' : hex; + } +} + +class BleDebugLogService extends ChangeNotifier { + static const int maxEntries = 500; + final List _entries = []; + final List _rawLogRxEntries = []; + + List get entries => List.unmodifiable(_entries); + List get rawLogRxEntries => List.unmodifiable(_rawLogRxEntries); + + void logFrame(Uint8List frame, {required bool outgoing, String? note}) { + if (frame.isEmpty) return; + final code = frame[0]; + final description = _describeFrame(code, frame, outgoing, note); + _entries.add( + BleDebugLogEntry( + timestamp: DateTime.now(), + outgoing: outgoing, + description: description, + payload: Uint8List.fromList(frame), + ), + ); + + if (_entries.length > maxEntries) { + _entries.removeRange(0, _entries.length - maxEntries); + } + + if (!outgoing && code == pushCodeLogRxData && frame.length > 3) { + _rawLogRxEntries.add( + BleRawLogRxEntry( + timestamp: DateTime.now(), + payload: Uint8List.fromList(frame.sublist(3)), + ), + ); + if (_rawLogRxEntries.length > maxEntries) { + _rawLogRxEntries.removeRange(0, _rawLogRxEntries.length - maxEntries); + } + } + + notifyListeners(); + } + + void clear() { + _entries.clear(); + _rawLogRxEntries.clear(); + notifyListeners(); + } + + String _describeFrame(int code, Uint8List frame, bool outgoing, String? note) { + final label = _codeLabel(code); + final prefix = outgoing ? 'TX' : 'RX'; + final extra = _frameDetail(code, frame); + final noteText = note != null ? ' • $note' : ''; + return '$prefix $label$extra$noteText'; + } + + String _codeLabel(int code) { + switch (code) { + case cmdAppStart: + return 'CMD_APP_START'; + case cmdSendTxtMsg: + return 'CMD_SEND_TXT_MSG'; + case cmdSendChannelTxtMsg: + return 'CMD_SEND_CHANNEL_TXT_MSG'; + case cmdGetContacts: + return 'CMD_GET_CONTACTS'; + case cmdGetDeviceTime: + return 'CMD_GET_DEVICE_TIME'; + case cmdSetDeviceTime: + return 'CMD_SET_DEVICE_TIME'; + case cmdSendSelfAdvert: + return 'CMD_SEND_SELF_ADVERT'; + case cmdSetAdvertName: + return 'CMD_SET_ADVERT_NAME'; + case cmdAddUpdateContact: + return 'CMD_ADD_UPDATE_CONTACT'; + case cmdSyncNextMessage: + return 'CMD_SYNC_NEXT_MESSAGE'; + case cmdSetRadioParams: + return 'CMD_SET_RADIO_PARAMS'; + case cmdSetRadioTxPower: + return 'CMD_SET_RADIO_TX_POWER'; + case cmdResetPath: + return 'CMD_RESET_PATH'; + case cmdRemoveContact: + return 'CMD_REMOVE_CONTACT'; + case cmdReboot: + return 'CMD_REBOOT'; + case cmdGetBattAndStorage: + return 'CMD_GET_BATT_AND_STORAGE'; + case cmdSendLogin: + return 'CMD_SEND_LOGIN'; + case cmdGetChannel: + return 'CMD_GET_CHANNEL'; + case cmdSetChannel: + return 'CMD_SET_CHANNEL'; + case cmdGetRadioSettings: + return 'CMD_GET_RADIO_SETTINGS'; + case respCodeOk: + return 'RESP_CODE_OK'; + case respCodeErr: + return 'RESP_CODE_ERR'; + case respCodeContactsStart: + return 'RESP_CODE_CONTACTS_START'; + case respCodeContact: + return 'RESP_CODE_CONTACT'; + case respCodeEndOfContacts: + return 'RESP_CODE_END_OF_CONTACTS'; + case respCodeSelfInfo: + return 'RESP_CODE_SELF_INFO'; + case respCodeSent: + return 'RESP_CODE_SENT'; + case respCodeContactMsgRecv: + return 'RESP_CODE_CONTACT_MSG_RECV'; + case respCodeChannelMsgRecv: + return 'RESP_CODE_CHANNEL_MSG_RECV'; + case respCodeCurrTime: + return 'RESP_CODE_CURR_TIME'; + case respCodeNoMoreMessages: + return 'RESP_CODE_NO_MORE_MESSAGES'; + case respCodeBattAndStorage: + return 'RESP_CODE_BATT_AND_STORAGE'; + case respCodeContactMsgRecvV3: + return 'RESP_CODE_CONTACT_MSG_RECV_V3'; + case respCodeChannelMsgRecvV3: + return 'RESP_CODE_CHANNEL_MSG_RECV_V3'; + case respCodeChannelInfo: + return 'RESP_CODE_CHANNEL_INFO'; + case respCodeRadioSettings: + return 'RESP_CODE_RADIO_SETTINGS'; + case pushCodeAdvert: + return 'PUSH_CODE_ADVERT'; + case pushCodePathUpdated: + return 'PUSH_CODE_PATH_UPDATED'; + case pushCodeSendConfirmed: + return 'PUSH_CODE_SEND_CONFIRMED'; + case pushCodeMsgWaiting: + return 'PUSH_CODE_MSG_WAITING'; + case pushCodeLoginSuccess: + return 'PUSH_CODE_LOGIN_SUCCESS'; + case pushCodeLoginFail: + return 'PUSH_CODE_LOGIN_FAIL'; + case pushCodeLogRxData: + return 'PUSH_CODE_LOG_RX_DATA'; + case pushCodeNewAdvert: + return 'PUSH_CODE_NEW_ADVERT'; + default: + return 'CODE_$code'; + } + } + + String _frameDetail(int code, Uint8List frame) { + switch (code) { + case respCodeSent: + if (frame.length >= 10) { + final timeoutMs = readUint32LE(frame, 6); + return ' • timeout=${timeoutMs}ms'; + } + return ''; + case pushCodeSendConfirmed: + if (frame.length >= 9) { + final tripMs = readUint32LE(frame, 5); + return ' • trip=${tripMs}ms'; + } + return ''; + case pushCodeLoginSuccess: + return ' • login ok'; + case pushCodeLoginFail: + return ' • login fail'; + case respCodeBattAndStorage: + if (frame.length >= 3) { + final mv = readUint16LE(frame, 1); + return ' • ${mv}mV'; + } + return ''; + default: + return ''; + } + } +} diff --git a/lib/services/map_marker_service.dart b/lib/services/map_marker_service.dart new file mode 100644 index 00000000..9ae109e5 --- /dev/null +++ b/lib/services/map_marker_service.dart @@ -0,0 +1,16 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +class MapMarkerService { + static const String _removedKey = 'map_removed_marker_ids'; + + Future> loadRemovedIds() async { + final prefs = await SharedPreferences.getInstance(); + final items = prefs.getStringList(_removedKey) ?? const []; + return items.toSet(); + } + + Future saveRemovedIds(Set ids) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setStringList(_removedKey, ids.toList()); + } +} diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart new file mode 100644 index 00000000..34433639 --- /dev/null +++ b/lib/services/message_retry_service.dart @@ -0,0 +1,348 @@ +import 'dart:async'; +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import 'package:uuid/uuid.dart'; +import '../models/contact.dart'; +import '../models/message.dart'; +import '../models/path_selection.dart'; +import 'storage_service.dart'; +import 'app_settings_service.dart'; + +class MessageRetryService extends ChangeNotifier { + static const int maxRetries = 5; + + final StorageService _storage; + final Map _timeoutTimers = {}; + final Map _pendingMessages = {}; + final Map _pendingContacts = {}; + final Map _pendingPathSelections = {}; + + Function(Contact, String, bool, int, int)? _sendMessageCallback; + Function(String, Message)? _addMessageCallback; + Function(Message)? _updateMessageCallback; + Function(Contact)? _clearContactPathCallback; + Function(int, int)? _calculateTimeoutCallback; + AppSettingsService? _appSettingsService; + Function(String, PathSelection, bool, int?)? _recordPathResultCallback; + + MessageRetryService(this._storage); + + void initialize({ + required Function(Contact, String, bool, int, int) sendMessageCallback, + required Function(String, Message) addMessageCallback, + required Function(Message) updateMessageCallback, + Function(Contact)? clearContactPathCallback, + Function(int pathLength, int messageBytes)? calculateTimeoutCallback, + AppSettingsService? appSettingsService, + Function(String, PathSelection, bool, int?)? recordPathResultCallback, + }) { + _sendMessageCallback = sendMessageCallback; + _addMessageCallback = addMessageCallback; + _updateMessageCallback = updateMessageCallback; + _clearContactPathCallback = clearContactPathCallback; + _calculateTimeoutCallback = calculateTimeoutCallback; + _appSettingsService = appSettingsService; + _recordPathResultCallback = recordPathResultCallback; + } + + Future sendMessageWithRetry({ + required Contact contact, + required String text, + bool forceFlood = false, + PathSelection? pathSelection, + Uint8List? pathBytes, + int? pathLength, + }) async { + final messageId = const Uuid().v4(); + final effectiveForceFlood = forceFlood || (pathSelection?.useFlood ?? false); + final messagePathBytes = + pathBytes ?? _resolveMessagePathBytes(contact, effectiveForceFlood, pathSelection); + final messagePathLength = + pathLength ?? _resolveMessagePathLength(contact, effectiveForceFlood, pathSelection); + final message = Message( + senderKey: contact.publicKey, + text: text, + timestamp: DateTime.now(), + isOutgoing: true, + status: MessageStatus.pending, + messageId: messageId, + retryCount: 0, + forceFlood: effectiveForceFlood, + pathLength: messagePathLength, + pathBytes: messagePathBytes, + ); + + _pendingMessages[messageId] = message; + _pendingContacts[messageId] = contact; + if (pathSelection != null) { + _pendingPathSelections[messageId] = pathSelection; + } + + if (_addMessageCallback != null) { + _addMessageCallback!(contact.publicKeyHex, message); + } + + await _attemptSend(messageId); + } + + Future _attemptSend(String messageId) async { + final message = _pendingMessages[messageId]; + final contact = _pendingContacts[messageId]; + + if (message == null || contact == null) return; + + Contact sendContact = contact; + final attempt = message.retryCount.clamp(0, 3); + + if (message.forceFlood && contact.pathLength >= 0) { + sendContact = Contact( + publicKey: contact.publicKey, + name: contact.name, + type: contact.type, + pathLength: -1, + path: contact.path, + latitude: contact.latitude, + longitude: contact.longitude, + lastSeen: contact.lastSeen, + ); + } + + if (_sendMessageCallback != null) { + final timestampSeconds = message.timestamp.millisecondsSinceEpoch ~/ 1000; + _sendMessageCallback!( + sendContact, + message.text, + message.forceFlood, + attempt, + timestampSeconds, + ); + } + } + + void updateMessageFromSent(Uint8List ackHash, int timeoutMs) { + for (var entry in _pendingMessages.entries) { + final message = entry.value; + if (message.status == MessageStatus.pending) { + final contact = _pendingContacts[entry.key]; + final selection = _pendingPathSelections[entry.key]; + + // Use device-provided timeout, or calculate from radio settings if timeout is 0 or invalid + int actualTimeout = timeoutMs; + if (timeoutMs <= 0 && _calculateTimeoutCallback != null && contact != null) { + int pathLengthValue; + if (selection != null) { + pathLengthValue = selection.useFlood ? -1 : selection.hopCount; + if (pathLengthValue < 0) pathLengthValue = contact.pathLength; + } else if (message.pathLength != null) { + pathLengthValue = message.pathLength!; + } else { + pathLengthValue = message.forceFlood ? -1 : contact.pathLength; + } + actualTimeout = _calculateTimeoutCallback!(pathLengthValue, message.text.length); + debugPrint('Using calculated timeout: ${actualTimeout}ms for ${contact.pathLength} hops'); + } + + final updatedMessage = message.copyWith( + status: MessageStatus.sent, + expectedAckHash: ackHash, + estimatedTimeoutMs: actualTimeout, + sentAt: DateTime.now(), + ); + + _pendingMessages[entry.key] = updatedMessage; + + if (_updateMessageCallback != null) { + _updateMessageCallback!(updatedMessage); + } + + _startTimeoutTimer(entry.key, actualTimeout); + return; + } + } + } + + void _startTimeoutTimer(String messageId, int timeoutMs) { + _timeoutTimers[messageId]?.cancel(); + _timeoutTimers[messageId] = Timer(Duration(milliseconds: timeoutMs), () { + _handleTimeout(messageId); + }); + } + + void _handleTimeout(String messageId) { + final message = _pendingMessages[messageId]; + final contact = _pendingContacts[messageId]; + final selection = _pendingPathSelections[messageId]; + + if (message == null || contact == null) return; + + if (message.retryCount < maxRetries - 1) { + final backoffMs = 1000 * (1 << message.retryCount); + + final updatedMessage = message.copyWith( + retryCount: message.retryCount + 1, + status: MessageStatus.pending, + ); + + _pendingMessages[messageId] = updatedMessage; + + if (_updateMessageCallback != null) { + _updateMessageCallback!(updatedMessage); + } + + Timer(Duration(milliseconds: backoffMs), () { + _attemptSend(messageId); + }); + } else { + // Max retries reached - mark as failed + final failedMessage = message.copyWith(status: MessageStatus.failed); + + _pendingMessages.remove(messageId); + _pendingContacts.remove(messageId); + _pendingPathSelections.remove(messageId); + _timeoutTimers[messageId]?.cancel(); + _timeoutTimers.remove(messageId); + + // Check if we should clear the path on max retry + if (_appSettingsService?.settings.clearPathOnMaxRetry == true && + _clearContactPathCallback != null) { + _clearContactPathCallback!(contact); + } + + _recordPathResultFromMessage(contact.publicKeyHex, message, selection, false, null); + + if (_updateMessageCallback != null) { + _updateMessageCallback!(failedMessage); + } + + notifyListeners(); + } + } + + void handleAckReceived(Uint8List ackHash, int tripTimeMs) { + String? matchedMessageId; + + for (var entry in _pendingMessages.entries) { + final message = entry.value; + if (message.expectedAckHash != null && + listEquals(message.expectedAckHash, ackHash)) { + matchedMessageId = entry.key; + break; + } + } + + if (matchedMessageId != null) { + final message = _pendingMessages[matchedMessageId]!; + final contact = _pendingContacts[matchedMessageId]; + final selection = _pendingPathSelections[matchedMessageId]; + _timeoutTimers[matchedMessageId]?.cancel(); + _timeoutTimers.remove(matchedMessageId); + + final deliveredMessage = message.copyWith( + status: MessageStatus.delivered, + deliveredAt: DateTime.now(), + tripTimeMs: tripTimeMs, + ); + + _pendingMessages.remove(matchedMessageId); + _pendingContacts.remove(matchedMessageId); + _pendingPathSelections.remove(matchedMessageId); + + if (_updateMessageCallback != null) { + _updateMessageCallback!(deliveredMessage); + } + + if (contact != null) { + _recordPathResultFromMessage(contact.publicKeyHex, message, selection, true, tripTimeMs); + } + + notifyListeners(); + } + } + + Uint8List _resolveMessagePathBytes( + Contact contact, + bool forceFlood, + PathSelection? selection, + ) { + if (forceFlood || contact.pathLength < 0 || selection?.useFlood == true) { + return Uint8List(0); + } + if (selection != null && selection.pathBytes.isNotEmpty) { + return Uint8List.fromList(selection.pathBytes); + } + return contact.path; + } + + int? _resolveMessagePathLength( + Contact contact, + bool forceFlood, + PathSelection? selection, + ) { + if (forceFlood || contact.pathLength < 0 || selection?.useFlood == true) { + return -1; + } + if (selection != null && selection.pathBytes.isNotEmpty) { + return selection.hopCount; + } + return contact.pathLength; + } + + String? getContactKeyForAckHash(Uint8List ackHash) { + for (var entry in _pendingMessages.entries) { + final message = entry.value; + if (message.expectedAckHash != null && + listEquals(message.expectedAckHash, ackHash)) { + final contact = _pendingContacts[entry.key]; + return contact?.publicKeyHex; + } + } + return null; + } + + int calculateDefaultTimeout(Contact contact) { + if (contact.pathLength < 0) { + return 15000; + } else { + return 3000 + (3000 * contact.pathLength); + } + } + + void _recordPathResultFromMessage( + String contactKey, + Message message, + PathSelection? selection, + bool success, + int? tripTimeMs, + ) { + if (_recordPathResultCallback == null) return; + final recordSelection = selection ?? _selectionFromMessage(message); + if (recordSelection == null) return; + _recordPathResultCallback!(contactKey, recordSelection, success, tripTimeMs); + } + + PathSelection? _selectionFromMessage(Message message) { + if (message.forceFlood || (message.pathLength != null && message.pathLength! < 0)) { + return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true); + } + if (message.pathBytes.isEmpty && message.pathLength == null) { + return null; + } + return PathSelection( + pathBytes: message.pathBytes, + hopCount: message.pathLength ?? message.pathBytes.length, + useFlood: false, + ); + } + + @override + void dispose() { + for (var timer in _timeoutTimers.values) { + timer.cancel(); + } + _timeoutTimers.clear(); + _pendingMessages.clear(); + _pendingContacts.clear(); + _pendingPathSelections.clear(); + super.dispose(); + } +} diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart new file mode 100644 index 00000000..24610818 --- /dev/null +++ b/lib/services/notification_service.dart @@ -0,0 +1,158 @@ +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter/foundation.dart'; + +class NotificationService { + static final NotificationService _instance = NotificationService._internal(); + factory NotificationService() => _instance; + NotificationService._internal(); + + final FlutterLocalNotificationsPlugin _notifications = FlutterLocalNotificationsPlugin(); + bool _isInitialized = false; + + Future initialize() async { + if (_isInitialized) return; + + const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher'); + const iosSettings = DarwinInitializationSettings( + requestAlertPermission: true, + requestBadgePermission: true, + requestSoundPermission: true, + ); + + const initSettings = InitializationSettings( + android: androidSettings, + iOS: iosSettings, + ); + + try { + await _notifications.initialize( + initSettings, + onDidReceiveNotificationResponse: _onNotificationTapped, + ); + _isInitialized = true; + } catch (e) { + debugPrint('Error initializing notifications: $e'); + } + } + + Future requestPermissions() async { + if (!_isInitialized) { + await initialize(); + } + + // Request Android 13+ notification permission + final androidPlugin = _notifications.resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin>(); + if (androidPlugin != null) { + final granted = await androidPlugin.requestNotificationsPermission(); + return granted ?? false; + } + + // iOS permissions are requested during initialization + final iosPlugin = _notifications.resolvePlatformSpecificImplementation< + IOSFlutterLocalNotificationsPlugin>(); + if (iosPlugin != null) { + final granted = await iosPlugin.requestPermissions( + alert: true, + badge: true, + sound: true, + ); + return granted ?? false; + } + + return true; + } + + Future showMessageNotification({ + required String contactName, + required String message, + String? contactId, + }) async { + if (!_isInitialized) { + await initialize(); + } + + const androidDetails = AndroidNotificationDetails( + 'messages', + 'Messages', + channelDescription: 'New message notifications', + importance: Importance.high, + priority: Priority.high, + icon: '@mipmap/ic_launcher', + ); + + const iosDetails = DarwinNotificationDetails( + presentAlert: true, + presentBadge: true, + presentSound: true, + ); + + const notificationDetails = NotificationDetails( + android: androidDetails, + iOS: iosDetails, + ); + + await _notifications.show( + contactId?.hashCode ?? 0, + 'New message from $contactName', + message.length > 100 ? '${message.substring(0, 100)}...' : message, + notificationDetails, + payload: 'message:$contactId', + ); + } + + Future showAdvertNotification({ + required String contactName, + required String contactType, + String? contactId, + }) async { + if (!_isInitialized) { + await initialize(); + } + + const androidDetails = AndroidNotificationDetails( + 'adverts', + 'Advertisements', + channelDescription: 'New node advertisement notifications', + importance: Importance.defaultImportance, + priority: Priority.defaultPriority, + icon: '@mipmap/ic_launcher', + ); + + const iosDetails = DarwinNotificationDetails( + presentAlert: true, + presentBadge: true, + presentSound: true, + ); + + const notificationDetails = NotificationDetails( + android: androidDetails, + iOS: iosDetails, + ); + + await _notifications.show( + contactId?.hashCode ?? DateTime.now().millisecondsSinceEpoch, + 'New $contactType discovered', + contactName, + notificationDetails, + payload: 'advert:$contactId', + ); + } + + void _onNotificationTapped(NotificationResponse response) { + final payload = response.payload; + if (payload != null) { + debugPrint('Notification tapped: $payload'); + // Handle navigation based on payload + // This can be extended to navigate to specific screens + } + } + + Future cancelAll() async { + await _notifications.cancelAll(); + } + + Future cancel(int id) async { + await _notifications.cancel(id); + } +} diff --git a/lib/services/path_history_service.dart b/lib/services/path_history_service.dart new file mode 100644 index 00000000..9c8d8041 --- /dev/null +++ b/lib/services/path_history_service.dart @@ -0,0 +1,324 @@ +import 'package:flutter/foundation.dart'; +import '../models/contact.dart'; +import '../models/path_history.dart'; +import '../models/path_selection.dart'; +import 'storage_service.dart'; + +class PathHistoryService extends ChangeNotifier { + final StorageService _storage; + final Map _cache = {}; + final Map _autoRotationIndex = {}; + final Map _floodStats = {}; + + static const int _maxHistoryEntries = 100; + static const int _autoRotationTopCount = 3; + + PathHistoryService(this._storage); + + Future initialize() async { + // Load cached path histories on startup if needed + } + + void handlePathUpdated(Contact contact) { + if (contact.pathLength < 0) return; + + _addPathRecord( + contactPubKeyHex: contact.publicKeyHex, + hopCount: contact.pathLength, + tripTimeMs: 0, + wasFloodDiscovery: true, + pathBytes: contact.path, + successCount: 0, + failureCount: 0, + ); + } + + void recordPathAttempt(String contactPubKeyHex, PathSelection selection) { + if (selection.useFlood) { + _updateFloodStats(contactPubKeyHex); + return; + } + + _addPathRecord( + contactPubKeyHex: contactPubKeyHex, + hopCount: selection.hopCount, + tripTimeMs: 0, + wasFloodDiscovery: false, + pathBytes: selection.pathBytes, + successCount: 0, + failureCount: 0, + ); + } + + void recordPathResult( + String contactPubKeyHex, + PathSelection selection, { + required bool success, + int? tripTimeMs, + }) { + if (selection.useFlood) { + final stats = _floodStats.putIfAbsent(contactPubKeyHex, () => _FloodStats()); + if (success) { + stats.successCount += 1; + if (tripTimeMs != null) stats.lastTripTimeMs = tripTimeMs; + } else { + stats.failureCount += 1; + } + stats.lastUsed = DateTime.now(); + return; + } + + final existing = _findPathRecord(contactPubKeyHex, selection.pathBytes); + final successCount = (existing?.successCount ?? 0) + (success ? 1 : 0); + final failureCount = (existing?.failureCount ?? 0) + (success ? 0 : 1); + + _addPathRecord( + contactPubKeyHex: contactPubKeyHex, + hopCount: selection.hopCount, + tripTimeMs: success ? (tripTimeMs ?? 0) : (existing?.tripTimeMs ?? 0), + wasFloodDiscovery: existing?.wasFloodDiscovery ?? false, + pathBytes: selection.pathBytes, + successCount: successCount, + failureCount: failureCount, + ); + } + + PathSelection getNextAutoPathSelection(String contactPubKeyHex) { + final ranked = _getRankedPaths(contactPubKeyHex) + .take(_autoRotationTopCount) + .toList(); + if (ranked.isEmpty) { + return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true); + } + + final selections = ranked + .map((path) => PathSelection( + pathBytes: path.pathBytes, + hopCount: path.hopCount, + useFlood: false, + )) + .toList() + ..add(const PathSelection(pathBytes: [], hopCount: -1, useFlood: true)); + + final currentIndex = _autoRotationIndex[contactPubKeyHex] ?? 0; + final selection = selections[currentIndex % selections.length]; + _autoRotationIndex[contactPubKeyHex] = currentIndex + 1; + return selection; + } + + void _addPathRecord({ + required String contactPubKeyHex, + required int hopCount, + required int tripTimeMs, + required bool wasFloodDiscovery, + required List pathBytes, + required int successCount, + required int failureCount, + }) { + var history = _cache[contactPubKeyHex]; + + if (history == null) { + _loadHistoryFromStorage(contactPubKeyHex).then((loaded) { + if (loaded != null) { + _cache[contactPubKeyHex] = loaded; + _addPathRecordInternal( + contactPubKeyHex, + hopCount, + tripTimeMs, + wasFloodDiscovery, + pathBytes, + successCount, + failureCount, + ); + } else { + _cache[contactPubKeyHex] = ContactPathHistory( + contactPubKeyHex: contactPubKeyHex, + recentPaths: [], + ); + _addPathRecordInternal( + contactPubKeyHex, + hopCount, + tripTimeMs, + wasFloodDiscovery, + pathBytes, + successCount, + failureCount, + ); + } + }); + return; + } + + _addPathRecordInternal( + contactPubKeyHex, + hopCount, + tripTimeMs, + wasFloodDiscovery, + pathBytes, + successCount, + failureCount, + ); + } + + void _addPathRecordInternal( + String contactPubKeyHex, + int hopCount, + int tripTimeMs, + bool wasFloodDiscovery, + List pathBytes, + int successCount, + int failureCount, + ) { + var history = _cache[contactPubKeyHex]; + if (history == null) return; + + final existing = _findPathRecord(contactPubKeyHex, pathBytes); + if (existing != null) { + successCount = successCount == 0 ? existing.successCount : successCount; + failureCount = failureCount == 0 ? existing.failureCount : failureCount; + if (tripTimeMs == 0) { + tripTimeMs = existing.tripTimeMs; + } + wasFloodDiscovery = existing.wasFloodDiscovery || wasFloodDiscovery; + } + + final newRecord = PathRecord( + hopCount: hopCount, + tripTimeMs: tripTimeMs, + timestamp: DateTime.now(), + wasFloodDiscovery: wasFloodDiscovery, + pathBytes: pathBytes, + successCount: successCount, + failureCount: failureCount, + ); + + final updatedPaths = List.from(history.recentPaths); + + updatedPaths.removeWhere((p) => _pathsEqual(p.pathBytes, pathBytes)); + + if (existing == null && updatedPaths.length >= _maxHistoryEntries) { + return; + } + + updatedPaths.insert(0, newRecord); + + final updatedHistory = ContactPathHistory( + contactPubKeyHex: contactPubKeyHex, + recentPaths: updatedPaths, + ); + + _cache[contactPubKeyHex] = updatedHistory; + _storage.savePathHistory(contactPubKeyHex, updatedHistory); + + notifyListeners(); + } + + List getRecentPaths(String contactPubKeyHex) { + final history = _cache[contactPubKeyHex]; + if (history != null) { + return history.recentPaths; + } + + _loadHistoryFromStorage(contactPubKeyHex).then((loaded) { + if (loaded != null) { + _cache[contactPubKeyHex] = loaded; + notifyListeners(); + } + }); + + return []; + } + + Future _loadHistoryFromStorage( + String contactPubKeyHex) async { + return await _storage.loadPathHistory(contactPubKeyHex); + } + + PathRecord? getFastestPath(String contactPubKeyHex) { + final history = _cache[contactPubKeyHex]; + return history?.fastest; + } + + PathRecord? getMostRecentPath(String contactPubKeyHex) { + final history = _cache[contactPubKeyHex]; + return history?.mostRecent; + } + + Future clearPathHistory(String contactPubKeyHex) async { + _cache.remove(contactPubKeyHex); + _autoRotationIndex.remove(contactPubKeyHex); + _floodStats.remove(contactPubKeyHex); + await _storage.clearPathHistory(contactPubKeyHex); + notifyListeners(); + } + + Future removePathRecord( + String contactPubKeyHex, + List pathBytes, + ) async { + final history = _cache[contactPubKeyHex]; + if (history == null) return; + + final updatedPaths = List.from(history.recentPaths) + ..removeWhere((p) => _pathsEqual(p.pathBytes, pathBytes)); + + _cache[contactPubKeyHex] = ContactPathHistory( + contactPubKeyHex: contactPubKeyHex, + recentPaths: updatedPaths, + ); + + await _storage.savePathHistory(contactPubKeyHex, _cache[contactPubKeyHex]!); + notifyListeners(); + } + + PathRecord? _findPathRecord(String contactPubKeyHex, List pathBytes) { + final history = _cache[contactPubKeyHex]; + if (history == null) return null; + for (final record in history.recentPaths) { + if (_pathsEqual(record.pathBytes, pathBytes)) { + return record; + } + } + return null; + } + + List _getRankedPaths(String contactPubKeyHex) { + final history = _cache[contactPubKeyHex]; + if (history == null) return []; + + final ranked = List.from(history.recentPaths) + ..removeWhere((p) => p.pathBytes.isEmpty); + + ranked.sort((a, b) { + final aRate = (a.successCount + 1) / (a.successCount + a.failureCount + 2); + final bRate = (b.successCount + 1) / (b.successCount + b.failureCount + 2); + if (aRate != bRate) return bRate.compareTo(aRate); + if (a.successCount != b.successCount) { + return b.successCount.compareTo(a.successCount); + } + + final aTrip = a.tripTimeMs == 0 ? 999999 : a.tripTimeMs; + final bTrip = b.tripTimeMs == 0 ? 999999 : b.tripTimeMs; + if (aTrip != bTrip) return aTrip.compareTo(bTrip); + return b.timestamp.compareTo(a.timestamp); + }); + + return ranked; + } + + bool _pathsEqual(List a, List b) { + return listEquals(a, b); + } + + void _updateFloodStats(String contactPubKeyHex) { + final stats = _floodStats.putIfAbsent(contactPubKeyHex, () => _FloodStats()); + stats.lastUsed = DateTime.now(); + } +} + +class _FloodStats { + int successCount = 0; + int failureCount = 0; + int lastTripTimeMs = 0; + DateTime? lastUsed; +} diff --git a/lib/services/repeater_command_service.dart b/lib/services/repeater_command_service.dart new file mode 100644 index 00000000..f1fd1574 --- /dev/null +++ b/lib/services/repeater_command_service.dart @@ -0,0 +1,133 @@ +import 'dart:async'; +import 'dart:typed_data'; +import '../models/contact.dart'; +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; + +class RepeaterCommandService { + final MeshCoreConnector _connector; + final Map> _pendingCommands = {}; + final Map _commandTimeouts = {}; + final Map _commandPrefixes = {}; + final Map _pendingByPrefix = {}; + int _prefixCounter = 0; + + static const int timeoutSeconds = 10; // Flood mode timeout + static const int maxRetries = 5; + + RepeaterCommandService(this._connector); + + /// Send a CLI command to a repeater with automatic retries + /// Returns a future that completes when a response is received or after max retries + Future sendCommand( + Contact repeater, + String command, { + Function(String)? onResponse, + Function(int)? onAttempt, + }) async { + final repeaterKey = repeater.publicKeyHex; + final hasPending = _pendingCommands.keys.any((id) => id.startsWith(repeaterKey)); + if (hasPending) { + throw Exception('Another command is still awaiting a response.'); + } + + // Create completer for this command + final commandId = '${repeaterKey}_${DateTime.now().millisecondsSinceEpoch}'; + final completer = Completer(); + _pendingCommands[commandId] = completer; + + onAttempt?.call(0); + + // Send frame once (no retries) + try { + final prefix = _nextPrefixToken(); + _commandPrefixes[commandId] = prefix; + _pendingByPrefix[prefix] = commandId; + final framedCommand = '$prefix$command'; + final frame = buildSendCliCommandFrame(repeater.publicKey, framedCommand, attempt: 0); + await _connector.sendFrame(frame); + } catch (e) { + _cleanup(commandId); + throw Exception('Failed to send command: $e'); + } + + // Set timeout for this attempt + _commandTimeouts[commandId]?.cancel(); + _commandTimeouts[commandId] = Timer( + Duration(seconds: timeoutSeconds), + () { + final completer = _pendingCommands[commandId]; + if (completer != null && !completer.isCompleted) { + completer.completeError('Command timeout after $timeoutSeconds seconds'); + _cleanup(commandId); + } + }, + ); + + // Wait for response or timeout + try { + final response = await completer.future; + return response; + } finally { + _cleanup(commandId); + } + } + + /// Call this when a text message response is received from a repeater + void handleResponse(Contact repeater, String responseText) { + // Find pending command for this repeater and complete it + final repeaterKey = repeater.publicKeyHex; + + String? commandId; + String responsePayload = responseText; + if (responseText.length >= 3 && responseText[2] == '|') { + final prefix = responseText.substring(0, 3); + commandId = _pendingByPrefix[prefix]; + responsePayload = responseText.substring(3).trimLeft(); + } + + commandId ??= _pendingCommands.keys.firstWhere( + (id) => id.startsWith(repeaterKey), + orElse: () => '', + ); + + if (commandId.isEmpty) return; + + final completer = _pendingCommands[commandId]; + if (completer != null && !completer.isCompleted) { + completer.complete(responsePayload); + _cleanup(commandId); + } + } + + void _cleanup(String commandId) { + _commandTimeouts[commandId]?.cancel(); + _commandTimeouts.remove(commandId); + _pendingCommands.remove(commandId); + final prefix = _commandPrefixes.remove(commandId); + if (prefix != null) { + _pendingByPrefix.remove(prefix); + } + } + + void dispose() { + for (final timer in _commandTimeouts.values) { + timer.cancel(); + } + _commandTimeouts.clear(); + _pendingCommands.clear(); + _commandPrefixes.clear(); + _pendingByPrefix.clear(); + } + + String _nextPrefixToken() { + for (var i = 0; i < 256; i++) { + final value = _prefixCounter++ & 0xFF; + final token = '${value.toRadixString(16).padLeft(2, '0').toUpperCase()}|'; + if (!_pendingByPrefix.containsKey(token)) { + return token; + } + } + return '00|'; + } +} diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart new file mode 100644 index 00000000..052f0c8d --- /dev/null +++ b/lib/services/storage_service.dart @@ -0,0 +1,120 @@ +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../models/path_history.dart'; + +class StorageService { + static const String _pathHistoryPrefix = 'path_history_'; + static const String _pendingMessagesKey = 'pending_messages'; + static const String _repeaterPasswordsKey = 'repeater_passwords'; + + Future savePathHistory( + String contactPubKeyHex, ContactPathHistory history) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_pathHistoryPrefix$contactPubKeyHex'; + final jsonStr = jsonEncode(history.toJson()); + await prefs.setString(key, jsonStr); + } + + Future loadPathHistory(String contactPubKeyHex) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_pathHistoryPrefix$contactPubKeyHex'; + final jsonStr = prefs.getString(key); + + if (jsonStr == null) return null; + + try { + final json = jsonDecode(jsonStr) as Map; + return ContactPathHistory.fromJson(contactPubKeyHex, json); + } catch (e) { + return null; + } + } + + Future clearPathHistory(String contactPubKeyHex) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_pathHistoryPrefix$contactPubKeyHex'; + await prefs.remove(key); + } + + Future clearAllPathHistories() async { + final prefs = await SharedPreferences.getInstance(); + final keys = prefs.getKeys(); + final pathHistoryKeys = + keys.where((key) => key.startsWith(_pathHistoryPrefix)); + + for (final key in pathHistoryKeys) { + await prefs.remove(key); + } + } + + Future> loadPendingMessages() async { + final prefs = await SharedPreferences.getInstance(); + final jsonStr = prefs.getString(_pendingMessagesKey); + + if (jsonStr == null) return {}; + + try { + final json = jsonDecode(jsonStr) as Map; + return json.map((key, value) => MapEntry(key, value as String)); + } catch (e) { + return {}; + } + } + + Future savePendingMessages(Map pending) async { + final prefs = await SharedPreferences.getInstance(); + final jsonStr = jsonEncode(pending); + await prefs.setString(_pendingMessagesKey, jsonStr); + } + + Future clearPendingMessages() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_pendingMessagesKey); + } + + /// Save a repeater password by public key hex + Future saveRepeaterPassword( + String repeaterPubKeyHex, String password) async { + final prefs = await SharedPreferences.getInstance(); + final passwords = await loadRepeaterPasswords(); + passwords[repeaterPubKeyHex] = password; + final jsonStr = jsonEncode(passwords); + await prefs.setString(_repeaterPasswordsKey, jsonStr); + } + + /// Load all saved repeater passwords (map of pubKeyHex -> password) + Future> loadRepeaterPasswords() async { + final prefs = await SharedPreferences.getInstance(); + final jsonStr = prefs.getString(_repeaterPasswordsKey); + + if (jsonStr == null) return {}; + + try { + final json = jsonDecode(jsonStr) as Map; + return json.map((key, value) => MapEntry(key, value as String)); + } catch (e) { + return {}; + } + } + + /// Get a specific repeater's saved password + Future getRepeaterPassword(String repeaterPubKeyHex) async { + final passwords = await loadRepeaterPasswords(); + return passwords[repeaterPubKeyHex]; + } + + /// Remove a saved repeater password + Future removeRepeaterPassword(String repeaterPubKeyHex) async { + final prefs = await SharedPreferences.getInstance(); + final passwords = await loadRepeaterPasswords(); + passwords.remove(repeaterPubKeyHex); + final jsonStr = jsonEncode(passwords); + await prefs.setString(_repeaterPasswordsKey, jsonStr); + } + + /// Clear all saved repeater passwords + Future clearAllRepeaterPasswords() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_repeaterPasswordsKey); + } +} diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart new file mode 100644 index 00000000..f40377e1 --- /dev/null +++ b/lib/storage/channel_message_store.dart @@ -0,0 +1,119 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../models/channel_message.dart'; +import '../helpers/smaz.dart'; + +class ChannelMessageStore { + static const String _keyPrefix = 'channel_messages_'; + + /// Save messages for a specific channel + Future saveChannelMessages(int channelIndex, List messages) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_keyPrefix$channelIndex'; + + // Convert messages to JSON + final jsonList = messages.map((msg) => _messageToJson(msg)).toList(); + final jsonString = jsonEncode(jsonList); + + await prefs.setString(key, jsonString); + } + + /// Load messages for a specific channel + Future> loadChannelMessages(int channelIndex) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_keyPrefix$channelIndex'; + + final jsonString = prefs.getString(key); + if (jsonString == null) return []; + + try { + final jsonList = jsonDecode(jsonString) as List; + return jsonList.map((json) => _messageFromJson(json)).toList(); + } catch (e) { + // If parsing fails, return empty list + return []; + } + } + + /// Clear messages for a specific channel + Future clearChannelMessages(int channelIndex) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_keyPrefix$channelIndex'; + await prefs.remove(key); + } + + /// Clear all channel messages + Future clearAllChannelMessages() async { + final prefs = await SharedPreferences.getInstance(); + final keys = prefs.getKeys().where((k) => k.startsWith(_keyPrefix)); + for (var key in keys) { + await prefs.remove(key); + } + } + + /// Convert ChannelMessage to JSON map + Map _messageToJson(ChannelMessage msg) { + return { + 'senderKey': msg.senderKey != null ? base64Encode(msg.senderKey!) : null, + 'senderName': msg.senderName, + 'text': msg.text, + 'timestamp': msg.timestamp.millisecondsSinceEpoch, + 'isOutgoing': msg.isOutgoing, + 'status': msg.status.index, + 'channelIndex': msg.channelIndex, + 'repeatCount': msg.repeatCount, + 'pathLength': msg.pathLength, + 'pathBytes': base64Encode(msg.pathBytes), + 'repeats': msg.repeats.map(_repeatToJson).toList(), + }; + } + + /// Convert JSON map to ChannelMessage + ChannelMessage _messageFromJson(Map json) { + final rawText = json['text'] as String; + final decodedText = Smaz.tryDecodePrefixed(rawText) ?? rawText; + return ChannelMessage( + senderKey: json['senderKey'] != null + ? Uint8List.fromList(base64Decode(json['senderKey'])) + : null, + senderName: json['senderName'] as String, + text: decodedText, + timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int), + isOutgoing: json['isOutgoing'] as bool, + status: ChannelMessageStatus.values[json['status'] as int], + repeatCount: (json['repeatCount'] as int?) ?? 0, + pathLength: json['pathLength'] as int?, + pathBytes: json['pathBytes'] != null + ? Uint8List.fromList(base64Decode(json['pathBytes'] as String)) + : Uint8List(0), + repeats: (json['repeats'] as List?) + ?.map((entry) => _repeatFromJson(entry as Map)) + .toList() ?? + const [], + channelIndex: json['channelIndex'] as int?, + ); + } + + Map _repeatToJson(Repeat repeat) { + return { + 'repeaterKey': repeat.repeaterKey != null ? base64Encode(repeat.repeaterKey!) : null, + 'repeaterName': repeat.repeaterName, + 'tripTimeMs': repeat.tripTimeMs, + 'path': repeat.path?.map((bytes) => base64Encode(bytes)).toList() ?? [], + }; + } + + Repeat _repeatFromJson(Map json) { + return Repeat( + repeaterKey: json['repeaterKey'] != null + ? Uint8List.fromList(base64Decode(json['repeaterKey'])) + : null, + repeaterName: json['repeaterName'] as String? ?? 'Unknown', + tripTimeMs: json['tripTimeMs'] as int? ?? 0, + path: (json['path'] as List?) + ?.map((entry) => Uint8List.fromList(base64Decode(entry as String))) + .toList(), + ); + } +} diff --git a/lib/storage/channel_order_store.dart b/lib/storage/channel_order_store.dart new file mode 100644 index 00000000..510061ac --- /dev/null +++ b/lib/storage/channel_order_store.dart @@ -0,0 +1,30 @@ +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; + +class ChannelOrderStore { + static const String _key = 'channel_order'; + + Future saveChannelOrder(List order) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_key, jsonEncode(order)); + } + + Future> loadChannelOrder() async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_key); + if (raw == null || raw.isEmpty) return []; + try { + final decoded = jsonDecode(raw); + if (decoded is List) { + return decoded.map((value) => value is int ? value : int.tryParse('$value')).whereType().toList(); + } + } catch (_) { + // fall through to legacy parse + } + return raw + .split(',') + .map((value) => int.tryParse(value)) + .whereType() + .toList(); + } +} diff --git a/lib/storage/channel_settings_store.dart b/lib/storage/channel_settings_store.dart new file mode 100644 index 00000000..17358378 --- /dev/null +++ b/lib/storage/channel_settings_store.dart @@ -0,0 +1,17 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +class ChannelSettingsStore { + static const String _smazKeyPrefix = 'channel_smaz_'; + + Future loadSmazEnabled(int channelIndex) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_smazKeyPrefix$channelIndex'; + return prefs.getBool(key) ?? false; + } + + Future saveSmazEnabled(int channelIndex, bool enabled) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_smazKeyPrefix$channelIndex'; + await prefs.setBool(key, enabled); + } +} diff --git a/lib/storage/contact_group_store.dart b/lib/storage/contact_group_store.dart new file mode 100644 index 00000000..53582ee2 --- /dev/null +++ b/lib/storage/contact_group_store.dart @@ -0,0 +1,32 @@ +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../models/contact_group.dart'; + +class ContactGroupStore { + static const String _key = 'contact_groups'; + + Future> loadGroups() async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_key); + if (raw == null || raw.isEmpty) return []; + + try { + final decoded = jsonDecode(raw); + if (decoded is List) { + return decoded + .whereType>() + .map(ContactGroup.fromJson) + .toList(); + } + } catch (_) { + // Return empty list on parse errors. + } + return []; + } + + Future saveGroups(List groups) async { + final prefs = await SharedPreferences.getInstance(); + final encoded = jsonEncode(groups.map((group) => group.toJson()).toList()); + await prefs.setString(_key, encoded); + } +} diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart new file mode 100644 index 00000000..18ce056d --- /dev/null +++ b/lib/storage/contact_store.dart @@ -0,0 +1,57 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/contact.dart'; + +class ContactStore { + static const String _key = 'contacts'; + + Future> loadContacts() async { + final prefs = await SharedPreferences.getInstance(); + final jsonStr = prefs.getString(_key); + if (jsonStr == null) return []; + + try { + final jsonList = jsonDecode(jsonStr) as List; + return jsonList.map((entry) => _fromJson(entry as Map)).toList(); + } catch (_) { + return []; + } + } + + Future saveContacts(List contacts) async { + final prefs = await SharedPreferences.getInstance(); + final jsonList = contacts.map(_toJson).toList(); + await prefs.setString(_key, jsonEncode(jsonList)); + } + + Map _toJson(Contact contact) { + return { + 'publicKey': base64Encode(contact.publicKey), + 'name': contact.name, + 'type': contact.type, + 'pathLength': contact.pathLength, + 'path': base64Encode(contact.path), + 'latitude': contact.latitude, + 'longitude': contact.longitude, + 'lastSeen': contact.lastSeen.millisecondsSinceEpoch, + }; + } + + Contact _fromJson(Map json) { + return Contact( + publicKey: Uint8List.fromList(base64Decode(json['publicKey'] as String)), + name: json['name'] as String? ?? 'Unknown', + type: json['type'] as int? ?? 0, + pathLength: json['pathLength'] as int? ?? -1, + path: json['path'] != null + ? Uint8List.fromList(base64Decode(json['path'] as String)) + : Uint8List(0), + latitude: (json['latitude'] as num?)?.toDouble(), + longitude: (json['longitude'] as num?)?.toDouble(), + lastSeen: DateTime.fromMillisecondsSinceEpoch(json['lastSeen'] as int? ?? 0), + ); + } +} diff --git a/lib/storage/message_store.dart b/lib/storage/message_store.dart new file mode 100644 index 00000000..9bc1cdec --- /dev/null +++ b/lib/storage/message_store.dart @@ -0,0 +1,85 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../models/message.dart'; + +class MessageStore { + static const String _keyPrefix = 'messages_'; + + Future saveMessages(String contactKeyHex, List messages) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_keyPrefix$contactKeyHex'; + final jsonList = messages.map(_messageToJson).toList(); + await prefs.setString(key, jsonEncode(jsonList)); + } + + Future> loadMessages(String contactKeyHex) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_keyPrefix$contactKeyHex'; + final jsonString = prefs.getString(key); + if (jsonString == null) return []; + + try { + final jsonList = jsonDecode(jsonString) as List; + return jsonList.map((json) => _messageFromJson(json)).toList(); + } catch (e) { + return []; + } + } + + Future clearMessages(String contactKeyHex) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_keyPrefix$contactKeyHex'; + await prefs.remove(key); + } + + Map _messageToJson(Message msg) { + return { + 'senderKey': base64Encode(msg.senderKey), + 'text': msg.text, + 'timestamp': msg.timestamp.millisecondsSinceEpoch, + 'isOutgoing': msg.isOutgoing, + 'isCli': msg.isCli, + 'status': msg.status.index, + 'messageId': msg.messageId, + 'retryCount': msg.retryCount, + 'estimatedTimeoutMs': msg.estimatedTimeoutMs, + 'expectedAckHash': msg.expectedAckHash != null ? base64Encode(msg.expectedAckHash!) : null, + 'sentAt': msg.sentAt?.millisecondsSinceEpoch, + 'deliveredAt': msg.deliveredAt?.millisecondsSinceEpoch, + 'tripTimeMs': msg.tripTimeMs, + 'forceFlood': msg.forceFlood, + 'pathLength': msg.pathLength, + 'pathBytes': msg.pathBytes.isNotEmpty ? base64Encode(msg.pathBytes) : null, + }; + } + + Message _messageFromJson(Map json) { + return Message( + senderKey: Uint8List.fromList(base64Decode(json['senderKey'] as String)), + text: json['text'] as String, + timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int), + isOutgoing: json['isOutgoing'] as bool, + isCli: json['isCli'] as bool? ?? false, + status: MessageStatus.values[json['status'] as int], + messageId: json['messageId'] as String?, + retryCount: json['retryCount'] as int? ?? 0, + estimatedTimeoutMs: json['estimatedTimeoutMs'] as int?, + expectedAckHash: json['expectedAckHash'] != null + ? Uint8List.fromList(base64Decode(json['expectedAckHash'] as String)) + : null, + sentAt: json['sentAt'] != null + ? DateTime.fromMillisecondsSinceEpoch(json['sentAt'] as int) + : null, + deliveredAt: json['deliveredAt'] != null + ? DateTime.fromMillisecondsSinceEpoch(json['deliveredAt'] as int) + : null, + tripTimeMs: json['tripTimeMs'] as int?, + forceFlood: json['forceFlood'] as bool? ?? false, + pathLength: json['pathLength'] as int?, + pathBytes: json['pathBytes'] != null + ? Uint8List.fromList(base64Decode(json['pathBytes'] as String)) + : Uint8List(0), + ); + } +} diff --git a/lib/utils/emoji_utils.dart b/lib/utils/emoji_utils.dart new file mode 100644 index 00000000..d2b8bebf --- /dev/null +++ b/lib/utils/emoji_utils.dart @@ -0,0 +1,33 @@ +import 'package:characters/characters.dart'; + +String? firstEmoji(String name) { + if (name.isEmpty) return null; + for (final cluster in name.characters) { + if (_containsEmoji(cluster)) { + return cluster; + } + } + return null; +} + +bool _containsEmoji(String cluster) { + for (final rune in cluster.runes) { + if (_isEmojiRune(rune)) return true; + } + return false; +} + +bool _isEmojiRune(int rune) { + if (rune == 0x00A9 || rune == 0x00AE) return true; + if (rune == 0x203C || rune == 0x2049) return true; + if (rune == 0x2122 || rune == 0x2139) return true; + if (rune >= 0x2194 && rune <= 0x21AA) return true; + if (rune >= 0x2300 && rune <= 0x23FF) return true; + if (rune >= 0x2460 && rune <= 0x24FF) return true; + if (rune >= 0x25A0 && rune <= 0x27BF) return true; + if (rune >= 0x2900 && rune <= 0x297F) return true; + if (rune >= 0x2B00 && rune <= 0x2BFF) return true; + if (rune >= 0x1F000 && rune <= 0x1FAFF) return true; + if (rune >= 0x1FC00 && rune <= 0x1FFFD) return true; + return false; +} diff --git a/lib/widgets/debug_frame_viewer.dart b/lib/widgets/debug_frame_viewer.dart new file mode 100644 index 00000000..7c417f9c --- /dev/null +++ b/lib/widgets/debug_frame_viewer.dart @@ -0,0 +1,68 @@ +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import '../connector/meshcore_protocol.dart'; + +/// Debug widget to show the hex dump of a frame +class DebugFrameViewer { + static void showFrameDebug(BuildContext context, Uint8List frame, String title) { + final hexString = frame + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join(' '); + + final details = StringBuffer(); + details.writeln('Frame Length: ${frame.length} bytes\n'); + details.writeln('Command: 0x${frame[0].toRadixString(16).padLeft(2, '0')}'); + + if (frame[0] == cmdSendTxtMsg && frame.length > 37) { + details.writeln('\nText Message Frame:'); + details.writeln('- Destination PubKey: ${pubKeyToHex(frame.sublist(1, 33))}'); + details.writeln('- Timestamp: ${readUint32LE(frame, 33)}'); + details.writeln('- Flags: 0x${frame[37].toRadixString(16).padLeft(2, '0')}'); + final txtType = (frame[37] >> 2) & 0x03; + details.writeln('- Text Type: $txtType ${txtType == txtTypeCliData ? "(CLI)" : "(Plain)"}'); + if (frame.length > 38) { + final textBytes = frame.sublist(38); + final nullIdx = textBytes.indexOf(0); + final text = String.fromCharCodes( + nullIdx >= 0 ? textBytes.sublist(0, nullIdx) : textBytes + ); + details.writeln('- Text: "$text"'); + } + } + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(title), + content: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + details.toString(), + style: const TextStyle(fontFamily: 'monospace', fontSize: 12), + ), + const Divider(), + const Text( + 'Hex Dump:', + style: TextStyle(fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Text( + hexString, + style: const TextStyle(fontFamily: 'monospace', fontSize: 11), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/device_tile.dart b/lib/widgets/device_tile.dart new file mode 100644 index 00000000..2d6de8da --- /dev/null +++ b/lib/widgets/device_tile.dart @@ -0,0 +1,68 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_blue_plus/flutter_blue_plus.dart'; + +/// A reusable tile widget for displaying a MeshCore device in a list +class DeviceTile extends StatelessWidget { + final ScanResult scanResult; + final VoidCallback onTap; + + const DeviceTile({ + super.key, + required this.scanResult, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + final device = scanResult.device; + final rssi = scanResult.rssi; + final name = device.platformName.isNotEmpty + ? device.platformName + : scanResult.advertisementData.advName; + + return ListTile( + leading: _buildSignalIcon(rssi), + title: Text( + name.isNotEmpty ? name : 'Unknown Device', + style: const TextStyle(fontWeight: FontWeight.w500), + ), + subtitle: Text(device.remoteId.toString()), + trailing: ElevatedButton( + onPressed: onTap, + child: const Text('Connect'), + ), + onTap: onTap, + ); + } + + Widget _buildSignalIcon(int rssi) { + IconData icon; + Color color; + + if (rssi >= -60) { + icon = Icons.signal_cellular_4_bar; + color = Colors.green; + } else if (rssi >= -70) { + icon = Icons.signal_cellular_alt; + color = Colors.lightGreen; + } else if (rssi >= -80) { + icon = Icons.signal_cellular_alt_2_bar; + color = Colors.orange; + } else { + icon = Icons.signal_cellular_alt_1_bar; + color = Colors.red; + } + + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, color: color), + Text( + '$rssi dBm', + style: TextStyle(fontSize: 10, color: color), + ), + ], + ); + } +} + diff --git a/lib/widgets/gif_message.dart b/lib/widgets/gif_message.dart new file mode 100644 index 00000000..402565f1 --- /dev/null +++ b/lib/widgets/gif_message.dart @@ -0,0 +1,185 @@ +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; + +class GifMessage extends StatefulWidget { + final String url; + final Color backgroundColor; + final Color fallbackTextColor; + final double width; + final double height; + + const GifMessage({ + super.key, + required this.url, + required this.backgroundColor, + required this.fallbackTextColor, + this.width = 200, + this.height = 140, + }); + + @override + State createState() => _GifMessageState(); +} + +class _GifMessageState extends State { + ImageStream? _imageStream; + ImageStreamListener? _listener; + ui.Image? _image; + Object? _error; + bool _isLoading = true; + bool _isPaused = false; + + @override + void initState() { + super.initState(); + _resolveImage(); + } + + @override + void didUpdateWidget(covariant GifMessage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.url != widget.url) { + _unsubscribe(); + _image = null; + _error = null; + _isLoading = true; + _isPaused = false; + _resolveImage(); + } + } + + @override + void dispose() { + _unsubscribe(); + super.dispose(); + } + + void _resolveImage() { + setState(() { + _isLoading = true; + _error = null; + }); + final provider = NetworkImage(widget.url); + final stream = provider.resolve(ImageConfiguration.empty); + _imageStream = stream; + _listener = ImageStreamListener( + (imageInfo, _) { + if (_isPaused) { + return; + } + setState(() { + _image = imageInfo.image; + _isLoading = false; + }); + }, + onError: (error, _) { + setState(() { + _error = error; + _isLoading = false; + }); + }, + ); + stream.addListener(_listener!); + } + + void _retryLoad() { + _unsubscribe(); + _image = null; + _isPaused = false; + _resolveImage(); + } + + void _unsubscribe() { + if (_imageStream != null && _listener != null) { + _imageStream!.removeListener(_listener!); + } + } + + void _togglePause() { + if (_error != null) { + _retryLoad(); + return; + } + if (_image == null) { + if (!_isLoading) { + _retryLoad(); + } + return; + } + setState(() { + _isPaused = !_isPaused; + }); + if (_listener == null || _imageStream == null) { + return; + } + if (_isPaused) { + _imageStream!.removeListener(_listener!); + } else { + _imageStream!.addListener(_listener!); + } + } + + @override + Widget build(BuildContext context) { + Widget content; + + if (_error != null) { + content = Center( + child: Text( + "Can't load GIF\nTap to retry", + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: widget.fallbackTextColor), + ), + ); + } else if (_isLoading && _image == null) { + content = const Center( + child: SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ); + } else if (_image == null) { + content = Center( + child: Text( + 'Tap to load GIF', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: widget.fallbackTextColor), + ), + ); + } else { + content = RawImage( + image: _image, + fit: BoxFit.cover, + width: widget.width, + height: widget.height, + ); + } + + return GestureDetector( + onTap: _togglePause, + child: ClipRRect( + borderRadius: BorderRadius.circular(10), + child: Container( + color: widget.backgroundColor, + width: widget.width, + height: widget.height, + child: Stack( + fit: StackFit.expand, + children: [ + content, + if (_isPaused && _image != null) + Container( + color: Colors.black.withValues(alpha: 0.2), + child: const Center( + child: Icon(Icons.pause, color: Colors.white70, size: 28), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/gif_picker.dart b/lib/widgets/gif_picker.dart new file mode 100644 index 00000000..94a75bfe --- /dev/null +++ b/lib/widgets/gif_picker.dart @@ -0,0 +1,283 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; + +class GifPicker extends StatefulWidget { + final Function(String gifId) onGifSelected; + + const GifPicker({ + super.key, + required this.onGifSelected, + }); + + @override + State createState() => _GifPickerState(); +} + +class _GifPickerState extends State { + final TextEditingController _searchController = TextEditingController(); + List> _gifs = []; + bool _isLoading = false; + String? _error; + + // Giphy API key - Using public beta key (limited usage) + // For production, replace with your own Giphy API key from developers.giphy.com + static const String _giphyApiKey = 'sXpGFDGZs0Dv1mmNFvYaGUvYwKX0PWIh'; + + @override + void initState() { + super.initState(); + _loadTrendingGifs(); + } + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + Future _loadTrendingGifs() async { + setState(() { + _isLoading = true; + _error = null; + }); + + try { + final response = await http.get( + Uri.parse( + 'https://api.giphy.com/v1/gifs/trending?api_key=$_giphyApiKey&limit=25&rating=g', + ), + ).timeout(const Duration(seconds: 10)); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + setState(() { + _gifs = List>.from(data['data']); + _isLoading = false; + }); + } else { + setState(() { + _error = 'Failed to load GIFs'; + _isLoading = false; + }); + } + } catch (e) { + setState(() { + _error = 'No internet connection'; + _isLoading = false; + }); + } + } + + Future _searchGifs(String query) async { + if (query.trim().isEmpty) { + _loadTrendingGifs(); + return; + } + + setState(() { + _isLoading = true; + _error = null; + }); + + try { + final response = await http.get( + Uri.parse( + 'https://api.giphy.com/v1/gifs/search?api_key=$_giphyApiKey&q=${Uri.encodeComponent(query)}&limit=25&rating=g', + ), + ).timeout(const Duration(seconds: 10)); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + setState(() { + _gifs = List>.from(data['data']); + _isLoading = false; + }); + } else { + setState(() { + _error = 'Failed to search GIFs'; + _isLoading = false; + }); + } + } catch (e) { + setState(() { + _error = 'No internet connection'; + _isLoading = false; + }); + } + } + + @override + Widget build(BuildContext context) { + return Container( + height: MediaQuery.of(context).size.height * 0.7, + padding: const EdgeInsets.all(16), + child: Column( + children: [ + // Header + Row( + children: [ + const Icon(Icons.gif_box, size: 28), + const SizedBox(width: 8), + const Text( + 'Choose a GIF', + style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + ), + const Spacer(), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => Navigator.pop(context), + ), + ], + ), + const SizedBox(height: 16), + + // Search bar + TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: 'Search GIFs...', + prefixIcon: const Icon(Icons.search), + suffixIcon: _searchController.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear), + onPressed: () { + _searchController.clear(); + _loadTrendingGifs(); + }, + ) + : null, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + ), + textInputAction: TextInputAction.search, + onSubmitted: _searchGifs, + onChanged: (value) { + setState(() {}); // Update to show/hide clear button + }, + ), + const SizedBox(height: 16), + + // GIF grid + Expanded( + child: _buildContent(), + ), + + // Powered by Giphy attribution + const SizedBox(height: 8), + Text( + 'Powered by GIPHY', + style: TextStyle( + fontSize: 11, + color: Colors.grey[600], + ), + ), + ], + ), + ); + } + + Widget _buildContent() { + if (_isLoading) { + return const Center( + child: CircularProgressIndicator(), + ); + } + + if (_error != null) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.error_outline, size: 64, color: Colors.grey[400]), + const SizedBox(height: 16), + Text( + _error!, + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: _loadTrendingGifs, + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + ), + ], + ), + ); + } + + if (_gifs.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.search_off, size: 64, color: Colors.grey[400]), + const SizedBox(height: 16), + Text( + 'No GIFs found', + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + ], + ), + ); + } + + return GridView.builder( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + crossAxisSpacing: 8, + mainAxisSpacing: 8, + childAspectRatio: 1.0, + ), + itemCount: _gifs.length, + itemBuilder: (context, index) { + final gif = _gifs[index]; + final gifId = gif['id'] as String; + final previewUrl = gif['images']?['fixed_height_small']?['url'] as String?; + + return GestureDetector( + onTap: () { + widget.onGifSelected(gifId); + Navigator.pop(context); + }, + child: ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Container( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: previewUrl != null + ? Image.network( + previewUrl, + fit: BoxFit.cover, + loadingBuilder: (context, child, loadingProgress) { + if (loadingProgress == null) return child; + return Center( + child: CircularProgressIndicator( + value: loadingProgress.expectedTotalBytes != null + ? loadingProgress.cumulativeBytesLoaded / + loadingProgress.expectedTotalBytes! + : null, + ), + ); + }, + errorBuilder: (context, error, stackTrace) { + return const Center( + child: Icon(Icons.error_outline), + ); + }, + ) + : const Center( + child: Icon(Icons.gif_box), + ), + ), + ), + ); + }, + ); + } +} diff --git a/lib/widgets/repeater_login_dialog.dart b/lib/widgets/repeater_login_dialog.dart new file mode 100644 index 00000000..8dab1608 --- /dev/null +++ b/lib/widgets/repeater_login_dialog.dart @@ -0,0 +1,286 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:provider/provider.dart'; +import '../models/contact.dart'; +import '../services/storage_service.dart'; +import '../services/repeater_command_service.dart'; +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; + +class RepeaterLoginDialog extends StatefulWidget { + final Contact repeater; + final Function(String password) onLogin; + + const RepeaterLoginDialog({ + super.key, + required this.repeater, + required this.onLogin, + }); + + @override + State createState() => _RepeaterLoginDialogState(); +} + +class _RepeaterLoginDialogState extends State { + final TextEditingController _passwordController = TextEditingController(); + final StorageService _storage = StorageService(); + bool _savePassword = false; + bool _isLoading = true; + bool _obscurePassword = true; + late MeshCoreConnector _connector; + int _currentAttempt = 0; + final int _maxAttempts = RepeaterCommandService.maxRetries; + static const int _loginTimeoutSeconds = 10; + + @override + void initState() { + super.initState(); + _connector = Provider.of(context, listen: false); + _loadSavedPassword(); + } + + Future _loadSavedPassword() async { + final savedPassword = + await _storage.getRepeaterPassword(widget.repeater.publicKeyHex); + if (savedPassword != null) { + setState(() { + _passwordController.text = savedPassword; + _savePassword = true; + _isLoading = false; + }); + } else { + setState(() { + _isLoading = false; + }); + } + } + + @override + void dispose() { + _passwordController.dispose(); + super.dispose(); + } + + bool _isLoggingIn = false; + + Future _handleLogin() async { + if (_isLoggingIn) return; + + setState(() { + _isLoggingIn = true; + _currentAttempt = 0; + }); + + try { + final password = _passwordController.text; + bool? loginResult; + for (int attempt = 0; attempt < _maxAttempts; attempt++) { + if (!mounted) return; + setState(() { + _currentAttempt = attempt + 1; + }); + + await _connector.sendFrame( + buildSendLoginFrame(widget.repeater.publicKey, password), + ); + + loginResult = await _awaitLoginResponse(); + if (loginResult == true) { + break; + } + if (loginResult == false) { + throw Exception('Wrong password or node is unreachable'); + } + } + + if (loginResult != true) { + throw Exception('Wrong password or node is unreachable'); + } + + // If we got a response, login succeeded + if (mounted) { + // Save password if requested + if (_savePassword) { + await _storage.saveRepeaterPassword( + widget.repeater.publicKeyHex, password); + } else { + // Remove saved password if user unchecked the box + await _storage.removeRepeaterPassword(widget.repeater.publicKeyHex); + } + + Navigator.pop(context, password); + Future.microtask(() => widget.onLogin(password)); + } + } catch (e) { + if (mounted) { + setState(() { + _isLoggingIn = false; + }); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Login failed: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + } + + Future _awaitLoginResponse() async { + final completer = Completer(); + Timer? timer; + StreamSubscription? subscription; + final targetPrefix = widget.repeater.publicKey.sublist(0, 6); + + subscription = _connector.receivedFrames.listen((frame) { + if (frame.isEmpty) return; + final code = frame[0]; + if (code != pushCodeLoginSuccess && code != pushCodeLoginFail) return; + if (frame.length < 8) return; + final prefix = frame.sublist(2, 8); + if (!listEquals(prefix, targetPrefix)) return; + + completer.complete(code == pushCodeLoginSuccess); + subscription?.cancel(); + timer?.cancel(); + }); + + timer = Timer(const Duration(seconds: _loginTimeoutSeconds), () { + if (!completer.isCompleted) { + completer.complete(null); + subscription?.cancel(); + } + }); + + final result = await completer.future; + timer?.cancel(); + await subscription?.cancel(); + return result; + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Row( + children: [ + const Icon(Icons.cell_tower, color: Colors.orange), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Repeater Login'), + Text( + widget.repeater.name, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.normal, + color: Colors.grey[600], + ), + ), + ], + ), + ), + ], + ), + content: _isLoading + ? const Center( + child: Padding( + padding: EdgeInsets.all(20.0), + child: CircularProgressIndicator(), + ), + ) + : Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Enter the repeater password to access settings and status.', + style: TextStyle(fontSize: 14), + ), + const SizedBox(height: 16), + TextField( + controller: _passwordController, + obscureText: _obscurePassword, + decoration: InputDecoration( + labelText: 'Password', + hintText: 'Enter password', + border: const OutlineInputBorder(), + prefixIcon: const Icon(Icons.lock), + suffixIcon: IconButton( + icon: Icon( + _obscurePassword + ? Icons.visibility + : Icons.visibility_off, + ), + onPressed: () { + setState(() { + _obscurePassword = !_obscurePassword; + }); + }, + ), + ), + onSubmitted: (_) => _handleLogin(), + autofocus: _passwordController.text.isEmpty, + ), + const SizedBox(height: 12), + CheckboxListTile( + value: _savePassword, + onChanged: (value) { + setState(() { + _savePassword = value ?? false; + }); + }, + title: const Text( + 'Save password', + style: TextStyle(fontSize: 14), + ), + subtitle: const Text( + 'Password will be stored securely on this device', + style: TextStyle(fontSize: 12), + ), + controlAffinity: ListTileControlAffinity.leading, + contentPadding: EdgeInsets.zero, + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + if (_isLoggingIn) + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: null, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ), + const SizedBox(width: 12), + Text('Retries $_currentAttempt/$_maxAttempts'), + ], + ), + ), + ) + else + FilledButton.icon( + onPressed: _isLoading ? null : _handleLogin, + icon: const Icon(Icons.login, size: 18), + label: const Text('Login'), + ), + ], + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 00000000..d3896c98 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 00000000..6867349b --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "meshcore_open") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.meshcore.meshcore_open") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 00000000..d5bd0164 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 00000000..e71a16d2 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000..e0f0a47b --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 00000000..2e1de87a --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 00000000..e97dabc7 --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 00000000..e7c5c543 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 00000000..1d9a9edd --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,144 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView *view) +{ + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "meshcore_open"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "meshcore_open"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 00000000..72271d5e --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 00000000..746adbb6 --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 00000000..c2efd0b6 --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 00000000..c2efd0b6 --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 00000000..7b9bdcf8 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,16 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import flutter_blue_plus_darwin +import flutter_local_notifications +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin")) + FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..6a856469 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* meshcore_open.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "meshcore_open.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* meshcore_open.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* meshcore_open.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshcore_open.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshcore_open"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshcore_open.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshcore_open"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshcore_open.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshcore_open"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000..fd43b250 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..1d526a16 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 00000000..b3c17614 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..a2ec33f1 --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 00000000..82b6f9d9 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 00000000..13b35eba Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 00000000..0a3f5fa4 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 00000000..bdb57226 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 00000000..f083318e Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 00000000..326c0e72 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 00000000..2f1632cf Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 00000000..80e867a4 --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 00000000..8d4afce6 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = meshcore_open + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.meshcore.meshcoreOpen + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2025 com.meshcore. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 00000000..36b0fd94 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 00000000..dff4f495 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 00000000..42bcbf47 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 00000000..dddb8a30 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 00000000..4789daa6 --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 00000000..3cc05eb2 --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 00000000..852fa1a4 --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000..61f3bd1f --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 00000000..75819f3b --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,658 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + bluez: + dependency: transitive + description: + name: bluez + sha256: "61a7204381925896a374301498f2f5399e59827c6498ae1e924aaa598751b545" + url: "https://pub.dev" + source: hosted + version: "0.8.3" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dart_earcut: + dependency: transitive + description: + name: dart_earcut + sha256: e485001bfc05dcbc437d7bfb666316182e3522d4c3f9668048e004d0eb2ce43b + url: "https://pub.dev" + source: hosted + version: "1.2.0" + dbus: + dependency: transitive + description: + name: dbus + sha256: "79e0c23480ff85dc68de79e2cd6334add97e48f7f4865d17686dd6ea81a47e8c" + url: "https://pub.dev" + source: hosted + version: "0.7.11" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_blue_plus: + dependency: "direct main" + description: + name: flutter_blue_plus + sha256: "399b3dbc15562ef59749f04e43a99ccbb91540022380d5f269aff3c2787534e4" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + flutter_blue_plus_android: + dependency: transitive + description: + name: flutter_blue_plus_android + sha256: "5010b0960cce533a8fa71401573f044362c3e2e111dc6eb4898c92e85f85f50c" + url: "https://pub.dev" + source: hosted + version: "8.1.0" + flutter_blue_plus_darwin: + dependency: transitive + description: + name: flutter_blue_plus_darwin + sha256: d160a8128e3a016fa58dd65ab6dac05cbc73e0fa799a1f24211d041641ed63ba + url: "https://pub.dev" + source: hosted + version: "8.1.0" + flutter_blue_plus_linux: + dependency: transitive + description: + name: flutter_blue_plus_linux + sha256: f5b02244d89465ba82c8c512686c66362fbb01f52fa03d645ed353ebf3883242 + url: "https://pub.dev" + source: hosted + version: "8.1.0" + flutter_blue_plus_platform_interface: + dependency: transitive + description: + name: flutter_blue_plus_platform_interface + sha256: "6e0fc04b77491dbfdbcd46c1a021b12f2f5fc5d6e01777f93a38a8431989b7f0" + url: "https://pub.dev" + source: hosted + version: "8.1.0" + flutter_blue_plus_web: + dependency: transitive + description: + name: flutter_blue_plus_web + sha256: "376aad9595ee389c7cd56e0c373e78abcaa790c821ece9cb81f0969ec94c5bca" + url: "https://pub.dev" + source: hosted + version: "8.1.0" + flutter_blue_plus_winrt: + dependency: transitive + description: + name: flutter_blue_plus_winrt + sha256: "5cfa5960ac8723771cbc59586588b100f38494390154b8a3268c95db37e21617" + url: "https://pub.dev" + source: hosted + version: "0.0.7" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_local_notifications: + dependency: "direct main" + description: + name: flutter_local_notifications + sha256: ef41ae901e7529e52934feba19ed82827b11baa67336829564aeab3129460610 + url: "https://pub.dev" + source: hosted + version: "18.0.1" + flutter_local_notifications_linux: + dependency: transitive + description: + name: flutter_local_notifications_linux + sha256: "8f685642876742c941b29c32030f6f4f6dacd0e4eaecb3efbb187d6a3812ca01" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_local_notifications_platform_interface: + dependency: transitive + description: + name: flutter_local_notifications_platform_interface + sha256: "6c5b83c86bf819cdb177a9247a3722067dd8cc6313827ce7c77a4b238a26fd52" + url: "https://pub.dev" + source: hosted + version: "8.0.0" + flutter_map: + dependency: "direct main" + description: + name: flutter_map + sha256: "2ecb34619a4be19df6f40c2f8dce1591675b4eff7a6857bd8f533706977385da" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + intl: + dependency: transitive + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" + js: + dependency: transitive + description: + name: js + sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + url: "https://pub.dev" + source: hosted + version: "0.7.2" + latlong2: + dependency: "direct main" + description: + name: latlong2 + sha256: "98227922caf49e6056f91b6c56945ea1c7b166f28ffcd5fb8e72fc0b453cc8fe" + url: "https://pub.dev" + source: hosted + version: "0.9.1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + lists: + dependency: transitive + description: + name: lists + sha256: "4ca5c19ae4350de036a7e996cdd1ee39c93ac0a2b840f4915459b7d0a7d4ab27" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + logger: + dependency: transitive + description: + name: logger + sha256: a7967e31b703831a893bbc3c3dd11db08126fe5f369b5c648a36f821979f5be3 + url: "https://pub.dev" + source: hosted + version: "2.6.2" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + mgrs_dart: + dependency: transitive + description: + name: mgrs_dart + sha256: fb89ae62f05fa0bb90f70c31fc870bcbcfd516c843fb554452ab3396f78586f7 + url: "https://pub.dev" + source: hosted + version: "2.0.0" + nested: + dependency: transitive + description: + name: nested + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "1a97266a94f7350d30ae522c0af07890c70b8e62c71e8e3920d1db4d23c057d1" + url: "https://pub.dev" + source: hosted + version: "7.0.1" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pointycastle: + dependency: "direct main" + description: + name: pointycastle + sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe" + url: "https://pub.dev" + source: hosted + version: "3.9.1" + polylabel: + dependency: transitive + description: + name: polylabel + sha256: "41b9099afb2aa6c1730bdd8a0fab1400d287694ec7615dd8516935fa3144214b" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + proj4dart: + dependency: transitive + description: + name: proj4dart + sha256: c8a659ac9b6864aa47c171e78d41bbe6f5e1d7bd790a5814249e6b68bc44324e + url: "https://pub.dev" + source: hosted + version: "2.1.0" + provider: + dependency: "direct main" + description: + name: provider + sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272" + url: "https://pub.dev" + source: hosted + version: "6.1.5+1" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "83af5c682796c0f7719c2bbf74792d113e40ae97981b8f266fa84574573556bc" + url: "https://pub.dev" + source: hosted + version: "2.4.18" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + url: "https://pub.dev" + source: hosted + version: "0.7.6" + timezone: + dependency: transitive + description: + name: timezone + sha256: dd14a3b83cfd7cb19e7888f1cbc20f258b8d71b54c06f79ac585f14093a287d1 + url: "https://pub.dev" + source: hosted + version: "0.10.1" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + unicode: + dependency: transitive + description: + name: unicode + sha256: "0f69e46593d65245774d4f17125c6084d2c20b4e473a983f6e21b7d7762218f1" + url: "https://pub.dev" + source: hosted + version: "0.3.1" + uuid: + dependency: "direct main" + description: + name: uuid + sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8 + url: "https://pub.dev" + source: hosted + version: "4.5.2" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + url: "https://pub.dev" + source: hosted + version: "15.0.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + wkt_parser: + dependency: transitive + description: + name: wkt_parser + sha256: "8a555fc60de3116c00aad67891bcab20f81a958e4219cc106e3c037aa3937f13" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" +sdks: + dart: ">=3.9.2 <4.0.0" + flutter: ">=3.35.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 00000000..7868d7b8 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,99 @@ +name: meshcore_open +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.9.2 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + flutter_blue_plus: ^2.1.0 + provider: ^6.1.5+1 + shared_preferences: ^2.2.2 + uuid: ^4.3.3 + flutter_map: ^7.0.2 + latlong2: ^0.9.1 + flutter_local_notifications: ^18.0.1 + crypto: ^3.0.3 + pointycastle: ^3.7.4 + http: ^1.2.0 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^5.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 00000000..ba020e63 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,12 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/main.dart'; + +void main() { + testWidgets('App loads successfully', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MeshCoreApp()); + + // Verify that the app title appears + expect(find.text('MeshCore Open'), findsOneWidget); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 00000000..8aaa46ac Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 00000000..b749bfef Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 00000000..88cfd48d Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 00000000..eb9b4d76 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 00000000..d69c5669 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 00000000..3087ec27 --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + meshcore_open + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 00000000..9b0c25f2 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "meshcore_open", + "short_name": "meshcore_open", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 00000000..d492d0d9 --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 00000000..daf32c2f --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(meshcore_open LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "meshcore_open") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 00000000..903f4899 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 00000000..c158b14b --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterBluePlusPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterBluePlusPlugin")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000..dc139d85 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 00000000..905321af --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_blue_plus_winrt +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 00000000..394917c0 --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 00000000..3f1fc898 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.meshcore" "\0" + VALUE "FileDescription", "meshcore_open" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "meshcore_open" "\0" + VALUE "LegalCopyright", "Copyright (C) 2025 com.meshcore. All rights reserved." "\0" + VALUE "OriginalFilename", "meshcore_open.exe" "\0" + VALUE "ProductName", "meshcore_open" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 00000000..955ee303 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 00000000..6da0652f --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 00000000..c66f3253 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"meshcore_open", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 00000000..66a65d1e --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 00000000..c04e20ca Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 00000000..153653e8 --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 00000000..3a0b4651 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 00000000..3879d547 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 00000000..60608d0f --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 00000000..e901dde6 --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_