diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..24476c5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..ff2d6f1 --- /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: "2e9cb0aa71a386a91f73f7088d115c0d96654829" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + base_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + - platform: android + create_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + base_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + - platform: ios + create_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + base_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + - platform: linux + create_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + base_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + - platform: macos + create_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + base_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + - platform: web + create_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + base_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + - platform: windows + create_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + base_revision: 2e9cb0aa71a386a91f73f7088d115c0d96654829 + + # 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/LICENSE b/LICENSE new file mode 100644 index 0000000..1b8cef1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Pedro Pontes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index c747d37..fa2e4d3 100644 --- a/README.md +++ b/README.md @@ -1 +1,53 @@ -Descrição: [desafio_flutter.pdf](./desafio_flutter.pdf) +# Wattio + +Teste Flutter Wattio + +## Visão Geral + +O Aplicativo Wattio é uma aplicação Flutter onde o usuário insere alguns dados sobre si mesmo e, com base nesses dados, recebe diferentes ofertas das cooperativas pré-cadastradas. As ofertas são listadas de acordo com as condições de cada cooperativa, se os dados que o usuário inseriu combinam com elas. Após receber as ofertas, o usuário escolhe uma e a aplicação mostra a economia que ele vai ganhar com essa oferta. + +## Imagens screen + + + + + + +## test unitario screen + + + +## Como Usar + +### Pré-requisitos + +- Flutter 3.10.6 +- Dart 3.0.6 + +### Instalação + +1. Clone o repositório: + + ```bash + git clone https://github.com/pontes2014/wattio-frontend-desafio + ``` + +2. Navegue até o diretório do projeto: + + ```bash + cd seu-repositorio + ``` + +3. Execute os comandos: + + ```bash + flutter pub get + flutter run + ``` + +Agora você pode abrir o aplicativo no seu dispositivo ou emulador. + +## Licença + +@pontes2014 + 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..6f56801 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..6ecea00 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,67 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +android { + namespace "com.example.wattio_test" + compileSdkVersion flutter.compileSdkVersion + ndkVersion flutter.ndkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "com.example.wattio_test" + // You can update the following values to match your application needs. + // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + + 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.debug + } + } +} + +flutter { + source '../..' +} + +dependencies {} 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..6c369c3 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/wattio_test/MainActivity.kt b/android/app/src/main/kotlin/com/example/wattio_test/MainActivity.kt new file mode 100644 index 0000000..05365b1 --- /dev/null +++ b/android/app/src/main/kotlin/com/example/wattio_test/MainActivity.kt @@ -0,0 +1,6 @@ +package com.example.wattio_test + +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 b/android/build.gradle new file mode 100644 index 0000000..e83fb5d --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,30 @@ +buildscript { + ext.kotlin_version = '1.7.10' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..598d13f --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx4G +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3c472b9 --- /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-7.5-all.zip diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..7cd7128 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,29 @@ +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + } + settings.ext.flutterSdkPath = flutterSdkPath() + + includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } + + plugins { + id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false + } +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "7.3.0" apply false +} + +include ":app" diff --git a/assets/images/calculadora.png b/assets/images/calculadora.png new file mode 100644 index 0000000..b0cb985 Binary files /dev/null and b/assets/images/calculadora.png differ diff --git a/assets/images/companhia.png b/assets/images/companhia.png new file mode 100644 index 0000000..53b6858 Binary files /dev/null and b/assets/images/companhia.png differ diff --git a/assets/images/consumo-de-energia.png b/assets/images/consumo-de-energia.png new file mode 100644 index 0000000..c348b07 Binary files /dev/null and b/assets/images/consumo-de-energia.png differ diff --git a/assets/images/desconto.png b/assets/images/desconto.png new file mode 100644 index 0000000..8ff63b1 Binary files /dev/null and b/assets/images/desconto.png differ diff --git a/assets/images/economico.png b/assets/images/economico.png new file mode 100644 index 0000000..b9aff69 Binary files /dev/null and b/assets/images/economico.png differ diff --git a/assets/images/icon_energia.png b/assets/images/icon_energia.png new file mode 100644 index 0000000..dfc5db4 Binary files /dev/null and b/assets/images/icon_energia.png differ diff --git a/assets/images/livro.png b/assets/images/livro.png new file mode 100644 index 0000000..def027e Binary files /dev/null and b/assets/images/livro.png differ diff --git a/assets/json/descontos_pf_empresas.json b/assets/json/descontos_pf_empresas.json new file mode 100644 index 0000000..3ed9cdb --- /dev/null +++ b/assets/json/descontos_pf_empresas.json @@ -0,0 +1,178 @@ +{ + "empresas": [ + { + "nome": "EnerLimpa", + "valorMinimoMensal": 100, + "valorMaximoMensal": 500, + "desconto": 5 + }, + { + "nome": "EcoEnergia", + "valorMinimoMensal": 180, + "valorMaximoMensal": 600, + "desconto": 4 + }, + { + "nome": "SustentaPower", + "valorMinimoMensal": 10, + "valorMaximoMensal": 700, + "desconto": 3 + }, + { + "nome": "GreenTech", + "valorMinimoMensal": 250, + "valorMaximoMensal": 800, + "desconto": 2 + }, + { + "nome": "RenovaEco", + "valorMinimoMensal": 170, + "valorMaximoMensal": 550, + "desconto": 5 + }, + { + "nome": "EcoPower", + "valorMinimoMensal": 190, + "valorMaximoMensal": 620, + "desconto": 4 + }, + { + "nome": "NaturezaViva", + "valorMinimoMensal": 220, + "valorMaximoMensal": 680, + "desconto": 3 + }, + { + "nome": "LimpEnergia", + "valorMinimoMensal": 280, + "valorMaximoMensal": 750, + "desconto": 2 + }, + { + "nome": "VerdeSustentável", + "valorMinimoMensal": 160, + "valorMaximoMensal": 530, + "desconto": 5 + }, + { + "nome": "EcoFriendlyPower", + "valorMinimoMensal": 200, + "valorMaximoMensal": 690, + "desconto": 4 + }, + { + "nome": "LimpaEnergia", + "valorMinimoMensal": 240, + "valorMaximoMensal": 770, + "desconto": 3 + }, + { + "nome": "SustainableSolutions", + "valorMinimoMensal": 210, + "valorMaximoMensal": 730, + "desconto": 2 + }, + { + "nome": "EnergiaVerde", + "valorMinimoMensal": 190, + "valorMaximoMensal": 620, + "desconto": 5 + }, + { + "nome": "CleanPowerCo", + "valorMinimoMensal": 160, + "valorMaximoMensal": 530, + "desconto": 4 + }, + { + "nome": "EcoSource", + "valorMinimoMensal": 230, + "valorMaximoMensal": 700, + "desconto": 3 + }, + { + "nome": "GreenGenius", + "valorMinimoMensal": 250, + "valorMaximoMensal": 780, + "desconto": 2 + }, + { + "nome": "RenewableEnergyCorp", + "valorMinimoMensal": 210, + "valorMaximoMensal": 730, + "desconto": 5 + }, + { + "nome": "PureEcoPower", + "valorMinimoMensal": 180, + "valorMaximoMensal": 600, + "desconto": 4 + }, + { + "nome": "GreenHarmony", + "valorMinimoMensal": 200, + "valorMaximoMensal": 650, + "desconto": 3 + }, + { + "nome": "EcoWave", + "valorMinimoMensal": 240, + "valorMaximoMensal": 720, + "desconto": 2 + }, + { + "nome": "CleanEnergySolutions", + "valorMinimoMensal": 170, + "valorMaximoMensal": 550, + "desconto": 5 + }, + { + "nome": "SustainablePowerCo", + "valorMinimoMensal": 230, + "valorMaximoMensal": 770, + "desconto": 4 + }, + { + "nome": "EcoBright", + "valorMinimoMensal": 210, + "valorMaximoMensal": 730, + "desconto": 3 + }, + { + "nome": "GreenEnergize", + "valorMinimoMensal": 190, + "valorMaximoMensal": 620, + "desconto": 2 + }, + { + "nome": "RenewablePowerSolutions", + "valorMinimoMensal": 160, + "valorMaximoMensal": 530, + "desconto": 5 + }, + { + "nome": "EcoSpark", + "valorMinimoMensal": 180, + "valorMaximoMensal": 600, + "desconto": 4 + }, + { + "nome": "PureGreenEnergy", + "valorMinimoMensal": 220, + "valorMaximoMensal": 680, + "desconto": 3 + }, + { + "nome": "GreenTechSolutions", + "valorMinimoMensal": 250, + "valorMaximoMensal": 800, + "desconto": 2 + }, + { + "nome": "EcoInnovate", + "valorMinimoMensal": 240, + "valorMaximoMensal": 720, + "desconto": 5 + } + ] +} diff --git a/assets/json/descontos_pj_empresas.json b/assets/json/descontos_pj_empresas.json new file mode 100644 index 0000000..49f8604 --- /dev/null +++ b/assets/json/descontos_pj_empresas.json @@ -0,0 +1,454 @@ +{ + "empresas": [ + { + "nome": "EnerLimpa", + "valorMinimoMensal": 1000, + "valorMaximoMensal": 2500, + "desconto": 8 + }, + { + "nome": "EcoEnergia", + "valorMinimoMensal": 1200, + "valorMaximoMensal": 2800, + "desconto": 10 + }, + { + "nome": "SustentaPower", + "valorMinimoMensal": 1300, + "valorMaximoMensal": 3000, + "desconto": 12 + }, + { + "nome": "GreenTech", + "valorMinimoMensal": 1100, + "valorMaximoMensal": 2600, + "desconto": 14 + }, + { + "nome": "RenovaEco", + "valorMinimoMensal": 1400, + "valorMaximoMensal": 3200, + "desconto": 16 + }, + { + "nome": "EcoPower", + "valorMinimoMensal": 1500, + "valorMaximoMensal": 3400, + "desconto": 18 + }, + { + "nome": "NaturezaViva", + "valorMinimoMensal": 1600, + "valorMaximoMensal": 3600, + "desconto": 20 + }, + { + "nome": "LimpEnergia", + "valorMinimoMensal": 1700, + "valorMaximoMensal": 3800, + "desconto": 22 + }, + { + "nome": "VerdeSustentável", + "valorMinimoMensal": 1800, + "valorMaximoMensal": 4000, + "desconto": 24 + }, + { + "nome": "EcoFriendlyPower", + "valorMinimoMensal": 1900, + "valorMaximoMensal": 4200, + "desconto": 26 + }, + { + "nome": "LimpaEnergia", + "valorMinimoMensal": 2000, + "valorMaximoMensal": 4400, + "desconto": 28 + }, + { + "nome": "SustainableSolutions", + "valorMinimoMensal": 2100, + "valorMaximoMensal": 4600, + "desconto": 30 + }, + { + "nome": "EnergiaVerde", + "valorMinimoMensal": 2200, + "valorMaximoMensal": 4800, + "desconto": 32 + }, + { + "nome": "CleanPowerCo", + "valorMinimoMensal": 2300, + "valorMaximoMensal": 5000, + "desconto": 34 + }, + { + "nome": "EcoSource", + "valorMinimoMensal": 2400, + "valorMaximoMensal": 5200, + "desconto": 36 + }, + { + "nome": "PontesEletricas", + "valorMinimoMensal": 100, + "valorMaximoMensal": 5200, + "desconto": 10 + }, + { + "nome": "GreenGenius", + "valorMinimoMensal": 2500, + "valorMaximoMensal": 5400, + "desconto": 38 + }, + { + "nome": "RenewableEnergyCorp", + "valorMinimoMensal": 2600, + "valorMaximoMensal": 5600, + "desconto": 40 + }, + { + "nome": "PureEcoPower", + "valorMinimoMensal": 2700, + "valorMaximoMensal": 5800, + "desconto": 42 + }, + { + "nome": "GreenHarmony", + "valorMinimoMensal": 2800, + "valorMaximoMensal": 6000, + "desconto": 43 + }, + { + "nome": "EcoWave", + "valorMinimoMensal": 2900, + "valorMaximoMensal": 6200, + "desconto": 42 + }, + { + "nome": "CleanEnergySolutions", + "valorMinimoMensal": 3000, + "valorMaximoMensal": 6400, + "desconto": 40 + }, + { + "nome": "SustainablePowerCo", + "valorMinimoMensal": 3100, + "valorMaximoMensal": 6600, + "desconto": 38 + }, + { + "nome": "EcoBright", + "valorMinimoMensal": 3200, + "valorMaximoMensal": 6800, + "desconto": 36 + }, + { + "nome": "GreenEnergize", + "valorMinimoMensal": 3300, + "valorMaximoMensal": 7000, + "desconto": 34 + }, + { + "nome": "RenewablePowerSolutions", + "valorMinimoMensal": 3400, + "valorMaximoMensal": 7200, + "desconto": 32 + }, + { + "nome": "EcoSpark", + "valorMinimoMensal": 3500, + "valorMaximoMensal": 7400, + "desconto": 30 + }, + { + "nome": "PureGreenEnergy", + "valorMinimoMensal": 3600, + "valorMaximoMensal": 7600, + "desconto": 28 + }, + { + "nome": "GreenTechSolutions", + "valorMinimoMensal": 3700, + "valorMaximoMensal": 7800, + "desconto": 26 + }, + { + "nome": "EcoInnovate", + "valorMinimoMensal": 3800, + "valorMaximoMensal": 8000, + "desconto": 24 + }, + { + "nome": "EcoMax", + "valorMinimoMensal": 3900, + "valorMaximoMensal": 8200, + "desconto": 22 + }, + { + "nome": "PowerSavings", + "valorMinimoMensal": 4000, + "valorMaximoMensal": 8400, + "desconto": 20 + }, + { + "nome": "EcoSolution", + "valorMinimoMensal": 4100, + "valorMaximoMensal": 8600, + "desconto": 18 + }, + { + "nome": "GreenEnergyGroup", + "valorMinimoMensal": 4200, + "valorMaximoMensal": 8800, + "desconto": 16 + }, + { + "nome": "RenewablePowerTech", + "valorMinimoMensal": 4300, + "valorMaximoMensal": 9000, + "desconto": 14 + }, + { + "nome": "EcoHarmony", + "valorMinimoMensal": 4400, + "valorMaximoMensal": 9200, + "desconto": 12 + }, + { + "nome": "SustainableEnergyCo", + "valorMinimoMensal": 4500, + "valorMaximoMensal": 9400, + "desconto": 10 + }, + { + "nome": "GreenTechInnovate", + "valorMinimoMensal": 4600, + "valorMaximoMensal": 9600, + "desconto": 8 + }, + { + "nome": "EcoPowerSolutions", + "valorMinimoMensal": 4700, + "valorMaximoMensal": 9800, + "desconto": 10 + }, + { + "nome": "RenewableEcoTech", + "valorMinimoMensal": 4800, + "valorMaximoMensal": 10000, + "desconto": 12 + }, + { + "nome": "EcoDynamic", + "valorMinimoMensal": 4900, + "valorMaximoMensal": 10200, + "desconto": 14 + }, + { + "nome": "GreenInnovators", + "valorMinimoMensal": 5000, + "valorMaximoMensal": 10400, + "desconto": 16 + }, + { + "nome": "EcoRevolution", + "valorMinimoMensal": 5100, + "valorMaximoMensal": 10600, + "desconto": 18 + }, + { + "nome": "EcoFuture", + "valorMinimoMensal": 5200, + "valorMaximoMensal": 10800, + "desconto": 20 + }, + { + "nome": "SustainableInnovate", + "valorMinimoMensal": 5300, + "valorMaximoMensal": 11000, + "desconto": 22 + }, + { + "nome": "GreenSolutions", + "valorMinimoMensal": 5400, + "valorMaximoMensal": 11200, + "desconto": 24 + }, + { + "nome": "EcoTechGroup", + "valorMinimoMensal": 5500, + "valorMaximoMensal": 11400, + "desconto": 26 + }, + { + "nome": "RenewableEnergyInnovate", + "valorMinimoMensal": 5600, + "valorMaximoMensal": 11600, + "desconto": 28 + }, + { + "nome": "EcoInnovation", + "valorMinimoMensal": 5700, + "valorMaximoMensal": 11800, + "desconto": 30 + }, + { + "nome": "GreenPowerTech", + "valorMinimoMensal": 5800, + "valorMaximoMensal": 12000, + "desconto": 32 + }, + { + "nome": "EcoHarvest", + "valorMinimoMensal": 5900, + "valorMaximoMensal": 12200, + "desconto": 34 + }, + { + "nome": "SustainableTech", + "valorMinimoMensal": 6000, + "valorMaximoMensal": 12400, + "desconto": 36 + }, + { + "nome": "GreenEcoSolutions", + "valorMinimoMensal": 6100, + "valorMaximoMensal": 12600, + "desconto": 38 + }, + { + "nome": "RenewableInnovate", + "valorMinimoMensal": 6200, + "valorMaximoMensal": 12800, + "desconto": 40 + }, + { + "nome": "EcoGenius", + "valorMinimoMensal": 6300, + "valorMaximoMensal": 13000, + "desconto": 42 + }, + { + "nome": "GreenPowerSolutions", + "valorMinimoMensal": 6400, + "valorMaximoMensal": 13200, + "desconto": 43 + }, + { + "nome": "EcoRenew", + "valorMinimoMensal": 6500, + "valorMaximoMensal": 13400, + "desconto": 42 + }, + { + "nome": "SustainableEnergyCo", + "valorMinimoMensal": 6600, + "valorMaximoMensal": 13600, + "desconto": 40 + }, + { + "nome": "GreenTechInnovate", + "valorMinimoMensal": 6700, + "valorMaximoMensal": 13800, + "desconto": 38 + }, + { + "nome": "EcoBright", + "valorMinimoMensal": 6800, + "valorMaximoMensal": 14000, + "desconto": 36 + }, + { + "nome": "GreenEnergize", + "valorMinimoMensal": 6900, + "valorMaximoMensal": 14200, + "desconto": 34 + }, + { + "nome": "EcoRevolution", + "valorMinimoMensal": 6400, + "valorMaximoMensal": 13200, + "desconto": 43 + }, + { + "nome": "EcoMax", + "valorMinimoMensal": 6500, + "valorMaximoMensal": 13400, + "desconto": 42 + }, + { + "nome": "PowerSavings", + "valorMinimoMensal": 6600, + "valorMaximoMensal": 13600, + "desconto": 4 + }, + { + "nome": "EcoSolution", + "valorMinimoMensal": 6700, + "valorMaximoMensal": 13800, + "desconto": 38 + }, + { + "nome": "GreenEnergyGroup", + "valorMinimoMensal": 6800, + "valorMaximoMensal": 14000, + "desconto": 36 + }, + { + "nome": "RenewablePowerTech", + "valorMinimoMensal": 6900, + "valorMaximoMensal": 14200, + "desconto": 34 + }, + { + "nome": "GreenEnergyGroup", + "valorMinimoMensal": 8000, + "valorMaximoMensal": 14200, + "desconto": 40 + }, + { + "nome": "RenewablePowerTech", + "valorMinimoMensal": 8300, + "valorMaximoMensal": 16000, + "desconto": 40 + }, + { + "nome": "EcoHarmony", + "valorMinimoMensal": 8400, + "valorMaximoMensal": 16000, + "desconto": 12 + }, + { + "nome": "SustainableEnergyCo", + "valorMinimoMensal": 9000, + "valorMaximoMensal": 19400, + "desconto": 54 + }, + { + "nome": "GreenTechInnovate", + "valorMinimoMensal": 9000, + "valorMaximoMensal": 19600, + "desconto": 8 + }, + { + "nome": "EcoPowerSolutions", + "valorMinimoMensal": 14700, + "valorMaximoMensal": 20000, + "desconto": 14 + }, + { + "nome": "RenewableEcoTech", + "valorMinimoMensal": 13800, + "valorMaximoMensal": 20000, + "desconto": 12 + }, + { + "nome": "EcoDynamic", + "valorMinimoMensal": 12900, + "valorMaximoMensal": 19200, + "desconto": 14 + } + ] +} \ No newline at end of file diff --git a/calculete_screen2.jpeg b/calculete_screen2.jpeg new file mode 100644 index 0000000..99f5164 Binary files /dev/null and b/calculete_screen2.jpeg differ diff --git a/empresas_screen.jpeg b/empresas_screen.jpeg new file mode 100644 index 0000000..b7ed7df Binary files /dev/null and b/empresas_screen.jpeg differ diff --git a/initial_screen.jpeg b/initial_screen.jpeg new file mode 100644 index 0000000..d7f78b8 Binary files /dev/null and b/initial_screen.jpeg differ diff --git a/lib/data/repositories/api_service.dart.dart b/lib/data/repositories/api_service.dart.dart new file mode 100644 index 0000000..a3cf6fd --- /dev/null +++ b/lib/data/repositories/api_service.dart.dart @@ -0,0 +1,15 @@ +import 'dart:convert'; +import 'package:flutter/services.dart'; + +class ApiService { + static Future> fetchData(String fileName) async { + try { + String data = await rootBundle.loadString('assets/json/$fileName'); + return json.decode(data)['empresas']; + } catch (error) { + throw Exception('Failed to load data: $error'); + } + } +} + + diff --git a/lib/data/repositories/desconto_repository.dart b/lib/data/repositories/desconto_repository.dart new file mode 100644 index 0000000..47d2566 --- /dev/null +++ b/lib/data/repositories/desconto_repository.dart @@ -0,0 +1,22 @@ +import 'package:wattio_test/data/repositories/api_service.dart.dart'; + +class DescontoRepository { + Future>> fetchDescontos(String tipoCliente) async { + try { + String fileName = tipoCliente == 'PF' + ? 'descontos_pf_empresas.json' + : 'descontos_pj_empresas.json'; + + List data = await ApiService.fetchData(fileName); + + if (data.every((element) => element is Map)) { + return List>.from(data); + } else { + throw Exception('Invalid data format'); + } + } catch (error) { + throw Exception('Failed to load descontos: $error'); + } + } +} + diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..474bd59 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,30 @@ +import 'package:flutter/material.dart'; +import 'package:wattio_test/presentation/tabbar.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'wattio test', + debugShowCheckedModeBanner: false, + themeMode: ThemeMode.dark, + darkTheme: ThemeData( + scaffoldBackgroundColor: Colors.black, + brightness: Brightness.dark, + bottomNavigationBarTheme: const BottomNavigationBarThemeData( + backgroundColor: Colors.white10, + type: BottomNavigationBarType.fixed, + selectedLabelStyle: TextStyle(fontSize: 12), + unselectedLabelStyle: TextStyle(fontSize: 12), + selectedItemColor: Colors.white, + unselectedItemColor: Colors.white38)), + home: Tabbar(), + ); + } +} diff --git a/lib/presentation/screens/calculete_screen.dart b/lib/presentation/screens/calculete_screen.dart new file mode 100644 index 0000000..fa28c76 --- /dev/null +++ b/lib/presentation/screens/calculete_screen.dart @@ -0,0 +1,170 @@ +import 'package:flutter/material.dart'; +import 'package:wattio_test/data/repositories/desconto_repository.dart'; +import 'package:wattio_test/presentation/widgets/dialog_helper.dart'; + +class CalculateScreen extends StatefulWidget { + const CalculateScreen({Key? key}) : super(key: key); + + @override + _CalculateScreenState createState() => _CalculateScreenState(); +} + +class _CalculateScreenState extends State { + TextEditingController gastoMensalController = TextEditingController(); + String selectedType = 'PF'; + List> ofertaData = []; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Calcular Ofertas'), + ), + body: ListView( + padding: const EdgeInsets.all(16.0), + children: [ + const Text( + 'Calcule a economia da sua energia', + style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 16), + const Text( + 'O valor médio mensal da sua conta de energia é:', + style: TextStyle(fontSize: 18), + ), + Row( + children: [ + const Text( + 'R\$', + style: TextStyle(fontSize: 18), + ), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: gastoMensalController, + keyboardType: TextInputType.number, + decoration: const InputDecoration( + hintText: 'Insira o valor', + ), + ), + ), + ], + ), + const SizedBox(height: 16), + const Text( + 'Selecione o tipo de cliente:', + style: TextStyle(fontSize: 18), + ), + DropdownButton( + value: selectedType, + onChanged: (String? newValue) { + setState(() { + selectedType = newValue!; + }); + }, + items: ['Pessoa Física', 'Pessoa Jurídica'] + .map>((String value) { + return DropdownMenuItem( + value: value == 'Pessoa Física' ? 'PF' : 'PJ', + child: Text(value), + ); + }).toList(), + ), + const SizedBox(height: 16), + ElevatedButton( + onPressed: () { + _handleCalculateButton(); + }, + child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + const Text("Calcular Ofertas"), + const SizedBox( + width: 20, + ), + Image.asset("assets/images/desconto.png", height: 24, width: 24) + ]), + ), + if (ofertaData.isNotEmpty) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16), + const Text( + 'Ofertas Disponíveis:', + style: TextStyle(fontSize: 18), + ), + SizedBox( + height: MediaQuery.of(context).size.height * 0.4, + child: ListView.builder( + shrinkWrap: true, + itemCount: ofertaData.length, + itemBuilder: (context, index) { + return GestureDetector( + onTap: () { + _showSavingsDialog(ofertaData[index]); + }, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Nome: ${ofertaData[index]['nome']}'), + Text( + 'Desconto: ${_formatarDesconto(ofertaData[index]['desconto'])}', + ), + const Divider(), + ], + ), + ); + }, + ), + ), + ], + ), + if (ofertaData.isEmpty) + const Center( + child: Padding( + padding: EdgeInsets.only(top: 20), + child: Text( + 'Sem ofertas disponíveis', + style: TextStyle(fontSize: 18), + ), + ), + ), + ], + ), + ); + } + + void _showSavingsDialog(Map oferta) { + DialogHelper.showSavingsDialog(context, oferta, gastoMensalController); + } + + void _handleCalculateButton() async { + if (gastoMensalController.text.isEmpty || selectedType.isEmpty) { + DialogHelper.showAlertDialog( + context, 'Aviso', 'Preencha todos os campos para calcular.'); + } else { + double valorMensal = double.parse(gastoMensalController.text); + + try { + List> data = + await DescontoRepository().fetchDescontos(selectedType); + + List> filteredData = data + .where((oferta) => + oferta['valorMinimoMensal'] <= valorMensal && + oferta['valorMaximoMensal'] >= valorMensal) + .toList(); + + setState(() { + ofertaData = List>.from(filteredData); + }); + } catch (error) { + DialogHelper.showAlertDialog( + context, 'Erro', 'Erro ao carregar dados da oferta: $error'); + } + } + } + + String _formatarDesconto(int desconto) { + return '$desconto%'; + } +} diff --git a/lib/presentation/screens/companies_screen.dart b/lib/presentation/screens/companies_screen.dart new file mode 100644 index 0000000..8c33935 --- /dev/null +++ b/lib/presentation/screens/companies_screen.dart @@ -0,0 +1,114 @@ +import 'package:flutter/material.dart'; +import 'package:wattio_test/data/repositories/api_service.dart.dart'; + +class CompaniesScreen extends StatefulWidget { + const CompaniesScreen({Key? key}) : super(key: key); + + @override + _CompaniesScreenState createState() => _CompaniesScreenState(); +} + +class _CompaniesScreenState extends State { + List empresasPF = []; + List empresasPJ = []; + + Future fetchData() async { + try { + List dataPF = + await ApiService.fetchData('descontos_pf_empresas.json'); + List dataPJ = + await ApiService.fetchData('descontos_pj_empresas.json'); + + setState(() { + empresasPF = dataPF; + empresasPJ = dataPJ; + }); + } catch (error) { + print('Error: $error'); + } + } + + @override + void initState() { + super.initState(); + fetchData(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: SingleChildScrollView( + child: Column( + children: [ + const SizedBox(height: 50), + const Text( + "COOPERATIVAS HIDRELETRICAS", + style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), + ), + const Text( + "Empresas", + ), + const SizedBox(height: 50), + Row( + children: [ + SizedBox( + width: MediaQuery.of(context).size.width / 2, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + "Pessoa Física", + style: TextStyle( + fontSize: 18, fontWeight: FontWeight.bold), + ), + SizedBox( + height: MediaQuery.of(context).size.height - 100, + child: ListView.builder( + shrinkWrap: true, + itemCount: empresasPF.length, + itemBuilder: (BuildContext context, int index) { + return ListTile( + title: Text(empresasPF[index]['nome']), + ); + }, + ), + ), + ], + ), + ), + SizedBox( + width: MediaQuery.of(context).size.width / 2, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + "Pessoa Jurídica", + style: TextStyle( + fontSize: 25, fontWeight: FontWeight.bold), + ), + SizedBox( + height: MediaQuery.of(context).size.height - 100, + child: ListView.builder( + shrinkWrap: true, + itemCount: empresasPJ.length, + itemBuilder: (BuildContext context, int index) { + return ListTile( + title: Text(empresasPJ[index]['nome']), + ); + }, + ), + ), + ], + ), + ), + ], + ), + ], + ), + ), + + ), + ); + } +} diff --git a/lib/presentation/screens/initial_screen.dart b/lib/presentation/screens/initial_screen.dart new file mode 100644 index 0000000..d50efea --- /dev/null +++ b/lib/presentation/screens/initial_screen.dart @@ -0,0 +1,17 @@ +import 'package:flutter/material.dart'; + +class InitialScreen extends StatelessWidget { + const InitialScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text("Marketplace de Energia", style: TextStyle(fontSize: 24)), + Image.asset("assets/images/consumo-de-energia.png") + ], + )); + } +} diff --git a/lib/presentation/screens/who_we_are_screen.dart b/lib/presentation/screens/who_we_are_screen.dart new file mode 100644 index 0000000..dd445e5 --- /dev/null +++ b/lib/presentation/screens/who_we_are_screen.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; + +class WhoWeAreScreen extends StatelessWidget { + const WhoWeAreScreen({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return const Scaffold( + body: SingleChildScrollView( + padding: EdgeInsets.only(top: 100,), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + "Iniciativa: Empoderando Consumidores através das Cooperativas de Energia", + style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + Text( + "No Brasil, uma crescente iniciativa tem revolucionado o modo como as pessoas consomem energia. Agora, é possível gerar a própria eletricidade, afastando-se das tradicionais distribuidoras como CEMIG, Energia, CPFL, entre outras. Este movimento não apenas oferece autonomia energética, mas também proporciona significativas economias nas contas mensais de residências e empresas."), + Text( + "Embora as placas de energia solar tenham se popularizado, a instalação de sistemas próprios ainda é uma realidade acessível a poucos. No entanto, uma solução inovadora tem se destacado: a possibilidade de adquirir energia diretamente de usinas locais a preços mais vantajosos do que os praticados pelas distribuidoras convencionais."), + Text( + "A chave para essa transformação reside nas Cooperativas de Energia. Estas entidades atuam como intermediárias, adquirindo o excedente de energia de usinas e de outras residências e empresas com sistemas de geração própria. Posteriormente, comercializam essa energia a consumidores a preços mais competitivos em comparação com as tarifas das distribuidoras tradicionais."), + Text( + "Apesar dos benefícios evidentes, o desconhecimento sobre as Cooperativas de Energia ainda persiste entre os consumidores. Poucos estão cientes das empresas que se autodenominam como cooperativas e do papel crucial que desempenham no novo mercado energético. A falta de informação torna desafiador para os consumidores entenderem como podem se beneficiar dessas iniciativas."), + Text( + "Além disso, a ausência de uma ferramenta unificada para pesquisar e comparar as diferentes ofertas na região dificulta a tomada de decisão. Os consumidores se veem diante da incerteza sobre qual cooperativa escolher para atender às suas necessidades específicas, tornando essencial a criação de ferramentas que facilitem essa busca e comparação."), + Text( + "Dessa forma, ao conscientizar a população sobre as Cooperativas de Energia e proporcionar meios eficazes de pesquisa e comparação, essa iniciativa visa empoderar os consumidores, permitindo-lhes fazer escolhas informadas e usufruir de uma energia mais acessível, sustentável e alinhada com suas necessidades individuais e comerciais."), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/tabbar.dart b/lib/presentation/tabbar.dart new file mode 100644 index 0000000..76172ae --- /dev/null +++ b/lib/presentation/tabbar.dart @@ -0,0 +1,66 @@ +import 'package:flutter/material.dart'; +import 'package:wattio_test/presentation/screens/calculete_screen.dart'; +import 'package:wattio_test/presentation/screens/companies_screen.dart'; +import 'package:wattio_test/presentation/screens/initial_screen.dart'; +import 'package:wattio_test/presentation/screens/who_we_are_screen.dart'; + +class Tabbar extends StatefulWidget { + const Tabbar({super.key}); + + @override + State createState() => _TabbarState(); +} + +class _TabbarState extends State { + int _selectedTab = 0; + + @override + Widget build(BuildContext context) { + return Scaffold( + bottomNavigationBar: BottomNavigationBar( + currentIndex: _selectedTab, + onTap: (index) { + setState(() { + this._selectedTab = index; + }); + }, + items: [ + BottomNavigationBarItem( + icon: Image.asset('assets/images/icon_energia.png', height: 24, width: 24), + label: "Inicio", + ), + BottomNavigationBarItem( + icon: Image.asset('assets/images/calculadora.png', height: 24, width: 24), + label: "Calcular", + ), + BottomNavigationBarItem( + icon: Image.asset('assets/images/companhia.png', height: 24, width: 24), + label: "Empresas", + ), + BottomNavigationBarItem( + icon: Image.asset('assets/images/livro.png', height: 24, width: 24), + label: "Quem somos", + ), + ], + ), + body: Stack( + children: [ + renderView(0, const InitialScreen()), + renderView(1, const CalculateScreen()), + renderView(2, const CompaniesScreen()), + renderView(3, const WhoWeAreScreen()), + ], + ), + ); + } + + Widget renderView(int tabIndex, Widget view) { + return IgnorePointer( + ignoring: _selectedTab != tabIndex, + child: Opacity( + opacity: _selectedTab == tabIndex ? 1 : 0, + child: view, + ), + ); + } +} diff --git a/lib/presentation/widgets/alert_dialog_widget.dart b/lib/presentation/widgets/alert_dialog_widget.dart new file mode 100644 index 0000000..699ef73 --- /dev/null +++ b/lib/presentation/widgets/alert_dialog_widget.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +class AlertDialogWidget { + static void show(BuildContext context, String title, String message) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () { + Navigator.pop(context); + }, + child: Text('OK'), + ), + ], + ); + }, + ); + } +} diff --git a/lib/presentation/widgets/dialog_helper.dart b/lib/presentation/widgets/dialog_helper.dart new file mode 100644 index 0000000..b22564f --- /dev/null +++ b/lib/presentation/widgets/dialog_helper.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; + +class DialogHelper { + static void showAlertDialog(BuildContext context, String title, String message) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: const Text('OK'), + ), + ], + ); + }, + ); + } + + static void showSavingsDialog(BuildContext context, Map oferta, TextEditingController gastoMensalController) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text('Economia Estimada'), + content: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text('Economia Mensal: R\$${_calculateMonthlySavings(oferta, gastoMensalController)}'), + Text('Economia Anual: R\$${_calculateAnnualSavings(oferta, gastoMensalController)}'), + ], + ), + actions: [ + TextButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text('OK'), + ), + TextButton(onPressed: () {}, child: const Text("Contratar")) + ], + ); + }, + ); + } + + static String _calculateMonthlySavings(Map oferta, TextEditingController gastoMensalController) { + int desconto = oferta['desconto']; + double valorMensal = double.parse(gastoMensalController.text); + double descontoPercentual = desconto / 100.0; + double economiaMensal = valorMensal * descontoPercentual; + return economiaMensal.toStringAsFixed(2); + } + + static String _calculateAnnualSavings(Map oferta, TextEditingController gastoMensalController) { + double monthlySavings = double.parse(_calculateMonthlySavings(oferta, gastoMensalController)); + return (monthlySavings * 12.0).toStringAsFixed(2); + } +} diff --git a/lib/presentation/widgets/savings_dialog_widget.dart b/lib/presentation/widgets/savings_dialog_widget.dart new file mode 100644 index 0000000..0df4101 --- /dev/null +++ b/lib/presentation/widgets/savings_dialog_widget.dart @@ -0,0 +1,37 @@ +import 'package:flutter/material.dart'; + +class SavingsDialog { + static void show(BuildContext context, Map oferta, TextEditingController gastoMensalController) { + int desconto = oferta['desconto']; + double valorMensal = double.parse(gastoMensalController.text); + + double descontoPercentual = desconto / 100.0; + double economiaMensal = valorMensal * descontoPercentual; + + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text('Economia Estimada'), + content: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text('Economia Mensal: R\$${economiaMensal.toStringAsFixed(2)}'), + Text('Economia Anual: R\$${economiaMensal * 12.0}'), + ], + ), + actions: [ + TextButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text('OK'), + ), + TextButton(onPressed: () {}, child: const Text("Contratar")) + ], + ); + }, + ); + } +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..1f025a0 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,372 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 + url: "https://pub.dev" + source: hosted + version: "64.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" + url: "https://pub.dev" + source: hosted + version: "6.2.0" + args: + dependency: transitive + description: + name: args + sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + build: + dependency: transitive + description: + name: build + sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.dev" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + sha256: c9aabae0718ec394e5bc3c7272e6bb0dc0b32201a08fe185ec1d8401d3e39309 + url: "https://pub.dev" + source: hosted + version: "8.8.1" + characters: + dependency: transitive + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + clock: + dependency: transitive + description: + name: clock + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + url: "https://pub.dev" + source: hosted + version: "1.1.1" + code_builder: + dependency: transitive + description: + name: code_builder + sha256: f692079e25e7869c14132d39f223f8eec9830eb76131925143b2129c4bb01b37 + url: "https://pub.dev" + source: hosted + version: "4.10.0" + collection: + dependency: transitive + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + convert: + dependency: transitive + description: + name: convert + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + crypto: + dependency: transitive + description: + name: crypto + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + url: "https://pub.dev" + source: hosted + version: "3.0.3" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: d57953e10f9f8327ce64a508a355f0b1ec902193f66288e8cb5070e7c47eeb2d + url: "https://pub.dev" + source: hosted + version: "1.0.6" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: "40ae61a5d43feea6d24bd22c0537a6629db858963b99b4bc1c3db80676f32368" + url: "https://pub.dev" + source: hosted + version: "2.3.4" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + file: + dependency: transitive + description: + name: file + sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" + url: "https://pub.dev" + source: hosted + version: "7.0.0" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04 + url: "https://pub.dev" + source: hosted + version: "2.0.3" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + http: + dependency: "direct main" + description: + name: http + sha256: d4872660c46d929f6b8a9ef4e7a7eff7e49bbf0c4ec3f385ee32df5119175139 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + logging: + dependency: transitive + description: + name: logging + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" + url: "https://pub.dev" + source: hosted + version: "0.12.16" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" + url: "https://pub.dev" + source: hosted + version: "0.5.0" + meta: + dependency: transitive + description: + name: meta + sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e + url: "https://pub.dev" + source: hosted + version: "1.10.0" + mockito: + dependency: "direct main" + description: + name: mockito + sha256: "6841eed20a7befac0ce07df8116c8b8233ed1f4486a7647c7fc5a02ae6163917" + url: "https://pub.dev" + source: hosted + version: "5.4.4" + package_config: + dependency: transitive + description: + name: package_config + sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + path: + dependency: transitive + description: + name: path + sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" + url: "https://pub.dev" + source: hosted + version: "1.8.3" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.dev" + source: hosted + version: "1.3.2" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + watcher: + dependency: transitive + description: + name: watcher + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + web: + dependency: transitive + description: + name: web + sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152 + url: "https://pub.dev" + source: hosted + version: "0.3.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + url: "https://pub.dev" + source: hosted + version: "3.1.2" +sdks: + dart: ">=3.2.3 <4.0.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..ba0a042 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,90 @@ +name: wattio_test +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.2.3 <4.0.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.2 + http: ^1.1.2 + mockito: ^5.4.4 + +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: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + assets: + - assets/images/ + - assets/json/ + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # 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/custom-fonts/#from-packages diff --git a/quem_somos_screen.jpeg b/quem_somos_screen.jpeg new file mode 100644 index 0000000..b0b77a4 Binary files /dev/null and b/quem_somos_screen.jpeg differ diff --git a/test/dialog_helper_test.dart b/test/dialog_helper_test.dart new file mode 100644 index 0000000..cc3e3ea --- /dev/null +++ b/test/dialog_helper_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wattio_test/presentation/widgets/dialog_helper.dart'; + + +void main() { + testWidgets('DialogHelper showSavingsDialog test', (WidgetTester tester) async { + final TextEditingController gastoMensalController = TextEditingController(); + gastoMensalController.text = '1000'; + + final Map oferta = {'desconto': 10}; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () => DialogHelper.showSavingsDialog(context, oferta, gastoMensalController), + child: const Text('Show Dialog'), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + expect(find.text('Economia Mensal: R\$100.00'), findsOneWidget); + expect(find.text('Economia Anual: R\$1200.00'), findsOneWidget); + }); +} diff --git a/test/savings_dialog_test.dart b/test/savings_dialog_test.dart new file mode 100644 index 0000000..c9ebd4b --- /dev/null +++ b/test/savings_dialog_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wattio_test/presentation/widgets/savings_dialog_widget.dart'; + +void main() { + testWidgets('SavingsDialog show test', (WidgetTester tester) async { + final TextEditingController gastoMensalController = TextEditingController(); + gastoMensalController.text = '1000'; + + final Map oferta = {'desconto': 10}; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () => + SavingsDialog.show(context, oferta, gastoMensalController), + child: const Text('Show Dialog'), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + + expect(find.text('Economia Mensal: R\$100.00'), findsOneWidget); + expect(find.text('Economia Anual: R\$1200.0'), findsOneWidget); + }); +} 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..60500d9 --- /dev/null +++ b/web/index.html @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + wattio_test + + + + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..22d7ec2 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "wattio_test", + "short_name": "wattio_test", + "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..a5f3149 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(wattio_test 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 "wattio_test") + +# 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..8b6d468 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} 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..b93c4c3 --- /dev/null +++ b/windows/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}/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..0cb433c --- /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", "wattio_test" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "wattio_test" "\0" + VALUE "LegalCopyright", "Copyright (C) 2024 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "wattio_test.exe" "\0" + VALUE "ProductName", "wattio_test" "\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..73a39c1 --- /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"wattio_test", 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..a42ea76 --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..b2b0873 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length <= 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 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_