diff --git a/.gitignore b/.gitignore index f4c3b0c..3bc27a9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,12 @@ -# ---> Flutter # Miscellaneous *.class -*.lock *.log *.pyc *.swp +.DS_Store .buildlog/ .history - - # Flutter repo-specific /bin/cache/ /bin/internal/bootstrap.bat @@ -41,7 +38,7 @@ analysis_benchmark.json .packages .pub-preload-cache/ .pub/ -build/ +/build/ flutter_*.png linked_*.ds unlinked.ds @@ -57,6 +54,14 @@ unlinked_spec.ds **/android/**/GeneratedPluginRegistrant.java **/android/key.properties *.jks +*.keystore +captures/ +.externalNativeBuild/ +.cxx/ +*.apk +output.json +google-services.json +*.hprof # iOS/XCode related **/ios/**/*.mode1v3 @@ -118,38 +123,8 @@ app.*.symbols !**/ios/**/default.perspectivev3 !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages !/dev/ci/**/Gemfile.lock -# ---> Android -# Gradle files -.gradle/ -build/ -# Local configuration file (sdk path, etc) -local.properties - -# Log/OS Files -*.log - -# Android Studio generated files and folders -captures/ -.externalNativeBuild/ -.cxx/ -*.apk -output.json - -# IntelliJ -*.iml +# IDE / project files .idea/ -misc.xml -deploymentTargetDropDown.xml -render.experimental.xml - -# Keystore files -*.jks -*.keystore - -# Google Services (e.g. APIs or Firebase) -google-services.json - -# Android Profiling -*.hprof +*.iml diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..768732a --- /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: "559ffa3f75e7402d65a8def9c28389a9b2e6fe42" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: android + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: ios + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: linux + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: macos + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: web + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + - platform: windows + create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42 + + # 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/README.md b/README.md index d7fa947..0849554 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,77 @@ +<<<<<<< HEAD # ProxyTrash -Una aplicacion para saber si el camion mas sercano es Organico o inorganico junto con su distancia y otras funciones mas. \ No newline at end of file +Una aplicacion para saber si el camion mas sercano es Organico o inorganico junto con su distancia y otras funciones mas. +======= +# flutter_application_1 + +Aplicación móvil desarrollada en Flutter como una preview funcional para consulta de rutas de camiones, validación de usuarios y simulación de información local. El proyecto fue construido para mostrar una experiencia completa de usuario sin depender todavía de una base de datos real en producción. + +## Resumen del proyecto + +La app ofrece un flujo completo de inicio de sesión, registro, captura de dirección y acceso a un tablero principal con mapa, calendario, avisos y guía de rutas. La información que se muestra no depende de un backend activo en el frontend: se trabajó con archivos JSON locales como fuente de datos principal para simular usuarios, rutas, eventos y configuraciones. + +## Qué resuelve + +- Inicio de sesión y registro con validación local. +- Captura de dirección del usuario para personalizar la experiencia. +- Visualización de rutas de recolección con información resumida y detalle por ruta. +- Calendario con eventos importantes y notas locales. +- Mapa orientado a la zona del usuario, con comportamiento adaptado por orientación de pantalla. +- Base de datos simulada con JSON para demostrar el flujo completo sin depender de infraestructura externa. + +<<<<<<< HEAD +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. +>>>>>>> 8e51b9c (initial commit 2) +======= +## Por qué se puede vender como preview + +Esta versión ya permite explicar la idea de negocio al usuario final o a un cliente potencial porque presenta una experiencia realista y navegable. Aunque aún faltan ajustes de producto y una capa de datos más robusta, la aplicación ya comunica claramente el valor principal: ayudar a visualizar rutas, horarios y eventos de recolección desde una interfaz móvil práctica. + +La propuesta se puede presentar como una preview comercial porque: + +- demuestra el flujo principal de usuario de punta a punta; +- usa datos locales para simular operación real; +- ya integra pantallas funcionales y una navegación completa; +- deja abierta la migración a una base de datos más fluida y escalable. + +## Pruebas y validación + +Durante el desarrollo se realizaron pruebas con JSON locales en `assets/json/` para simular la base de datos y validar la estructura de la app. Esto permitió probar login, registro, direcciones, rutas, calendario y guía de rutas sin depender de servicios externos. + +La idea de base de datos se mantiene pensada de forma más fluida para una siguiente etapa, donde los JSON pueden ser reemplazados por una fuente centralizada, sincronizada y más dinámica. + +## Tecnologías usadas + +- Flutter / Dart +- `flutter_map` +- `geolocator` +- `latlong2` +- `table_calendar` +- `shared_preferences` + +## Estructura funcional + +- `lib/screens/auth_screen.dart`: login y registro. +- `lib/screens/address_screen.dart`: captura de dirección local. +- `lib/screens/dashboard_screen.dart`: mapa, calendario, avisos y guía de rutas. +- `lib/services/local_seed_repository.dart`: carga de los JSON locales. +- `assets/json/`: datos de prueba que actúan como preview de base de datos. + +## Estado actual + +El proyecto ya funciona como una demo presentable y estable para mostrar la propuesta. Aun así, se considera una base en evolución: el siguiente paso natural es conectar una base de datos más flexible, reemplazar la simulación local por datos vivos y pulir algunos detalles de UX. + +## Cómo ejecutar + +```bash +flutter pub get +flutter run +``` + +## Nota final + +Este proyecto no pretende ser todavía el producto final, sino una preview sólida que demuestra la idea, la navegación y el valor de la solución. Es útil para presentaciones, validación temprana con usuarios y como base para una futura versión con backend y almacenamiento centralizado. +>>>>>>> c9e584a (Proyecto Flutter inicial) diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /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 0000000..be3943c --- /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 0000000..b686dc7 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,45 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.flutter_application_1" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.flutter_application_1" + // 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") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /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 0000000..f2daf87 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/flutter_application_1/MainActivity.kt b/android/app/src/main/kotlin/com/example/flutter_application_1/MainActivity.kt new file mode 100644 index 0000000..aa48e52 --- /dev/null +++ b/android/app/src/main/kotlin/com/example/flutter_application_1/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.flutter_application_1 + +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 0000000..f74085f --- /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 0000000..304732f --- /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 0000000..db77bb4 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 0000000..17987b7 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 0000000..09d4391 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 0000000..d5f1c8d 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 0000000..4d6372e 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 0000000..06952be --- /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 0000000..cb1ef88 --- /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 0000000..399f698 --- /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 0000000..dbee657 --- /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 0000000..e96108c --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2d428bf --- /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-9.1.0-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..c21f0c5 --- /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 "9.0.1" apply false + id("org.jetbrains.kotlin.android") version "2.3.20" apply false +} + +include(":app") diff --git a/assets/json/calendario.json b/assets/json/calendario.json new file mode 100644 index 0000000..2ae5e17 --- /dev/null +++ b/assets/json/calendario.json @@ -0,0 +1,44 @@ +[ + { + "date": "2026-05-23", + "title": "Camión de orgánico", + "description": "Este día pasa el camión de orgánico por la ruta asignada.", + "category": "organic" + }, + { + "date": "2026-05-24", + "title": "Camión de inorgánico", + "description": "Este día pasará el camión inorgánico.", + "category": "inorganic" + }, + { + "date": "2026-05-25", + "title": "Evento vecinal", + "description": "El camión no puede pasar ese día por evento en la colonia.", + "category": "blocked" + }, + { + "date": "2026-05-27", + "title": "Ruta especial", + "description": "Día con recolección especial para residuos voluminosos.", + "category": "special" + }, + { + "date": "2026-05-29", + "title": "Recolección de orgánico", + "description": "El servicio orgánico pasa a partir de las 07:00.", + "category": "organic" + }, + { + "date": "2026-05-31", + "title": "Recolección de inorgánico", + "description": "El servicio inorgánico pasa a partir de las 08:00.", + "category": "inorganic" + }, + { + "date": "2026-06-02", + "title": "Bloqueo por evento", + "description": "No hay paso del camión por evento municipal.", + "category": "blocked" + } +] diff --git a/assets/json/colonias-rutas.json b/assets/json/colonias-rutas.json new file mode 100644 index 0000000..8d98999 --- /dev/null +++ b/assets/json/colonias-rutas.json @@ -0,0 +1,9 @@ +[ + { "colonia": "Zona Centro", "routeId": "RUTA-01", "horarioEstimado": "Matutino (06:30 - 07:15)" }, + { "colonia": "Las Arboledas", "routeId": "RUTA-01", "horarioEstimado": "Matutino (07:00 - 07:30)" }, + { "colonia": "Trojes", "routeId": "RUTA-13", "horarioEstimado": "Matutino (06:40 - 07:10)" }, + { "colonia": "San Juanico", "routeId": "RUTA-03", "horarioEstimado": "Matutino (06:45 - 07:15)" }, + { "colonia": "Los Olivos", "routeId": "RUTA-04", "horarioEstimado": "Matutino (07:00 - 07:40)" }, + { "colonia": "Rancho Seco", "routeId": "RUTA-05", "horarioEstimado": "Vespertino (14:15 - 15:00)" }, + { "colonia": "Las Insurgentes", "routeId": "RUTA-12", "horarioEstimado": "Matutino (06:35 - 07:10)" } +] diff --git a/assets/json/guia-rutas.json b/assets/json/guia-rutas.json new file mode 100644 index 0000000..6a6707f --- /dev/null +++ b/assets/json/guia-rutas.json @@ -0,0 +1,107 @@ +[ + { + "routeId": "RUTA-01", + "wasteType": "Orgánico", + "schedule": "06:30 - 07:15", + "days": ["Lunes", "Miércoles", "Viernes"], + "note": "Ruta base para zonas centro y arboledas." + }, + { + "routeId": "RUTA-02", + "wasteType": "Inorgánico", + "schedule": "07:15 - 08:00", + "days": ["Martes", "Jueves", "Sábado"], + "note": "Recolección de material no orgánico y reciclable." + }, + { + "routeId": "RUTA-03", + "wasteType": "Orgánico", + "schedule": "06:45 - 07:20", + "days": ["Lunes", "Miércoles", "Viernes"], + "note": "Cobertura para San Juanico y sectores cercanos." + }, + { + "routeId": "RUTA-04", + "wasteType": "Inorgánico", + "schedule": "07:00 - 07:40", + "days": ["Martes", "Jueves"], + "note": "Ruta de oriente con prioridad en residuos inorgánicos." + }, + { + "routeId": "RUTA-05", + "wasteType": "Orgánico", + "schedule": "14:15 - 15:00", + "days": ["Lunes", "Jueves"], + "note": "Turno vespertino para Rancho Seco y zonas similares." + }, + { + "routeId": "RUTA-06", + "wasteType": "Mixto", + "schedule": "07:00 - 08:00", + "days": ["Lunes", "Miércoles", "Viernes"], + "note": "Ruta extendida para zonas lejanas con recolección mixta." + }, + { + "routeId": "RUTA-07", + "wasteType": "Inorgánico", + "schedule": "08:00 - 08:45", + "days": ["Martes", "Jueves", "Sábado"], + "note": "Ciudad Industrial y corredores de comercio." + }, + { + "routeId": "RUTA-08", + "wasteType": "Orgánico", + "schedule": "06:40 - 07:25", + "days": ["Lunes", "Miércoles", "Viernes"], + "note": "Ruta universitaria y residencial con paso temprano." + }, + { + "routeId": "RUTA-09", + "wasteType": "Inorgánico", + "schedule": "07:30 - 08:10", + "days": ["Martes", "Jueves"], + "note": "Hospital y colonias cercanas con recolección inorgánica." + }, + { + "routeId": "RUTA-10", + "wasteType": "Orgánico", + "schedule": "06:50 - 07:35", + "days": ["Lunes", "Miércoles"], + "note": "Eje Juan Pablo II y zonas sur." + }, + { + "routeId": "RUTA-11", + "wasteType": "Mixto", + "schedule": "07:20 - 08:05", + "days": ["Martes", "Viernes"], + "note": "Zona de Oro con paso de ambos tipos por puntos especiales." + }, + { + "routeId": "RUTA-12", + "wasteType": "Inorgánico", + "schedule": "06:35 - 07:10", + "days": ["Martes", "Jueves"], + "note": "Las Insurgentes y calles aledañas." + }, + { + "routeId": "RUTA-13", + "wasteType": "Orgánico", + "schedule": "06:40 - 07:10", + "days": ["Lunes", "Miércoles", "Viernes"], + "note": "Trojes e Irrigación con salida temprana." + }, + { + "routeId": "RUTA-14", + "wasteType": "Inorgánico", + "schedule": "07:00 - 07:50", + "days": ["Martes", "Jueves"], + "note": "La Toscana con enfoque en inorgánico y reciclaje." + }, + { + "routeId": "RUTA-15", + "wasteType": "Orgánico", + "schedule": "07:15 - 07:55", + "days": ["Lunes", "Viernes"], + "note": "Camino a San José de Celaya, turno matutino." + } +] diff --git a/assets/json/notificaciones.json b/assets/json/notificaciones.json new file mode 100644 index 0000000..3f3114e --- /dev/null +++ b/assets/json/notificaciones.json @@ -0,0 +1,26 @@ +[ + { + "triggerEvent": "ROUTE_START", + "condition": "Cuando positionId cambia de 1 a 2", + "pushPayload": { + "title": "¡Ruta Iniciada!", + "body": "El camión recolector ha salido del Relleno Sanitario rumbo a tu sector. Asegúrate de tener listos tus residuos." + } + }, + { + "triggerEvent": "TRUCK_PROXIMITY", + "condition": "Cuando positionId llega a 4 (punto previo al destino)", + "pushPayload": { + "title": "Camión Cercano", + "body": "El camión está a menos de 15 minutos de tu domicilio. Es momento de sacar tus bolsas a la acera." + } + }, + { + "triggerEvent": "ROUTE_COMPLETED", + "condition": "Cuando positionId llega a 8 (retorno al basurero)", + "pushPayload": { + "title": "Servicio Finalizado", + "body": "El camión de tu sector ha concluido su jornada de recolección diaria." + } + } +] diff --git a/assets/json/perfiles.json b/assets/json/perfiles.json new file mode 100644 index 0000000..63297db --- /dev/null +++ b/assets/json/perfiles.json @@ -0,0 +1,6 @@ +[ + { "name": "Usuario Demo Centro", "email": "centro@demo.local", "password": "123456", "colonia": "Zona Centro", "routeId": "RUTA-01" }, + { "name": "Usuario Demo Arboledas", "email": "arboledas@demo.local", "password": "123456", "colonia": "Las Arboledas", "routeId": "RUTA-01" }, + { "name": "Usuario Demo Trojes", "email": "trojes@demo.local", "password": "123456", "colonia": "Trojes", "routeId": "RUTA-13" }, + { "name": "Usuario Demo Insurgentes", "email": "insurgentes@demo.local", "password": "123456", "colonia": "Las Insurgentes", "routeId": "RUTA-12" } +] diff --git a/assets/json/rutas.json b/assets/json/rutas.json new file mode 100644 index 0000000..06ea707 --- /dev/null +++ b/assets/json/rutas.json @@ -0,0 +1,242 @@ +[ + { + "routeId": "RUTA-01", + "name": "Zona Centro - Las Arboledas", + "truckId": 101, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:00:00Z" }, + { "positionId": 2, "lat": 20.5185, "lng": -100.8450, "speed": 45, "timestamp": "2026-05-22T06:12:00Z" }, + { "positionId": 3, "lat": 20.5215, "lng": -100.8142, "speed": 22, "timestamp": "2026-05-22T06:25:00Z" }, + { "positionId": 4, "lat": 20.5212, "lng": -100.8175, "speed": 15, "timestamp": "2026-05-22T06:38:00Z" }, + { "positionId": 5, "lat": 20.5210, "lng": -100.8210, "speed": 0, "timestamp": "2026-05-22T06:50:00Z" }, + { "positionId": 6, "lat": 20.5235, "lng": -100.8212, "speed": 18, "timestamp": "2026-05-22T07:05:00Z" }, + { "positionId": 7, "lat": 20.5260, "lng": -100.8215, "speed": 20, "timestamp": "2026-05-22T07:18:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 40, "timestamp": "2026-05-22T07:40:00Z" } + ] + }, + { + "routeId": "RUTA-02", + "name": "Sector Norte - Av. Tecnológico", + "truckId": 102, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:05:00Z" }, + { "positionId": 2, "lat": 20.5280, "lng": -100.8135, "speed": 38, "timestamp": "2026-05-22T06:18:00Z" }, + { "positionId": 3, "lat": 20.5410, "lng": -100.8130, "speed": 25, "timestamp": "2026-05-22T06:30:00Z" }, + { "positionId": 4, "lat": 20.5445, "lng": -100.8132, "speed": 12, "timestamp": "2026-05-22T06:45:00Z" }, + { "positionId": 5, "lat": 20.5480, "lng": -100.8135, "speed": 0, "timestamp": "2026-05-22T06:58:00Z" }, + { "positionId": 6, "lat": 20.5515, "lng": -100.8138, "speed": 15, "timestamp": "2026-05-22T07:10:00Z" }, + { "positionId": 7, "lat": 20.5540, "lng": -100.8110, "speed": 22, "timestamp": "2026-05-22T07:25:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 45, "timestamp": "2026-05-22T07:50:00Z" } + ] + }, + { + "routeId": "RUTA-03", + "name": "Sector Poniente - San Juanico", + "truckId": 103, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:10:00Z" }, + { "positionId": 2, "lat": 20.5250, "lng": -100.8510, "speed": 42, "timestamp": "2026-05-22T06:20:00Z" }, + { "positionId": 3, "lat": 20.5290, "lng": -100.8320, "speed": 20, "timestamp": "2026-05-22T06:35:00Z" }, + { "positionId": 4, "lat": 20.5315, "lng": -100.8355, "speed": 15, "timestamp": "2026-05-22T06:48:00Z" }, + { "positionId": 5, "lat": 20.5340, "lng": -100.8390, "speed": 0, "timestamp": "2026-05-22T07:00:00Z" }, + { "positionId": 6, "lat": 20.5362, "lng": -100.8425, "speed": 10, "timestamp": "2026-05-22T07:15:00Z" }, + { "positionId": 7, "lat": 20.5330, "lng": -100.8430, "speed": 18, "timestamp": "2026-05-22T07:28:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 35, "timestamp": "2026-05-22T07:45:00Z" } + ] + }, + { + "routeId": "RUTA-04", + "name": "Oriente - Los Olivos", + "truckId": 104, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:15:00Z" }, + { "positionId": 2, "lat": 20.5260, "lng": -100.8010, "speed": 45, "timestamp": "2026-05-22T06:30:00Z" }, + { "positionId": 3, "lat": 20.5295, "lng": -100.7890, "speed": 24, "timestamp": "2026-05-22T06:45:00Z" }, + { "positionId": 4, "lat": 20.5320, "lng": -100.7850, "speed": 12, "timestamp": "2026-05-22T06:58:00Z" }, + { "positionId": 5, "lat": 20.5350, "lng": -100.7790, "speed": 0, "timestamp": "2026-05-22T07:12:00Z" }, + { "positionId": 6, "lat": 20.5310, "lng": -100.7760, "speed": 15, "timestamp": "2026-05-22T07:25:00Z" }, + { "positionId": 7, "lat": 20.5270, "lng": -100.7820, "speed": 26, "timestamp": "2026-05-22T07:38:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 48, "timestamp": "2026-05-22T07:58:00Z" } + ] + }, + { + "routeId": "RUTA-05", + "name": "Sector Sur - Rancho Seco", + "truckId": 105, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:20:00Z" }, + { "positionId": 2, "lat": 20.5050, "lng": -100.8620, "speed": 35, "timestamp": "2026-05-22T06:32:00Z" }, + { "positionId": 3, "lat": 20.5020, "lng": -100.8350, "speed": 22, "timestamp": "2026-05-22T06:45:00Z" }, + { "positionId": 4, "lat": 20.4995, "lng": -100.8210, "speed": 14, "timestamp": "2026-05-22T06:58:00Z" }, + { "positionId": 5, "lat": 20.4970, "lng": -100.8150, "speed": 0, "timestamp": "2026-05-22T07:10:00Z" }, + { "positionId": 6, "lat": 20.5010, "lng": -100.8120, "speed": 16, "timestamp": "2026-05-22T07:22:00Z" }, + { "positionId": 7, "lat": 20.5060, "lng": -100.8160, "speed": 25, "timestamp": "2026-05-22T07:35:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 40, "timestamp": "2026-05-22T07:55:00Z" } + ] + }, + { + "routeId": "RUTA-06", + "name": "Norte Extremo - Rumbos de Roque", + "truckId": 106, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:00:00Z" }, + { "positionId": 2, "lat": 20.5380, "lng": -100.8380, "speed": 40, "timestamp": "2026-05-22T06:15:00Z" }, + { "positionId": 3, "lat": 20.5610, "lng": -100.8370, "speed": 30, "timestamp": "2026-05-22T06:30:00Z" }, + { "positionId": 4, "lat": 20.5750, "lng": -100.8360, "speed": 15, "timestamp": "2026-05-22T06:45:00Z" }, + { "positionId": 5, "lat": 20.5820, "lng": -100.8350, "speed": 0, "timestamp": "2026-05-22T07:00:00Z" }, + { "positionId": 6, "lat": 20.5780, "lng": -100.8310, "speed": 20, "timestamp": "2026-05-22T07:15:00Z" }, + { "positionId": 7, "lat": 20.5650, "lng": -100.8320, "speed": 28, "timestamp": "2026-05-22T07:30:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 45, "timestamp": "2026-05-22T07:55:00Z" } + ] + }, + { + "routeId": "RUTA-07", + "name": "Nororiente - Ciudad Industrial", + "truckId": 107, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:10:00Z" }, + { "positionId": 2, "lat": 20.5350, "lng": -100.8050, "speed": 44, "timestamp": "2026-05-22T06:24:00Z" }, + { "positionId": 3, "lat": 20.5450, "lng": -100.7950, "speed": 25, "timestamp": "2026-05-22T06:38:00Z" }, + { "positionId": 4, "lat": 20.5480, "lng": -100.7850, "speed": 18, "timestamp": "2026-05-22T06:52:00Z" }, + { "positionId": 5, "lat": 20.5510, "lng": -100.7750, "speed": 0, "timestamp": "2026-05-22T07:05:00Z" }, + { "positionId": 6, "lat": 20.5460, "lng": -100.7720, "speed": 12, "timestamp": "2026-05-22T07:18:00Z" }, + { "positionId": 7, "lat": 20.5390, "lng": -100.7820, "speed": 30, "timestamp": "2026-05-22T07:30:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 42, "timestamp": "2026-05-22T07:52:00Z" } + ] + }, + { + "routeId": "RUTA-08", + "name": "Suroriente - Universidad Latina", + "truckId": 108, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:15:00Z" }, + { "positionId": 2, "lat": 20.5180, "lng": -100.8310, "speed": 38, "timestamp": "2026-05-22T06:28:00Z" }, + { "positionId": 3, "lat": 20.5245, "lng": -100.7980, "speed": 30, "timestamp": "2026-05-22T06:42:00Z" }, + { "positionId": 4, "lat": 20.5210, "lng": -100.7995, "speed": 14, "timestamp": "2026-05-22T06:55:00Z" }, + { "positionId": 5, "lat": 20.5175, "lng": -100.8010, "speed": 0, "timestamp": "2026-05-22T07:08:00Z" }, + { "positionId": 6, "lat": 20.5140, "lng": -100.8030, "speed": 18, "timestamp": "2026-05-22T07:20:00Z" }, + { "positionId": 7, "lat": 20.5110, "lng": -100.8055, "speed": 22, "timestamp": "2026-05-22T07:32:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 40, "timestamp": "2026-05-22T07:54:00Z" } + ] + }, + { + "routeId": "RUTA-09", + "name": "Poniente - Hospital General", + "truckId": 109, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:02:00Z" }, + { "positionId": 2, "lat": 20.5210, "lng": -100.8650, "speed": 45, "timestamp": "2026-05-22T06:12:00Z" }, + { "positionId": 3, "lat": 20.5260, "lng": -100.8520, "speed": 26, "timestamp": "2026-05-22T06:24:00Z" }, + { "positionId": 4, "lat": 20.5275, "lng": -100.8490, "speed": 12, "timestamp": "2026-05-22T06:36:00Z" }, + { "positionId": 5, "lat": 20.5285, "lng": -100.8460, "speed": 0, "timestamp": "2026-05-22T06:48:00Z" }, + { "positionId": 6, "lat": 20.5250, "lng": -100.8470, "speed": 15, "timestamp": "2026-05-22T07:00:00Z" }, + { "positionId": 7, "lat": 20.5220, "lng": -100.8550, "speed": 32, "timestamp": "2026-05-22T07:12:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 44, "timestamp": "2026-05-22T07:30:00Z" } + ] + }, + { + "routeId": "RUTA-10", + "name": "Eje Juan Pablo II - Sede UG Sur", + "truckId": 110, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:22:00Z" }, + { "positionId": 2, "lat": 20.5015, "lng": -100.8520, "speed": 40, "timestamp": "2026-05-22T06:34:00Z" }, + { "positionId": 3, "lat": 20.4990, "lng": -100.8390, "speed": 28, "timestamp": "2026-05-22T06:46:00Z" }, + { "positionId": 4, "lat": 20.4950, "lng": -100.8320, "speed": 18, "timestamp": "2026-05-22T06:58:00Z" }, + { "positionId": 5, "lat": 20.4920, "lng": -100.8280, "speed": 0, "timestamp": "2026-05-22T07:10:00Z" }, + { "positionId": 6, "lat": 20.4945, "lng": -100.8240, "speed": 14, "timestamp": "2026-05-22T07:22:00Z" }, + { "positionId": 7, "lat": 20.4980, "lng": -100.8300, "speed": 30, "timestamp": "2026-05-22T07:34:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 38, "timestamp": "2026-05-22T07:52:00Z" } + ] + }, + { + "routeId": "RUTA-11", + "name": "Zona de Oro - Torres Landa", + "truckId": 111, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:04:00Z" }, + { "positionId": 2, "lat": 20.5240, "lng": -100.8350, "speed": 36, "timestamp": "2026-05-22T06:16:00Z" }, + { "positionId": 3, "lat": 20.5280, "lng": -100.8250, "speed": 22, "timestamp": "2026-05-22T06:29:00Z" }, + { "positionId": 4, "lat": 20.5295, "lng": -100.8210, "speed": 10, "timestamp": "2026-05-22T06:42:00Z" }, + { "positionId": 5, "lat": 20.5310, "lng": -100.8170, "speed": 0, "timestamp": "2026-05-22T06:55:00Z" }, + { "positionId": 6, "lat": 20.5290, "lng": -100.8140, "speed": 16, "timestamp": "2026-05-22T07:08:00Z" }, + { "positionId": 7, "lat": 20.5260, "lng": -100.8220, "speed": 28, "timestamp": "2026-05-22T07:21:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 42, "timestamp": "2026-05-22T07:42:00Z" } + ] + }, + { + "routeId": "RUTA-12", + "name": "Nororiente - Las Insurgentes", + "truckId": 112, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:08:00Z" }, + { "positionId": 2, "lat": 20.5280, "lng": -100.8080, "speed": 40, "timestamp": "2026-05-22T06:22:00Z" }, + { "positionId": 3, "lat": 20.5320, "lng": -100.7980, "speed": 24, "timestamp": "2026-05-22T06:35:00Z" }, + { "positionId": 4, "lat": 20.5340, "lng": -100.7940, "speed": 15, "timestamp": "2026-05-22T06:48:00Z" }, + { "positionId": 5, "lat": 20.5360, "lng": -100.7900, "speed": 0, "timestamp": "2026-05-22T07:00:00Z" }, + { "positionId": 6, "lat": 20.5310, "lng": -100.7920, "speed": 12, "timestamp": "2026-05-22T07:12:00Z" }, + { "positionId": 7, "lat": 20.5270, "lng": -100.8020, "speed": 26, "timestamp": "2026-05-22T07:25:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 44, "timestamp": "2026-05-22T07:48:00Z" } + ] + }, + { + "routeId": "RUTA-13", + "name": "Sector Norte - Trojes e Irrigación", + "truckId": 113, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:12:00Z" }, + { "positionId": 2, "lat": 20.5360, "lng": -100.8190, "speed": 35, "timestamp": "2026-05-22T06:26:00Z" }, + { "positionId": 3, "lat": 20.5420, "lng": -100.8080, "speed": 28, "timestamp": "2026-05-22T06:40:00Z" }, + { "positionId": 4, "lat": 20.5440, "lng": -100.8040, "speed": 14, "timestamp": "2026-05-22T06:54:00Z" }, + { "positionId": 5, "lat": 20.5460, "lng": -100.8000, "speed": 0, "timestamp": "2026-05-22T07:06:00Z" }, + { "positionId": 6, "lat": 20.5410, "lng": -100.8020, "speed": 18, "timestamp": "2026-05-22T07:18:00Z" }, + { "positionId": 7, "lat": 20.5370, "lng": -100.8120, "speed": 25, "timestamp": "2026-05-22T07:30:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 39, "timestamp": "2026-05-22T07:54:00Z" } + ] + }, + { + "routeId": "RUTA-14", + "name": "Sur Poniente - La Toscana", + "truckId": 114, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:16:00Z" }, + { "positionId": 2, "lat": 20.5150, "lng": -100.8580, "speed": 42, "timestamp": "2026-05-22T06:28:00Z" }, + { "positionId": 3, "lat": 20.5140, "lng": -100.8390, "speed": 26, "timestamp": "2026-05-22T06:41:00Z" }, + { "positionId": 4, "lat": 20.5125, "lng": -100.8310, "speed": 16, "timestamp": "2026-05-22T06:54:00Z" }, + { "positionId": 5, "lat": 20.5110, "lng": -100.8250, "speed": 0, "timestamp": "2026-05-22T07:06:00Z" }, + { "positionId": 6, "lat": 20.5135, "lng": -100.8280, "speed": 12, "timestamp": "2026-05-22T07:18:00Z" }, + { "positionId": 7, "lat": 20.5160, "lng": -100.8420, "speed": 32, "timestamp": "2026-05-22T07:30:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 45, "timestamp": "2026-05-22T07:51:00Z" } + ] + }, + { + "routeId": "RUTA-15", + "name": "Norponiente - Camino a San José de Celaya", + "truckId": 115, + "status": "EN_RUTA", + "positions": [ + { "positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "timestamp": "2026-05-22T06:18:00Z" }, + { "positionId": 2, "lat": 20.5320, "lng": -100.8590, "speed": 38, "timestamp": "2026-05-22T06:31:00Z" }, + { "positionId": 3, "lat": 20.5390, "lng": -100.8480, "speed": 24, "timestamp": "2026-05-22T06:44:00Z" }, + { "positionId": 4, "lat": 20.5420, "lng": -100.8440, "speed": 15, "timestamp": "2026-05-22T06:57:00Z" }, + { "positionId": 5, "lat": 20.5450, "lng": -100.8410, "speed": 0, "timestamp": "2026-05-22T07:09:00Z" }, + { "positionId": 6, "lat": 20.5410, "lng": -100.8430, "speed": 14, "timestamp": "2026-05-22T07:21:00Z" }, + { "positionId": 7, "lat": 20.5360, "lng": -100.8520, "speed": 28, "timestamp": "2026-05-22T07:33:00Z" }, + { "positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 41, "timestamp": "2026-05-22T07:54:00Z" } + ] + } +] diff --git a/backend/.env b/backend/.env new file mode 100644 index 0000000..3b3d333 --- /dev/null +++ b/backend/.env @@ -0,0 +1,4 @@ +DATABASE_URL=postgresql+psycopg://postgres:password@127.0.0.1:5432/hackaton +SECRET_KEY=change-this-in-production +ACCESS_TOKEN_EXPIRE_MINUTES=10080 +CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000 diff --git a/backend/.env.copy-paste.example b/backend/.env.copy-paste.example new file mode 100644 index 0000000..d4e056e --- /dev/null +++ b/backend/.env.copy-paste.example @@ -0,0 +1,5 @@ +# Copia este contenido a backend/.env y reemplaza los valores entre < > +DATABASE_URL=postgresql+psycopg://:@:5432/ +SECRET_KEY= +ACCESS_TOKEN_EXPIRE_MINUTES=10080 +CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000,http://:8000 diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..f07443e --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,4 @@ +DATABASE_URL=postgresql+psycopg://postgres:TU_PASSWORD@10.77.234.29:5432/hackaton +SECRET_KEY=pon-una-clave-larga-y-segura-aqui +ACCESS_TOKEN_EXPIRE_MINUTES=10080 +CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000,http://10.77.234.6:8000 diff --git a/backend/README.md b/backend/README.md new file mode 100644 index 0000000..975d09b --- /dev/null +++ b/backend/README.md @@ -0,0 +1,128 @@ +# Backend Python para Flutter + +Backend en Python con FastAPI para autenticar usuarios y guardar direcciones en PostgreSQL. No usa HTTPS; expone HTTP en el puerto 8000 por defecto. + +## Qué debes cambiar + +### 1. Configuración del backend +Crea el archivo `backend/.env` copiando `backend/.env.example` y reemplaza estos valores: + +```env +DATABASE_URL=postgresql+psycopg://postgres:TU_PASSWORD@10.77.234.29:5432/hackaton +SECRET_KEY=pon-una-clave-larga-y-segura-aqui +ACCESS_TOKEN_EXPIRE_MINUTES=10080 +CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000,http://10.77.234.6:8000 +``` + +### 2. Configuración de Flutter +En Flutter, la URL base del backend está en [lib/app_config.dart](../lib/app_config.dart). Debe apuntar al backend HTTP, por ejemplo: + +```dart +static const String apiBaseUrl = String.fromEnvironment( + 'API_BASE_URL', + defaultValue: 'http://10.77.234.6:8000', +); +``` + +No pongas la cadena `postgresql://...` en Flutter. Esa cadena solo va en el backend. + +## Variables que usa el backend + +- `DATABASE_URL`: conexión a PostgreSQL. +- `SECRET_KEY`: clave para firmar el token JWT. +- `ACCESS_TOKEN_EXPIRE_MINUTES`: tiempo de vida del token. +- `CORS_ORIGINS`: orígenes permitidos para la app Flutter o pruebas web. + +## Estructura de PostgreSQL + +El backend crea las tablas automáticamente al arrancar con `Base.metadata.create_all(...)`, pero si quieres crearlas manualmente, este es el esquema esperado. + +### Tabla `users` + +```sql +CREATE TABLE IF NOT EXISTS users ( + id SERIAL PRIMARY KEY, + name VARCHAR(120) NOT NULL, + email VARCHAR(255) NOT NULL UNIQUE, + password_hash VARCHAR(255) NOT NULL, + last_login_at TIMESTAMPTZ NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +``` + +### Tabla `addresses` + +```sql +CREATE TABLE IF NOT EXISTS addresses ( + id SERIAL PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + house_number VARCHAR(50) NOT NULL, + colonia VARCHAR(120) NOT NULL, + street VARCHAR(160) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +``` + +## Datos que se envían desde Flutter + +### Registro +Se envía al endpoint `POST /auth/register`: + +```json +{ + "name": "Juan Perez", + "email": "juan@mail.com", + "password": "123456" +} +``` + +### Inicio de sesión +Se envía al endpoint `POST /auth/login`: + +```json +{ + "email": "juan@mail.com", + "password": "123456" +} +``` + +### Dirección +Se envía al endpoint `POST /addresses` con token Bearer: + +```json +{ + "email": "juan@mail.com", + "houseNumber": "12A", + "colonia": "Centro", + "street": "Reforma" +} +``` + +## Endpoints disponibles + +- `POST /auth/register` +- `POST /auth/login` +- `GET /me` +- `POST /addresses` +- `GET /health` + +## Instalar y ejecutar + +```bash +cd backend +python -m venv .venv +.venv\Scripts\activate +pip install -r requirements.txt +uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 +``` + +## Cómo funciona la conexión + +1. Flutter llama a `http://IP_DEL_BACKEND:8000`. +2. El backend recibe login/registro y crea el token JWT. +3. El backend conecta a PostgreSQL usando `DATABASE_URL`. +4. Al guardar la dirección, el backend asocia la dirección al usuario autenticado. + +## Nota importante + +Si pruebas desde un celular físico, `10.0.2.2` no sirve para la API. Debes usar la IP real de la computadora donde corre el backend. diff --git a/backend/app/auth.py b/backend/app/auth.py new file mode 100644 index 0000000..be9e0ea --- /dev/null +++ b/backend/app/auth.py @@ -0,0 +1,22 @@ +from datetime import datetime, timedelta, timezone + +from jose import jwt +from passlib.context import CryptContext + +from .core.config import settings + +pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto') + + +def hash_password(password: str) -> str: + return pwd_context.hash(password) + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + return pwd_context.verify(plain_password, hashed_password) + + +def create_access_token(*, user_id: int, email: str) -> str: + expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes) + payload = {'sub': str(user_id), 'email': email, 'exp': expire} + return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm) diff --git a/backend/app/core/__init__.py b/backend/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/core/config.py b/backend/app/core/config.py new file mode 100644 index 0000000..7129c50 --- /dev/null +++ b/backend/app/core/config.py @@ -0,0 +1,25 @@ +from functools import lru_cache + +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8', extra='ignore') + + database_url: str = 'postgresql+psycopg://postgres:password@127.0.0.1:5432/hackaton' + secret_key: str = 'change-this-in-production' + algorithm: str = 'HS256' + access_token_expire_minutes: int = 60 * 24 * 7 + cors_origins: str = 'http://localhost:3000,http://10.0.2.2:3000' + + @property + def cors_origin_list(self) -> list[str]: + return [origin.strip() for origin in self.cors_origins.split(',') if origin.strip()] + + +@lru_cache +def get_settings() -> Settings: + return Settings() + + +settings = get_settings() diff --git a/backend/app/crud.py b/backend/app/crud.py new file mode 100644 index 0000000..c4dc5a6 --- /dev/null +++ b/backend/app/crud.py @@ -0,0 +1,56 @@ +from datetime import datetime, timezone + +from sqlalchemy import select +from sqlalchemy.orm import Session + +from .auth import hash_password, verify_password +from .models import Address, User +from .schemas import AddressCreate, UserCreate + + +def get_user_by_id(db: Session, user_id: int) -> User | None: + return db.get(User, user_id) + + +def get_user_by_email(db: Session, email: str) -> User | None: + statement = select(User).where(User.email == email) + return db.scalar(statement) + + +def create_user(db: Session, user_in: UserCreate) -> User: + user = User( + name=user_in.name, + email=user_in.email, + password_hash=hash_password(user_in.password), + ) + db.add(user) + db.commit() + db.refresh(user) + return user + + +def authenticate_user(db: Session, email: str, password: str) -> User | None: + user = get_user_by_email(db, email) + if user is None: + return None + if not verify_password(password, user.password_hash): + return None + + user.last_login_at = datetime.now(timezone.utc) + db.add(user) + db.commit() + db.refresh(user) + return user + + +def create_address(db: Session, user: User, address_in: AddressCreate) -> Address: + address = Address( + user_id=user.id, + house_number=address_in.house_number, + colonia=address_in.colonia, + street=address_in.street, + ) + db.add(address) + db.commit() + db.refresh(address) + return address diff --git a/backend/app/db/__init__.py b/backend/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/db/session.py b/backend/app/db/session.py new file mode 100644 index 0000000..9b5137c --- /dev/null +++ b/backend/app/db/session.py @@ -0,0 +1,22 @@ +from collections.abc import Generator + +from sqlalchemy import create_engine +from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker + +from ..core.config import settings + + +class Base(DeclarativeBase): + pass + + +engine = create_engine(settings.database_url, pool_pre_ping=True) +SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False) + + +def get_db() -> Generator[Session, None, None]: + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/backend/app/dependencies.py b/backend/app/dependencies.py new file mode 100644 index 0000000..be590fd --- /dev/null +++ b/backend/app/dependencies.py @@ -0,0 +1,31 @@ +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from sqlalchemy.orm import Session + +from .core.config import settings +from .crud import get_user_by_id +from .db.session import get_db +from .models import User + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/auth/login') + + +def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User: + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail='Token inválido o expirado', + headers={'WWW-Authenticate': 'Bearer'}, + ) + try: + payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) + user_id = payload.get('sub') + if user_id is None: + raise credentials_exception + except JWTError as exc: + raise credentials_exception from exc + + user = get_user_by_id(db, int(user_id)) + if user is None: + raise credentials_exception + return user diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000..0446077 --- /dev/null +++ b/backend/app/main.py @@ -0,0 +1,79 @@ +from fastapi import Depends, FastAPI, HTTPException, status +from fastapi.middleware.cors import CORSMiddleware +from sqlalchemy.orm import Session + +from .auth import create_access_token +from .core.config import settings +from .crud import authenticate_user, create_address, create_user, get_user_by_email +from .db.session import Base, engine, get_db +from .dependencies import get_current_user +from .models import Address, User +from .schemas import AddressCreate, AddressRead, TokenResponse, UserCreate, UserLogin, UserRead + +app = FastAPI(title='Flutter Auth API', version='1.0.0') + +app.add_middleware( + CORSMiddleware, + allow_origins=settings.cors_origin_list, + allow_credentials=True, + allow_methods=['*'], + allow_headers=['*'], +) + + +@app.on_event('startup') +def on_startup() -> None: + Base.metadata.create_all(bind=engine) + + +@app.get('/health') +def health_check() -> dict[str, str]: + return {'status': 'ok'} + + +@app.post('/auth/register', response_model=TokenResponse, status_code=status.HTTP_201_CREATED) +def register(payload: UserCreate, db: Session = Depends(get_db)) -> TokenResponse: + existing_user = get_user_by_email(db, payload.email) + if existing_user is not None: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Ya existe un usuario con ese correo') + + user = create_user(db, payload) + token = create_access_token(user_id=user.id, email=user.email) + return TokenResponse(token=token, user=UserRead.model_validate(user)) + + +@app.post('/auth/login', response_model=TokenResponse) +def login(payload: UserLogin, db: Session = Depends(get_db)) -> TokenResponse: + user = authenticate_user(db, payload.email, payload.password) + if user is None: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Correo o contraseña inválidos') + + token = create_access_token(user_id=user.id, email=user.email) + return TokenResponse(token=token, user=UserRead.model_validate(user)) + + +@app.get('/me', response_model=UserRead) +def read_me(current_user: User = Depends(get_current_user)) -> UserRead: + return UserRead.model_validate(current_user) + + +@app.post('/addresses', response_model=AddressRead, status_code=status.HTTP_201_CREATED) +def save_address( + payload: AddressCreate, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +) -> AddressRead: + if payload.email is not None and payload.email != current_user.email: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='El correo no coincide con el usuario autenticado') + + address = create_address(db, current_user, payload) + return AddressRead.model_validate(address) + + +@app.get('/addresses/me', response_model=list[AddressRead]) +def read_my_addresses( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +) -> list[AddressRead]: + addresses = sorted(current_user.addresses, key=lambda address: address.created_at, reverse=True) + return [AddressRead.model_validate(address) for address in addresses] diff --git a/backend/app/models.py b/backend/app/models.py new file mode 100644 index 0000000..b0774dd --- /dev/null +++ b/backend/app/models.py @@ -0,0 +1,32 @@ +from datetime import datetime + +from sqlalchemy import DateTime, ForeignKey, Integer, String, func +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from .db.session import Base + + +class User(Base): + __tablename__ = 'users' + + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + name: Mapped[str] = mapped_column(String(120), nullable=False) + email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False) + password_hash: Mapped[str] = mapped_column(String(255), nullable=False) + last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False) + + addresses: Mapped[list['Address']] = relationship(back_populates='user', cascade='all, delete-orphan') + + +class Address(Base): + __tablename__ = 'addresses' + + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + user_id: Mapped[int] = mapped_column(ForeignKey('users.id', ondelete='CASCADE'), index=True, nullable=False) + house_number: Mapped[str] = mapped_column(String(50), nullable=False) + colonia: Mapped[str] = mapped_column(String(120), nullable=False) + street: Mapped[str] = mapped_column(String(160), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False) + + user: Mapped['User'] = relationship(back_populates='addresses') diff --git a/backend/app/schemas.py b/backend/app/schemas.py new file mode 100644 index 0000000..f77e257 --- /dev/null +++ b/backend/app/schemas.py @@ -0,0 +1,50 @@ +from datetime import datetime + +from pydantic import BaseModel, ConfigDict, EmailStr, Field + + +class UserBase(BaseModel): + name: str + email: EmailStr + + +class UserCreate(UserBase): + password: str + + +class UserLogin(BaseModel): + email: EmailStr + password: str + + +class UserRead(UserBase): + model_config = ConfigDict(from_attributes=True) + + id: int + last_login_at: datetime | None = None + created_at: datetime + + +class TokenResponse(BaseModel): + token: str + user: UserRead + + +class AddressCreate(BaseModel): + model_config = ConfigDict(populate_by_name=True) + + house_number: str = Field(alias='houseNumber') + colonia: str + street: str + email: EmailStr | None = None + + +class AddressRead(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + house_number: str + colonia: str + street: str + user_id: int + created_at: datetime diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..9842d1e --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,9 @@ +fastapi==0.115.0 +uvicorn[standard]==0.32.0 +SQLAlchemy==2.0.36 +psycopg[binary]==3.2.3 +pydantic-settings==2.6.0 +python-jose[cryptography]==3.3.0 +passlib[bcrypt]==1.7.4 +python-multipart==0.0.12 +email-validator==2.2.0 diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /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 0000000..391a902 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /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 0000000..592ceee --- /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 0000000..8988472 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,644 @@ +// !$*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 */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 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 = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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 */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + 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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift 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.example.flutterApplication1; + 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.example.flutterApplication1.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.example.flutterApplication1.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.example.flutterApplication1.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.example.flutterApplication1; + 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.example.flutterApplication1; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency 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 0000000..919434a --- /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 0000000..18d9810 --- /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 0000000..f9b0d7c --- /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 0000000..c3fedb2 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /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 0000000..18d9810 --- /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 0000000..f9b0d7c --- /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 0000000..c30b367 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} 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 0000000..d36b1fa --- /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 0000000..dc9ada4 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 0000000..7353c41 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 0000000..797d452 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 0000000..6ed2d93 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 0000000..4cd7b00 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 0000000..fe73094 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 0000000..321773c 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 0000000..797d452 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 0000000..502f463 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 0000000..0ec3034 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 0000000..0ec3034 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 0000000..e9f5fea 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 0000000..84ac32a 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 0000000..8953cba 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 0000000..0467bf1 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 0000000..0bedcf2 --- /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 0000000..9da19ea 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 0000000..9da19ea 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 0000000..9da19ea 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 0000000..89c2725 --- /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 0000000..f2e259c --- /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 0000000..f3c2851 --- /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 0000000..5323135 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Flutter Application 1 + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + flutter_application_1 + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /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/app.dart b/lib/app.dart new file mode 100644 index 0000000..c88c7c5 --- /dev/null +++ b/lib/app.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; + +import 'screens/auth_screen.dart'; +import 'services/address_repository.dart'; +import 'services/auth_repository.dart'; + +class MyApp extends StatelessWidget { + const MyApp({ + super.key, + AuthRepository? authRepository, + AddressRepository? addressRepository, + this.enableLiveFeatures = true, + }) : _authRepository = authRepository ?? const LocalAuthRepository(), + _addressRepository = addressRepository ?? const LocalAddressRepository(); + + final AuthRepository _authRepository; + final AddressRepository _addressRepository; + final bool enableLiveFeatures; + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'Acceso', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF0F766E)), + useMaterial3: true, + ), + home: AuthBootstrap( + authRepository: _authRepository, + addressRepository: _addressRepository, + enableLiveFeatures: enableLiveFeatures, + ), + ); + } +} + +class AuthBootstrap extends StatelessWidget { + const AuthBootstrap({ + super.key, + required this.authRepository, + required this.addressRepository, + this.enableLiveFeatures = true, + }); + + final AuthRepository authRepository; + final AddressRepository addressRepository; + final bool enableLiveFeatures; + + @override + Widget build(BuildContext context) { + return AuthScreen( + authRepository: authRepository, + addressRepository: addressRepository, + enableLiveFeatures: enableLiveFeatures, + ); + } +} diff --git a/lib/app_config.dart b/lib/app_config.dart new file mode 100644 index 0000000..598d6ab --- /dev/null +++ b/lib/app_config.dart @@ -0,0 +1,4 @@ +class AppConfig { + static const String appName = 'Acceso Local'; + static const bool useLocalDataOnly = true; +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..7773b62 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,9 @@ +export 'app.dart'; + +import 'package:flutter/material.dart'; + +import 'app.dart'; + +void main() { + runApp(const MyApp()); +} diff --git a/lib/models/address_entry.dart b/lib/models/address_entry.dart new file mode 100644 index 0000000..2c8ef2b --- /dev/null +++ b/lib/models/address_entry.dart @@ -0,0 +1,19 @@ +class AddressEntry { + const AddressEntry({ + required this.houseNumber, + required this.colonia, + required this.street, + }); + + final String houseNumber; + final String colonia; + final String street; + + Map toJson() { + return { + 'houseNumber': houseNumber, + 'colonia': colonia, + 'street': street, + }; + } +} \ No newline at end of file diff --git a/lib/models/address_record.dart b/lib/models/address_record.dart new file mode 100644 index 0000000..abf1518 --- /dev/null +++ b/lib/models/address_record.dart @@ -0,0 +1,22 @@ +class AddressRecord { + const AddressRecord({ + required this.id, + required this.houseNumber, + required this.colonia, + required this.street, + }); + + final int id; + final String houseNumber; + final String colonia; + final String street; + + factory AddressRecord.fromJson(Map json) { + return AddressRecord( + id: (json['id'] as num).toInt(), + houseNumber: json['house_number']?.toString() ?? json['houseNumber']?.toString() ?? '', + colonia: json['colonia']?.toString() ?? '', + street: json['street']?.toString() ?? '', + ); + } +} \ No newline at end of file diff --git a/lib/models/auth_session.dart b/lib/models/auth_session.dart new file mode 100644 index 0000000..462ed3f --- /dev/null +++ b/lib/models/auth_session.dart @@ -0,0 +1,11 @@ +class AuthSession { + const AuthSession({ + required this.token, + required this.email, + required this.displayName, + }); + + final String token; + final String email; + final String displayName; +} \ No newline at end of file diff --git a/lib/models/calendar_event_entry.dart b/lib/models/calendar_event_entry.dart new file mode 100644 index 0000000..a5f314a --- /dev/null +++ b/lib/models/calendar_event_entry.dart @@ -0,0 +1,22 @@ +class CalendarEventEntry { + const CalendarEventEntry({ + required this.date, + required this.title, + required this.description, + required this.category, + }); + + final DateTime date; + final String title; + final String description; + final String category; + + factory CalendarEventEntry.fromJson(Map json) { + return CalendarEventEntry( + date: DateTime.parse(json['date'].toString()), + title: json['title'].toString(), + description: json['description'].toString(), + category: json['category'].toString(), + ); + } +} diff --git a/lib/models/colony_route.dart b/lib/models/colony_route.dart new file mode 100644 index 0000000..43a3d3f --- /dev/null +++ b/lib/models/colony_route.dart @@ -0,0 +1,19 @@ +class ColonyRoute { + const ColonyRoute({ + required this.colonia, + required this.routeId, + required this.horarioEstimado, + }); + + final String colonia; + final String routeId; + final String horarioEstimado; + + factory ColonyRoute.fromJson(Map json) { + return ColonyRoute( + colonia: json['colonia'].toString(), + routeId: json['routeId'].toString(), + horarioEstimado: json['horarioEstimado'].toString(), + ); + } +} diff --git a/lib/models/demo_profile.dart b/lib/models/demo_profile.dart new file mode 100644 index 0000000..e84e5d6 --- /dev/null +++ b/lib/models/demo_profile.dart @@ -0,0 +1,25 @@ +class DemoProfile { + const DemoProfile({ + required this.name, + required this.email, + required this.password, + required this.colonia, + required this.routeId, + }); + + final String name; + final String email; + final String password; + final String colonia; + final String routeId; + + factory DemoProfile.fromJson(Map json) { + return DemoProfile( + name: json['name'].toString(), + email: json['email'].toString(), + password: json['password'].toString(), + colonia: json['colonia'].toString(), + routeId: json['routeId'].toString(), + ); + } +} diff --git a/lib/models/route_guide_entry.dart b/lib/models/route_guide_entry.dart new file mode 100644 index 0000000..477620e --- /dev/null +++ b/lib/models/route_guide_entry.dart @@ -0,0 +1,30 @@ +class RouteGuideEntry { + const RouteGuideEntry({ + required this.routeId, + required this.wasteType, + required this.schedule, + required this.days, + required this.note, + }); + + final String routeId; + final String wasteType; + final String schedule; + final List days; + final String note; + + factory RouteGuideEntry.fromJson(Map json) { + final daysJson = json['days']; + final days = daysJson is List + ? daysJson.map((day) => day.toString()).toList(growable: false) + : []; + + return RouteGuideEntry( + routeId: json['routeId'].toString(), + wasteType: json['wasteType'].toString(), + schedule: json['schedule'].toString(), + days: days, + note: json['note'].toString(), + ); + } +} diff --git a/lib/models/route_notification.dart b/lib/models/route_notification.dart new file mode 100644 index 0000000..a8ff73d --- /dev/null +++ b/lib/models/route_notification.dart @@ -0,0 +1,26 @@ +class RouteNotification { + const RouteNotification({ + required this.triggerEvent, + required this.condition, + required this.title, + required this.body, + }); + + final String triggerEvent; + final String condition; + final String title; + final String body; + + factory RouteNotification.fromJson(Map json) { + final payload = json['pushPayload'] is Map + ? json['pushPayload'] as Map + : {}; + + return RouteNotification( + triggerEvent: json['triggerEvent'].toString(), + condition: json['condition'].toString(), + title: payload['title']?.toString() ?? '', + body: payload['body']?.toString() ?? '', + ); + } +} diff --git a/lib/models/route_position.dart b/lib/models/route_position.dart new file mode 100644 index 0000000..5eda9e1 --- /dev/null +++ b/lib/models/route_position.dart @@ -0,0 +1,25 @@ +class RoutePosition { + const RoutePosition({ + required this.positionId, + required this.lat, + required this.lng, + required this.speed, + required this.timestamp, + }); + + final int positionId; + final double lat; + final double lng; + final double speed; + final DateTime timestamp; + + factory RoutePosition.fromJson(Map json) { + return RoutePosition( + positionId: (json['positionId'] as num).toInt(), + lat: (json['lat'] as num).toDouble(), + lng: (json['lng'] as num).toDouble(), + speed: (json['speed'] as num).toDouble(), + timestamp: DateTime.parse(json['timestamp'].toString()), + ); + } +} diff --git a/lib/models/truck_route.dart b/lib/models/truck_route.dart new file mode 100644 index 0000000..9840ec7 --- /dev/null +++ b/lib/models/truck_route.dart @@ -0,0 +1,35 @@ +import 'route_position.dart'; + +class TruckRoute { + const TruckRoute({ + required this.routeId, + required this.name, + required this.truckId, + required this.status, + required this.positions, + }); + + final String routeId; + final String name; + final int truckId; + final String status; + final List positions; + + factory TruckRoute.fromJson(Map json) { + final positionsJson = json['positions']; + final positions = positionsJson is List + ? positionsJson + .whereType>() + .map(RoutePosition.fromJson) + .toList(growable: false) + : []; + + return TruckRoute( + routeId: json['routeId'].toString(), + name: json['name'].toString(), + truckId: (json['truckId'] as num).toInt(), + status: json['status'].toString(), + positions: positions, + ); + } +} diff --git a/lib/screens/address_screen.dart b/lib/screens/address_screen.dart new file mode 100644 index 0000000..8caf4cd --- /dev/null +++ b/lib/screens/address_screen.dart @@ -0,0 +1,263 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../models/address_entry.dart'; +import '../models/auth_session.dart'; +import '../services/auth_repository.dart'; +import '../services/address_repository.dart'; +import 'dashboard_screen.dart'; + +final RegExp _lettersOnly = RegExp(r"[a-zA-ZáéíóúÁÉÍÓÚñÑüÜ\s]"); +final RegExp _digitsOnly = RegExp(r'[0-9]'); + +class AddressScreen extends StatefulWidget { + const AddressScreen({ + super.key, + required this.authRepository, + required this.addressRepository, + required this.session, + this.enableLiveFeatures = true, + }); + + final AuthRepository authRepository; + final AddressRepository addressRepository; + final AuthSession session; + final bool enableLiveFeatures; + + @override + State createState() => _AddressScreenState(); +} + +class _AddressScreenState extends State { + final GlobalKey _formKey = GlobalKey(); + final TextEditingController _houseNumberController = TextEditingController(); + final TextEditingController _coloniaController = TextEditingController(); + final TextEditingController _streetController = TextEditingController(); + + bool _isSaving = false; + String? _errorMessage; + + @override + void dispose() { + _houseNumberController.dispose(); + _coloniaController.dispose(); + _streetController.dispose(); + super.dispose(); + } + + Future _saveAddress() async { + if (!(_formKey.currentState?.validate() ?? false)) { + setState(() { + _errorMessage = 'Respete los campos'; + }); + return; + } + + setState(() { + _isSaving = true; + _errorMessage = null; + }); + + try { + await widget.addressRepository.saveAddress( + session: widget.session, + address: AddressEntry( + houseNumber: _houseNumberController.text.trim(), + colonia: _coloniaController.text.trim(), + street: _streetController.text.trim(), + ), + ); + + if (!mounted) { + return; + } + + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute( + builder: (_) => DashboardScreen( + authRepository: widget.authRepository, + addressRepository: widget.addressRepository, + session: widget.session, + savedAddress: AddressEntry( + houseNumber: _houseNumberController.text.trim(), + colonia: _coloniaController.text.trim(), + street: _streetController.text.trim(), + ), + enableLiveFeatures: widget.enableLiveFeatures, + ), + ), + (route) => false, + ); + } on AddressException catch (error) { + if (!mounted) { + return; + } + setState(() { + _errorMessage = error.message; + }); + } catch (_) { + if (!mounted) { + return; + } + setState(() { + _errorMessage = 'No se pudo guardar la dirección. Revisa los datos locales.'; + }); + } finally { + if (mounted) { + setState(() { + _isSaving = false; + }); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [Color(0xFFF8FAFC), Color(0xFFE2E8F0), Color(0xFFCCFBF1)], + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + ), + ), + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(20), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520), + child: Card( + elevation: 12, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + 'Dirección', + style: TextStyle(fontSize: 30, fontWeight: FontWeight.w800), + ), + const SizedBox(height: 8), + Text( + 'Ingresa la dirección de tu casa. La app la guardará de forma local para usarla en el tablero.', + style: TextStyle(color: Colors.grey.shade700, height: 1.4), + ), + const SizedBox(height: 20), + if (_errorMessage != null) ...[ + _AddressStatusBanner(message: _errorMessage!), + const SizedBox(height: 16), + ], + Form( + key: _formKey, + child: Column( + children: [ + TextFormField( + controller: _houseNumberController, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.allow(_digitsOnly)], + decoration: const InputDecoration( + labelText: 'Número de casa', + prefixIcon: Icon(Icons.home_outlined), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Respete los campos'; + } + return null; + }, + ), + const SizedBox(height: 16), + TextFormField( + controller: _coloniaController, + keyboardType: TextInputType.name, + textCapitalization: TextCapitalization.words, + inputFormatters: [FilteringTextInputFormatter.allow(_lettersOnly)], + decoration: const InputDecoration( + labelText: 'Colonia', + prefixIcon: Icon(Icons.location_city_outlined), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Respete los campos'; + } + return null; + }, + ), + const SizedBox(height: 16), + TextFormField( + controller: _streetController, + keyboardType: TextInputType.name, + textCapitalization: TextCapitalization.words, + inputFormatters: [FilteringTextInputFormatter.allow(_lettersOnly)], + decoration: const InputDecoration( + labelText: 'Calle', + prefixIcon: Icon(Icons.signpost_outlined), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Respete los campos'; + } + return null; + }, + ), + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + height: 52, + child: FilledButton( + onPressed: _isSaving ? null : _saveAddress, + child: _isSaving + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white), + ) + : const Text('Guardar dirección'), + ), + ), + const SizedBox(height: 12), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ), + ); + } +} + +class _AddressStatusBanner extends StatelessWidget { + const _AddressStatusBanner({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFFFEE2E2), + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFFCA5A5)), + ), + child: Text( + message, + style: const TextStyle(color: Color(0xFF991B1B), height: 1.35), + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/auth_screen.dart b/lib/screens/auth_screen.dart new file mode 100644 index 0000000..7816b7b --- /dev/null +++ b/lib/screens/auth_screen.dart @@ -0,0 +1,563 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../models/demo_profile.dart'; +import '../models/auth_session.dart'; +import '../services/address_repository.dart'; +import '../services/auth_repository.dart'; +import '../services/local_seed_repository.dart'; +import 'address_screen.dart'; + +final RegExp _lettersOnly = RegExp(r"[a-zA-ZáéíóúÁÉÍÓÚñÑüÜ\s]"); +final RegExp _addressText = RegExp(r"[a-zA-Z0-9áéíóúÁÉÍÓÚñÑüÜ#\-\s]"); +final RegExp _emailChars = RegExp(r"[a-zA-Z0-9@._+\-]"); + +class AuthScreen extends StatefulWidget { + const AuthScreen({ + super.key, + required this.authRepository, + required this.addressRepository, + this.enableLiveFeatures = true, + }); + + final AuthRepository authRepository; + final AddressRepository addressRepository; + final bool enableLiveFeatures; + + @override + State createState() => _AuthScreenState(); +} + +class _AuthScreenState extends State { + final GlobalKey _loginFormKey = GlobalKey(); + final GlobalKey _registerFormKey = GlobalKey(); + final TextEditingController _loginEmailController = TextEditingController(); + final TextEditingController _loginPasswordController = TextEditingController(); + final TextEditingController _registerNameController = TextEditingController(); + final TextEditingController _registerEmailController = TextEditingController(); + final TextEditingController _registerPasswordController = TextEditingController(); + final TextEditingController _registerConfirmPasswordController = TextEditingController(); + + bool _isLoading = false; + String? _errorMessage; + LocalSeedData? _seedData; + bool _loadingSeedData = true; + + @override + void initState() { + super.initState(); + _loadSeedData(); + } + + @override + void dispose() { + _loginEmailController.dispose(); + _loginPasswordController.dispose(); + _registerNameController.dispose(); + _registerEmailController.dispose(); + _registerPasswordController.dispose(); + _registerConfirmPasswordController.dispose(); + super.dispose(); + } + + Future _loadSeedData() async { + final seedData = await LocalSeedRepository.instance.load(); + if (!mounted) { + return; + } + + setState(() { + _seedData = seedData; + _loadingSeedData = false; + }); + } + + void _fillDemoProfile(DemoProfile profile) { + _loginEmailController.text = profile.email; + _loginPasswordController.text = profile.password; + _registerNameController.text = profile.name; + _registerEmailController.text = profile.email; + _registerPasswordController.text = profile.password; + _registerConfirmPasswordController.text = profile.password; + } + + Future _useDemoProfile(DemoProfile profile) async { + _fillDemoProfile(profile); + await _submit(() { + return widget.authRepository.signIn( + email: profile.email, + password: profile.password, + ); + }); + } + + Future _signIn() async { + if (!(_loginFormKey.currentState?.validate() ?? false)) { + setState(() { + _errorMessage = 'Respete los campos'; + }); + return; + } + + await _submit(() { + return widget.authRepository.signIn( + email: _loginEmailController.text.trim(), + password: _loginPasswordController.text, + ); + }); + } + + Future _signUp() async { + if (!(_registerFormKey.currentState?.validate() ?? false)) { + setState(() { + _errorMessage = 'Respete los campos'; + }); + return; + } + + await _submit(() { + return widget.authRepository.signUp( + name: _registerNameController.text.trim(), + email: _registerEmailController.text.trim(), + password: _registerPasswordController.text, + ); + }); + } + + Future _submit(Future Function() action) async { + setState(() { + _isLoading = true; + _errorMessage = null; + }); + + try { + final session = await action(); + if (!mounted) { + return; + } + Navigator.of(context).pushReplacement( + MaterialPageRoute( + builder: (_) => AddressScreen( + authRepository: widget.authRepository, + addressRepository: widget.addressRepository, + session: session, + enableLiveFeatures: widget.enableLiveFeatures, + ), + ), + ); + } on AuthException catch (error) { + if (!mounted) { + return; + } + setState(() { + _errorMessage = error.message; + }); + } catch (_) { + if (!mounted) { + return; + } + setState(() { + _errorMessage = 'No se pudo completar la operación. Revisa los datos locales y vuelve a intentar.'; + }); + } finally { + if (mounted) { + setState(() { + _isLoading = false; + }); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [Color(0xFF06141B), Color(0xFF0F766E), Color(0xFFE2E8F0)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + ), + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(20), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 440), + child: Card( + elevation: 18, + color: Colors.white.withValues(alpha: 0.94), + shadowColor: Colors.black26, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: DefaultTabController( + length: 2, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 72, + height: 72, + decoration: BoxDecoration( + color: const Color(0xFF0F766E).withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(20), + ), + child: const Icon(Icons.lock_outline, size: 36, color: Color(0xFF0F766E)), + ), + const SizedBox(height: 20), + const Text( + 'Bienvenido', + style: TextStyle(fontSize: 30, fontWeight: FontWeight.w800), + ), + const SizedBox(height: 8), + Text( + 'Inicia sesión o crea una cuenta para continuar. Luego irás a la pantalla Dirección.', + style: TextStyle(color: Colors.grey.shade700, height: 1.4), + ), + const SizedBox(height: 20), + if (!_loadingSeedData && _seedData != null && _seedData!.demoProfiles.isNotEmpty) ...[ + _DemoProfilesSection( + profiles: _seedData!.demoProfiles, + onProfileSelected: _useDemoProfile, + ), + const SizedBox(height: 16), + ], + Container( + decoration: BoxDecoration( + color: const Color(0xFFF1F5F9), + borderRadius: BorderRadius.circular(16), + ), + child: TabBar( + onTap: (_) { + setState(() { + _errorMessage = null; + }); + }, + indicatorSize: TabBarIndicatorSize.tab, + dividerColor: Colors.transparent, + indicator: BoxDecoration( + color: const Color(0xFF0F766E), + borderRadius: BorderRadius.circular(16), + ), + labelColor: Colors.white, + unselectedLabelColor: Colors.grey.shade700, + tabs: const [ + Tab(text: 'Entrar'), + Tab(text: 'Crear cuenta'), + ], + ), + ), + const SizedBox(height: 20), + if (_errorMessage != null) ...[ + _AuthStatusBanner(message: _errorMessage!), + const SizedBox(height: 16), + ], + SizedBox( + height: 200, + child: TabBarView( + children: [ + _LoginForm( + formKey: _loginFormKey, + emailController: _loginEmailController, + passwordController: _loginPasswordController, + onSubmit: _signIn, + isLoading: _isLoading, + ), + _RegisterForm( + formKey: _registerFormKey, + nameController: _registerNameController, + emailController: _registerEmailController, + passwordController: _registerPasswordController, + confirmPasswordController: _registerConfirmPasswordController, + onSubmit: _signUp, + isLoading: _isLoading, + ), + ], + ), + ), + const SizedBox(height: 12), + ], + ), + ), + ), + ), + ), + ), + ), + ), + ), + ); + } +} + +class _LoginForm extends StatelessWidget { + const _LoginForm({ + required this.formKey, + required this.emailController, + required this.passwordController, + required this.onSubmit, + required this.isLoading, + }); + + final GlobalKey formKey; + final TextEditingController emailController; + final TextEditingController passwordController; + final Future Function() onSubmit; + final bool isLoading; + + @override + Widget build(BuildContext context) { + return Form( + key: formKey, + child: Column( + children: [ + TextFormField( + controller: emailController, + keyboardType: TextInputType.emailAddress, + inputFormatters: [FilteringTextInputFormatter.allow(_emailChars)], + decoration: const InputDecoration( + labelText: 'Correo electrónico', + prefixIcon: Icon(Icons.email_outlined), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Ingresa tu correo'; + } + if (!value.contains('@') || value.startsWith('@') || value.endsWith('@')) { + return 'Ingresa un correo válido'; + } + return null; + }, + ), + const SizedBox(height: 16), + TextFormField( + controller: passwordController, + obscureText: true, + decoration: const InputDecoration( + labelText: 'Contraseña', + prefixIcon: Icon(Icons.lock_outline), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Ingresa tu contraseña'; + } + if (value.length < 6) { + return 'Usa al menos 6 caracteres'; + } + return null; + }, + ), + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + height: 52, + child: FilledButton( + onPressed: isLoading ? null : onSubmit, + child: isLoading + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white), + ) + : const Text('Ingresar'), + ), + ), + ], + ), + ); + } +} + +class _RegisterForm extends StatelessWidget { + const _RegisterForm({ + required this.formKey, + required this.nameController, + required this.emailController, + required this.passwordController, + required this.confirmPasswordController, + required this.onSubmit, + required this.isLoading, + }); + + final GlobalKey formKey; + final TextEditingController nameController; + final TextEditingController emailController; + final TextEditingController passwordController; + final TextEditingController confirmPasswordController; + final Future Function() onSubmit; + final bool isLoading; + + @override + Widget build(BuildContext context) { + return Form( + key: formKey, + child: ListView( + children: [ + TextFormField( + controller: nameController, + textCapitalization: TextCapitalization.words, + keyboardType: TextInputType.name, + inputFormatters: [FilteringTextInputFormatter.allow(_lettersOnly)], + decoration: const InputDecoration( + labelText: 'Nombre', + prefixIcon: Icon(Icons.person_outline), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Ingresa tu nombre'; + } + return null; + }, + ), + const SizedBox(height: 16), + TextFormField( + controller: emailController, + keyboardType: TextInputType.emailAddress, + inputFormatters: [FilteringTextInputFormatter.allow(_emailChars)], + decoration: const InputDecoration( + labelText: 'Correo electrónico', + prefixIcon: Icon(Icons.email_outlined), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.trim().isEmpty) { + return 'Ingresa tu correo'; + } + if (!value.contains('@') || value.startsWith('@') || value.endsWith('@')) { + return 'Ingresa un correo válido'; + } + return null; + }, + ), + const SizedBox(height: 16), + TextFormField( + controller: passwordController, + obscureText: true, + inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))], + decoration: const InputDecoration( + labelText: 'Contraseña', + prefixIcon: Icon(Icons.lock_outline), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Ingresa una contraseña'; + } + if (value.length < 6) { + return 'Usa al menos 6 caracteres'; + } + return null; + }, + ), + const SizedBox(height: 16), + TextFormField( + controller: confirmPasswordController, + obscureText: true, + inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))], + decoration: const InputDecoration( + labelText: 'Confirmar contraseña', + prefixIcon: Icon(Icons.lock_reset_outlined), + border: OutlineInputBorder(), + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Confirma tu contraseña'; + } + if (value != passwordController.text) { + return 'Las contraseñas no coinciden'; + } + return null; + }, + ), + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + height: 52, + child: FilledButton( + onPressed: isLoading ? null : onSubmit, + child: isLoading + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white), + ) + : const Text('Registrarme'), + ), + ), + ], + ), + ); + } +} + +class _AuthStatusBanner extends StatelessWidget { + const _AuthStatusBanner({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFFFEE2E2), + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFFCA5A5)), + ), + child: Text( + message, + style: const TextStyle(color: Color(0xFF991B1B), height: 1.35), + ), + ); + } +} + +class _DemoProfilesSection extends StatelessWidget { + const _DemoProfilesSection({ + required this.profiles, + required this.onProfileSelected, + }); + + final List profiles; + final Future Function(DemoProfile profile) onProfileSelected; + + @override + Widget build(BuildContext context) { + return Card( + elevation: 2, + color: const Color(0xFFF8FAFC), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Perfiles demo', style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w800)), + const SizedBox(height: 8), + Text('Toca un perfil para llenar el formulario de acceso.', style: TextStyle(color: Colors.grey.shade700)), + const SizedBox(height: 12), + Wrap( + spacing: 8, + runSpacing: 8, + children: profiles + .map( + (profile) => ActionChip( + label: Text('${profile.name} • ${profile.routeId}'), + onPressed: () => onProfileSelected(profile), + ), + ) + .toList(growable: false), + ), + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/screens/dashboard_screen.dart b/lib/screens/dashboard_screen.dart new file mode 100644 index 0000000..9ff7192 --- /dev/null +++ b/lib/screens/dashboard_screen.dart @@ -0,0 +1,1858 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:table_calendar/table_calendar.dart'; + +import '../models/address_entry.dart'; +import '../models/colony_route.dart'; +import '../models/calendar_event_entry.dart'; +import '../models/address_record.dart'; +import '../models/auth_session.dart'; +import '../models/route_guide_entry.dart'; +import '../models/route_notification.dart'; +import '../models/truck_route.dart'; +import '../services/address_repository.dart'; +import '../services/auth_repository.dart'; +import '../services/local_seed_repository.dart'; +import 'auth_screen.dart'; + +String formatScheduleAsAmPm(String schedule) { + final segments = schedule.split('-').map((segment) => segment.trim()).toList(growable: false); + if (segments.length != 2) { + return schedule; + } + + TimeOfDay? parseSegment(String value) { + final parts = value.split(':'); + if (parts.length != 2) { + return null; + } + final hour = int.tryParse(parts[0].trim()); + final minute = int.tryParse(parts[1].trim()); + if (hour == null || minute == null) { + return null; + } + return TimeOfDay(hour: hour, minute: minute); + } + + String formatTime(TimeOfDay timeOfDay) { + final hour = timeOfDay.hourOfPeriod == 0 ? 12 : timeOfDay.hourOfPeriod; + final minute = timeOfDay.minute.toString().padLeft(2, '0'); + final suffix = timeOfDay.period == DayPeriod.am ? 'AM' : 'PM'; + return '$hour:$minute $suffix'; + } + + final start = parseSegment(segments[0]); + final end = parseSegment(segments[1]); + if (start == null || end == null) { + return schedule; + } + + return '${formatTime(start)} - ${formatTime(end)}'; +} + +String guideCountdownText(RouteGuideEntry guide, DateTime now) { + final weekdays = guide.days.map((day) { + switch (day.trim().toLowerCase()) { + case 'lunes': + return DateTime.monday; + case 'martes': + return DateTime.tuesday; + case 'miercoles': + case 'miércoles': + return DateTime.wednesday; + case 'jueves': + return DateTime.thursday; + case 'viernes': + return DateTime.friday; + case 'sabado': + case 'sábado': + return DateTime.saturday; + case 'domingo': + return DateTime.sunday; + default: + return null; + } + }).whereType().toList(growable: false); + + if (weekdays.isEmpty) { + return 'Sin horario definido'; + } + + DateTime? parseStart(DateTime date) { + final parts = guide.schedule.split('-').first.trim().split(':'); + if (parts.length != 2) { + return null; + } + final hour = int.tryParse(parts[0].trim()); + final minute = int.tryParse(parts[1].trim()); + if (hour == null || minute == null) { + return null; + } + return DateTime(date.year, date.month, date.day, hour, minute); + } + + for (var offset = 0; offset < 8; offset++) { + final candidateDate = now.add(Duration(days: offset)); + if (!weekdays.contains(candidateDate.weekday)) { + continue; + } + final start = parseStart(candidateDate); + if (start == null) { + return 'Sin horario definido'; + } + if (start.isAfter(now)) { + return 'Faltan ${formatDuration(start.difference(now))}'; + } + if (offset == 0) { + return 'Llega ahora'; + } + } + + return 'Próxima llegada en breve'; +} + +String formatDuration(Duration duration) { + final totalMinutes = duration.inMinutes; + if (totalMinutes <= 0) { + return '0 min'; + } + final hours = totalMinutes ~/ 60; + final minutes = totalMinutes % 60; + if (hours > 0) { + return minutes > 0 ? '$hours h $minutes min' : '$hours h'; + } + return '$minutes min'; +} + +class DashboardScreen extends StatefulWidget { + const DashboardScreen({ + super.key, + required this.authRepository, + required this.addressRepository, + required this.session, + this.savedAddress, + this.enableLiveFeatures = true, + }); + + final AuthRepository authRepository; + final AddressRepository addressRepository; + final AuthSession session; + final AddressEntry? savedAddress; + final bool enableLiveFeatures; + + @override + State createState() => _DashboardScreenState(); +} + +class _DashboardScreenState extends State { + final MapController _mapController = MapController(); + final TextEditingController _calendarNoteController = TextEditingController(); + final TextEditingController _newHouseNumberController = TextEditingController(); + final TextEditingController _newColoniaController = TextEditingController(); + final TextEditingController _newStreetController = TextEditingController(); + + final List<_AppNotification> _notifications = <_AppNotification>[]; + final Map _calendarNotes = {}; + final Random _random = Random(); + + int _selectedIndex = 0; + LatLng _center = const LatLng(19.4326, -99.1332); + bool _isLoadingLocation = true; + bool _showLiveFeatures = true; + String? _locationError; + Timer? _truckTimer; + LatLng? _truckPosition; + bool _truckVisible = false; + LocalSeedData? _seedData; + TruckRoute? _activeRoute; + ColonyRoute? _selectedColonyRoute; + int _routePlaybackIndex = 0; + + bool _loadingAddresses = true; + String? _addressesError; + List _addresses = []; + String? _selectedGuideRouteId; + bool _mapCenterResolved = false; + DateTime _now = DateTime.now(); + Timer? _clockTimer; + + DateTime _focusedDay = DateTime.now(); + DateTime? _selectedDay; + CalendarFormat _calendarFormat = CalendarFormat.month; + + @override + void initState() { + super.initState(); + _showLiveFeatures = widget.enableLiveFeatures; + if (!_showLiveFeatures) { + _isLoadingLocation = false; + _loadingAddresses = false; + } + + _clockTimer = Timer.periodic(const Duration(seconds: 1), (_) { + if (!mounted) { + return; + } + setState(() { + _now = DateTime.now(); + }); + }); + + unawaited(_loadLocalSeedData()); + unawaited(_loadLocation()); + unawaited(_loadAddresses()); + } + + @override + void dispose() { + _truckTimer?.cancel(); + _clockTimer?.cancel(); + _calendarNoteController.dispose(); + _newHouseNumberController.dispose(); + _newColoniaController.dispose(); + _newStreetController.dispose(); + super.dispose(); + } + + DateTime _normalizeDay(DateTime day) => DateTime(day.year, day.month, day.day); + + String _formatTimeAsAmPm(TimeOfDay timeOfDay) { + final hour = timeOfDay.hourOfPeriod == 0 ? 12 : timeOfDay.hourOfPeriod; + final minute = timeOfDay.minute.toString().padLeft(2, '0'); + final suffix = timeOfDay.period == DayPeriod.am ? 'AM' : 'PM'; + return '$hour:$minute $suffix'; + } + + String _formatScheduleAmPm(String schedule) { + final segments = schedule.split('-').map((segment) => segment.trim()).toList(growable: false); + if (segments.length != 2) { + return schedule; + } + + TimeOfDay? parseSegment(String value) { + final parts = value.split(':'); + if (parts.length != 2) { + return null; + } + final hour = int.tryParse(parts[0].trim()); + final minute = int.tryParse(parts[1].trim()); + if (hour == null || minute == null) { + return null; + } + return TimeOfDay(hour: hour, minute: minute); + } + + final start = parseSegment(segments[0]); + final end = parseSegment(segments[1]); + if (start == null || end == null) { + return schedule; + } + + return '${_formatTimeAsAmPm(start)} - ${_formatTimeAsAmPm(end)}'; + } + + int? _weekdayFromSpanish(String day) { + switch (day.trim().toLowerCase()) { + case 'lunes': + return DateTime.monday; + case 'martes': + return DateTime.tuesday; + case 'miercoles': + case 'miércoles': + return DateTime.wednesday; + case 'jueves': + return DateTime.thursday; + case 'viernes': + return DateTime.friday; + case 'sabado': + case 'sábado': + return DateTime.saturday; + case 'domingo': + return DateTime.sunday; + default: + return null; + } + } + + DateTime? _parseScheduleStart(String schedule, DateTime baseDate) { + final segments = schedule.split('-').map((segment) => segment.trim()).toList(growable: false); + if (segments.isEmpty) { + return null; + } + + final parts = segments.first.split(':'); + if (parts.length != 2) { + return null; + } + + final hour = int.tryParse(parts[0].trim()); + final minute = int.tryParse(parts[1].trim()); + if (hour == null || minute == null) { + return null; + } + + return DateTime(baseDate.year, baseDate.month, baseDate.day, hour, minute); + } + + DateTime? _nextGuideArrival(RouteGuideEntry guide, DateTime reference) { + final availableWeekdays = guide.days + .map(_weekdayFromSpanish) + .whereType() + .toList(growable: false); + + if (availableWeekdays.isEmpty) { + return null; + } + + for (var offset = 0; offset < 8; offset++) { + final candidateDate = reference.add(Duration(days: offset)); + if (!availableWeekdays.contains(candidateDate.weekday)) { + continue; + } + + final candidateStart = _parseScheduleStart(guide.schedule, candidateDate); + if (candidateStart == null) { + return null; + } + + if (candidateStart.isAfter(reference)) { + return candidateStart; + } + + if (offset == 0 && candidateStart.difference(reference).inMinutes.abs() <= 30) { + return candidateStart; + } + } + + final nextDay = reference.add(const Duration(days: 7)); + final nextMatch = guide.days.map(_weekdayFromSpanish).whereType().first; + var searchDate = nextDay; + while (searchDate.weekday != nextMatch) { + searchDate = searchDate.add(const Duration(days: 1)); + } + return _parseScheduleStart(guide.schedule, searchDate); + } + + String _formatDuration(Duration duration) { + final totalMinutes = duration.inMinutes; + if (totalMinutes <= 0) { + return 'ahora'; + } + final hours = totalMinutes ~/ 60; + final minutes = totalMinutes % 60; + if (hours > 0) { + return minutes > 0 ? '$hours h $minutes min' : '$hours h'; + } + return '$minutes min'; + } + + LatLng _fallbackMapCenter(LocalSeedData seedData) { + final route = seedData.routeForColonia(widget.savedAddress?.colonia) ?? seedData.defaultRoute; + if (route == null || route.positions.isEmpty) { + return const LatLng(20.5111, -100.9037); + } + + final points = route.positions; + final averageLat = points.map((point) => point.lat).reduce((value, element) => value + element) / points.length; + final averageLng = points.map((point) => point.lng).reduce((value, element) => value + element) / points.length; + return LatLng(averageLat, averageLng); + } + + List _projectRoutePoints(TruckRoute? route, LatLng center) { + final positions = route?.positions; + if (positions == null || positions.isEmpty) { + return []; + } + + final baseLat = positions.first.lat; + final baseLng = positions.first.lng; + return positions + .map( + (position) => LatLng( + center.latitude + (position.lat - baseLat), + center.longitude + (position.lng - baseLng), + ), + ) + .toList(growable: false); + } + + void _moveMapTo(LatLng targetCenter) { + _center = targetCenter; + if (_mapCenterResolved) { + _mapController.move(targetCenter, 15); + return; + } + _mapCenterResolved = true; + } + + Future _loadLocalSeedData() async { + final seedData = await LocalSeedRepository.instance.load(); + if (!mounted) { + return; + } + + final selectedColonyRoute = seedData.colonyRouteForColonia(widget.savedAddress?.colonia ?? widget.session.displayName); + final activeRoute = seedData.routeForColonia(widget.savedAddress?.colonia) ?? seedData.defaultRoute; + + setState(() { + _seedData = seedData; + _selectedColonyRoute = selectedColonyRoute; + _activeRoute = activeRoute; + _selectedGuideRouteId = activeRoute?.routeId ?? seedData.defaultRoute?.routeId; + if (!_showLiveFeatures) { + final fallbackCenter = _fallbackMapCenter(seedData); + _moveMapTo(fallbackCenter); + if (_activeRoute != null && _activeRoute!.positions.isNotEmpty) { + final projectedRoute = _projectRoutePoints(_activeRoute, fallbackCenter); + _truckPosition = projectedRoute.isNotEmpty ? projectedRoute.first : fallbackCenter; + _truckVisible = true; + } + } + }); + + _startTruckSimulation(); + } + + void _addNotification(String message) { + if (!mounted) { + return; + } + setState(() { + _notifications.insert(0, _AppNotification(message: message, timestamp: DateTime.now())); + }); + } + + void _seedTruckSimulation() { + final visible = _random.nextBool(); + _truckVisible = visible; + _truckPosition = _truckOffsetFromCenter(_random.nextDouble() * 20.0); + _notifications.add( + _AppNotification( + message: visible ? 'El camión de basura apareció cerca de tu ubicación.' : 'El camión de basura está fuera de rango.', + timestamp: DateTime.now(), + ), + ); + } + + void _startRandomTruckSimulation() { + _truckTimer?.cancel(); + _truckTimer = Timer.periodic(const Duration(seconds: 4), (_) { + final distanceMeters = _random.nextDouble() * 40.0; + final newTruckPosition = _truckOffsetFromCenter(distanceMeters); + final wasVisible = _truckVisible; + final isVisible = distanceMeters <= 20.0; + + if (!mounted) { + return; + } + + setState(() { + _truckPosition = newTruckPosition; + _truckVisible = isVisible; + }); + + if (isVisible != wasVisible) { + _addNotification( + isVisible + ? 'El camión de basura apareció a ${distanceMeters.toStringAsFixed(1)} m.' + : 'El camión de basura salió del rango visible.', + ); + } + }); + } + + Future _loadLocation() async { + try { + final permission = await Geolocator.checkPermission(); + var currentPermission = permission; + if (currentPermission == LocationPermission.denied) { + currentPermission = await Geolocator.requestPermission(); + } + + if (currentPermission == LocationPermission.denied || currentPermission == LocationPermission.deniedForever) { + if (!mounted) { + return; + } + setState(() { + _locationError = 'Permiso de ubicación no concedido. Mostrando mapa por defecto.'; + _isLoadingLocation = false; + }); + + if (_seedData != null) { + final fallbackCenter = _fallbackMapCenter(_seedData!); + if (mounted) { + setState(() { + _center = fallbackCenter; + if (_activeRoute != null && _activeRoute!.positions.isNotEmpty) { + final projectedRoute = _projectRoutePoints(_activeRoute, fallbackCenter); + _truckPosition = projectedRoute.isNotEmpty ? projectedRoute.first : fallbackCenter; + _truckVisible = true; + } + }); + _mapController.move(fallbackCenter, 15); + } + } + return; + } + + final position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); + final newCenter = LatLng(position.latitude, position.longitude); + + if (!mounted) { + return; + } + + setState(() { + _moveMapTo(newCenter); + _isLoadingLocation = false; + _locationError = null; + }); + + _mapController.move(newCenter, 15); + } catch (_) { + if (!mounted) { + return; + } + setState(() { + _locationError = 'No se pudo obtener la ubicación actual. Se usó una referencia por defecto.'; + _isLoadingLocation = false; + }); + + if (_seedData != null) { + final fallbackCenter = _fallbackMapCenter(_seedData!); + setState(() { + _center = fallbackCenter; + if (_activeRoute != null && _activeRoute!.positions.isNotEmpty) { + final projectedRoute = _projectRoutePoints(_activeRoute, fallbackCenter); + _truckPosition = projectedRoute.isNotEmpty ? projectedRoute.first : fallbackCenter; + _truckVisible = true; + } + }); + _mapController.move(fallbackCenter, 15); + } + } + } + + Future _loadAddresses() async { + try { + final addresses = await widget.addressRepository.getMyAddresses(session: widget.session); + if (!mounted) { + return; + } + setState(() { + _addresses = addresses; + _loadingAddresses = false; + _addressesError = null; + }); + } catch (error) { + if (!mounted) { + return; + } + setState(() { + _addressesError = error.toString(); + _loadingAddresses = false; + }); + } + } + + void _startTruckSimulation() { + final route = _activeRoute; + final positions = route?.positions; + if (positions == null || positions.isEmpty) { + _startRandomTruckSimulation(); + return; + } + + _truckTimer?.cancel(); + _routePlaybackIndex = 0; + _truckTimer = Timer.periodic(const Duration(seconds: 4), (_) { + if (!mounted) { + return; + } + + final projectedRoute = _projectRoutePoints(route, _center); + final currentPosition = positions[_routePlaybackIndex % positions.length]; + final currentLatLng = projectedRoute.isEmpty + ? LatLng(currentPosition.lat, currentPosition.lng) + : projectedRoute[_routePlaybackIndex % projectedRoute.length]; + final distanceMeters = Geolocator.distanceBetween( + _center.latitude, + _center.longitude, + currentLatLng.latitude, + currentLatLng.longitude, + ); + final wasVisible = _truckVisible; + final isVisible = distanceMeters <= 20.0; + + setState(() { + _truckPosition = currentLatLng; + _truckVisible = isVisible; + }); + + _pushRouteNotification(currentPosition.positionId); + + if (isVisible != wasVisible) { + _addNotification( + isVisible + ? 'El camión apareció sobre la ruta ${route?.routeId ?? 'RUTA'}.' + : 'El camión salió del rango visible.', + ); + } + + _routePlaybackIndex++; + }); + } + + void _pushRouteNotification(int positionId) { + final triggerEvent = switch (positionId) { + 2 => 'ROUTE_START', + 4 => 'TRUCK_PROXIMITY', + 8 => 'ROUTE_COMPLETED', + _ => '', + }; + + final notification = _notificationByTrigger(triggerEvent); + + if (notification != null) { + _addNotification('${notification.title}: ${notification.body}'); + } + } + + RouteNotification? _notificationByTrigger(String triggerEvent) { + if (triggerEvent.isEmpty) { + return null; + } + + final seedData = _seedData; + if (seedData == null) { + return null; + } + + for (final notification in seedData.notifications) { + if (notification.triggerEvent == triggerEvent) { + return notification; + } + } + + return null; + } + + LatLng _truckOffsetFromCenter(double distanceMeters) { + final angle = _random.nextDouble() * 2 * pi; + final metersPerDegreeLat = 111320.0; + final metersPerDegreeLng = 111320.0 * cos(_center.latitude * pi / 180.0).abs().clamp(0.2, 1.0); + final deltaLat = (distanceMeters * cos(angle)) / metersPerDegreeLat; + final deltaLng = (distanceMeters * sin(angle)) / metersPerDegreeLng; + return LatLng(_center.latitude + deltaLat, _center.longitude + deltaLng); + } + + Future _logOut(BuildContext context) async { + await widget.authRepository.signOut(); + if (!context.mounted) { + return; + } + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute( + builder: (_) => AuthScreen( + authRepository: widget.authRepository, + addressRepository: widget.addressRepository, + ), + ), + (route) => false, + ); + } + + Future _saveCalendarNote() async { + final note = _calendarNoteController.text.trim(); + if (note.isEmpty || _selectedDay == null) { + return; + } + + final normalizedDay = _normalizeDay(_selectedDay!); + setState(() { + _calendarNotes[normalizedDay] = note; + }); + _calendarNoteController.clear(); + _addNotification('Se guardó texto en el calendario para ${_selectedDay!.day}/${_selectedDay!.month}.'); + } + + void _selectCalendarDay(DateTime day, DateTime focusedDay) { + final normalizedDay = _normalizeDay(day); + final savedNote = _calendarNotes[normalizedDay]; + + setState(() { + _selectedDay = day; + _focusedDay = focusedDay; + _calendarNoteController.text = savedNote ?? ''; + }); + } + + CalendarEventEntry? _seedEventForDay(DateTime day) { + final seedData = _seedData; + if (seedData == null) { + return null; + } + + final normalizedDay = _normalizeDay(day); + for (final event in seedData.calendarEvents) { + if (event.date.year == normalizedDay.year && event.date.month == normalizedDay.month && event.date.day == normalizedDay.day) { + return event; + } + } + return null; + } + + Future _saveNewAddress() async { + if (_newHouseNumberController.text.trim().isEmpty || + _newColoniaController.text.trim().isEmpty || + _newStreetController.text.trim().isEmpty) { + _addNotification('Completa la nueva dirección antes de guardarla.'); + return; + } + + final newAddress = AddressEntry( + houseNumber: _newHouseNumberController.text.trim(), + colonia: _newColoniaController.text.trim(), + street: _newStreetController.text.trim(), + ); + + try { + await widget.addressRepository.saveAddress(session: widget.session, address: newAddress); + if (!mounted) { + return; + } + setState(() { + _addresses = [ + AddressRecord( + id: DateTime.now().millisecondsSinceEpoch, + houseNumber: newAddress.houseNumber, + colonia: newAddress.colonia, + street: newAddress.street, + ), + ..._addresses, + ]; + }); + _newHouseNumberController.clear(); + _newColoniaController.clear(); + _newStreetController.clear(); + _addNotification('Se agregó una nueva dirección a tu perfil.'); + } catch (error) { + _addNotification('No se pudo guardar la nueva dirección: $error'); + } + } + + void _selectGuideRoute(String routeId) { + setState(() { + _selectedGuideRouteId = routeId; + }); + } + + @override + Widget build(BuildContext context) { + final routePoints = _projectRoutePoints(_activeRoute, _center); + final selectedDay = _selectedDay == null ? null : _normalizeDay(_selectedDay!); + final selectedSavedNote = selectedDay == null ? null : _calendarNotes[selectedDay]; + final selectedSeedEvents = selectedDay == null ? [] : (_seedData?.eventsForDay(selectedDay) ?? []); + final isLandscape = MediaQuery.of(context).orientation == Orientation.landscape; + final bottomNavigation = NavigationBar( + selectedIndex: _selectedIndex, + onDestinationSelected: (index) { + setState(() { + _selectedIndex = index; + }); + }, + destinations: const [ + NavigationDestination(icon: Icon(Icons.my_location_outlined), selectedIcon: Icon(Icons.my_location), label: 'Mapa'), + NavigationDestination(icon: Icon(Icons.calendar_month_outlined), selectedIcon: Icon(Icons.calendar_month), label: 'Calendario'), + NavigationDestination(icon: Icon(Icons.notifications_outlined), selectedIcon: Icon(Icons.notifications), label: 'Avisos'), + NavigationDestination(icon: Icon(Icons.input_outlined), selectedIcon: Icon(Icons.input), label: 'Datos'), + ], + ); + + final pages = [ + _MapSection( + center: _center, + truckPosition: _truckPosition, + truckVisible: _truckVisible, + isLoadingLocation: _isLoadingLocation, + locationError: _locationError, + mapController: _mapController, + showTiles: _showLiveFeatures, + address: widget.savedAddress, + activeRoute: _activeRoute, + selectedColonyRoute: _selectedColonyRoute, + routePoints: routePoints, + ), + _CalendarSection( + focusedDay: _focusedDay, + selectedDay: _selectedDay, + calendarFormat: _calendarFormat, + notes: _calendarNotes, + seedEvents: _seedData?.calendarEvents ?? const [], + selectedSavedNote: selectedSavedNote, + selectedSeedEvents: selectedSeedEvents, + noteController: _calendarNoteController, + onSelectedDay: _selectCalendarDay, + onFormatChanged: (format) { + setState(() { + _calendarFormat = format; + }); + }, + onPageChanged: (focusedDay) { + _focusedDay = focusedDay; + }, + onSaveNote: _saveCalendarNote, + ), + _NotificationsSection(notifications: _notifications), + _DataSection( + session: widget.session, + loadingAddresses: _loadingAddresses, + addressesError: _addressesError, + addresses: _addresses, + seedData: _seedData, + activeRoute: _activeRoute, + selectedGuideRouteId: _selectedGuideRouteId, + selectedColonyRoute: _selectedColonyRoute, + now: _now, + onSelectGuideRoute: _selectGuideRoute, + houseNumberController: _newHouseNumberController, + coloniaController: _newColoniaController, + streetController: _newStreetController, + onSaveAddress: _saveNewAddress, + ), + ]; + + return Scaffold( + body: SafeArea( + child: isLandscape + ? Row( + children: [ + NavigationRail( + selectedIndex: _selectedIndex, + onDestinationSelected: (index) { + setState(() { + _selectedIndex = index; + }); + }, + labelType: NavigationRailLabelType.all, + leading: Padding( + padding: const EdgeInsets.only(top: 8), + child: CircleAvatar( + radius: 22, + backgroundColor: Colors.teal.shade700, + child: Text( + widget.session.displayName.isNotEmpty ? widget.session.displayName[0].toUpperCase() : 'U', + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w800), + ), + ), + ), + destinations: const [ + NavigationRailDestination( + icon: Icon(Icons.my_location_outlined), + selectedIcon: Icon(Icons.my_location), + label: Text('Mapa'), + ), + NavigationRailDestination( + icon: Icon(Icons.calendar_month_outlined), + selectedIcon: Icon(Icons.calendar_month), + label: Text('Calendario'), + ), + NavigationRailDestination( + icon: Icon(Icons.notifications_outlined), + selectedIcon: Icon(Icons.notifications), + label: Text('Avisos'), + ), + NavigationRailDestination( + icon: Icon(Icons.input_outlined), + selectedIcon: Icon(Icons.input), + label: Text('Datos'), + ), + ], + ), + const VerticalDivider(width: 1), + Expanded( + child: Column( + children: [ + _UserHeader( + session: widget.session, + onLogout: () => _logOut(context), + ), + Expanded( + child: IndexedStack( + index: _selectedIndex, + children: pages, + ), + ), + ], + ), + ), + ], + ) + : Column( + children: [ + _UserHeader( + session: widget.session, + onLogout: () => _logOut(context), + ), + Expanded( + child: IndexedStack( + index: _selectedIndex, + children: pages, + ), + ), + ], + ), + ), + bottomNavigationBar: isLandscape ? Offstage(offstage: true, child: bottomNavigation) : bottomNavigation, + ); + } +} + +class _UserHeader extends StatelessWidget { + const _UserHeader({required this.session, required this.onLogout}); + + final AuthSession session; + final VoidCallback onLogout; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [Colors.teal.shade900, Colors.teal.shade700], + ), + ), + child: Row( + children: [ + CircleAvatar( + radius: 24, + backgroundColor: Colors.white.withValues(alpha: 0.18), + child: Text( + session.displayName.isNotEmpty ? session.displayName[0].toUpperCase() : 'U', + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w800), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(session.displayName, style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w700)), + Text(session.email, style: TextStyle(color: Colors.white.withValues(alpha: 0.85))), + ], + ), + ), + IconButton( + onPressed: onLogout, + icon: const Icon(Icons.logout, color: Colors.white), + tooltip: 'Cerrar sesión', + ), + ], + ), + ); + } +} + +class _MapSection extends StatelessWidget { + const _MapSection({ + required this.center, + required this.truckPosition, + required this.truckVisible, + required this.isLoadingLocation, + required this.locationError, + required this.mapController, + required this.showTiles, + required this.address, + required this.activeRoute, + required this.selectedColonyRoute, + required this.routePoints, + }); + + final LatLng center; + final LatLng? truckPosition; + final bool truckVisible; + final bool isLoadingLocation; + final String? locationError; + final MapController mapController; + final bool showTiles; + final AddressEntry? address; + final TruckRoute? activeRoute; + final ColonyRoute? selectedColonyRoute; + final List routePoints; + + @override + Widget build(BuildContext context) { + final markers = [ + Marker( + width: 60, + height: 60, + point: center, + child: const Icon(Icons.person_pin_circle, size: 56, color: Colors.blue), + ), + if (truckVisible && truckPosition != null) + Marker( + width: 60, + height: 60, + point: truckPosition!, + child: const Icon(Icons.local_shipping, size: 50, color: Colors.red), + ), + ]; + + return Container( + color: const Color(0xFFF8FAFC), + child: Column( + children: [ + if (locationError != null) + Padding( + padding: const EdgeInsets.all(12), + child: _NoticeBanner(message: locationError!), + ), + Expanded( + child: Center( + child: Padding( + padding: const EdgeInsets.all(16), + child: ClipRRect( + borderRadius: BorderRadius.circular(24), + child: Stack( + children: [ + if (showTiles) + FlutterMap( + mapController: mapController, + options: MapOptions( + initialCenter: center, + initialZoom: 15, + interactionOptions: const InteractionOptions(flags: InteractiveFlag.all), + ), + children: [ + TileLayer( + urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', + userAgentPackageName: 'flutter_application_1', + ), + if (routePoints.length > 1) + PolylineLayer( + polylines: [ + Polyline( + points: routePoints, + strokeWidth: 4, + color: Colors.teal.shade700, + ), + ], + ), + MarkerLayer(markers: markers), + ], + ) + else + _MapPlaceholder( + center: center, + truckVisible: truckVisible, + truckPosition: truckPosition, + ), + Positioned( + top: 16, + left: 16, + right: 16, + child: Card( + elevation: 8, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text('Mapa y camión', style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w800)), + const SizedBox(height: 4), + Text( + address == null + ? 'No hay una dirección guardada todavía.' + : 'Dirección: ${address!.houseNumber}, ${address!.colonia}, ${address!.street}', + style: TextStyle(color: Colors.grey.shade700), + ), + const SizedBox(height: 4), + Text( + activeRoute == null + ? 'Ruta por defecto no disponible.' + : 'Ruta activa: ${activeRoute!.routeId} - ${activeRoute!.name}', + style: const TextStyle(fontWeight: FontWeight.w700), + ), + if (selectedColonyRoute != null) ...[ + const SizedBox(height: 2), + Text( + 'Horario estimado: ${selectedColonyRoute!.horarioEstimado}', + style: TextStyle(color: Colors.grey.shade700), + ), + ], + const SizedBox(height: 4), + Text( + truckVisible ? 'El camión está dentro de 20 m.' : 'El camión está fuera de rango.', + style: const TextStyle(fontWeight: FontWeight.w700), + ), + ], + ), + ), + ), + ), + if (isLoadingLocation) + const Center( + child: CircularProgressIndicator(), + ), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } +} + +class _MapPlaceholder extends StatelessWidget { + const _MapPlaceholder({ + required this.center, + required this.truckVisible, + required this.truckPosition, + }); + + final LatLng center; + final bool truckVisible; + final LatLng? truckPosition; + + @override + Widget build(BuildContext context) { + return Container( + color: const Color(0xFFE2E8F0), + alignment: Alignment.center, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.map_outlined, size: 72, color: Colors.teal), + const SizedBox(height: 12), + const Text('Mapa centrado en tu ubicación', style: TextStyle(fontWeight: FontWeight.w700)), + const SizedBox(height: 4), + Text('Lat: ${center.latitude.toStringAsFixed(5)}, Lng: ${center.longitude.toStringAsFixed(5)}'), + const SizedBox(height: 12), + Text( + truckVisible && truckPosition != null + ? 'Camión visible cerca de ti' + : 'Camión fuera del rango de 20 m', + style: const TextStyle(fontWeight: FontWeight.w700), + ), + ], + ), + ); + } +} + +class _CalendarSection extends StatelessWidget { + const _CalendarSection({ + required this.focusedDay, + required this.selectedDay, + required this.calendarFormat, + required this.notes, + required this.seedEvents, + required this.selectedSavedNote, + required this.selectedSeedEvents, + required this.noteController, + required this.onSelectedDay, + required this.onFormatChanged, + required this.onPageChanged, + required this.onSaveNote, + }); + + final DateTime focusedDay; + final DateTime? selectedDay; + final CalendarFormat calendarFormat; + final Map notes; + final List seedEvents; + final String? selectedSavedNote; + final List selectedSeedEvents; + final TextEditingController noteController; + final void Function(DateTime day, DateTime focusedDay) onSelectedDay; + final void Function(CalendarFormat format) onFormatChanged; + final void Function(DateTime focusedDay) onPageChanged; + final Future Function() onSaveNote; + + DateTime _normalizeDay(DateTime day) => DateTime(day.year, day.month, day.day); + + CalendarEventEntry? _seedEventForDay(DateTime day) { + final normalizedDay = _normalizeDay(day); + for (final event in seedEvents) { + if (event.date.year == normalizedDay.year && event.date.month == normalizedDay.month && event.date.day == normalizedDay.day) { + return event; + } + } + return null; + } + + @override + Widget build(BuildContext context) { + final selectedNormalized = selectedDay == null ? null : _normalizeDay(selectedDay!); + final carouselDays = {}; + if (selectedNormalized != null) { + carouselDays.add(selectedNormalized); + } + for (final day in notes.keys) { + carouselDays.add(_normalizeDay(day)); + } + for (final event in seedEvents) { + carouselDays.add(_normalizeDay(event.date)); + } + final carouselDayList = carouselDays.toList()..sort((a, b) => a.compareTo(b)); + + return Container( + color: const Color(0xFFF8FAFC), + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Card( + elevation: 8, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + TableCalendar( + firstDay: DateTime.utc(2020, 1, 1), + lastDay: DateTime.utc(2035, 12, 31), + focusedDay: focusedDay, + calendarFormat: calendarFormat, + selectedDayPredicate: (day) => isSameDay(selectedDay, day), + eventLoader: (day) { + final normalizedDay = _normalizeDay(day); + final userNote = notes[normalizedDay]; + final seededTitles = seedEvents + .where((event) => event.date.year == normalizedDay.year && event.date.month == normalizedDay.month && event.date.day == normalizedDay.day) + .map((event) => event.title) + .toList(growable: false); + final events = []; + if (userNote != null && userNote.isNotEmpty) { + events.add(userNote); + } + events.addAll(seededTitles); + return events; + }, + onDaySelected: onSelectedDay, + onFormatChanged: onFormatChanged, + onPageChanged: onPageChanged, + calendarBuilders: CalendarBuilders( + defaultBuilder: (context, day, focusedDay) { + final note = notes[_normalizeDay(day)]; + final seedEvent = _seedEventForDay(day); + return _CalendarDayCell( + day: day, + note: note, + seededTitle: seedEvent?.title, + selected: false, + ); + }, + selectedBuilder: (context, day, focusedDay) { + final note = notes[_normalizeDay(day)]; + final seedEvent = _seedEventForDay(day); + return _CalendarDayCell( + day: day, + note: note, + seededTitle: seedEvent?.title, + selected: true, + ); + }, + todayBuilder: (context, day, focusedDay) { + final note = notes[_normalizeDay(day)]; + final seedEvent = _seedEventForDay(day); + return _CalendarDayCell( + day: day, + note: note, + seededTitle: seedEvent?.title, + selected: false, + today: true, + ); + }, + ), + ), + const SizedBox(height: 12), + TextField( + controller: noteController, + maxLines: 2, + decoration: const InputDecoration( + labelText: 'Texto del día', + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: 12), + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: onSaveNote, + child: const Text('Guardar texto y resaltar casilla'), + ), + ), + const SizedBox(height: 12), + Text( + selectedNormalized == null + ? 'Desliza el carrusel para ver las fechas importantes.' + : 'Fecha seleccionada: ${selectedNormalized.day}/${selectedNormalized.month}/${selectedNormalized.year}', + style: TextStyle(color: Colors.grey.shade700), + ), + const SizedBox(height: 12), + if (carouselDayList.isEmpty) + const Padding( + padding: EdgeInsets.symmetric(vertical: 24), + child: Text('No hay fechas importantes registradas todavía.'), + ) + else + SizedBox( + height: 170, + child: PageView.builder( + itemCount: carouselDayList.length, + onPageChanged: (index) { + final day = carouselDayList[index]; + onSelectedDay(day, day); + }, + itemBuilder: (context, index) { + final day = carouselDayList[index]; + final note = notes[day]; + final events = seedEvents + .where((event) => event.date.year == day.year && event.date.month == day.month && event.date.day == day.day) + .toList(growable: false); + final isSelected = selectedNormalized != null && isSameDay(selectedNormalized, day); + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Card( + elevation: isSelected ? 10 : 4, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), + color: isSelected ? const Color(0xFFE6FFFB) : Colors.white, + child: Padding( + padding: const EdgeInsets.all(16), + child: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${day.day}/${day.month}/${day.year}', + style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800), + ), + const SizedBox(height: 8), + Text( + note == null || note.trim().isEmpty + ? 'No hay texto guardado para esta fecha.' + : note, + style: TextStyle(color: Colors.grey.shade800), + ), + const SizedBox(height: 10), + if (events.isEmpty) + Text( + 'Sin evento local para este día.', + style: TextStyle(color: Colors.grey.shade600), + ) + else + ...events.map( + (event) => Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Container( + width: double.infinity, + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: const Color(0xFFF8FAFC), + borderRadius: BorderRadius.circular(14), + border: Border.all(color: const Color(0xFFD1D5DB)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(event.title, style: const TextStyle(fontWeight: FontWeight.w700)), + const SizedBox(height: 4), + Text(event.description, style: TextStyle(color: Colors.grey.shade700)), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + }, + ), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +class _CalendarDayCell extends StatelessWidget { + const _CalendarDayCell({ + required this.day, + required this.note, + required this.seededTitle, + required this.selected, + this.today = false, + }); + + final DateTime day; + final String? note; + final String? seededTitle; + final bool selected; + final bool today; + + @override + Widget build(BuildContext context) { + final backgroundColor = selected + ? Colors.teal.shade700 + : today + ? Colors.teal.shade100 + : Colors.white; + final hasNote = note != null && note!.trim().isNotEmpty; + final hasSeedTitle = seededTitle != null && seededTitle!.trim().isNotEmpty; + + return Container( + margin: const EdgeInsets.all(4), + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: hasNote || hasSeedTitle ? Colors.teal : Colors.grey.shade300), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${day.day}', + style: TextStyle( + color: selected ? Colors.white : Colors.black, + fontWeight: FontWeight.w800, + ), + ), + if (hasNote || hasSeedTitle) ...[ + const SizedBox(height: 4), + Wrap( + alignment: WrapAlignment.center, + spacing: 4, + runSpacing: 4, + children: [ + if (hasNote) + Container( + width: 8, + height: 8, + decoration: BoxDecoration( + color: selected ? Colors.white : Colors.teal.shade700, + shape: BoxShape.circle, + ), + ), + if (hasSeedTitle) + Container( + width: 8, + height: 8, + decoration: BoxDecoration( + color: selected ? Colors.white : Colors.deepOrange.shade700, + shape: BoxShape.circle, + ), + ), + ], + ), + ], + ], + ), + ); + } +} + +class _SelectedDaySummary extends StatelessWidget { + const _SelectedDaySummary({ + required this.day, + required this.savedNote, + required this.events, + }); + + final DateTime day; + final String? savedNote; + final List events; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFFE0F2FE), + borderRadius: BorderRadius.circular(18), + border: Border.all(color: const Color(0xFF7DD3FC)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Detalle del día ${day.day}/${day.month}/${day.year}', + style: const TextStyle(fontWeight: FontWeight.w800), + ), + const SizedBox(height: 8), + Text( + savedNote == null || savedNote!.trim().isEmpty + ? 'No hay texto escrito por el usuario para este día.' + : 'Texto guardado: $savedNote', + style: TextStyle(color: Colors.grey.shade800), + ), + if (events.isNotEmpty) ...[ + const SizedBox(height: 10), + const Text('Eventos del calendario:', style: TextStyle(fontWeight: FontWeight.w700)), + const SizedBox(height: 6), + ...events.map( + (event) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text('• ${event.title}: ${event.description}'), + ), + ), + ], + ], + ), + ); + } +} + +class _NotificationsSection extends StatelessWidget { + const _NotificationsSection({required this.notifications}); + + final List<_AppNotification> notifications; + + @override + Widget build(BuildContext context) { + return Container( + color: const Color(0xFFF8FAFC), + child: ListView.builder( + padding: const EdgeInsets.all(16), + itemCount: notifications.isEmpty ? 1 : notifications.length, + itemBuilder: (context, index) { + if (notifications.isEmpty) { + return const Center( + child: Padding( + padding: EdgeInsets.only(top: 48), + child: Text('Aquí aparecerán las notificaciones.'), + ), + ); + } + + final notification = notifications[index]; + return Card( + margin: const EdgeInsets.only(bottom: 12), + child: ListTile( + leading: const Icon(Icons.notifications_active, color: Colors.teal), + title: Text(notification.message), + subtitle: Text( + '${notification.timestamp.hour.toString().padLeft(2, '0')}:${notification.timestamp.minute.toString().padLeft(2, '0')}', + ), + ), + ); + }, + ), + ); + } +} + +class _DataSection extends StatelessWidget { + const _DataSection({ + required this.session, + required this.loadingAddresses, + required this.addressesError, + required this.addresses, + required this.seedData, + required this.activeRoute, + required this.selectedGuideRouteId, + required this.selectedColonyRoute, + required this.now, + required this.onSelectGuideRoute, + required this.houseNumberController, + required this.coloniaController, + required this.streetController, + required this.onSaveAddress, + }); + + final AuthSession session; + final bool loadingAddresses; + final String? addressesError; + final List addresses; + final LocalSeedData? seedData; + final TruckRoute? activeRoute; + final String? selectedGuideRouteId; + final ColonyRoute? selectedColonyRoute; + final DateTime now; + final void Function(String routeId) onSelectGuideRoute; + final TextEditingController houseNumberController; + final TextEditingController coloniaController; + final TextEditingController streetController; + final Future Function() onSaveAddress; + + @override + Widget build(BuildContext context) { + return Container( + color: const Color(0xFFF8FAFC), + padding: const EdgeInsets.all(16), + child: ListView( + children: [ + Card( + elevation: 8, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Datos de la cuenta', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)), + const SizedBox(height: 12), + _ProfileRow(label: 'Nombre', value: session.displayName), + _ProfileRow(label: 'Correo', value: session.email), + if (selectedColonyRoute != null) ...[ + const SizedBox(height: 8), + _ProfileRow(label: 'Colonia', value: selectedColonyRoute!.colonia), + _ProfileRow(label: 'Ruta', value: selectedColonyRoute!.routeId), + _ProfileRow(label: 'Horario', value: selectedColonyRoute!.horarioEstimado), + ], + ], + ), + ), + ), + const SizedBox(height: 16), + Card( + elevation: 8, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Agregar otra dirección', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)), + const SizedBox(height: 12), + TextField( + controller: houseNumberController, + decoration: const InputDecoration(labelText: 'Número de casa', border: OutlineInputBorder()), + ), + const SizedBox(height: 12), + TextField( + controller: coloniaController, + decoration: const InputDecoration(labelText: 'Colonia', border: OutlineInputBorder()), + ), + const SizedBox(height: 12), + TextField( + controller: streetController, + decoration: const InputDecoration(labelText: 'Calle', border: OutlineInputBorder()), + ), + const SizedBox(height: 12), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: onSaveAddress, + icon: const Icon(Icons.add_location_alt_outlined), + label: const Text('Guardar nueva dirección'), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 16), + Card( + elevation: 8, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Guía de rutas', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)), + const SizedBox(height: 12), + if (seedData == null || seedData!.routes.isEmpty) + const Text('No hay rutas locales disponibles.'), + if (seedData != null && seedData!.routes.isNotEmpty) + ...seedData!.routes.map( + (route) { + final isSelected = route.routeId == selectedGuideRouteId; + final guide = seedData!.guideForRouteId(route.routeId); + return Card( + margin: const EdgeInsets.only(bottom: 12), + child: InkWell( + onTap: () => onSelectGuideRoute(route.routeId), + borderRadius: BorderRadius.circular(16), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + route.routeId == activeRoute?.routeId ? Icons.route : Icons.alt_route, + color: route.routeId == activeRoute?.routeId ? Colors.teal : Colors.grey.shade700, + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${route.routeId} - ${route.name}'), + const SizedBox(height: 4), + Text( + guide == null + ? 'Camión ${route.truckId} • ${route.status} • ${route.positions.length} puntos' + : 'Camión ${route.truckId} • ${guide.wasteType} • ${formatScheduleAsAmPm(guide.schedule)}', + style: TextStyle(color: Colors.grey.shade700), + ), + ], + ), + ), + Icon(isSelected ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down), + ], + ), + if (isSelected && guide != null) ...[ + const SizedBox(height: 14), + _RouteGuideDetailContent(guide: guide, now: now), + ], + ], + ), + ), + ), + ); + }, + ), + ], + ), + ), + ), + const SizedBox(height: 16), + Card( + elevation: 8, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Direcciones registradas', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)), + const SizedBox(height: 12), + if (loadingAddresses) const Center(child: CircularProgressIndicator()), + if (addressesError != null) Text(addressesError!, style: const TextStyle(color: Colors.red)), + if (!loadingAddresses && addresses.isEmpty) + const Text('Todavía no hay direcciones registradas.'), + if (addresses.isNotEmpty) + ...addresses.map( + (address) => Card( + margin: const EdgeInsets.only(bottom: 12), + child: ListTile( + leading: const Icon(Icons.home_work_outlined, color: Colors.teal), + title: Text('Casa ${address.houseNumber}'), + subtitle: Text('${address.colonia}, ${address.street}'), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +class _ProfileRow extends StatelessWidget { + const _ProfileRow({required this.label, required this.value}); + + final String label; + final String value; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(width: 90, child: Text(label, style: const TextStyle(fontWeight: FontWeight.w700))), + Expanded(child: Text(value)), + ], + ), + ); + } +} + +class _RouteGuideDetailContent extends StatelessWidget { + const _RouteGuideDetailContent({required this.guide, required this.now}); + + final RouteGuideEntry guide; + final DateTime now; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFFF8FAFC), + borderRadius: BorderRadius.circular(18), + border: Border.all(color: const Color(0xFFD1D5DB)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _ProfileRow(label: 'Ruta', value: guide.routeId), + _ProfileRow(label: 'Tipo', value: guide.wasteType), + _ProfileRow(label: 'Horario', value: formatScheduleAsAmPm(guide.schedule)), + _ProfileRow(label: 'Días', value: guide.days.join(', ')), + const SizedBox(height: 6), + Text( + 'Cronómetro: ${guideCountdownText(guide, now)}', + style: const TextStyle(fontWeight: FontWeight.w800), + ), + const SizedBox(height: 6), + Text(guide.note, style: TextStyle(color: Colors.grey.shade700, height: 1.35)), + ], + ), + ); + } + +} + +class _AppNotification { + _AppNotification({required this.message, required this.timestamp}); + + final String message; + final DateTime timestamp; +} + +class _NoticeBanner extends StatelessWidget { + const _NoticeBanner({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFFE0F2FE), + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFF7DD3FC)), + ), + child: Text(message, style: const TextStyle(color: Color(0xFF075985))), + ); + } +} diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart new file mode 100644 index 0000000..d64ba4e --- /dev/null +++ b/lib/screens/home_screen.dart @@ -0,0 +1,155 @@ +import 'package:flutter/material.dart'; + +import '../models/address_entry.dart'; +import '../models/auth_session.dart'; +import '../services/auth_repository.dart'; +import '../services/address_repository.dart'; +import 'auth_screen.dart'; + +class HomeScreen extends StatelessWidget { + const HomeScreen({ + super.key, + required this.authRepository, + required this.addressRepository, + required this.session, + this.savedAddress, + }); + + final AuthRepository authRepository; + final AddressRepository addressRepository; + final AuthSession session; + final AddressEntry? savedAddress; + + Future _logOut(BuildContext context) async { + await authRepository.signOut(); + if (!context.mounted) { + return; + } + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute( + builder: (_) => AuthScreen( + authRepository: authRepository, + addressRepository: addressRepository, + ), + ), + (route) => false, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [Color(0xFFF8FAFC), Color(0xFFE2E8F0), Color(0xFFCCFBF1)], + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + ), + ), + child: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520), + child: Padding( + padding: const EdgeInsets.all(20), + child: Card( + elevation: 12, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + CircleAvatar( + radius: 34, + backgroundColor: const Color(0xFF0F766E).withValues(alpha: 0.12), + child: Text( + session.displayName.isNotEmpty ? session.displayName[0].toUpperCase() : 'U', + style: const TextStyle( + fontSize: 28, + fontWeight: FontWeight.w800, + color: Color(0xFF0F766E), + ), + ), + ), + const SizedBox(height: 16), + Text( + 'Hola, ${session.displayName}', + style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w800), + ), + const SizedBox(height: 8), + Text( + session.email, + style: TextStyle(color: Colors.grey.shade700), + ), + const SizedBox(height: 20), + _InfoTile( + icon: Icons.dns_outlined, + title: 'Dirección guardada', + subtitle: savedAddress == null + ? 'Todavía no hay una dirección registrada para esta sesión.' + : 'Casa ${savedAddress!.houseNumber}, Colonia ${savedAddress!.colonia}, Calle ${savedAddress!.street}', + ), + const SizedBox(height: 12), + _InfoTile( + icon: Icons.storage_outlined, + title: 'Persistencia local', + subtitle: 'La información se conserva dentro de la app usando los JSON y el almacenamiento local.', + ), + const SizedBox(height: 24), + FilledButton.icon( + onPressed: () => _logOut(context), + icon: const Icon(Icons.logout), + label: const Text('Cerrar sesión'), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ), + ); + } +} + +class _InfoTile extends StatelessWidget { + const _InfoTile({required this.icon, required this.title, required this.subtitle}); + + final IconData icon; + final String title; + final String subtitle; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFFF8FAFC), + borderRadius: BorderRadius.circular(18), + border: Border.all(color: const Color(0xFFE2E8F0)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, color: const Color(0xFF0F766E)), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: const TextStyle(fontWeight: FontWeight.w700)), + const SizedBox(height: 4), + Text(subtitle, style: TextStyle(color: Colors.grey.shade700, height: 1.35)), + ], + ), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/services/address_repository.dart b/lib/services/address_repository.dart new file mode 100644 index 0000000..42acb50 --- /dev/null +++ b/lib/services/address_repository.dart @@ -0,0 +1,90 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/address_entry.dart'; +import '../models/address_record.dart'; +import '../models/auth_session.dart'; + +abstract class AddressRepository { + Future saveAddress({ + required AuthSession session, + required AddressEntry address, + }); + + Future> getMyAddresses({required AuthSession session}); +} + +class LocalAddressRepository implements AddressRepository { + const LocalAddressRepository(); + static const String _localAddressPrefix = 'local_addresses_'; + + @override + Future saveAddress({ + required AuthSession session, + required AddressEntry address, + }) async { + await _persistLocalAddress(session: session, address: address); + } + + @override + Future> getMyAddresses({required AuthSession session}) async { + return _loadLocalAddresses(session); + } + + Future _persistLocalAddress({required AuthSession session, required AddressEntry address}) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_localAddressPrefix${session.email.toLowerCase()}'; + final existing = await _loadLocalAddresses(session); + final records = [ + AddressRecord( + id: DateTime.now().millisecondsSinceEpoch, + houseNumber: address.houseNumber, + colonia: address.colonia, + street: address.street, + ), + ...existing, + ]; + + final encoded = jsonEncode( + records + .map( + (record) => { + 'id': record.id, + 'houseNumber': record.houseNumber, + 'colonia': record.colonia, + 'street': record.street, + }, + ) + .toList(growable: false), + ); + await prefs.setString(key, encoded); + } + + Future> _loadLocalAddresses(AuthSession session) async { + final prefs = await SharedPreferences.getInstance(); + final key = '$_localAddressPrefix${session.email.toLowerCase()}'; + final raw = prefs.getString(key); + if (raw == null || raw.trim().isEmpty) { + return []; + } + + final decoded = jsonDecode(raw); + if (decoded is! List) { + return []; + } + + return decoded + .whereType>() + .map(AddressRecord.fromJson) + .toList(growable: false); + } +} + +class AddressException implements Exception { + AddressException(this.message); + final String message; + + @override + String toString() => message; +} \ No newline at end of file diff --git a/lib/services/auth_repository.dart b/lib/services/auth_repository.dart new file mode 100644 index 0000000..776238e --- /dev/null +++ b/lib/services/auth_repository.dart @@ -0,0 +1,189 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/auth_session.dart'; +import 'local_seed_repository.dart'; + +abstract class AuthRepository { + Future restoreSession(); + Future signIn({required String email, required String password}); + Future signUp({required String name, required String email, required String password}); + Future signOut(); +} + +class LocalAuthRepository implements AuthRepository { + const LocalAuthRepository(); + + static const String _tokenKey = 'auth_token'; + static const String _emailKey = 'auth_email'; + static const String _nameKey = 'auth_name'; + static const String _sessionKey = 'auth_session_json'; + static const String _usersKey = 'auth_users_json'; + + @override + Future restoreSession() async { + final prefs = await SharedPreferences.getInstance(); + final sessionJson = prefs.getString(_sessionKey); + if (sessionJson != null && sessionJson.trim().isNotEmpty) { + final decoded = jsonDecode(sessionJson); + if (decoded is Map) { + final token = decoded['token']?.toString(); + final email = decoded['email']?.toString(); + final name = decoded['displayName']?.toString(); + if (token != null && email != null && token.isNotEmpty && email.isNotEmpty) { + return AuthSession(token: token, email: email, displayName: name ?? email); + } + } + } + + final token = prefs.getString(_tokenKey); + final email = prefs.getString(_emailKey); + final name = prefs.getString(_nameKey); + + if (token == null || email == null) { + return null; + } + + return AuthSession(token: token, email: email, displayName: name ?? email); + } + + @override + Future signIn({required String email, required String password}) { + return _authenticate( + endpoint: '/auth/login', + body: {'email': email, 'password': password}, + ); + } + + @override + Future signUp({required String name, required String email, required String password}) { + return _authenticate( + endpoint: '/auth/register', + body: {'name': name, 'email': email, 'password': password}, + ); + } + + Future _authenticate({required String endpoint, required Map body}) async { + final email = body['email']?.toString().trim(); + final password = body['password']?.toString(); + if (email == null || password == null || email.isEmpty) { + throw AuthException('Ingresa correo y contraseña válidos.'); + } + + final seedData = await LocalSeedRepository.instance.load(); + final profile = seedData.profileForCredentials(email, password); + if (profile != null) { + final session = AuthSession( + token: 'local-${profile.email}', + email: profile.email, + displayName: profile.name, + ); + await _persistSession(session); + return session; + } + + final localUsers = await _loadLocalUsers(); + final normalizedEmail = email.toLowerCase(); + final localMatch = localUsers.where((user) { + final userEmail = user['email']?.toString().trim().toLowerCase(); + final userPassword = user['password']?.toString(); + return userEmail == normalizedEmail && userPassword == password; + }).toList(growable: false); + + if (localMatch.isNotEmpty) { + final user = localMatch.first; + final displayName = user['name']?.toString().trim(); + final session = AuthSession( + token: 'local-${email.toLowerCase()}', + email: email, + displayName: displayName == null || displayName.isEmpty ? email : displayName, + ); + await _persistSession(session); + return session; + } + + if (endpoint == '/auth/register') { + final displayName = body['name']?.toString().trim(); + final alreadyInSeed = seedData.profileForCredentials(email, password) != null || + seedData.demoProfiles.any((profile) => profile.email.trim().toLowerCase() == normalizedEmail); + final alreadyInLocal = localUsers.any((user) => user['email']?.toString().trim().toLowerCase() == normalizedEmail); + if (alreadyInSeed || alreadyInLocal) { + throw AuthException('Este correo ya está registrado.'); + } + + final createdUser = { + 'name': displayName == null || displayName.isEmpty ? email : displayName, + 'email': email, + 'password': password, + 'createdAt': DateTime.now().toIso8601String(), + }; + await _saveLocalUsers(>[...localUsers, createdUser]); + + final session = AuthSession( + token: 'local-$email', + email: email, + displayName: displayName == null || displayName.isEmpty ? email : displayName, + ); + await _persistSession(session); + return session; + } + + throw AuthException('Usuario o contraseña no encontrados en los perfiles locales.'); + } + + Future _persistSession(AuthSession session) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_tokenKey, session.token); + await prefs.setString(_emailKey, session.email); + await prefs.setString(_nameKey, session.displayName); + await prefs.setString( + _sessionKey, + jsonEncode( + { + 'token': session.token, + 'email': session.email, + 'displayName': session.displayName, + }, + ), + ); + } + + Future>> _loadLocalUsers() async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_usersKey); + if (raw == null || raw.trim().isEmpty) { + return >[]; + } + + final decoded = jsonDecode(raw); + if (decoded is! List) { + return >[]; + } + + return decoded.whereType>().toList(growable: false); + } + + Future _saveLocalUsers(List> users) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_usersKey, jsonEncode(users)); + } + + @override + Future signOut() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_tokenKey); + await prefs.remove(_emailKey); + await prefs.remove(_nameKey); + await prefs.remove(_sessionKey); + } +} + +class AuthException implements Exception { + AuthException(this.message); + + final String message; + + @override + String toString() => message; +} \ No newline at end of file diff --git a/lib/services/local_seed_repository.dart b/lib/services/local_seed_repository.dart new file mode 100644 index 0000000..fea2fd6 --- /dev/null +++ b/lib/services/local_seed_repository.dart @@ -0,0 +1,159 @@ +import 'dart:convert'; + +import 'package:flutter/services.dart' show rootBundle; + +import '../models/colony_route.dart'; +import '../models/calendar_event_entry.dart'; +import '../models/demo_profile.dart'; +import '../models/route_guide_entry.dart'; +import '../models/route_notification.dart'; +import '../models/truck_route.dart'; + +class LocalSeedRepository { + LocalSeedRepository._(); + + static final LocalSeedRepository instance = LocalSeedRepository._(); + Future? _cachedLoad; + + Future load() { + return _cachedLoad ??= _loadInternal(); + } + + Future _loadInternal() async { + try { + final routesJson = await rootBundle.loadString('assets/json/rutas.json'); + final notificationsJson = await rootBundle.loadString('assets/json/notificaciones.json'); + final colonyRoutesJson = await rootBundle.loadString('assets/json/colonias-rutas.json'); + final profilesJson = await rootBundle.loadString('assets/json/perfiles.json'); + final calendarEventsJson = await rootBundle.loadString('assets/json/calendario.json'); + final routeGuidesJson = await rootBundle.loadString('assets/json/guia-rutas.json'); + + final routes = _decodeList(routesJson).map(TruckRoute.fromJson).toList(growable: false); + final notifications = _decodeList(notificationsJson).map(RouteNotification.fromJson).toList(growable: false); + final colonyRoutes = _decodeList(colonyRoutesJson).map(ColonyRoute.fromJson).toList(growable: false); + final profiles = _decodeList(profilesJson).map(DemoProfile.fromJson).toList(growable: false); + final calendarEvents = _decodeList(calendarEventsJson).map(CalendarEventEntry.fromJson).toList(growable: false); + final routeGuides = _decodeList(routeGuidesJson).map(RouteGuideEntry.fromJson).toList(growable: false); + + return LocalSeedData( + routes: routes, + notifications: notifications, + colonyRoutes: colonyRoutes, + demoProfiles: profiles, + calendarEvents: calendarEvents, + routeGuides: routeGuides, + ); + } catch (_) { + return LocalSeedData.empty(); + } + } + + List> _decodeList(String responseBody) { + final decoded = jsonDecode(responseBody); + if (decoded is! List) { + return >[]; + } + + return decoded.whereType>().toList(growable: false); + } +} + +class LocalSeedData { + const LocalSeedData({ + required this.routes, + required this.notifications, + required this.colonyRoutes, + required this.demoProfiles, + required this.calendarEvents, + required this.routeGuides, + }); + + final List routes; + final List notifications; + final List colonyRoutes; + final List demoProfiles; + final List calendarEvents; + final List routeGuides; + + const LocalSeedData.empty() + : routes = const [], + notifications = const [], + colonyRoutes = const [], + demoProfiles = const [], + calendarEvents = const [], + routeGuides = const []; + + TruckRoute? get defaultRoute => routes.isEmpty ? null : routes.first; + + TruckRoute? routeForColonia(String? colonia) { + if (colonia == null || colonia.trim().isEmpty) { + return defaultRoute; + } + + final routeId = colonyRouteForColonia(colonia)?.routeId; + if (routeId == null) { + return defaultRoute; + } + + return routeById(routeId) ?? defaultRoute; + } + + ColonyRoute? colonyRouteForColonia(String colonia) { + final normalized = colonia.trim().toLowerCase(); + for (final item in colonyRoutes) { + if (item.colonia.trim().toLowerCase() == normalized) { + return item; + } + } + return null; + } + + TruckRoute? routeById(String routeId) { + for (final route in routes) { + if (route.routeId == routeId) { + return route; + } + } + return null; + } + + DemoProfile? profileForCredentials(String email, String password) { + final normalizedEmail = email.trim().toLowerCase(); + for (final profile in demoProfiles) { + if (profile.email.trim().toLowerCase() == normalizedEmail && profile.password == password) { + return profile; + } + } + return null; + } + + DemoProfile? profileForColonia(String? colonia) { + if (colonia == null || colonia.trim().isEmpty) { + return demoProfiles.isEmpty ? null : demoProfiles.first; + } + + final normalized = colonia.trim().toLowerCase(); + for (final profile in demoProfiles) { + if (profile.colonia.trim().toLowerCase() == normalized) { + return profile; + } + } + return demoProfiles.isEmpty ? null : demoProfiles.first; + } + + List eventsForDay(DateTime day) { + final normalized = DateTime(day.year, day.month, day.day); + return calendarEvents + .where((event) => event.date.year == normalized.year && event.date.month == normalized.month && event.date.day == normalized.day) + .toList(growable: false); + } + + RouteGuideEntry? guideForRouteId(String routeId) { + for (final guide in routeGuides) { + if (guide.routeId == routeId) { + return guide; + } + } + return null; + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /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 0000000..900e421 --- /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 "flutter_application_1") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.flutter_application_1") + +# 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 0000000..d5bd016 --- /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 0000000..e71a16d --- /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 0000000..e0f0a47 --- /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 0000000..2e1de87 --- /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 0000000..e97dabc --- /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 0000000..e7c5c54 --- /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 0000000..9f21c16 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#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, "flutter_application_1"); + 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, "flutter_application_1"); + } + + 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 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#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 0000000..746adbb --- /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 0000000..c2efd0b --- /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 0000000..c2efd0b --- /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 0000000..de906b1 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import geolocator_apple +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin")) + 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 0000000..703ede0 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*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 */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* 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 /* flutter_application_1.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "flutter_application_1.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 = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + 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 /* flutter_application_1.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 = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* flutter_application_1.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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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.example.flutterApplication1.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/flutter_application_1.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/flutter_application_1"; + }; + 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.example.flutterApplication1.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/flutter_application_1.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/flutter_application_1"; + }; + 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.example.flutterApplication1.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/flutter_application_1.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/flutter_application_1"; + }; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency 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 0000000..18d9810 --- /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 0000000..277525e --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /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 0000000..18d9810 --- /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 0000000..b3c1761 --- /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 0000000..a2ec33f --- /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 0000000..82b6f9d 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 0000000..13b35eb 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 0000000..0a3f5fa 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 0000000..bdb5722 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 0000000..f083318 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 0000000..326c0e7 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 0000000..2f1632c 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 0000000..80e867a --- /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 0000000..8092559 --- /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 = flutter_application_1 + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1 + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /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 0000000..dff4f49 --- /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 0000000..42bcbf4 --- /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 0000000..dddb8a3 --- /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 0000000..4789daa --- /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 0000000..3cc05eb --- /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 0000000..852fa1a --- /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 0000000..61f3bd1 --- /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 0000000..f2825cd --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,546 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + 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: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + 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" + crypto: + dependency: transitive + 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: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + dart_earcut: + dependency: transitive + description: + name: dart_earcut + sha256: e485001bfc05dcbc437d7bfb666316182e3522d4c3f9668048e004d0eb2ce43b + url: "https://pub.dev" + source: hosted + version: "1.2.0" + 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: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + 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_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.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" + geolocator: + dependency: "direct main" + description: + name: geolocator + sha256: f62bcd90459e63210bbf9c35deb6a51c521f992a78de19a1fe5c11704f9530e2 + url: "https://pub.dev" + source: hosted + version: "13.0.4" + geolocator_android: + dependency: transitive + description: + name: geolocator_android + sha256: fcb1760a50d7500deca37c9a666785c047139b5f9ee15aa5469fae7dbbe3170d + url: "https://pub.dev" + source: hosted + version: "4.6.2" + geolocator_apple: + dependency: transitive + description: + name: geolocator_apple + sha256: dbdd8789d5aaf14cf69f74d4925ad1336b4433a6efdf2fce91e8955dc921bf22 + url: "https://pub.dev" + source: hosted + version: "2.3.13" + geolocator_platform_interface: + dependency: transitive + description: + name: geolocator_platform_interface + sha256: "30cb64f0b9adcc0fb36f628b4ebf4f731a2961a0ebd849f4b56200205056fe67" + url: "https://pub.dev" + source: hosted + version: "4.2.6" + geolocator_web: + dependency: transitive + description: + name: geolocator_web + sha256: b1ae9bdfd90f861fde8fd4f209c37b953d65e92823cb73c7dee1fa021b06f172 + url: "https://pub.dev" + source: hosted + version: "4.1.3" + geolocator_windows: + dependency: transitive + description: + name: geolocator_windows + sha256: "175435404d20278ffd220de83c2ca293b73db95eafbdc8131fe8609be1421eb6" + url: "https://pub.dev" + source: hosted + version: "0.2.5" + 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" + 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: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + 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: "25aee487596a6257655a1e091ec2ae66bc30e7af663592cc3a27e6591e05035c" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + url: "https://pub.dev" + source: hosted + version: "1.18.0" + mgrs_dart: + dependency: transitive + description: + name: mgrs_dart + sha256: fb89ae62f05fa0bb90f70c31fc870bcbcfd516c843fb554452ab3396f78586f7 + url: "https://pub.dev" + source: hosted + version: "2.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" + 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" + 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" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.dev" + source: hosted + version: "2.5.5" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + url: "https://pub.dev" + source: hosted + version: "2.4.23" + 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: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + 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" + simple_gesture_detector: + dependency: transitive + description: + name: simple_gesture_detector + sha256: ba2cd5af24ff20a0b8d609cec3f40e5b0744d2a71804a2616ae086b9c19d19a3 + url: "https://pub.dev" + source: hosted + version: "0.2.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + 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" + table_calendar: + dependency: "direct main" + description: + name: table_calendar + sha256: "0c0c6219878b363a2d5f40c7afb159d845f253d061dc3c822aa0d5fe0f721982" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + 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: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + url: "https://pub.dev" + source: hosted + version: "0.7.11" + 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: transitive + description: + name: uuid + sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + url: "https://pub.dev" + source: hosted + version: "4.5.3" + 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: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" + 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" +sdks: + dart: ">=3.12.0 <4.0.0" + flutter: ">=3.35.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..1d15a15 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,98 @@ +name: flutter_application_1 +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.12.0 + +# 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 + http: ^1.3.0 + shared_preferences: ^2.3.3 + flutter_map: ^7.0.2 + latlong2: ^0.9.1 + geolocator: ^13.0.2 + table_calendar: ^3.1.2 + +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: ^6.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 + + assets: + - assets/json/ + + # 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 0000000..9153f04 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:flutter_application_1/main.dart'; +import 'package:flutter_application_1/models/address_entry.dart'; +import 'package:flutter_application_1/models/address_record.dart'; +import 'package:flutter_application_1/models/auth_session.dart'; +import 'package:flutter_application_1/services/address_repository.dart'; +import 'package:flutter_application_1/services/auth_repository.dart'; + +void main() { + testWidgets('Muestra login, pasa a dirección y abre el tablero', (WidgetTester tester) async { + final authRepository = FakeAuthRepository(); + final addressRepository = FakeAddressRepository(); + + await tester.pumpWidget( + MyApp( + authRepository: authRepository, + addressRepository: addressRepository, + enableLiveFeatures: false, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Bienvenido'), findsOneWidget); + expect(find.text('Entrar'), findsOneWidget); + expect(find.text('Crear cuenta'), findsOneWidget); + + await tester.enterText(find.byType(TextFormField).at(0), 'demo@correo.com'); + await tester.enterText(find.byType(TextFormField).at(1), '123456'); + await tester.ensureVisible(find.text('Ingresar')); + await tester.tap(find.text('Ingresar')); + await tester.pumpAndSettle(); + + expect(find.text('Dirección'), findsOneWidget); + expect(find.text('Guardar dirección'), findsOneWidget); + + await tester.enterText(find.byType(TextFormField).at(0), '12A'); + await tester.enterText(find.byType(TextFormField).at(1), 'Centro'); + await tester.enterText(find.byType(TextFormField).at(2), 'Reforma'); + await tester.tap(find.text('Guardar dirección')); + await tester.pump(); + await tester.pump(const Duration(seconds: 2)); + + expect(addressRepository.savedAddress, isNotNull); + final hasBottomNavigation = find.byType(NavigationBar).evaluate().isNotEmpty; + final hasNavigationRail = find.byType(NavigationRail).evaluate().isNotEmpty; + expect(hasBottomNavigation || hasNavigationRail, isTrue); + expect(find.text('Mapa'), findsOneWidget); + expect(find.text('Calendario'), findsOneWidget); + expect(find.text('Avisos'), findsOneWidget); + expect(find.text('Datos'), findsOneWidget); + }); +} + +class FakeAuthRepository implements AuthRepository { + AuthSession? _session; + + @override + Future restoreSession() async => _session; + + @override + Future signIn({required String email, required String password}) async { + _session = AuthSession(token: 'token-login', email: email, displayName: 'Usuario'); + return _session!; + } + + @override + Future signUp({required String name, required String email, required String password}) async { + _session = AuthSession(token: 'token-register', email: email, displayName: name); + return _session!; + } + + @override + Future signOut() async { + _session = null; + } +} + +class FakeAddressRepository implements AddressRepository { + AddressEntry? savedAddress; + + @override + Future saveAddress({required AuthSession session, required AddressEntry address}) async { + savedAddress = address; + } + + @override + Future> getMyAddresses({required AuthSession session}) async { + return savedAddress == null + ? [] + : [ + AddressRecord( + id: 1, + houseNumber: savedAddress!.houseNumber, + colonia: savedAddress!.colonia, + street: savedAddress!.street, + ), + ]; + } +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a 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 0000000..b749bfe 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 0000000..88cfd48 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 0000000..eb9b4d7 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 0000000..d69c566 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 0000000..0954158 --- /dev/null +++ b/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + flutter_application_1 + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..dd8e066 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "flutter_application_1", + "short_name": "flutter_application_1", + "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 0000000..d492d0d --- /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 0000000..8cc860b --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(flutter_application_1 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 "flutter_application_1") + +# 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 0000000..903f489 --- /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 0000000..1ece8f2 --- /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) { + GeolocatorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("GeolocatorWindows")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /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 0000000..7f101a7 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + geolocator_windows +) + +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 0000000..394917c --- /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 0000000..55bf283 --- /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.example" "\0" + VALUE "FileDescription", "flutter_application_1" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "flutter_application_1" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "flutter_application_1.exe" "\0" + VALUE "ProductName", "flutter_application_1" "\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 0000000..955ee30 --- /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 0000000..6da0652 --- /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 0000000..bb23060 --- /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"flutter_application_1", 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 0000000..66a65d1 --- /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 0000000..c04e20c 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 0000000..153653e --- /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 0000000..3cb7146 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#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(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(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 0000000..3879d54 --- /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 0000000..60608d0 --- /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 0000000..e901dde --- /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_